summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/CODEOWNERS1
-rw-r--r--.github/actions/godot-build/action.yml36
-rw-r--r--.github/actions/godot-cache/action.yml22
-rw-r--r--.github/actions/godot-deps/action.yml27
-rw-r--r--.github/actions/upload-artifact/action.yml19
-rw-r--r--.github/workflows/android_builds.yml61
-rw-r--r--.github/workflows/ios_builds.yml57
-rw-r--r--.github/workflows/javascript_builds.yml68
-rw-r--r--.github/workflows/linux_builds.yml256
-rw-r--r--.github/workflows/macos_builds.yml130
-rw-r--r--.github/workflows/windows_builds.yml159
-rw-r--r--COPYRIGHT.txt1
-rw-r--r--SConstruct2
-rw-r--r--core/extension/gdnative_interface.h2
-rw-r--r--core/extension/native_extension.h1
-rw-r--r--core/input/input_map.cpp66
-rw-r--r--core/input/input_map.h1
-rw-r--r--core/math/basis.cpp2
-rw-r--r--core/math/convex_hull.h2
-rw-r--r--core/math/dynamic_bvh.h2
-rw-r--r--core/math/triangle_mesh.h6
-rw-r--r--core/multiplayer/multiplayer_replicator.cpp7
-rw-r--r--core/os/os.cpp4
-rw-r--r--core/os/os.h3
-rw-r--r--core/string/ustring.cpp63
-rw-r--r--core/templates/cowdata.h10
-rw-r--r--core/templates/vector.h2
-rw-r--r--core/variant/variant.cpp20
-rw-r--r--doc/classes/@GlobalScope.xml2
-rw-r--r--doc/classes/Array.xml2
-rw-r--r--doc/classes/Camera3D.xml2
-rw-r--r--doc/classes/CanvasItem.xml2
-rw-r--r--doc/classes/ConfigFile.xml3
-rw-r--r--doc/classes/Control.xml3
-rw-r--r--doc/classes/EditorCommandPalette.xml25
-rw-r--r--doc/classes/EditorInterface.xml1
-rw-r--r--doc/classes/EditorSceneImporterMesh.xml8
-rw-r--r--doc/classes/Engine.xml18
-rw-r--r--doc/classes/File.xml16
-rw-r--r--doc/classes/FontData.xml3
-rw-r--r--doc/classes/HScrollBar.xml6
-rw-r--r--doc/classes/JNISingleton.xml3
-rw-r--r--doc/classes/Light3D.xml3
-rw-r--r--doc/classes/Listener2D.xml35
-rw-r--r--doc/classes/Listener3D.xml1
-rw-r--r--doc/classes/Mesh.xml2
-rw-r--r--doc/classes/MeshLibrary.xml15
-rw-r--r--doc/classes/Node2D.xml1
-rw-r--r--doc/classes/Object.xml30
-rw-r--r--doc/classes/PackedByteArray.xml2
-rw-r--r--doc/classes/PackedColorArray.xml2
-rw-r--r--doc/classes/PackedFloat32Array.xml2
-rw-r--r--doc/classes/PackedFloat64Array.xml2
-rw-r--r--doc/classes/PackedInt32Array.xml2
-rw-r--r--doc/classes/PackedInt64Array.xml2
-rw-r--r--doc/classes/PackedStringArray.xml2
-rw-r--r--doc/classes/PackedVector2Array.xml2
-rw-r--r--doc/classes/PackedVector3Array.xml2
-rw-r--r--doc/classes/PhysicsDirectBodyState2D.xml1
-rw-r--r--doc/classes/PhysicsDirectBodyState3D.xml2
-rw-r--r--doc/classes/PhysicsDirectSpaceState2D.xml3
-rw-r--r--doc/classes/PhysicsDirectSpaceState3D.xml1
-rw-r--r--doc/classes/ProjectSettings.xml30
-rw-r--r--doc/classes/RenderingDevice.xml34
-rw-r--r--doc/classes/RenderingServer.xml18
-rw-r--r--doc/classes/SceneTree.xml2
-rw-r--r--doc/classes/StyleBoxFlat.xml1
-rw-r--r--doc/classes/TextServer.xml3
-rw-r--r--doc/classes/Thread.xml2
-rw-r--r--doc/classes/TileData.xml33
-rw-r--r--doc/classes/TileMap.xml47
-rw-r--r--doc/classes/TileSet.xml149
-rw-r--r--doc/classes/TileSetAtlasSource.xml74
-rw-r--r--doc/classes/TileSetScenesCollectionSource.xml52
-rw-r--r--doc/classes/TileSetSource.xml51
-rw-r--r--doc/classes/VScrollBar.xml6
-rw-r--r--doc/classes/Vector2.xml3
-rw-r--r--doc/classes/Viewport.xml6
-rw-r--r--doc/classes/Window.xml25
-rw-r--r--doc/classes/XRInterfaceExtension.xml6
-rw-r--r--drivers/register_driver_types.cpp3
-rw-r--r--drivers/vulkan/rendering_device_vulkan.cpp90
-rw-r--r--drivers/vulkan/rendering_device_vulkan.h4
-rw-r--r--drivers/vulkan/vulkan_context.cpp17
-rw-r--r--drivers/vulkan/vulkan_context.h4
-rw-r--r--drivers/wasapi/audio_driver_wasapi.cpp2
-rw-r--r--editor/action_map_editor.cpp2
-rw-r--r--editor/code_editor.cpp28
-rw-r--r--editor/debugger/editor_debugger_node.cpp8
-rw-r--r--editor/debugger/editor_debugger_node.h2
-rw-r--r--editor/debugger/editor_debugger_server.cpp17
-rw-r--r--editor/debugger/editor_debugger_server.h2
-rw-r--r--editor/editor_autoload_settings.cpp36
-rw-r--r--editor/editor_autoload_settings.h1
-rw-r--r--editor/editor_command_palette.cpp27
-rw-r--r--editor/editor_command_palette.h11
-rw-r--r--editor/editor_file_system.cpp4
-rw-r--r--editor/editor_help.cpp6
-rw-r--r--editor/editor_inspector.cpp25
-rw-r--r--editor/editor_inspector.h1
-rw-r--r--editor/editor_log.cpp2
-rw-r--r--editor/editor_node.cpp61
-rw-r--r--editor/editor_node.h4
-rw-r--r--editor/editor_plugin.cpp1
-rw-r--r--editor/editor_properties.cpp178
-rw-r--r--editor/editor_properties.h2
-rw-r--r--editor/editor_themes.cpp4
-rw-r--r--editor/filesystem_dock.cpp15
-rw-r--r--editor/icons/Listener2D.svg1
-rw-r--r--editor/import/resource_importer_scene.cpp189
-rw-r--r--editor/import/resource_importer_scene.h202
-rw-r--r--editor/import/scene_import_settings.cpp74
-rw-r--r--editor/import/scene_import_settings.h4
-rw-r--r--editor/import/scene_importer_mesh.cpp80
-rw-r--r--editor/import/scene_importer_mesh.h9
-rw-r--r--editor/multi_node_edit.cpp13
-rw-r--r--editor/plugins/animation_player_editor_plugin.cpp2
-rw-r--r--editor/plugins/animation_player_editor_plugin.h5
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp4
-rw-r--r--editor/plugins/mesh_instance_3d_editor_plugin.cpp3
-rw-r--r--editor/plugins/mesh_library_editor_plugin.cpp59
-rw-r--r--editor/plugins/mesh_library_editor_plugin.h14
-rw-r--r--editor/plugins/node_3d_editor_plugin.cpp2
-rw-r--r--editor/plugins/packed_scene_translation_parser_plugin.cpp49
-rw-r--r--editor/plugins/packed_scene_translation_parser_plugin.h4
-rw-r--r--editor/plugins/script_text_editor.cpp2
-rw-r--r--editor/plugins/skeleton_2d_editor_plugin.cpp5
-rw-r--r--editor/plugins/tiles/tile_atlas_view.cpp6
-rw-r--r--editor/plugins/tiles/tile_data_editors.cpp25
-rw-r--r--editor/plugins/tiles/tile_map_editor.cpp36
-rw-r--r--editor/plugins/visual_shader_editor_plugin.cpp2
-rw-r--r--editor/pot_generator.cpp13
-rw-r--r--editor/project_manager.cpp4
-rw-r--r--editor/rename_dialog.cpp12
-rw-r--r--editor/rename_dialog.h7
-rw-r--r--editor/scene_tree_dock.cpp19
-rw-r--r--editor/scene_tree_dock.h5
-rw-r--r--editor/translations/el.po2
-rw-r--r--main/main.cpp34
-rwxr-xr-xmisc/scripts/file_format.sh3
-rw-r--r--modules/csg/csg_shape.cpp2
-rw-r--r--modules/gdscript/gdscript.cpp15
-rw-r--r--modules/gdscript/gdscript.h1
-rw-r--r--modules/gdscript/gdscript_analyzer.cpp57
-rw-r--r--modules/gdscript/gdscript_byte_codegen.cpp6
-rw-r--r--modules/gdscript/gdscript_byte_codegen.h1
-rw-r--r--modules/gdscript/gdscript_codegen.h1
-rw-r--r--modules/gdscript/gdscript_compiler.cpp23
-rw-r--r--modules/gdscript/gdscript_disassembler.cpp8
-rw-r--r--modules/gdscript/gdscript_editor.cpp2
-rw-r--r--modules/gdscript/gdscript_function.h1
-rw-r--r--modules/gdscript/gdscript_parser.cpp155
-rw-r--r--modules/gdscript/gdscript_vm.cpp28
-rw-r--r--modules/gdscript/gdscript_warning.cpp4
-rw-r--r--modules/gdscript/gdscript_warning.h1
-rw-r--r--modules/gdscript/tests/gdscript_test_runner.cpp8
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.gd3
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.gd3
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.gd5
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.gd6
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.gd6
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.gd6
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.gd7
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.gd7
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.gd6
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.gd3
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.gd2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.gd2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.gd2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.gd5
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.gd3
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/missing_argument.gd6
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/missing_argument.out (renamed from modules/gdscript/tests/scripts/parser/errors/missing_argument.out)0
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.gd4
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.gd7
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.gd5
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.gd11
-rw-r--r--modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.out2
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/as.gd16
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/as.out8
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.gd16
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.out4
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.gd14
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.out4
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.gd14
-rw-r--r--modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_in_if.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_in_if.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_in_var.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_in_var.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.gd6
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.gd7
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.gd7
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/missing_argument.gd6
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/missing_colon.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.gd6
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/redefine_keyword.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/redefine_keyword.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.gd6
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.gd34
-rw-r--r--modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.out14
-rw-r--r--modules/gdscript/tests/scripts/parser/features/array.gd16
-rw-r--r--modules/gdscript/tests/scripts/parser/features/array.out11
-rw-r--r--modules/gdscript/tests/scripts/parser/features/basic_expression_matching.gd27
-rw-r--r--modules/gdscript/tests/scripts/parser/features/basic_expression_matching.out10
-rw-r--r--modules/gdscript/tests/scripts/parser/features/bitwise_operators.gd50
-rw-r--r--modules/gdscript/tests/scripts/parser/features/bitwise_operators.out14
-rw-r--r--modules/gdscript/tests/scripts/parser/features/class.gd25
-rw-r--r--modules/gdscript/tests/scripts/parser/features/class.out3
-rw-r--r--modules/gdscript/tests/scripts/parser/features/class_inheritance.gd33
-rw-r--r--modules/gdscript/tests/scripts/parser/features/class_inheritance.out10
-rw-r--r--modules/gdscript/tests/scripts/parser/features/class_name.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/features/class_name.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/concatenation.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/features/concatenation.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/features/constants.gd11
-rw-r--r--modules/gdscript/tests/scripts/parser/features/constants.out33
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dictionary.gd37
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dictionary.out14
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.gd9
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.gd12
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dollar_node_paths.gd20
-rw-r--r--modules/gdscript/tests/scripts/parser/features/dollar_node_paths.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/enum.gd14
-rw-r--r--modules/gdscript/tests/scripts/parser/features/enum.out6
-rw-r--r--modules/gdscript/tests/scripts/parser/features/export_variable.gd11
-rw-r--r--modules/gdscript/tests/scripts/parser/features/export_variable.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/features/float_notation.gd24
-rw-r--r--modules/gdscript/tests/scripts/parser/features/float_notation.out19
-rw-r--r--modules/gdscript/tests/scripts/parser/features/for_range.gd39
-rw-r--r--modules/gdscript/tests/scripts/parser/features/for_range.out58
-rw-r--r--modules/gdscript/tests/scripts/parser/features/in.gd14
-rw-r--r--modules/gdscript/tests/scripts/parser/features/in.out11
-rw-r--r--modules/gdscript/tests/scripts/parser/features/match.gd18
-rw-r--r--modules/gdscript/tests/scripts/parser/features/match.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_arrays.gd7
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_arrays.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.gd10
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_if.gd14
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_if.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_strings.gd15
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_strings.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_vector.gd17
-rw-r--r--modules/gdscript/tests/scripts/parser/features/multiline_vector.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_arithmetic.gd22
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_arithmetic.out82
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_array.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_array.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_dictionary.gd6
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_dictionary.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_if.gd57
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_if.out21
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_match.gd79
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_match.out22
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_parentheses.gd65
-rw-r--r--modules/gdscript/tests/scripts/parser/features/nested_parentheses.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/features/number_separators.gd12
-rw-r--r--modules/gdscript/tests/scripts/parser/features/number_separators.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/operator_assign.gd8
-rw-r--r--modules/gdscript/tests/scripts/parser/features/operator_assign.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/features/property_setter_getter.gd37
-rw-r--r--modules/gdscript/tests/scripts/parser/features/property_setter_getter.out19
-rw-r--r--modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.out2
-rw-r--r--modules/gdscript/tests/scripts/parser/features/space_indentation.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/features/space_indentation.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/features/static_typing.gd13
-rw-r--r--modules/gdscript/tests/scripts/parser/features/static_typing.out21
-rw-r--r--modules/gdscript/tests/scripts/parser/features/string_formatting.gd18
-rw-r--r--modules/gdscript/tests/scripts/parser/features/string_formatting.out11
-rw-r--r--modules/gdscript/tests/scripts/parser/features/super.gd60
-rw-r--r--modules/gdscript/tests/scripts/parser/features/super.out13
-rw-r--r--modules/gdscript/tests/scripts/parser/features/truthiness.gd30
-rw-r--r--modules/gdscript/tests/scripts/parser/features/truthiness.out65
-rw-r--r--modules/gdscript/tests/scripts/parser/features/variable_declaration.gd22
-rw-r--r--modules/gdscript/tests/scripts/parser/features/variable_declaration.out6
-rw-r--r--modules/gdscript/tests/scripts/parser/features/while.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/features/while.out6
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/assert_always_true.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/assert_always_true.out13
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.gd8
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.gd1
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.gd1
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.gd3
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.out4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.gd8
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/integer_division.gd10
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/integer_division.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.gd9
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.out6
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.gd5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.gd6
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out1
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.gd8
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.out9
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.gd8
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.out9
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.out9
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/standalone_expression.gd9
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/standalone_expression.out21
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.gd2
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.gd7
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unused_argument.gd12
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unused_argument.out5
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/unused_variable.gd4
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/void_assignment.gd6
-rw-r--r--modules/gdscript/tests/scripts/parser/warnings/void_assignment.out5
-rw-r--r--modules/gltf/config.py1
-rw-r--r--modules/gltf/doc_classes/GLTFCamera.xml8
-rw-r--r--modules/gltf/doc_classes/GLTFDocument.xml22
-rw-r--r--modules/gltf/doc_classes/GLTFLight.xml4
-rw-r--r--modules/gltf/doc_classes/GLTFNode.xml4
-rw-r--r--modules/gltf/doc_classes/PackedSceneGLTF.xml43
-rw-r--r--modules/gltf/editor_scene_exporter_gltf_plugin.cpp11
-rw-r--r--modules/gltf/editor_scene_exporter_gltf_plugin.h1
-rw-r--r--modules/gltf/editor_scene_importer_gltf.cpp117
-rw-r--r--modules/gltf/editor_scene_importer_gltf.h28
-rw-r--r--modules/gltf/gltf_accessor.h3
-rw-r--r--modules/gltf/gltf_animation.h2
-rw-r--r--modules/gltf/gltf_camera.cpp12
-rw-r--r--modules/gltf/gltf_camera.h12
-rw-r--r--modules/gltf/gltf_document.cpp395
-rw-r--r--modules/gltf/gltf_document.h12
-rw-r--r--modules/gltf/gltf_light.cpp14
-rw-r--r--modules/gltf/gltf_light.h6
-rw-r--r--modules/gltf/gltf_node.cpp14
-rw-r--r--modules/gltf/gltf_node.h7
-rw-r--r--modules/gltf/gltf_state.h1
-rw-r--r--modules/gltf/register_types.cpp1
-rw-r--r--modules/gridmap/grid_map.cpp2
-rw-r--r--modules/gridmap/grid_map_editor_plugin.cpp6
-rw-r--r--modules/lightmapper_rd/SCsub3
-rw-r--r--modules/lightmapper_rd/lightmapper_rd.cpp48
-rw-r--r--modules/lightmapper_rd/lightmapper_rd.h11
-rw-r--r--modules/lightmapper_rd/lm_common_inc.glsl30
-rw-r--r--modules/lightmapper_rd/lm_compute.glsl13
-rw-r--r--modules/mono/csharp_script.cpp42
-rw-r--r--modules/mono/csharp_script.h2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs8
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs6
-rw-r--r--modules/mono/editor/bindings_generator.cpp2
-rw-r--r--modules/mono/editor/code_completion.cpp4
-rw-r--r--modules/mono/editor/editor_internal_calls.cpp7
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs2
-rw-r--r--modules/ogg/config.py11
-rw-r--r--modules/ogg/doc_classes/OGGPacketSequence.xml32
-rw-r--r--modules/ogg/doc_classes/OGGPacketSequencePlayback.xml13
-rw-r--r--modules/ogg/ogg_packet_sequence.cpp220
-rw-r--r--modules/ogg/ogg_packet_sequence.h128
-rw-r--r--modules/ogg/register_types.cpp7
-rw-r--r--modules/raycast/SCsub3
-rw-r--r--modules/raycast/godot_update_embree.py12
-rw-r--r--modules/stb_vorbis/SCsub27
-rw-r--r--modules/stb_vorbis/audio_stream_ogg_vorbis.cpp278
-rw-r--r--modules/stb_vorbis/config.py16
-rw-r--r--modules/text_server_adv/script_iterator.cpp20
-rw-r--r--modules/text_server_adv/script_iterator.h2
-rw-r--r--modules/text_server_adv/text_server_adv.cpp18
-rw-r--r--modules/text_server_fb/text_server_fb.cpp7
-rw-r--r--modules/vhacd/register_types.cpp69
-rw-r--r--modules/visual_script/doc_classes/VisualScriptCustomNode.xml2
-rw-r--r--modules/visual_script/register_types.cpp2
-rw-r--r--modules/visual_script/visual_script_func_nodes.cpp2
-rw-r--r--modules/vorbis/SCsub3
-rw-r--r--modules/vorbis/audio_stream_ogg_vorbis.cpp435
-rw-r--r--modules/vorbis/audio_stream_ogg_vorbis.h (renamed from modules/stb_vorbis/audio_stream_ogg_vorbis.h)54
-rw-r--r--modules/vorbis/config.py11
-rw-r--r--modules/vorbis/doc_classes/AudioStreamOGGVorbis.xml (renamed from modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml)8
-rw-r--r--modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml13
-rw-r--r--modules/vorbis/register_types.cpp15
-rw-r--r--modules/vorbis/resource_importer_ogg_vorbis.cpp (renamed from modules/stb_vorbis/resource_importer_ogg_vorbis.cpp)116
-rw-r--r--modules/vorbis/resource_importer_ogg_vorbis.h (renamed from modules/stb_vorbis/resource_importer_ogg_vorbis.h)20
-rw-r--r--modules/websocket/editor_debugger_server_websocket.cpp14
-rw-r--r--modules/websocket/editor_debugger_server_websocket.h2
-rw-r--r--platform/android/README.md14
-rw-r--r--platform/android/export/export_plugin.cpp30
-rw-r--r--platform/android/export/export_plugin.h7
-rw-r--r--platform/android/export/gradle_export_util.cpp3
-rw-r--r--platform/android/export/gradle_export_util.h6
-rw-r--r--platform/android/java/app/assetPacks/installTime/build.gradle8
-rw-r--r--platform/android/java/app/build.gradle2
-rw-r--r--platform/android/java/app/settings.gradle4
-rw-r--r--platform/android/java/settings.gradle3
-rw-r--r--platform/android/logo.pngbin951 -> 968 bytes
-rw-r--r--platform/javascript/README.md15
-rw-r--r--platform/javascript/api/javascript_tools_editor_plugin.cpp4
-rw-r--r--platform/javascript/audio_driver_javascript.cpp2
-rw-r--r--platform/javascript/display_server_javascript.cpp21
-rw-r--r--platform/javascript/godot_audio.h2
-rw-r--r--platform/javascript/js/libs/audio.worklet.js14
-rw-r--r--platform/javascript/js/libs/library_godot_audio.js17
-rw-r--r--platform/linuxbsd/README.md11
-rw-r--r--platform/linuxbsd/detect.py49
-rw-r--r--platform/windows/display_server_windows.cpp295
-rw-r--r--scene/2d/audio_stream_player_2d.cpp21
-rw-r--r--scene/2d/listener_2d.cpp112
-rw-r--r--scene/2d/listener_2d.h (renamed from modules/stb_vorbis/register_types.cpp)47
-rw-r--r--scene/2d/parallax_layer.cpp4
-rw-r--r--scene/2d/tile_map.cpp121
-rw-r--r--scene/3d/mesh_instance_3d.cpp3
-rw-r--r--scene/3d/skeleton_ik_3d.cpp2
-rw-r--r--scene/animation/animation_player.cpp3
-rw-r--r--scene/animation/tween.cpp35
-rw-r--r--scene/animation/tween.h6
-rw-r--r--scene/gui/code_edit.cpp34
-rw-r--r--scene/gui/code_edit.h2
-rw-r--r--scene/gui/graph_edit.cpp10
-rw-r--r--scene/gui/label.cpp77
-rw-r--r--scene/gui/option_button.h4
-rw-r--r--scene/gui/popup_menu.h4
-rw-r--r--scene/gui/rich_text_label.cpp4
-rw-r--r--scene/gui/scroll_bar.cpp26
-rw-r--r--scene/gui/scroll_bar.h3
-rw-r--r--scene/gui/text_edit.cpp15
-rw-r--r--scene/gui/text_edit.h3
-rw-r--r--scene/gui/tree.cpp113
-rw-r--r--scene/gui/tree.h3
-rw-r--r--scene/main/scene_tree.cpp13
-rw-r--r--scene/main/viewport.cpp273
-rw-r--r--scene/main/viewport.h9
-rw-r--r--scene/register_scene_types.cpp2
-rw-r--r--scene/resources/default_theme/default_theme.cpp4
-rw-r--r--scene/resources/material.cpp4
-rw-r--r--scene/resources/mesh.cpp105
-rw-r--r--scene/resources/mesh.h38
-rw-r--r--scene/resources/mesh_library.cpp19
-rw-r--r--scene/resources/mesh_library.h3
-rw-r--r--scene/resources/resource_format_text.cpp10
-rw-r--r--scene/resources/surface_tool.cpp49
-rw-r--r--scene/resources/texture.cpp24
-rw-r--r--scene/resources/texture.h2
-rw-r--r--scene/resources/tile_set.cpp101
-rw-r--r--scene/resources/tile_set.h10
-rw-r--r--servers/audio_server.cpp1
-rw-r--r--servers/display_server.cpp1
-rw-r--r--servers/physics_3d/gjk_epa.cpp2
-rw-r--r--servers/physics_3d/joints/generic_6dof_joint_3d_sw.cpp2
-rw-r--r--servers/physics_3d/joints/generic_6dof_joint_3d_sw.h2
-rw-r--r--servers/physics_3d/joints/hinge_joint_3d_sw.cpp2
-rw-r--r--servers/physics_3d/joints/hinge_joint_3d_sw.h2
-rw-r--r--servers/physics_3d/joints/jacobian_entry_3d_sw.h2
-rw-r--r--servers/physics_3d/joints/pin_joint_3d_sw.cpp2
-rw-r--r--servers/physics_3d/joints/pin_joint_3d_sw.h2
-rw-r--r--servers/physics_3d/joints/slider_joint_3d_sw.cpp2
-rw-r--r--servers/physics_3d/joints/slider_joint_3d_sw.h2
-rw-r--r--servers/physics_3d/shape_3d_sw.cpp2
-rw-r--r--servers/physics_3d/soft_body_3d_sw.cpp2
-rw-r--r--servers/rendering/rasterizer_dummy.h5
-rw-r--r--servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp3
-rw-r--r--servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp8
-rw-r--r--servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp1
-rw-r--r--servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp8
-rw-r--r--servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp10
-rw-r--r--servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp6
-rw-r--r--servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl2
-rw-r--r--servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl2
-rw-r--r--servers/rendering/renderer_rd/shaders/tonemap.glsl48
-rw-r--r--servers/rendering/rendering_device.cpp16
-rw-r--r--servers/rendering/rendering_device.h20
-rw-r--r--servers/rendering_server.cpp24
-rw-r--r--servers/rendering_server.h2
-rw-r--r--servers/xr/xr_interface.cpp2
-rw-r--r--servers/xr/xr_interface_extension.cpp26
-rw-r--r--servers/xr/xr_interface_extension.h4
-rw-r--r--tests/test_array.h51
-rw-r--r--tests/test_code_edit.h813
-rw-r--r--tests/test_macros.h184
-rw-r--r--tests/test_main.cpp151
-rw-r--r--tests/test_string.h28
-rw-r--r--tests/test_tools.h (renamed from modules/stb_vorbis/register_types.h)36
-rw-r--r--tests/test_validate_testing.h12
-rw-r--r--thirdparty/README.md4
-rw-r--r--thirdparty/embree/include/embree3/rtcore_config.h6
-rw-r--r--thirdparty/embree/kernels/bvh/bvh_intersector_hybrid.cpp917
-rw-r--r--thirdparty/embree/kernels/bvh/bvh_intersector_hybrid4_bvh4.cpp59
-rw-r--r--thirdparty/embree/kernels/bvh/bvh_intersector_stream.cpp528
-rw-r--r--thirdparty/embree/kernels/bvh/bvh_intersector_stream_bvh4.cpp36
-rw-r--r--thirdparty/embree/kernels/bvh/bvh_intersector_stream_filters.cpp657
-rw-r--r--thirdparty/embree/kernels/config.h2
-rw-r--r--thirdparty/embree/kernels/hash.h2
-rw-r--r--thirdparty/misc/stb_vorbis.c5563
-rw-r--r--thirdparty/misc/stb_vorbis.h2
561 files changed, 10761 insertions, 8391 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 09ff2454ee..ebbbe345fd 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -73,7 +73,6 @@ doc_classes/* @godotengine/documentation
/modules/minimp3/ @godotengine/audio
/modules/ogg/ @godotengine/audio
/modules/opus/ @godotengine/audio
-/modules/stb_vorbis/ @godotengine/audio
/modules/theora/ @godotengine/audio
/modules/vorbis/ @godotengine/audio
/modules/webm/ @godotengine/audio
diff --git a/.github/actions/godot-build/action.yml b/.github/actions/godot-build/action.yml
new file mode 100644
index 0000000000..5ed64e7de2
--- /dev/null
+++ b/.github/actions/godot-build/action.yml
@@ -0,0 +1,36 @@
+name: Build Godot
+description: Build Godot with the provided options.
+inputs:
+ target:
+ description: The scons target (debug/release_debug/release).
+ default: "debug"
+ tools:
+ description: If tools are to be built.
+ default: false
+ tests:
+ description: If tests are to be built.
+ default: false
+ platform:
+ description: The Godot platform to build.
+ required: false
+ sconsflags:
+ default: ""
+ scons-cache:
+ description: The scons cache path.
+ default: "${{ github.workspace }}/.scons-cache/"
+ scons-cache-limit:
+ description: The scons cache size limit.
+ default: 4096
+runs:
+ using: "composite"
+ steps:
+ - name: Scons Build
+ shell: sh
+ env:
+ SCONSFLAGS: ${{ inputs.sconsflags }}
+ SCONS_CACHE: ${{ inputs.scons-cache }}
+ SCONS_CACHE_LIMIT: ${{ inputs.scons-cache-limit }}
+ run: |
+ echo "Building with flags:" ${{ env.SCONSFLAGS }}
+ scons p=${{ inputs.platform }} target=${{ inputs.target }} tools=${{ inputs.tools }} tests=${{ inputs.tests }} --jobs=2 ${{ env.SCONSFLAGS }}
+ ls -l bin/
diff --git a/.github/actions/godot-cache/action.yml b/.github/actions/godot-cache/action.yml
new file mode 100644
index 0000000000..db14a0b97a
--- /dev/null
+++ b/.github/actions/godot-cache/action.yml
@@ -0,0 +1,22 @@
+name: Setup Godot build cache
+description: Setup Godot build cache.
+inputs:
+ cache-name:
+ description: The cache base name (job name by default).
+ default: "${{github.job}}"
+ scons-cache:
+ description: The scons cache path.
+ default: "${{github.workspace}}/.scons-cache/"
+runs:
+ using: "composite"
+ steps:
+ # Upload cache on completion and check it out now
+ - name: Load .scons_cache directory
+ uses: actions/cache@v2
+ with:
+ path: ${{inputs.scons-cache}}
+ key: ${{inputs.cache-name}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
+ restore-keys: |
+ ${{inputs.cache-name}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
+ ${{inputs.cache-name}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
+ ${{inputs.cache-name}}-${{env.GODOT_BASE_BRANCH}}
diff --git a/.github/actions/godot-deps/action.yml b/.github/actions/godot-deps/action.yml
new file mode 100644
index 0000000000..ee4d7d3751
--- /dev/null
+++ b/.github/actions/godot-deps/action.yml
@@ -0,0 +1,27 @@
+name: Setup python and scons
+description: Setup python, install the pip version of scons.
+inputs:
+ python-version:
+ description: The python version to use.
+ default: "3.x"
+ python-arch:
+ description: The python architecture.
+ default: "x64"
+runs:
+ using: "composite"
+ steps:
+ # Use python 3.x release (works cross platform)
+ - name: Set up Python 3.x
+ uses: actions/setup-python@v2
+ with:
+ # Semantic version range syntax or exact version of a Python version
+ python-version: ${{ inputs.python-version }}
+ # Optional - x64 or x86 architecture, defaults to x64
+ architecture: ${{ inputs.python-arch }}
+
+ - name: Setup scons
+ shell: bash
+ run: |
+ python -c "import sys; print(sys.version)"
+ python -m pip install scons
+ scons --version
diff --git a/.github/actions/upload-artifact/action.yml b/.github/actions/upload-artifact/action.yml
new file mode 100644
index 0000000000..bc1871b914
--- /dev/null
+++ b/.github/actions/upload-artifact/action.yml
@@ -0,0 +1,19 @@
+name: Upload Godot artifact
+description: Upload the Godot artifact.
+inputs:
+ name:
+ description: The artifact name.
+ default: "${{ github.job }}"
+ path:
+ description: The path to upload.
+ required: true
+ default: "bin/*"
+runs:
+ using: "composite"
+ steps:
+ - name: Upload Godot Artifact
+ uses: actions/upload-artifact@v2
+ with:
+ name: ${{ inputs.name }}
+ path: ${{ inputs.path }}
+ retention-days: 14
diff --git a/.github/workflows/android_builds.yml b/.github/workflows/android_builds.yml
index 5efeba4b5f..74f8fa8eae 100644
--- a/.github/workflows/android_builds.yml
+++ b/.github/workflows/android_builds.yml
@@ -4,8 +4,7 @@ on: [push, pull_request]
# Global Settings
env:
GODOT_BASE_BRANCH: master
- SCONSFLAGS: platform=android verbose=yes warnings=extra werror=yes debug_symbols=no --jobs=2 module_text_server_fb_enabled=yes
- SCONS_CACHE_LIMIT: 4096
+ SCONSFLAGS: verbose=yes warnings=extra werror=yes debug_symbols=no module_text_server_fb_enabled=yes
concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-android
@@ -14,7 +13,6 @@ concurrency:
jobs:
android-template:
runs-on: "ubuntu-20.04"
-
name: Template (target=release, tools=no)
steps:
@@ -32,48 +30,37 @@ jobs:
with:
java-version: 8
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: android-template-cache
- uses: actions/cache@v2
- with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
+ - name: Setup Godot build cache
+ uses: ./.github/actions/godot-cache
continue-on-error: true
- # Use python 3.x release (works cross platform)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
+ - name: Setup python and scons
+ uses: ./.github/actions/godot-deps
+
+ - name: Compilation (armv7)
+ uses: ./.github/actions/godot-build
with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
+ sconsflags: ${{ env.SCONSFLAGS }} android_arch=armv7
+ platform: android
+ target: release
+ tools: false
+ tests: false
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
+ - name: Compilation (arm64v8)
+ uses: ./.github/actions/godot-build
+ with:
+ sconsflags: ${{ env.SCONSFLAGS }} android_arch=arm64v8
+ platform: android
+ target: release
+ tools: false
+ tests: false
- - name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
+ - name: Generate Godot templates
run: |
- scons target=release tools=no android_arch=armv7
- scons target=release tools=no android_arch=arm64v8
cd platform/android/java
./gradlew generateGodotTemplates
cd ../../..
ls -l bin/
- - uses: actions/upload-artifact@v2
- with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
+ - name: Upload artifact
+ uses: ./.github/actions/upload-artifact
diff --git a/.github/workflows/ios_builds.yml b/.github/workflows/ios_builds.yml
index 69809c6cb6..721d574dbe 100644
--- a/.github/workflows/ios_builds.yml
+++ b/.github/workflows/ios_builds.yml
@@ -4,8 +4,7 @@ on: [push, pull_request]
# Global Settings
env:
GODOT_BASE_BRANCH: master
- SCONSFLAGS: platform=iphone verbose=yes warnings=extra werror=yes debug_symbols=no --jobs=2 module_text_server_fb_enabled=yes
- SCONS_CACHE_LIMIT: 4096
+ SCONSFLAGS: verbose=yes warnings=extra werror=yes debug_symbols=no module_text_server_fb_enabled=yes
concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-ios
@@ -19,45 +18,21 @@ jobs:
steps:
- uses: actions/checkout@v2
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: ios-template-cache
- uses: actions/cache@v2
- with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
+ - name: Setup Godot build cache
+ uses: ./.github/actions/godot-cache
continue-on-error: true
- # Use python 3.x release (works cross platform)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # You can test your matrix by printing the current Python version
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
-
- - name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
- run: |
- scons target=release tools=no
- ls -l bin/
-
- - uses: actions/upload-artifact@v2
+ - name: Setup python and scons
+ uses: ./.github/actions/godot-deps
+
+ - name: Compilation (armv7)
+ uses: ./.github/actions/godot-build
with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
+ sconsflags: ${{ env.SCONSFLAGS }}
+ platform: iphone
+ target: release
+ tools: false
+ tests: false
+
+ - name: Upload artifact
+ uses: ./.github/actions/upload-artifact
diff --git a/.github/workflows/javascript_builds.yml b/.github/workflows/javascript_builds.yml
index 25a063c3b2..9163baab0f 100644
--- a/.github/workflows/javascript_builds.yml
+++ b/.github/workflows/javascript_builds.yml
@@ -4,10 +4,9 @@ on: [push, pull_request]
# Global Settings
env:
GODOT_BASE_BRANCH: master
- SCONSFLAGS: platform=javascript verbose=yes warnings=extra werror=yes debug_symbols=no --jobs=2
- SCONS_CACHE_LIMIT: 4096
+ SCONSFLAGS: verbose=yes warnings=extra werror=yes debug_symbols=no
EM_VERSION: 2.0.27
- EM_CACHE_FOLDER: 'emsdk-cache'
+ EM_CACHE_FOLDER: "emsdk-cache"
concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-javascript
@@ -21,26 +20,6 @@ jobs:
steps:
- uses: actions/checkout@v2
- # Azure repositories are not reliable, we need to prevent azure giving us packages.
- - name: Make apt sources.list use the default Ubuntu repositories
- run: |
- sudo rm -f /etc/apt/sources.list.d/*
- sudo cp -f misc/ci/sources.list /etc/apt/sources.list
- sudo apt-get update
-
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: javascript-template-cache
- uses: actions/cache@v2
- with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
- continue-on-error: true
-
# Additional cache for Emscripten generated system libraries
- name: Load Emscripten cache
id: javascript-template-emscripten-cache
@@ -49,23 +28,6 @@ jobs:
path: ${{env.EM_CACHE_FOLDER}}
key: ${{env.EM_VERSION}}-${{github.job}}
- # Use python 3.x release (works cross platform)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # You can test your matrix by printing the current Python version
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
-
- name: Set up Emscripten latest
uses: mymindstorm/setup-emsdk@v10
with:
@@ -76,15 +38,21 @@ jobs:
run: |
emcc -v
- - name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
- run: |
- scons target=release tools=no use_closure_compiler=yes
- ls -l bin/
+ - name: Setup Godot build cache
+ uses: ./.github/actions/godot-cache
+ continue-on-error: true
+
+ - name: Setup python and scons
+ uses: ./.github/actions/godot-deps
- - uses: actions/upload-artifact@v2
+ - name: Compilation
+ uses: ./.github/actions/godot-build
with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
+ sconsflags: ${{ env.SCONSFLAGS }}
+ platform: javascript
+ target: release
+ tools: false
+ tests: false
+
+ - name: Upload artifact
+ uses: ./.github/actions/upload-artifact
diff --git a/.github/workflows/linux_builds.yml b/.github/workflows/linux_builds.yml
index 6fe76345f3..54e9ef4c66 100644
--- a/.github/workflows/linux_builds.yml
+++ b/.github/workflows/linux_builds.yml
@@ -4,79 +4,91 @@ on: [push, pull_request]
# Global Settings
env:
GODOT_BASE_BRANCH: master
- SCONSFLAGS: platform=linuxbsd verbose=yes warnings=extra werror=yes debug_symbols=no --jobs=2 module_text_server_fb_enabled=yes
- SCONS_CACHE_LIMIT: 4096
+ SCONSFLAGS: verbose=yes warnings=extra werror=yes debug_symbols=no module_text_server_fb_enabled=yes
concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-linux
cancel-in-progress: true
jobs:
- linux-editor:
+ build-linux:
runs-on: "ubuntu-20.04"
- name: Editor (target=release_debug, tools=yes, tests=yes)
+ name: ${{ matrix.name }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - name: Editor (target=release_debug, tools=yes, tests=yes)
+ cache-name: linux-editor
+ target: release_debug
+ tools: true
+ tests: true
+ sconsflags: ""
+ doc-test: true
+ bin: "./bin/godot.linuxbsd.opt.tools.64"
+ artifact: true
+
+ - name: Editor and sanitizers (target=debug, tools=yes, tests=yes, use_asan=yes, use_ubsan=yes)
+ cache-name: linux-editor-sanitizers
+ target: debug
+ tools: true
+ tests: true
+ sconsflags: use_asan=yes use_ubsan=yes
+ proj-test: true
+ bin: "./bin/godot.linuxbsd.tools.64s"
+ # Skip 2GiB artifact speeding up action.
+ artifact: false
+
+ - name: Template w/ Mono (target=release, tools=no)
+ cache-name: linux-template-mono
+ target: release
+ tools: false
+ tests: false
+ sconsflags: module_mono_enabled=yes mono_glue=no
+ artifact: true
steps:
- uses: actions/checkout@v2
- # Azure repositories are not reliable, we need to prevent azure giving us packages.
- - name: Make apt sources.list use the default Ubuntu repositories
+ - name: Linux dependencies
+ shell: bash
run: |
+ # Azure repositories are not reliable, we need to prevent azure giving us packages.
sudo rm -f /etc/apt/sources.list.d/*
sudo cp -f misc/ci/sources.list /etc/apt/sources.list
sudo apt-get update
-
- # Install all packages (except scons)
- - name: Configure dependencies
- run: |
+ # The actual dependencies
sudo apt-get install build-essential pkg-config libx11-dev libxcursor-dev \
- libxinerama-dev libgl1-mesa-dev libglu-dev libasound2-dev libpulse-dev libdbus-1-dev libudev-dev libxi-dev libxrandr-dev yasm
+ libxinerama-dev libgl1-mesa-dev libglu-dev libasound2-dev libpulse-dev \
+ libdbus-1-dev libudev-dev libxi-dev libxrandr-dev yasm xvfb wget unzip
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: linux-editor-cache
- uses: actions/cache@v2
+ - name: Setup Godot build cache
+ uses: ./.github/actions/godot-cache
with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
+ cache-name: ${{ matrix.cache-name }}
continue-on-error: true
- # Use python 3.x release (works cross platform; best to keep self contained in it's own step)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # Setup scons, print python version and scons version info, so if anything is broken it won't run the build.
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
+ - name: Setup python and scons
+ uses: ./.github/actions/godot-deps
- # We should always be explicit with our flags usage here since it's gonna be sure to always set those flags
- name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
- run: |
- scons tools=yes tests=yes target=release_debug
- ls -l bin/
+ uses: ./.github/actions/godot-build
+ with:
+ sconsflags: ${{ env.SCONSFLAGS }} ${{ matrix.sconsflags }}
+ platform: linuxbsd
+ target: ${{ matrix.target }}
+ tools: ${{ matrix.tools }}
+ tests: ${{ matrix.tests }}
# Execute unit tests for the editor
- - name: Unit Tests
+ - name: Unit tests
+ if: ${{ matrix.tests }}
run: |
- ./bin/godot.linuxbsd.opt.tools.64 --test
+ ${{ matrix.bin }} --test
# Download, unzip and setup SwiftShader library [4466040]
- name: Download SwiftShader
+ if: ${{ matrix.tests }}
run: |
wget https://github.com/qarmin/gtk_library_store/releases/download/3.24.0/swiftshader2.zip
unzip swiftshader2.zip
@@ -86,93 +98,16 @@ jobs:
# Check class reference
- name: Check for class reference updates
+ if: ${{ matrix.doc-test }}
run: |
echo "Running --doctool to see if this changes the public API without updating the documentation."
echo -e "If a diff is shown, it means that your code/doc changes are incomplete and you should update the class reference with --doctool.\n\n"
- VK_ICD_FILENAMES=$(pwd)/vk_swiftshader_icd.json DRI_PRIME=0 xvfb-run bin/godot.linuxbsd.opt.tools.64 --doctool . 2>&1 > /dev/null || true
+ VK_ICD_FILENAMES=$(pwd)/vk_swiftshader_icd.json DRI_PRIME=0 xvfb-run ${{ matrix.bin }} --doctool . 2>&1 > /dev/null || true
git diff --color --exit-code && ! git ls-files --others --exclude-standard | sed -e 's/^/New doc file missing in PR: /' | grep 'xml$'
- - uses: actions/upload-artifact@v2
- with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
-
- linux-editor-sanitizers:
- runs-on: "ubuntu-20.04"
- name: Editor and sanitizers (target=debug, tools=yes, tests=yes, use_asan=yes, use_ubsan=yes)
-
- steps:
- - uses: actions/checkout@v2
-
- # Azure repositories are not reliable, we need to prevent azure giving us packages.
- - name: Make apt sources.list use the default Ubuntu repositories
- run: |
- sudo rm -f /etc/apt/sources.list.d/*
- sudo cp -f misc/ci/sources.list /etc/apt/sources.list
- sudo apt-get update
-
- # Install all packages (except scons)
- - name: Configure dependencies
- run: |
- sudo apt-get install build-essential pkg-config libx11-dev libxcursor-dev \
- libxinerama-dev libgl1-mesa-dev libglu-dev libasound2-dev libpulse-dev libdbus-1-dev libudev-dev libxi-dev libxrandr-dev yasm \
- xvfb wget unzip
-
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: linux-sanitizers-cache
- uses: actions/cache@v2
- with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
- continue-on-error: true
-
- # Use python 3.x release (works cross platform; best to keep self contained in it's own step)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # Setup scons, print python version and scons version info, so if anything is broken it won't run the build.
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
-
- # We should always be explicit with our flags usage here since it's gonna be sure to always set those flags
- - name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
- run: |
- scons tools=yes tests=yes target=debug debug_symbols=no use_asan=yes use_ubsan=yes
- ls -l bin/
-
- # Execute unit tests for the editor
- - name: Unit Tests
- run: |
- ./bin/godot.linuxbsd.tools.64s --test
-
- # Download, unzip and setup SwiftShader library [4466040]
- - name: Download SwiftShader
- run: |
- wget https://github.com/qarmin/gtk_library_store/releases/download/3.24.0/swiftshader2.zip
- unzip swiftshader2.zip
- rm swiftshader2.zip
- curr="$(pwd)/libvk_swiftshader.so"
- sed -i "s|PATH_TO_CHANGE|$curr|" vk_swiftshader_icd.json
-
# Download and extract zip archive with project, folder is renamed to be able to easy change used project
- name: Download test project
+ if: ${{ matrix.proj-test }}
run: |
wget https://github.com/qarmin/RegressionTestProject/archive/4.0.zip
unzip 4.0.zip
@@ -180,75 +115,20 @@ jobs:
# Editor is quite complicated piece of software, so it is easy to introduce bug here
- name: Open and close editor
+ if: ${{ matrix.proj-test }}
run: |
- VK_ICD_FILENAMES=$(pwd)/vk_swiftshader_icd.json DRI_PRIME=0 xvfb-run bin/godot.linuxbsd.tools.64s --audio-driver Dummy -e -q --path test_project 2>&1 | tee sanitizers_log.txt || true
+ VK_ICD_FILENAMES=$(pwd)/vk_swiftshader_icd.json DRI_PRIME=0 xvfb-run ${{ matrix.bin }} --audio-driver Dummy -e -q --path test_project 2>&1 | tee sanitizers_log.txt || true
misc/scripts/check_ci_log.py sanitizers_log.txt
# Run test project
- name: Run project
+ if: ${{ matrix.proj-test }}
run: |
- VK_ICD_FILENAMES=$(pwd)/vk_swiftshader_icd.json DRI_PRIME=0 xvfb-run bin/godot.linuxbsd.tools.64s 40 --audio-driver Dummy --path test_project 2>&1 | tee sanitizers_log.txt || true
+ VK_ICD_FILENAMES=$(pwd)/vk_swiftshader_icd.json DRI_PRIME=0 xvfb-run ${{ matrix.bin }} 40 --audio-driver Dummy --path test_project 2>&1 | tee sanitizers_log.txt || true
misc/scripts/check_ci_log.py sanitizers_log.txt
- linux-template-mono:
- runs-on: "ubuntu-20.04"
- name: Template w/ Mono (target=release, tools=no)
-
- steps:
- - uses: actions/checkout@v2
-
- # Azure repositories are not reliable, we need to prevent azure giving us packages.
- - name: Make apt sources.list use the default Ubuntu repositories
- run: |
- sudo rm -f /etc/apt/sources.list.d/*
- sudo cp -f misc/ci/sources.list /etc/apt/sources.list
- sudo apt-get update
-
- # Install all packages (except scons)
- - name: Configure dependencies
- run: |
- sudo apt-get install build-essential pkg-config libx11-dev libxcursor-dev \
- libxinerama-dev libgl1-mesa-dev libglu-dev libasound2-dev libpulse-dev libdbus-1-dev libudev-dev libxi-dev libxrandr-dev yasm
-
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: linux-template-cache
- uses: actions/cache@v2
- with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
- continue-on-error: true
-
- # Use python 3.x release (works cross platform)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # You can test your matrix by printing the current Python version
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
-
- - name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
- run: |
- scons target=release tools=no module_mono_enabled=yes mono_glue=no
- ls -l bin/
-
- - uses: actions/upload-artifact@v2
+ - name: Upload artifact
+ uses: ./.github/actions/upload-artifact
+ if: ${{ matrix.artifact }}
with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
+ name: ${{ matrix.cache-name }}
diff --git a/.github/workflows/macos_builds.yml b/.github/workflows/macos_builds.yml
index 2c9e0fa1a0..38d43a4b94 100644
--- a/.github/workflows/macos_builds.yml
+++ b/.github/workflows/macos_builds.yml
@@ -4,117 +4,61 @@ on: [push, pull_request]
# Global Settings
env:
GODOT_BASE_BRANCH: master
- SCONSFLAGS: platform=osx verbose=yes warnings=extra werror=yes debug_symbols=no --jobs=2 module_text_server_fb_enabled=yes
- SCONS_CACHE_LIMIT: 4096
+ SCONSFLAGS: verbose=yes warnings=extra werror=yes debug_symbols=no module_text_server_fb_enabled=yes
concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-macos
cancel-in-progress: true
jobs:
- macos-editor:
+ build-macos:
runs-on: "macos-latest"
-
- name: Editor (target=release_debug, tools=yes, tests=yes)
+ name: ${{ matrix.name }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - name: Editor (target=release_debug, tools=yes, tests=yes)
+ cache-name: macos-editor
+ target: release_debug
+ tools: true
+ tests: true
+ bin: "./bin/godot.osx.opt.tools.64"
+
+ - name: Template (target=release, tools=no)
+ cache-name: macos-template
+ target: release
+ tools: false
+ tests: false
steps:
- uses: actions/checkout@v2
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: macos-editor-cache
- uses: actions/cache@v2
+ - name: Setup Godot build cache
+ uses: ./.github/actions/godot-cache
with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
+ cache-name: ${{ matrix.cache-name }}
continue-on-error: true
- # Use python 3.x release (works cross platform; best to keep self contained in it's own step)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # Setup scons, print python version and scons version info, so if anything is broken it won't run the build.
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
+ - name: Setup python and scons
+ uses: ./.github/actions/godot-deps
- # We should always be explicit with our flags usage here since it's gonna be sure to always set those flags
- name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
- run: |
- scons tools=yes tests=yes target=release_debug
- ls -l bin/
-
- # Execute unit tests for the editor
- - name: Unit Tests
- run: |
- ./bin/godot.osx.opt.tools.64 --test
-
- - uses: actions/upload-artifact@v2
+ uses: ./.github/actions/godot-build
with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
+ sconsflags: ${{ env.SCONSFLAGS }}
+ platform: osx
+ target: ${{ matrix.target }}
+ tools: ${{ matrix.tools }}
+ tests: ${{ matrix.tests }}
- macos-template:
- runs-on: "macos-latest"
- name: Template (target=release, tools=no)
-
- steps:
- - uses: actions/checkout@v2
-
- # Upload cache on completion and check it out now
- - name: Load .scons_cache directory
- id: macos-template-cache
- uses: actions/cache@v2
- with:
- path: ${{github.workspace}}/.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
- continue-on-error: true
-
- # Use python 3.x release (works cross platform)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # You can test your matrix by printing the current Python version
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
-
- - name: Compilation
- env:
- SCONS_CACHE: ${{github.workspace}}/.scons_cache/
+ # Execute unit tests for the editor
+ - name: Unit tests
+ if: ${{ matrix.tests }}
run: |
- scons target=release tools=no
- ls -l bin/
+ ${{ matrix.bin }} --test
- - uses: actions/upload-artifact@v2
+ - name: Upload artifact
+ uses: ./.github/actions/upload-artifact
with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
+ name: ${{ matrix.cache-name }}
diff --git a/.github/workflows/windows_builds.yml b/.github/workflows/windows_builds.yml
index 53febd353b..ee689612f5 100644
--- a/.github/workflows/windows_builds.yml
+++ b/.github/workflows/windows_builds.yml
@@ -5,122 +5,65 @@ on: [push, pull_request]
# SCONS_CACHE for windows must be set in the build environment
env:
GODOT_BASE_BRANCH: master
- SCONSFLAGS: platform=windows verbose=yes warnings=all werror=yes debug_symbols=no --jobs=2 module_text_server_fb_enabled=yes
+ SCONSFLAGS: verbose=yes warnings=all werror=yes debug_symbols=no module_text_server_fb_enabled=yes
SCONS_CACHE_MSVC_CONFIG: true
- SCONS_CACHE_LIMIT: 3072
concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-windows
cancel-in-progress: true
jobs:
- windows-editor:
+ build-windows:
# Windows 10 with latest image
runs-on: "windows-latest"
-
- # Windows Editor - checkout with the plugin
- name: Editor (target=release_debug, tools=yes, tests=yes)
-
- steps:
- - uses: actions/checkout@v2
-
- # Upload cache on completion and check it out now
- # Editing this is pretty dangerous for Windows since it can break and needs to be properly tested with a fresh cache.
- - name: Load .scons_cache directory
- id: windows-editor-cache
- uses: actions/cache@v2
- with:
- path: /.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
- continue-on-error: true
-
- # Use python 3.x release (works cross platform; best to keep self contained in it's own step)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # Setup scons, print python version and scons version info, so if anything is broken it won't run the build.
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
-
- # We should always be explicit with our flags usage here since it's gonna be sure to always set those flags
- - name: Compilation
- env:
- SCONS_CACHE: /.scons_cache/
- run: |
- scons tools=yes tests=yes target=release_debug
- ls -l bin/
-
- # Execute unit tests for the editor
- - name: Unit Tests
- run: |
- ./bin/godot.windows.opt.tools.64.exe --test
-
- - uses: actions/upload-artifact@v2
- with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
-
- windows-template:
- runs-on: "windows-latest"
- name: Template (target=release, tools=no)
+ name: ${{ matrix.name }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - name: Editor (target=release_debug, tools=yes, tests=yes)
+ cache-name: windows-editor
+ target: release_debug
+ tools: true
+ tests: true
+ bin: "./bin/godot.windows.opt.tools.64.exe"
+
+ - name: Template (target=release, tools=no)
+ cache-name: windows-template
+ target: release
+ tools: false
+ tests: false
steps:
- - uses: actions/checkout@v2
-
- # Upload cache on completion and check it out now
- # Editing this is pretty dangerous for Windows since it can break and needs to be properly tested with a fresh cache.
- - name: Load .scons_cache directory
- id: windows-template-cache
- uses: RevoluPowered/cache@v2.1
- with:
- path: /.scons_cache/
- key: ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- restore-keys: |
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}-${{github.sha}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}-${{github.ref}}
- ${{github.job}}-${{env.GODOT_BASE_BRANCH}}
- continue-on-error: true
-
- # Use python 3.x release (works cross platform)
- - name: Set up Python 3.x
- uses: actions/setup-python@v2
- with:
- # Semantic version range syntax or exact version of a Python version
- python-version: '3.x'
- # Optional - x64 or x86 architecture, defaults to x64
- architecture: 'x64'
-
- # You can test your matrix by printing the current Python version
- - name: Configuring Python packages
- run: |
- python -c "import sys; print(sys.version)"
- python -m pip install scons
- python --version
- scons --version
-
- - name: Compilation
- env:
- SCONS_CACHE: /.scons_cache/
- run: |
- scons target=release tools=no
- ls -l bin/
-
- - uses: actions/upload-artifact@v2
- with:
- name: ${{ github.job }}
- path: bin/*
- retention-days: 14
+ - uses: actions/checkout@v2
+
+ - name: Setup Godot build cache
+ uses: ./.github/actions/godot-cache
+ with:
+ cache-name: ${{ matrix.cache-name }}
+ continue-on-error: true
+
+
+ - name: Setup python and scons
+ uses: ./.github/actions/godot-deps
+
+ - name: Compilation
+ uses: ./.github/actions/godot-build
+ with:
+ sconsflags: ${{ env.SCONSFLAGS }}
+ platform: windows
+ target: ${{ matrix.target }}
+ tools: ${{ matrix.tools }}
+ tests: ${{ matrix.tests }}
+ scons-cache-limit: 3072
+
+ # Execute unit tests for the editor
+ - name: Unit tests
+ if: ${{ matrix.tests }}
+ run: |
+ ${{ matrix.bin }} --test
+
+ - name: Upload artifact
+ uses: ./.github/actions/upload-artifact
+ with:
+ name: ${{ matrix.cache-name }}
diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt
index 4a38d0457c..e46cc6f3f4 100644
--- a/COPYRIGHT.txt
+++ b/COPYRIGHT.txt
@@ -367,7 +367,6 @@ Copyright: 2016-2020, Aras Pranckevicius
License: public-domain or Unlicense or Expat
Files: ./thirdparty/misc/stb_rect_pack.h
- ./thirdparty/misc/stb_vorbis.c
Comment: stb libraries
Copyright: Sean Barrett
License: public-domain or Unlicense or Expat
diff --git a/SConstruct b/SConstruct
index 8feb9e61bb..b6c98eea77 100644
--- a/SConstruct
+++ b/SConstruct
@@ -683,7 +683,7 @@ if selected_platform in platform_list:
if env["minizip"]:
env.Append(CPPDEFINES=["MINIZIP_ENABLED"])
- editor_module_list = ["freetype", "regex"]
+ editor_module_list = ["freetype"]
if env["tools"] and not env.module_check_dependencies("tools", editor_module_list):
print(
"Build option 'module_"
diff --git a/core/extension/gdnative_interface.h b/core/extension/gdnative_interface.h
index 63f4b0917c..30346f233f 100644
--- a/core/extension/gdnative_interface.h
+++ b/core/extension/gdnative_interface.h
@@ -449,6 +449,8 @@ typedef enum {
GDNATIVE_INITIALIZATION_SERVERS,
GDNATIVE_INITIALIZATION_SCENE,
GDNATIVE_INITIALIZATION_EDITOR,
+ GDNATIVE_INITIALIZATION_DRIVER,
+ GDNATIVE_MAX_INITIALIZATION_LEVEL,
} GDNativeInitializationLevel;
typedef struct {
diff --git a/core/extension/native_extension.h b/core/extension/native_extension.h
index b661381d64..9b1ebe0ed7 100644
--- a/core/extension/native_extension.h
+++ b/core/extension/native_extension.h
@@ -70,6 +70,7 @@ public:
INITIALIZATION_LEVEL_SERVERS,
INITIALIZATION_LEVEL_SCENE,
INITIALIZATION_LEVEL_EDITOR,
+ INITIALIZATION_LEVEL_DRIVER,
};
bool is_library_open() const;
diff --git a/core/input/input_map.cpp b/core/input/input_map.cpp
index fe4ee99204..c6db7be53a 100644
--- a/core/input/input_map.cpp
+++ b/core/input/input_map.cpp
@@ -317,36 +317,36 @@ static const _BuiltinActionDisplayName _builtin_action_display_names[] = {
{ "ui_text_dedent", TTRC("Dedent") },
{ "ui_text_backspace", TTRC("Backspace") },
{ "ui_text_backspace_word", TTRC("Backspace Word") },
- { "ui_text_backspace_word.osx", TTRC("Backspace Word") },
+ { "ui_text_backspace_word.macos", TTRC("Backspace Word") },
{ "ui_text_backspace_all_to_left", TTRC("Backspace all to Left") },
- { "ui_text_backspace_all_to_left.osx", TTRC("Backspace all to Left") },
+ { "ui_text_backspace_all_to_left.macos", TTRC("Backspace all to Left") },
{ "ui_text_delete", TTRC("Delete") },
{ "ui_text_delete_word", TTRC("Delete Word") },
- { "ui_text_delete_word.osx", TTRC("Delete Word") },
+ { "ui_text_delete_word.macos", TTRC("Delete Word") },
{ "ui_text_delete_all_to_right", TTRC("Delete all to Right") },
- { "ui_text_delete_all_to_right.osx", TTRC("Delete all to Right") },
+ { "ui_text_delete_all_to_right.macos", TTRC("Delete all to Right") },
{ "ui_text_caret_left", TTRC("Caret Left") },
{ "ui_text_caret_word_left", TTRC("Caret Word Left") },
- { "ui_text_caret_word_left.osx", TTRC("Caret Word Left") },
+ { "ui_text_caret_word_left.macos", TTRC("Caret Word Left") },
{ "ui_text_caret_right", TTRC("Caret Right") },
{ "ui_text_caret_word_right", TTRC("Caret Word Right") },
- { "ui_text_caret_word_right.osx", TTRC("Caret Word Right") },
+ { "ui_text_caret_word_right.macos", TTRC("Caret Word Right") },
{ "ui_text_caret_up", TTRC("Caret Up") },
{ "ui_text_caret_down", TTRC("Caret Down") },
{ "ui_text_caret_line_start", TTRC("Caret Line Start") },
- { "ui_text_caret_line_start.osx", TTRC("Caret Line Start") },
+ { "ui_text_caret_line_start.macos", TTRC("Caret Line Start") },
{ "ui_text_caret_line_end", TTRC("Caret Line End") },
- { "ui_text_caret_line_end.osx", TTRC("Caret Line End") },
+ { "ui_text_caret_line_end.macos", TTRC("Caret Line End") },
{ "ui_text_caret_page_up", TTRC("Caret Page Up") },
{ "ui_text_caret_page_down", TTRC("Caret Page Down") },
{ "ui_text_caret_document_start", TTRC("Caret Document Start") },
- { "ui_text_caret_document_start.osx", TTRC("Caret Document Start") },
+ { "ui_text_caret_document_start.macos", TTRC("Caret Document Start") },
{ "ui_text_caret_document_end", TTRC("Caret Document End") },
- { "ui_text_caret_document_end.osx", TTRC("Caret Document End") },
+ { "ui_text_caret_document_end.macos", TTRC("Caret Document End") },
{ "ui_text_scroll_up", TTRC("Scroll Up") },
- { "ui_text_scroll_up.osx", TTRC("Scroll Up") },
+ { "ui_text_scroll_up.macos", TTRC("Scroll Up") },
{ "ui_text_scroll_down", TTRC("Scroll Down") },
- { "ui_text_scroll_down.osx", TTRC("Scroll Down") },
+ { "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_toggle_insert_mode", TTRC("Toggle Insert Mode") },
@@ -516,14 +516,14 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_BACKSPACE | KEY_MASK_ALT));
- default_builtin_cache.insert("ui_text_backspace_word.osx", inputs);
+ default_builtin_cache.insert("ui_text_backspace_word.macos", inputs);
inputs = List<Ref<InputEvent>>();
default_builtin_cache.insert("ui_text_backspace_all_to_left", inputs);
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_BACKSPACE | KEY_MASK_CMD));
- default_builtin_cache.insert("ui_text_backspace_all_to_left.osx", inputs);
+ default_builtin_cache.insert("ui_text_backspace_all_to_left.macos", inputs);
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_DELETE));
@@ -535,14 +535,14 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_DELETE | KEY_MASK_ALT));
- default_builtin_cache.insert("ui_text_delete_word.osx", inputs);
+ default_builtin_cache.insert("ui_text_delete_word.macos", inputs);
inputs = List<Ref<InputEvent>>();
default_builtin_cache.insert("ui_text_delete_all_to_right", inputs);
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_DELETE | KEY_MASK_CMD));
- default_builtin_cache.insert("ui_text_delete_all_to_right.osx", inputs);
+ default_builtin_cache.insert("ui_text_delete_all_to_right.macos", inputs);
// Text Caret Movement Left/Right
@@ -556,7 +556,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_LEFT | KEY_MASK_ALT));
- default_builtin_cache.insert("ui_text_caret_word_left.osx", inputs);
+ default_builtin_cache.insert("ui_text_caret_word_left.macos", inputs);
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_RIGHT));
@@ -568,7 +568,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_RIGHT | KEY_MASK_ALT));
- default_builtin_cache.insert("ui_text_caret_word_right.osx", inputs);
+ default_builtin_cache.insert("ui_text_caret_word_right.macos", inputs);
// Text Caret Movement Up/Down
@@ -589,7 +589,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_A | KEY_MASK_CTRL));
inputs.push_back(InputEventKey::create_reference(KEY_LEFT | KEY_MASK_CMD));
- default_builtin_cache.insert("ui_text_caret_line_start.osx", inputs);
+ default_builtin_cache.insert("ui_text_caret_line_start.macos", inputs);
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_END));
@@ -598,7 +598,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_E | KEY_MASK_CTRL));
inputs.push_back(InputEventKey::create_reference(KEY_RIGHT | KEY_MASK_CMD));
- default_builtin_cache.insert("ui_text_caret_line_end.osx", inputs);
+ default_builtin_cache.insert("ui_text_caret_line_end.macos", inputs);
// Text Caret Movement Page Up/Down
@@ -618,7 +618,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_UP | KEY_MASK_CMD));
- default_builtin_cache.insert("ui_text_caret_document_start.osx", inputs);
+ default_builtin_cache.insert("ui_text_caret_document_start.macos", inputs);
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_END | KEY_MASK_CMD));
@@ -626,7 +626,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_DOWN | KEY_MASK_CMD));
- default_builtin_cache.insert("ui_text_caret_document_end.osx", inputs);
+ default_builtin_cache.insert("ui_text_caret_document_end.macos", inputs);
// Text Scrolling
@@ -636,7 +636,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_UP | KEY_MASK_CMD | KEY_MASK_ALT));
- default_builtin_cache.insert("ui_text_scroll_up.osx", inputs);
+ default_builtin_cache.insert("ui_text_scroll_up.macos", inputs);
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_DOWN | KEY_MASK_CMD));
@@ -644,7 +644,7 @@ const OrderedHashMap<String, List<Ref<InputEvent>>> &InputMap::get_builtins() {
inputs = List<Ref<InputEvent>>();
inputs.push_back(InputEventKey::create_reference(KEY_DOWN | KEY_MASK_CMD | KEY_MASK_ALT));
- default_builtin_cache.insert("ui_text_scroll_down.osx", inputs);
+ default_builtin_cache.insert("ui_text_scroll_down.macos", inputs);
// Text Misc
@@ -703,11 +703,11 @@ void InputMap::load_default() {
OrderedHashMap<String, List<Ref<InputEvent>>> builtins = get_builtins();
// List of Builtins which have an override for macOS.
- Vector<String> osx_builtins;
+ Vector<String> macos_builtins;
for (OrderedHashMap<String, List<Ref<InputEvent>>>::Element E = builtins.front(); E; E = E.next()) {
- if (String(E.key()).ends_with(".osx")) {
- // Strip .osx from name: some_input_name.osx -> some_input_name
- osx_builtins.push_back(String(E.key()).split(".")[0]);
+ if (String(E.key()).ends_with(".macos")) {
+ // Strip .macos from name: some_input_name.macos -> some_input_name
+ macos_builtins.push_back(String(E.key()).split(".")[0]);
}
}
@@ -717,12 +717,12 @@ void InputMap::load_default() {
String override_for = fullname.split(".").size() > 1 ? fullname.split(".")[1] : "";
#ifdef APPLE_STYLE_KEYS
- if (osx_builtins.has(name) && override_for != "osx") {
- // Name has `osx` builtin but this particular one is for non-macOS systems - so skip.
+ if (macos_builtins.has(name) && override_for != "macos") {
+ // Name has `macos` builtin but this particular one is for non-macOS systems - so skip.
continue;
}
#else
- if (override_for == "osx") {
+ if (override_for == "macos") {
// Override for macOS - not needed on non-macOS platforms.
continue;
}
@@ -746,3 +746,7 @@ InputMap::InputMap() {
ERR_FAIL_COND_MSG(singleton, "Singleton in InputMap already exist.");
singleton = this;
}
+
+InputMap::~InputMap() {
+ singleton = nullptr;
+}
diff --git a/core/input/input_map.h b/core/input/input_map.h
index a2d3952f94..c724fdb142 100644
--- a/core/input/input_map.h
+++ b/core/input/input_map.h
@@ -95,6 +95,7 @@ public:
const OrderedHashMap<String, List<Ref<InputEvent>>> &get_builtins();
InputMap();
+ ~InputMap();
};
#endif // INPUT_MAP_H
diff --git a/core/math/basis.cpp b/core/math/basis.cpp
index 5c42213e61..eec9caf149 100644
--- a/core/math/basis.cpp
+++ b/core/math/basis.cpp
@@ -775,7 +775,7 @@ Basis::operator String() const {
Quaternion Basis::get_quaternion() const {
#ifdef MATH_CHECKS
- ERR_FAIL_COND_V_MSG(!is_rotation(), Quaternion(), "Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quaternion() or call orthonormalized() instead.");
+ ERR_FAIL_COND_V_MSG(!is_rotation(), Quaternion(), "Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quaternion() or call orthonormalized() if the Basis contains linearly independent vectors.");
#endif
/* Allow getting a quaternion from an unnormalized transform */
Basis m = *this;
diff --git a/core/math/convex_hull.h b/core/math/convex_hull.h
index a860d60b02..806c6cc3fb 100644
--- a/core/math/convex_hull.h
+++ b/core/math/convex_hull.h
@@ -49,7 +49,7 @@ subject to the following restrictions:
#include "core/templates/vector.h"
/// Convex hull implementation based on Preparata and Hong
-/// See https://code.google.com/p/bullet/issues/detail?id=275
+/// See https://code.google.com/archive/p/bullet/issues/275
/// Ole Kniemeyer, MAXON Computer GmbH
class ConvexHullComputer {
public:
diff --git a/core/math/dynamic_bvh.h b/core/math/dynamic_bvh.h
index d63132b4da..0b6286cd9d 100644
--- a/core/math/dynamic_bvh.h
+++ b/core/math/dynamic_bvh.h
@@ -41,7 +41,7 @@
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2013 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org
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.
diff --git a/core/math/triangle_mesh.h b/core/math/triangle_mesh.h
index 463b0dd5c8..2d3b4db4bb 100644
--- a/core/math/triangle_mesh.h
+++ b/core/math/triangle_mesh.h
@@ -37,11 +37,13 @@
class TriangleMesh : public RefCounted {
GDCLASS(TriangleMesh, RefCounted);
+public:
struct Triangle {
Vector3 normal;
int indices[3];
};
+private:
Vector<Triangle> triangles;
Vector<Vector3> vertices;
@@ -86,8 +88,8 @@ public:
Vector3 get_area_normal(const AABB &p_aabb) const;
Vector<Face3> get_faces() const;
- Vector<Triangle> get_triangles() const { return triangles; }
- Vector<Vector3> get_vertices() const { return vertices; }
+ const Vector<Triangle> &get_triangles() const { return triangles; }
+ const Vector<Vector3> &get_vertices() const { return vertices; }
void get_indices(Vector<int> *r_triangles_indices) const;
void create(const Vector<Vector3> &p_faces);
diff --git a/core/multiplayer/multiplayer_replicator.cpp b/core/multiplayer/multiplayer_replicator.cpp
index 17af2c5ef8..a4ea74327c 100644
--- a/core/multiplayer/multiplayer_replicator.cpp
+++ b/core/multiplayer/multiplayer_replicator.cpp
@@ -350,9 +350,9 @@ void MultiplayerReplicator::process_sync(int p_from, const uint8_t *p_packet, in
}
}
PackedByteArray pba;
- pba.resize(p_packet_len - SPAWN_CMD_OFFSET);
+ pba.resize(p_packet_len - SYNC_CMD_OFFSET);
if (pba.size()) {
- memcpy(pba.ptrw(), p_packet, p_packet_len - SPAWN_CMD_OFFSET);
+ memcpy(pba.ptrw(), p_packet + SYNC_CMD_OFFSET, p_packet_len - SYNC_CMD_OFFSET);
}
Variant args[4] = { p_from, id, objs, pba };
Variant *argp[4] = { args, &args[1], &args[2], &args[3] };
@@ -749,6 +749,9 @@ Error MultiplayerReplicator::send_sync(int p_peer_id, const ResourceUID::ID &p_s
uint8_t *ptr = packet_cache.ptrw();
ptr[0] = MultiplayerAPI::NETWORK_COMMAND_SYNC;
encode_uint64(p_scene_id, &ptr[1]);
+ if (p_data.size()) {
+ memcpy(&ptr[SYNC_CMD_OFFSET], p_data.ptr(), p_data.size());
+ }
Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
peer->set_target_peer(p_peer_id);
peer->set_transfer_channel(p_channel);
diff --git a/core/os/os.cpp b/core/os/os.cpp
index 89ba73b35e..dc3fe29dca 100644
--- a/core/os/os.cpp
+++ b/core/os/os.cpp
@@ -146,6 +146,10 @@ bool OS::is_stdout_verbose() const {
return _verbose_stdout;
}
+bool OS::is_single_window() const {
+ return _single_window;
+}
+
bool OS::is_stdout_debug_enabled() const {
return _debug_stdout;
}
diff --git a/core/os/os.h b/core/os/os.h
index 55b21266fc..f585483300 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -52,6 +52,7 @@ class OS {
int low_processor_usage_mode_sleep_usec = 10000;
bool _verbose_stdout = false;
bool _debug_stdout = false;
+ bool _single_window = false;
String _local_clipboard;
int _exit_code = EXIT_FAILURE; // unexpected exit is marked as failure
int _orientation;
@@ -224,6 +225,8 @@ public:
void set_stdout_enabled(bool p_enabled);
void set_stderr_enabled(bool p_enabled);
+ bool is_single_window() const;
+
virtual void disable_crash_handler() {}
virtual bool is_disable_crash_handler() const { return false; }
virtual void initialize_debugging() {}
diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp
index ed6fd13cc8..daeb7fbd17 100644
--- a/core/string/ustring.cpp
+++ b/core/string/ustring.cpp
@@ -1551,19 +1551,21 @@ String String::num_real(double p_num, bool p_trailing) {
bool neg = p_num < 0;
p_num = ABS(p_num);
- int intn = (int)p_num;
+ int64_t intn = (int64_t)p_num;
// Decimal part.
if (intn != p_num) {
- double dec = p_num - (double)(intn);
+ double dec = p_num - (double)intn;
int digit = 0;
-#if REAL_T_IS_DOUBLE
+#ifdef REAL_T_IS_DOUBLE
int decimals = 14;
+ double tolerance = 1e-14;
#else
int decimals = 6;
+ double tolerance = 1e-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.
@@ -1575,16 +1577,21 @@ String String::num_real(double p_num, bool p_trailing) {
decimals = MAX_DECIMALS;
}
- int dec_int = 0;
- int dec_max = 0;
+ // In case the value ends up ending in "99999", we want to add a
+ // tiny bit to the value we're checking when deciding when to stop,
+ // so we multiply by slightly above 1 (1 + 1e-7 or 1e-15).
+ double check_multiplier = 1 + tolerance / 10;
+
+ int64_t dec_int = 0;
+ int64_t dec_max = 0;
while (true) {
dec *= 10.0;
- dec_int = dec_int * 10 + (int)dec % 10;
+ dec_int = dec_int * 10 + (int64_t)dec % 10;
dec_max = dec_max * 10 + 9;
digit++;
- if ((dec - (double)((int)dec)) < 1e-6) {
+ if ((dec - (double)(int64_t)(dec * check_multiplier)) < tolerance) {
break;
}
@@ -1594,7 +1601,7 @@ String String::num_real(double p_num, bool p_trailing) {
}
dec *= 10;
- int last = (int)dec % 10;
+ int last = (int64_t)dec % 10;
if (last > 5) {
if (dec_int == dec_max) {
@@ -3555,7 +3562,7 @@ String String::strip_edges(bool left, bool right) const {
}
if (right) {
- for (int i = (int)(len - 1); i >= 0; i--) {
+ for (int i = len - 1; i >= 0; i--) {
if (operator[](i) <= 32) {
end--;
} else {
@@ -4329,23 +4336,39 @@ bool String::is_relative_path() const {
}
String String::get_base_dir() const {
- int basepos = find(":/");
- if (basepos == -1) {
- basepos = find(":\\");
+ int end = 0;
+
+ // url scheme style base
+ int basepos = find("://");
+ if (basepos != -1) {
+ end = basepos + 3;
+ }
+
+ // windows top level directory base
+ if (end == 0) {
+ basepos = find(":/");
+ if (basepos == -1) {
+ basepos = find(":\\");
+ }
+ if (basepos != -1) {
+ end = basepos + 2;
+ }
+ }
+
+ // unix root directory base
+ if (end == 0) {
+ if (begins_with("/")) {
+ end = 1;
+ }
}
+
String rs;
String base;
- if (basepos != -1) {
- int end = basepos + 3;
+ if (end != 0) {
rs = substr(end, length());
base = substr(0, end);
} else {
- if (begins_with("/")) {
- rs = substr(1, length());
- base = "/";
- } else {
- rs = *this;
- }
+ rs = *this;
}
int sep = MAX(rs.rfind("/"), rs.rfind("\\"));
diff --git a/core/templates/cowdata.h b/core/templates/cowdata.h
index ba9babe0af..9b8c0eb528 100644
--- a/core/templates/cowdata.h
+++ b/core/templates/cowdata.h
@@ -49,6 +49,12 @@ class VMap;
SAFE_NUMERIC_TYPE_PUN_GUARANTEES(uint32_t)
#endif
+// Silence a false positive warning (see GH-52119).
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wplacement-new"
+#endif
+
template <class T>
class CowData {
template <class TV>
@@ -380,4 +386,8 @@ CowData<T>::~CowData() {
_unref(_ptr);
}
+#if defined(__GNUC__) && !defined(__clang__)
+#pragma GCC diagnostic pop
+#endif
+
#endif // COWDATA_H
diff --git a/core/templates/vector.h b/core/templates/vector.h
index 033345d04c..2600604eb7 100644
--- a/core/templates/vector.h
+++ b/core/templates/vector.h
@@ -92,7 +92,7 @@ public:
void append_array(Vector<T> p_other);
- bool has(const T &p_val) {
+ bool has(const T &p_val) const {
return find(p_val, 0) != -1;
}
diff --git a/core/variant/variant.cpp b/core/variant/variant.cpp
index c5cada674f..0dbeb6e4cb 100644
--- a/core/variant/variant.cpp
+++ b/core/variant/variant.cpp
@@ -2832,7 +2832,7 @@ uint32_t Variant::hash() const {
return _data._bool ? 1 : 0;
} break;
case INT: {
- return _data._int;
+ return hash_one_uint64((uint64_t)_data._int);
} break;
case FLOAT: {
return hash_djb2_one_float(_data._float);
@@ -2847,8 +2847,8 @@ uint32_t Variant::hash() const {
return hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->y, hash);
} break;
case VECTOR2I: {
- uint32_t hash = hash_djb2_one_32(reinterpret_cast<const Vector2i *>(_data._mem)->x);
- return hash_djb2_one_32(reinterpret_cast<const Vector2i *>(_data._mem)->y, hash);
+ uint32_t hash = hash_djb2_one_32((uint32_t) reinterpret_cast<const Vector2i *>(_data._mem)->x);
+ return hash_djb2_one_32((uint32_t) reinterpret_cast<const Vector2i *>(_data._mem)->y, hash);
} break;
case RECT2: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->position.x);
@@ -2857,10 +2857,10 @@ uint32_t Variant::hash() const {
return hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.y, hash);
} break;
case RECT2I: {
- uint32_t hash = hash_djb2_one_32(reinterpret_cast<const Rect2i *>(_data._mem)->position.x);
- hash = hash_djb2_one_32(reinterpret_cast<const Rect2i *>(_data._mem)->position.y, hash);
- hash = hash_djb2_one_32(reinterpret_cast<const Rect2i *>(_data._mem)->size.x, hash);
- return hash_djb2_one_32(reinterpret_cast<const Rect2i *>(_data._mem)->size.y, hash);
+ uint32_t hash = hash_djb2_one_32((uint32_t) reinterpret_cast<const Rect2i *>(_data._mem)->position.x);
+ hash = hash_djb2_one_32((uint32_t) reinterpret_cast<const Rect2i *>(_data._mem)->position.y, hash);
+ hash = hash_djb2_one_32((uint32_t) reinterpret_cast<const Rect2i *>(_data._mem)->size.x, hash);
+ return hash_djb2_one_32((uint32_t) reinterpret_cast<const Rect2i *>(_data._mem)->size.y, hash);
} break;
case TRANSFORM2D: {
uint32_t hash = 5831;
@@ -2878,9 +2878,9 @@ uint32_t Variant::hash() const {
return hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->z, hash);
} break;
case VECTOR3I: {
- uint32_t hash = hash_djb2_one_32(reinterpret_cast<const Vector3i *>(_data._mem)->x);
- hash = hash_djb2_one_32(reinterpret_cast<const Vector3i *>(_data._mem)->y, hash);
- return hash_djb2_one_32(reinterpret_cast<const Vector3i *>(_data._mem)->z, hash);
+ uint32_t hash = hash_djb2_one_32((uint32_t) reinterpret_cast<const Vector3i *>(_data._mem)->x);
+ hash = hash_djb2_one_32((uint32_t) reinterpret_cast<const Vector3i *>(_data._mem)->y, hash);
+ return hash_djb2_one_32((uint32_t) reinterpret_cast<const Vector3i *>(_data._mem)->z, hash);
} break;
case PLANE: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.x);
diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml
index 755902c709..c47ce81651 100644
--- a/doc/classes/@GlobalScope.xml
+++ b/doc/classes/@GlobalScope.xml
@@ -1069,7 +1069,7 @@
<member name="TranslationServer" type="TranslationServer" setter="" getter="">
The [TranslationServer] singleton.
</member>
- <member name="VisualScriptEditor" type="VisualScriptCustomNodes" setter="" getter="">
+ <member name="VisualScriptCustomNodes" type="VisualScriptCustomNodes" setter="" getter="">
The [VisualScriptCustomNodes] singleton.
</member>
<member name="XRServer" type="XRServer" setter="" getter="">
diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml
index 02c6b18d55..91450e50a4 100644
--- a/doc/classes/Array.xml
+++ b/doc/classes/Array.xml
@@ -495,7 +495,7 @@
<argument index="2" name="step" type="int" default="1" />
<argument index="3" name="deep" type="bool" default="false" />
<description>
- Duplicates the subset described in the function and returns it in an array, deeply copying the array if [code]deep[/code] is [code]true[/code]. Lower and upper index are inclusive, with the [code]step[/code] describing the change between indices while slicing. If [code]end[/code] is an invalid value, the end of the array is used.
+ Duplicates the subset described in the function and returns it in an array, deeply copying the array if [code]deep[/code] is [code]true[/code]. Lower and upper index are inclusive, with the [code]step[/code] describing the change between indices while slicing. Wraps around if [code]begin[/code] or [code]end[/code] are out of bounds or negative. Returns an empty array for invalid parameters.
</description>
</method>
<method name="sort">
diff --git a/doc/classes/Camera3D.xml b/doc/classes/Camera3D.xml
index 8a91a91b22..cd17a31e23 100644
--- a/doc/classes/Camera3D.xml
+++ b/doc/classes/Camera3D.xml
@@ -26,7 +26,7 @@
<method name="get_camera_transform" qualifiers="const">
<return type="Transform3D" />
<description>
- Gets the camera transform. Subclassed cameras such as [ClippedCamera3D] may provide different transforms than the [Node] transform.
+ Returns the transform of the camera plus the vertical ([member v_offset]) and horizontal ([member h_offset]) offsets; and any other adjustments made to the position and orientation of the camera by subclassed cameras such as [ClippedCamera3D] and [XRCamera3D].
</description>
</method>
<method name="get_cull_mask_value" qualifiers="const">
diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml
index 4641bc52a4..501f89fa0d 100644
--- a/doc/classes/CanvasItem.xml
+++ b/doc/classes/CanvasItem.xml
@@ -115,7 +115,7 @@
<argument index="4" name="outline" type="float" default="0.0" />
<argument index="5" name="pixel_range" type="float" default="4.0" />
<description>
- Draws a textured rectangle region of the multi-channel signed distance field texture at a given position, optionally modulated by a color.
+ Draws a textured rectangle region of the multi-channel signed distance field texture at a given position, optionally modulated by a color. See [method FontData.set_multichannel_signed_distance_field] for more information and caveats about MSDF font rendering.
If [code]outline[/code] is positive, each alpha channel value of pixel in region is set to maximum value of true distance in the [code]outline[/code] radius.
Value of the [code]pixel_range[/code] should the same that was used during distance field texture generation.
</description>
diff --git a/doc/classes/ConfigFile.xml b/doc/classes/ConfigFile.xml
index d6da4bc248..ce976e3d8b 100644
--- a/doc/classes/ConfigFile.xml
+++ b/doc/classes/ConfigFile.xml
@@ -84,8 +84,10 @@
}
[/csharp]
[/codeblocks]
+ Any operation that mutates the ConfigFile such as [method set_value], [method clear], or [method erase_section], only changes what is loaded in memory. If you want to write the change to a file, you have to save the changes with [method save], [method save_encrypted], or [method save_encrypted_pass].
Keep in mind that section and property names can't contain spaces. Anything after a space will be ignored on save and on load.
ConfigFiles can also contain manually written comment lines starting with a semicolon ([code];[/code]). Those lines will be ignored when parsing the file. Note that comments will be lost when saving the ConfigFile. This can still be useful for dedicated server configuration files, which are typically never overwritten without explicit user action.
+ [b]Note:[/b] The file extension given to a ConfigFile does not have any impact on its formatting or behavior. By convention, the [code].cfg[/code] extension is used here, but any other extension such as [code].ini[/code] is also valid. Since neither [code].cfg[/code] nor [code].ini[/code] are standardized, Godot's ConfigFile formatting may differ from files written by other programs.
</description>
<tutorials>
</tutorials>
@@ -93,6 +95,7 @@
<method name="clear">
<return type="void" />
<description>
+ Removes the entire contents of the config.
</description>
</method>
<method name="erase_section">
diff --git a/doc/classes/Control.xml b/doc/classes/Control.xml
index 5392189f6a..6602764cd4 100644
--- a/doc/classes/Control.xml
+++ b/doc/classes/Control.xml
@@ -921,7 +921,8 @@
Anchors the top edge of the node to the origin, the center or the end of its parent control. It changes how the top offset updates when the node moves or changes size. You can use one of the [enum Anchor] constants for convenience.
</member>
<member name="auto_translate" type="bool" setter="set_auto_translate" getter="is_auto_translating" default="true">
- Toggles if any text should automatically change to its translated version depending on the current locale.
+ Toggles if any text should automatically change to its translated version depending on the current locale. Note that this will not affect any internal nodes (e.g. the popup of a [MenuButton]).
+ Also decides if the node's strings should be parsed for POT generation.
</member>
<member name="focus_mode" type="int" setter="set_focus_mode" getter="get_focus_mode" enum="Control.FocusMode" default="0">
The focus access mode for the control (None, Click or All). Only one Control can be focused at the same time, and it will receive keyboard signals.
diff --git a/doc/classes/EditorCommandPalette.xml b/doc/classes/EditorCommandPalette.xml
index 743c59eec2..1d3b21255f 100644
--- a/doc/classes/EditorCommandPalette.xml
+++ b/doc/classes/EditorCommandPalette.xml
@@ -1,8 +1,26 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="EditorCommandPalette" inherits="ConfirmationDialog" version="4.0">
<brief_description>
+ Godot editor's command palette.
</brief_description>
<description>
+ Object that holds all the available Commands and their shortcuts text. These Commands can be accessed through [b]Editor &gt; Command Palette[/b] menu.
+ Command key names use slash delimiters to distinguish sections Example: [code]"example/command1"[/code] then [code]example[/code] will be the section name.
+ [codeblocks]
+ [gdscript]
+ var command_palette = get_editor_interface().get_command_palette()
+ # external_command is a function that will be called with the command is executed.
+ var command_callable = Callable(self, "external_command").bind(arguments)
+ command_palette.add_command("command", "test/command",command_callable)
+ [/gdscript]
+ [csharp]
+ EditorCommandPalette commandPalette = GetEditorInterface().GetCommandPalette();
+ // ExternalCommand is a function that will be called with the command is executed.
+ Callable commandCallable = new Callable(this, nameof(ExternalCommand));
+ commandPalette.AddCommand("command", "test/command", commandCallable)
+ [/csharp]
+ [/codeblocks]
+ [b]Note:[/b] This class shouldn't be instantiated directly. Instead, access the singleton using [method EditorInterface.get_command_palette].
</description>
<tutorials>
</tutorials>
@@ -14,12 +32,19 @@
<argument index="2" name="binded_callable" type="Callable" />
<argument index="3" name="shortcut_text" type="String" default="&quot;None&quot;" />
<description>
+ Adds a custom command to EditorCommandPalette.
+ - [code]command_name[/code]: [String] (Name of the [b]Command[/b]. This is displayed to the user.)
+ - [code]key_name[/code]: [String] (Name of the key for a particular [b]Command[/b]. This is used to uniquely identify the [b]Command[/b].)
+ - [code]binded_callable[/code]: [Callable] (Callable of the [b]Command[/b]. This will be executed when the [b]Command[/b] is selected.)
+ - [code]shortcut_text[/code]: [String] (Shortcut text of the [b]Command[/b] if available.)
</description>
</method>
<method name="remove_command">
<return type="void" />
<argument index="0" name="key_name" type="String" />
<description>
+ Removes the custom command from EditorCommandPalette.
+ - [code]key_name[/code]: [String] (Name of the key for a particular [b]Command[/b].)
</description>
</method>
</methods>
diff --git a/doc/classes/EditorInterface.xml b/doc/classes/EditorInterface.xml
index 91e1dfbf57..8558f4b9f7 100644
--- a/doc/classes/EditorInterface.xml
+++ b/doc/classes/EditorInterface.xml
@@ -33,6 +33,7 @@
<method name="get_command_palette" qualifiers="const">
<return type="EditorCommandPalette" />
<description>
+ Returns the editor's [EditorCommandPalette] instance.
</description>
</method>
<method name="get_current_path" qualifiers="const">
diff --git a/doc/classes/EditorSceneImporterMesh.xml b/doc/classes/EditorSceneImporterMesh.xml
index b0f233da2f..c0c53ff255 100644
--- a/doc/classes/EditorSceneImporterMesh.xml
+++ b/doc/classes/EditorSceneImporterMesh.xml
@@ -27,6 +27,7 @@
}" />
<argument index="4" name="material" type="Material" default="null" />
<argument index="5" name="name" type="String" default="&quot;&quot;" />
+ <argument index="6" name="flags" type="int" default="0" />
<description>
Creates a new surface, analogous to [method ArrayMesh.add_surface_from_arrays].
Surfaces are created to be rendered using a [code]primitive[/code], which may be any of the types defined in [enum Mesh.PrimitiveType]. (As a note, when using indices, it is recommended to only use points, lines, or triangles.) [method Mesh.get_surface_count] will become the [code]surf_idx[/code] for this new surface.
@@ -94,6 +95,13 @@
Returns the amount of surfaces that the mesh holds.
</description>
</method>
+ <method name="get_surface_format" qualifiers="const">
+ <return type="int" />
+ <argument index="0" name="surface_idx" type="int" />
+ <description>
+ Returns the format of the surface that the mesh holds.
+ </description>
+ </method>
<method name="get_surface_lod_count" qualifiers="const">
<return type="int" />
<argument index="0" name="surface_idx" type="int" />
diff --git a/doc/classes/Engine.xml b/doc/classes/Engine.xml
index 8b399f64c9..36590093bd 100644
--- a/doc/classes/Engine.xml
+++ b/doc/classes/Engine.xml
@@ -37,7 +37,7 @@
<method name="get_frames_drawn">
<return type="int" />
<description>
- Returns the total number of frames drawn. If the render loop is disabled with [code]--disable-render-loop[/code] via command line, this returns [code]0[/code]. See also [method get_process_frames].
+ Returns the total number of frames drawn. On headless platforms, or if the render loop is disabled with [code]--disable-render-loop[/code] via command line, [method get_frames_drawn] always returns [code]0[/code]. See [method get_process_frames].
</description>
</method>
<method name="get_frames_per_second" qualifiers="const">
@@ -67,7 +67,13 @@
<method name="get_physics_frames" qualifiers="const">
<return type="int" />
<description>
- Returns the total number of frames passed since engine initialization which is advanced on each [b]physics frame[/b].
+ Returns the total number of frames passed since engine initialization which is advanced on each [b]physics frame[/b]. See also [method get_process_frames].
+ [method get_physics_frames] can be used to run expensive logic less often without relying on a [Timer]:
+ [codeblock]
+ func _physics_process(_delta):
+ if Engine.get_physics_frames() % 2 == 0:
+ pass # Run expensive logic only once every 2 physics frames here.
+ [/codeblock]
</description>
</method>
<method name="get_physics_interpolation_fraction" qualifiers="const">
@@ -79,7 +85,13 @@
<method name="get_process_frames" qualifiers="const">
<return type="int" />
<description>
- Returns the total number of frames passed since engine initialization which is advanced on each [b]process frame[/b], regardless of whether the render loop is enabled. See also [method get_frames_drawn].
+ Returns the total number of frames passed since engine initialization which is advanced on each [b]process frame[/b], regardless of whether the render loop is enabled. See also [method get_frames_drawn] and [method get_physics_frames].
+ [method get_process_frames] can be used to run expensive logic less often without relying on a [Timer]:
+ [codeblock]
+ func _process(_delta):
+ if Engine.get_process_frames() % 2 == 0:
+ pass # Run expensive logic only once every 2 process (render) frames here.
+ [/codeblock]
</description>
</method>
<method name="get_singleton" qualifiers="const">
diff --git a/doc/classes/File.xml b/doc/classes/File.xml
index 8ecdc8b220..cf08029c72 100644
--- a/doc/classes/File.xml
+++ b/doc/classes/File.xml
@@ -58,8 +58,20 @@
<method name="eof_reached" qualifiers="const">
<return type="bool" />
<description>
- Returns [code]true[/code] if the file cursor has read past the end of the file.
- [b]Note:[/b] This function will still return [code]false[/code] while at the end of the file and only activates when reading past it. This can be confusing but it conforms to how low-level file access works in all operating systems. There is always [method get_length] and [method get_position] to implement a custom logic.
+ Returns [code]true[/code] if the file cursor has already read past the end of the file.
+ [b]Note:[/b] [code]eof_reached() == false[/code] cannot be used to check whether there is more data available. To loop while there is more data available, use:
+ [codeblocks]
+ [gdscript]
+ while file.get_position() &lt; file.get_length():
+ # Read data
+ [/gdscript]
+ [csharp]
+ while (file.GetPosition() &lt; file.GetLength())
+ {
+ // Read data
+ }
+ [/csharp]
+ [/codeblocks]
</description>
</method>
<method name="file_exists" qualifiers="const">
diff --git a/doc/classes/FontData.xml b/doc/classes/FontData.xml
index 72af7ca485..384d7c81f4 100644
--- a/doc/classes/FontData.xml
+++ b/doc/classes/FontData.xml
@@ -558,7 +558,8 @@
<return type="void" />
<argument index="0" name="msdf" type="bool" />
<description>
- If set to [code]true[/code], glyphs of all sizes are rendered using single multichannel signed distance field generated from the dynamic font vector data.
+ If set to [code]true[/code], glyphs of all sizes are rendered using single multichannel signed distance field (MSDF) generated from the dynamic font vector data. MSDF rendering allows displaying the font at any scaling factor without blurriness, and without incurring a CPU cost when the font size changes (since the font no longer needs to be rasterized on the CPU). As a downside, font hinting is not available with MSDF. The lack of font hinting may result in less crisp and less readable fonts at small sizes.
+ [b]Note:[/b] MSDF font rendering does not render glyphs with overlapping shapes correctly. Overlapping shapes are not valid per the OpenType standard, but are still commonly found in many font files, especially those converted by Google Fonts. To avoid issues with overlapping glyphs, consider downloading the font file directly from the type foundry instead of relying on Google Fonts.
</description>
</method>
<method name="set_oversampling">
diff --git a/doc/classes/HScrollBar.xml b/doc/classes/HScrollBar.xml
index 3bdd739cdf..36ff070a37 100644
--- a/doc/classes/HScrollBar.xml
+++ b/doc/classes/HScrollBar.xml
@@ -19,6 +19,9 @@
<theme_item name="decrement_highlight" data_type="icon" type="Texture2D">
Displayed when the mouse cursor hovers over the decrement button.
</theme_item>
+ <theme_item name="decrement_pressed" data_type="icon" type="Texture2D">
+ Displayed when the decrement button is being pressed.
+ </theme_item>
<theme_item name="grabber" data_type="style" type="StyleBox">
Used as texture for the grabber, the draggable element representing current scroll.
</theme_item>
@@ -34,6 +37,9 @@
<theme_item name="increment_highlight" data_type="icon" type="Texture2D">
Displayed when the mouse cursor hovers over the increment button.
</theme_item>
+ <theme_item name="increment_pressed" data_type="icon" type="Texture2D">
+ Displayed when the increment button is being pressed.
+ </theme_item>
<theme_item name="scroll" data_type="style" type="StyleBox">
Used as background of this [ScrollBar].
</theme_item>
diff --git a/doc/classes/JNISingleton.xml b/doc/classes/JNISingleton.xml
index 84ab1a49c1..fbf18ddc03 100644
--- a/doc/classes/JNISingleton.xml
+++ b/doc/classes/JNISingleton.xml
@@ -1,10 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="JNISingleton" inherits="Object" version="4.0">
<brief_description>
+ Singleton that connects the engine with Android plugins to interface with native Android code.
</brief_description>
<description>
+ The JNISingleton is implemented only in the Android export. It's used to call methods and connect signals from an Android plugin written in Java or Kotlin. Methods and signals can be called and connected to the JNISingleton as if it is a Node. See [url=https://en.wikipedia.org/wiki/Java_Native_Interface]Java Native Interface - Wikipedia[/url] for more information.
</description>
<tutorials>
+ <link title="Creating Android plugins">https://docs.godotengine.org/en/latest/tutorials/platform/android/android_plugin.html#doc-android-plugin</link>
</tutorials>
<methods>
</methods>
diff --git a/doc/classes/Light3D.xml b/doc/classes/Light3D.xml
index cd2f4eca18..52359b0ede 100644
--- a/doc/classes/Light3D.xml
+++ b/doc/classes/Light3D.xml
@@ -47,7 +47,8 @@
The light's strength multiplier (this is not a physical unit). For [OmniLight3D] and [SpotLight3D], changing this value will only change the light color's intensity, not the light's radius.
</member>
<member name="light_indirect_energy" type="float" setter="set_param" getter="get_param" default="1.0">
- Secondary multiplier used with indirect light (light bounces). Used with [VoxelGI].
+ Secondary multiplier used with indirect light (light bounces). Used with [VoxelGI] and SDFGI (see [member Environment.sdfgi_enabled]).
+ [b]Note:[/b] This property is ignored if [member light_energy] is equal to [code]0.0[/code], as the light won't be present at all in the GI shader.
</member>
<member name="light_negative" type="bool" setter="set_negative" getter="is_negative" default="false">
If [code]true[/code], the light's effect is reversed, darkening areas and casting bright shadows.
diff --git a/doc/classes/Listener2D.xml b/doc/classes/Listener2D.xml
new file mode 100644
index 0000000000..27ee63d201
--- /dev/null
+++ b/doc/classes/Listener2D.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="Listener2D" inherits="Node2D" version="4.0">
+ <brief_description>
+ Overrides the location sounds are heard from.
+ </brief_description>
+ <description>
+ Once added to the scene tree and enabled using [method make_current], this node will override the location sounds are heard from. Only one [Listener2D] can be current. Using [method make_current] will disable the previous [Listener2D].
+ If there is no active [Listener2D] in the current [Viewport], center of the screen will be used as a hearing point for the audio. [Listener2D] needs to be inside [SceneTree] to function.
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="clear_current">
+ <return type="void" />
+ <description>
+ Disables the [Listener2D]. If it's not set as current, this method will have no effect.
+ </description>
+ </method>
+ <method name="is_current" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if this [Listener2D] is currently active.
+ </description>
+ </method>
+ <method name="make_current">
+ <return type="void" />
+ <description>
+ Makes the [Listener2D] active, setting it as the hearing point for the sounds. If there is already another active [Listener2D], it will be disabled.
+ This method will have no effect if the [Listener2D] is not added to [SceneTree].
+ </description>
+ </method>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/doc/classes/Listener3D.xml b/doc/classes/Listener3D.xml
index 9cc803f241..5e1b2ce7fc 100644
--- a/doc/classes/Listener3D.xml
+++ b/doc/classes/Listener3D.xml
@@ -5,7 +5,6 @@
</brief_description>
<description>
Once added to the scene tree and enabled using [method make_current], this node will override the location sounds are heard from. This can be used to listen from a location different from the [Camera3D].
- [b]Note:[/b] There is no 2D equivalent for this node yet.
</description>
<tutorials>
</tutorials>
diff --git a/doc/classes/Mesh.xml b/doc/classes/Mesh.xml
index bfa55c2d35..c774528a39 100644
--- a/doc/classes/Mesh.xml
+++ b/doc/classes/Mesh.xml
@@ -210,6 +210,8 @@
</constant>
<constant name="ARRAY_FORMAT_CUSTOM_BASE" value="13" enum="ArrayFormat">
</constant>
+ <constant name="ARRAY_FORMAT_CUSTOM_BITS" value="3" enum="ArrayFormat">
+ </constant>
<constant name="ARRAY_FORMAT_CUSTOM0_SHIFT" value="13" enum="ArrayFormat">
</constant>
<constant name="ARRAY_FORMAT_CUSTOM1_SHIFT" value="16" enum="ArrayFormat">
diff --git a/doc/classes/MeshLibrary.xml b/doc/classes/MeshLibrary.xml
index 9e0292f946..1d07647ea7 100644
--- a/doc/classes/MeshLibrary.xml
+++ b/doc/classes/MeshLibrary.xml
@@ -45,6 +45,13 @@
Returns the item's mesh.
</description>
</method>
+ <method name="get_item_mesh_transform" qualifiers="const">
+ <return type="Transform3D" />
+ <argument index="0" name="id" type="int" />
+ <description>
+ Returns the transform applied to the item's mesh.
+ </description>
+ </method>
<method name="get_item_name" qualifiers="const">
<return type="String" />
<argument index="0" name="id" type="int" />
@@ -102,6 +109,14 @@
Sets the item's mesh.
</description>
</method>
+ <method name="set_item_mesh_transform">
+ <return type="void" />
+ <argument index="0" name="id" type="int" />
+ <argument index="1" name="mesh_transform" type="Transform3D" />
+ <description>
+ Sets the transform to apply to the item's mesh.
+ </description>
+ </method>
<method name="set_item_name">
<return type="void" />
<argument index="0" name="id" type="int" />
diff --git a/doc/classes/Node2D.xml b/doc/classes/Node2D.xml
index cc790b7c28..4f5c2bbd6e 100644
--- a/doc/classes/Node2D.xml
+++ b/doc/classes/Node2D.xml
@@ -23,6 +23,7 @@
<argument index="0" name="point" type="Vector2" />
<description>
Returns the angle between the node and the [code]point[/code] in radians.
+ [url=https://raw.githubusercontent.com/godotengine/godot-docs/master/img/node2d_get_angle_to.png]Illustration of the returned angle.[/url]
</description>
</method>
<method name="get_relative_transform_to_parent" qualifiers="const">
diff --git a/doc/classes/Object.xml b/doc/classes/Object.xml
index c9e9a0699c..ed045f8390 100644
--- a/doc/classes/Object.xml
+++ b/doc/classes/Object.xml
@@ -92,12 +92,12 @@
Calls the [code]method[/code] on the object and returns the result. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
[codeblocks]
[gdscript]
- var node = Node2D.new()
- node.call("set", "position", Vector2(42, 0))
+ var node = Node3D.new()
+ node.call("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
[/gdscript]
[csharp]
- var node = new Node2D();
- node.Call("set", "position", new Vector2(42, 0));
+ var node = new Node3D();
+ node.Call("rotate", new Vector3(1f, 0f, 0f), 1.571f);
[/csharp]
[/codeblocks]
[b]Note:[/b] In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).
@@ -110,12 +110,12 @@
Calls the [code]method[/code] on the object during idle time. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
[codeblocks]
[gdscript]
- var node = Node2D.new()
- node.call_deferred("set", "position", Vector2(42, 0))
+ var node = Node3D.new()
+ node.call_deferred("rotate", Vector3(1.0, 0.0, 0.0), 1.571)
[/gdscript]
[csharp]
- var node = new Node2D();
- node.CallDeferred("set", "position", new Vector2(42, 0));
+ var node = new Node3D();
+ node.CallDeferred("rotate", new Vector3(1f, 0f, 0f), 1.571f);
[/csharp]
[/codeblocks]
[b]Note:[/b] In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).
@@ -129,12 +129,12 @@
Calls the [code]method[/code] on the object and returns the result. Contrarily to [method call], this method does not support a variable number of arguments but expects all parameters to be via a single [Array].
[codeblocks]
[gdscript]
- var node = Node2D.new()
- node.callv("set", ["position", Vector2(42, 0)])
+ var node = Node3D.new()
+ node.callv("rotate", [Vector3(1.0, 0.0, 0.0), 1.571])
[/gdscript]
[csharp]
- var node = new Node2D();
- node.Callv("set", new Godot.Collections.Array { "position", new Vector2(42, 0) });
+ var node = new Node3D();
+ node.Callv("rotate", new Godot.Collections.Array { new Vector3(1f, 0f, 0f), 1.571f });
[/csharp]
[/codeblocks]
</description>
@@ -331,7 +331,8 @@
<method name="get_class" qualifiers="const">
<return type="String" />
<description>
- Returns the object's class as a [String].
+ Returns the object's class as a [String]. See also [method is_class].
+ [b]Note:[/b] [method get_class] does not take [code]class_name[/code] declarations into account. If the object has a [code]class_name[/code] defined, the base class name will be returned instead.
</description>
</method>
<method name="get_incoming_connections" qualifiers="const">
@@ -441,7 +442,8 @@
<return type="bool" />
<argument index="0" name="class" type="String" />
<description>
- Returns [code]true[/code] if the object inherits from the given [code]class[/code].
+ Returns [code]true[/code] if the object inherits from the given [code]class[/code]. See also [method get_class].
+ [b]Note:[/b] [method is_class] does not take [code]class_name[/code] declarations into account. If the object has a [code]class_name[/code] defined, [method is_class] will return [code]false[/code] for that name.
</description>
</method>
<method name="is_connected" qualifiers="const">
diff --git a/doc/classes/PackedByteArray.xml b/doc/classes/PackedByteArray.xml
index af92590da3..72f134e9e9 100644
--- a/doc/classes/PackedByteArray.xml
+++ b/doc/classes/PackedByteArray.xml
@@ -270,7 +270,7 @@
Converts UTF-8 encoded array to [String]. Slower than [method get_string_from_ascii] but supports UTF-8 encoded data. Use this function if you are unsure about the source of the data. For user input this function should always be preferred. Returns empty string if source array is not valid UTF-8 string.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="int" />
<description>
diff --git a/doc/classes/PackedColorArray.xml b/doc/classes/PackedColorArray.xml
index a5a5703bfa..2dfaefca23 100644
--- a/doc/classes/PackedColorArray.xml
+++ b/doc/classes/PackedColorArray.xml
@@ -56,7 +56,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="Color" />
<description>
diff --git a/doc/classes/PackedFloat32Array.xml b/doc/classes/PackedFloat32Array.xml
index 9e7dd8f99e..5c05dd9fa7 100644
--- a/doc/classes/PackedFloat32Array.xml
+++ b/doc/classes/PackedFloat32Array.xml
@@ -57,7 +57,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="float" />
<description>
diff --git a/doc/classes/PackedFloat64Array.xml b/doc/classes/PackedFloat64Array.xml
index ff4cf0edf8..921ca23859 100644
--- a/doc/classes/PackedFloat64Array.xml
+++ b/doc/classes/PackedFloat64Array.xml
@@ -57,7 +57,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="float" />
<description>
diff --git a/doc/classes/PackedInt32Array.xml b/doc/classes/PackedInt32Array.xml
index 2e9716b665..dfc9cbf939 100644
--- a/doc/classes/PackedInt32Array.xml
+++ b/doc/classes/PackedInt32Array.xml
@@ -57,7 +57,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="int" />
<description>
diff --git a/doc/classes/PackedInt64Array.xml b/doc/classes/PackedInt64Array.xml
index 1e7fff3bc6..dd38a4f5c2 100644
--- a/doc/classes/PackedInt64Array.xml
+++ b/doc/classes/PackedInt64Array.xml
@@ -57,7 +57,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="int" />
<description>
diff --git a/doc/classes/PackedStringArray.xml b/doc/classes/PackedStringArray.xml
index 04113d4a2e..c2055531a5 100644
--- a/doc/classes/PackedStringArray.xml
+++ b/doc/classes/PackedStringArray.xml
@@ -57,7 +57,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="String" />
<description>
diff --git a/doc/classes/PackedVector2Array.xml b/doc/classes/PackedVector2Array.xml
index 76d3aff20e..51b7c951da 100644
--- a/doc/classes/PackedVector2Array.xml
+++ b/doc/classes/PackedVector2Array.xml
@@ -57,7 +57,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="Vector2" />
<description>
diff --git a/doc/classes/PackedVector3Array.xml b/doc/classes/PackedVector3Array.xml
index 1a35f71619..04a5e3d42e 100644
--- a/doc/classes/PackedVector3Array.xml
+++ b/doc/classes/PackedVector3Array.xml
@@ -56,7 +56,7 @@
Assigns the given value to all elements in the array. This can typically be used together with [method resize] to create an array with a given size and initialized elements.
</description>
</method>
- <method name="has">
+ <method name="has" qualifiers="const">
<return type="bool" />
<argument index="0" name="value" type="Vector3" />
<description>
diff --git a/doc/classes/PhysicsDirectBodyState2D.xml b/doc/classes/PhysicsDirectBodyState2D.xml
index 8698fbec61..01c8933b51 100644
--- a/doc/classes/PhysicsDirectBodyState2D.xml
+++ b/doc/classes/PhysicsDirectBodyState2D.xml
@@ -7,6 +7,7 @@
Provides direct access to a physics body in the [PhysicsServer2D], allowing safe changes to physics properties. This object is passed via the direct state callback of dynamic bodies, and is intended for changing the direct state of that body. See [method RigidBody2D._integrate_forces].
</description>
<tutorials>
+ <link title="Physics introduction">https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html</link>
<link title="Ray-casting">https://docs.godotengine.org/en/latest/tutorials/physics/ray-casting.html</link>
</tutorials>
<methods>
diff --git a/doc/classes/PhysicsDirectBodyState3D.xml b/doc/classes/PhysicsDirectBodyState3D.xml
index 4599f86423..839a83cfc3 100644
--- a/doc/classes/PhysicsDirectBodyState3D.xml
+++ b/doc/classes/PhysicsDirectBodyState3D.xml
@@ -7,6 +7,8 @@
Provides direct access to a physics body in the [PhysicsServer3D], allowing safe changes to physics properties. This object is passed via the direct state callback of dynamic bodies, and is intended for changing the direct state of that body. See [method RigidBody3D._integrate_forces].
</description>
<tutorials>
+ <link title="Physics introduction">https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html</link>
+ <link title="Ray-casting">https://docs.godotengine.org/en/latest/tutorials/physics/ray-casting.html</link>
</tutorials>
<methods>
<method name="add_central_force">
diff --git a/doc/classes/PhysicsDirectSpaceState2D.xml b/doc/classes/PhysicsDirectSpaceState2D.xml
index 64e0fa4050..536c7e4e04 100644
--- a/doc/classes/PhysicsDirectSpaceState2D.xml
+++ b/doc/classes/PhysicsDirectSpaceState2D.xml
@@ -7,7 +7,8 @@
Direct access object to a space in the [PhysicsServer2D]. It's used mainly to do queries against objects and areas residing in a given space.
</description>
<tutorials>
- <link title="Ray-Casting">https://docs.godotengine.org/en/latest/tutorials/physics/ray-casting.html</link>
+ <link title="Physics introduction">https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html</link>
+ <link title="Ray-casting">https://docs.godotengine.org/en/latest/tutorials/physics/ray-casting.html</link>
</tutorials>
<methods>
<method name="cast_motion">
diff --git a/doc/classes/PhysicsDirectSpaceState3D.xml b/doc/classes/PhysicsDirectSpaceState3D.xml
index 360d6e8e92..4e6bd8456f 100644
--- a/doc/classes/PhysicsDirectSpaceState3D.xml
+++ b/doc/classes/PhysicsDirectSpaceState3D.xml
@@ -7,6 +7,7 @@
Direct access object to a space in the [PhysicsServer3D]. It's used mainly to do queries against objects and areas residing in a given space.
</description>
<tutorials>
+ <link title="Physics introduction">https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html</link>
<link title="Ray-casting">https://docs.godotengine.org/en/latest/tutorials/physics/ray-casting.html</link>
</tutorials>
<methods>
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml
index 21d974e233..22ed14743a 100644
--- a/doc/classes/ProjectSettings.xml
+++ b/doc/classes/ProjectSettings.xml
@@ -279,6 +279,9 @@
<member name="audio/driver/mix_rate" type="int" setter="" getter="" default="44100">
The mixing rate used for audio (in Hz). In general, it's better to not touch this and leave it to the host operating system.
</member>
+ <member name="audio/driver/mix_rate.web" type="int" setter="" getter="" default="0">
+ Safer override for [member audio/driver/mix_rate] in the Web platform. Here [code]0[/code] means "let the browser choose" (since some browsers do not like forcing the mix rate).
+ </member>
<member name="audio/driver/output_latency" type="int" setter="" getter="" default="15">
Output latency in milliseconds for audio. Lower values will result in lower audio latency at the cost of increased CPU usage. Low values may result in audible cracking on slower hardware.
</member>
@@ -328,6 +331,9 @@
<member name="debug/gdscript/warnings/deprecated_keyword" type="bool" setter="" getter="" default="true">
If [code]true[/code], enables warnings when deprecated keywords are used.
</member>
+ <member name="debug/gdscript/warnings/empty_file" type="bool" setter="" getter="" default="true">
+ If [code]true[/code], enables warnings when an empty file is parsed.
+ </member>
<member name="debug/gdscript/warnings/enable" type="bool" setter="" getter="" default="true">
If [code]true[/code], enables specific GDScript warnings (see [code]debug/gdscript/warnings/*[/code] settings). If [code]false[/code], disables all GDScript warnings.
</member>
@@ -625,19 +631,19 @@
</member>
<member name="input/ui_text_backspace_all_to_left" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_backspace_all_to_left.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_backspace_all_to_left.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_backspace_word" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_backspace_word.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_backspace_word.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_caret_document_end" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_caret_document_end.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_caret_document_end.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_caret_document_start" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_caret_document_start.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_caret_document_start.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_caret_down" type="Dictionary" setter="" getter="">
</member>
@@ -645,11 +651,11 @@
</member>
<member name="input/ui_text_caret_line_end" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_caret_line_end.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_caret_line_end.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_caret_line_start" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_caret_line_start.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_caret_line_start.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_caret_page_down" type="Dictionary" setter="" getter="">
</member>
@@ -661,11 +667,11 @@
</member>
<member name="input/ui_text_caret_word_left" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_caret_word_left.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_caret_word_left.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_caret_word_right" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_caret_word_right.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_caret_word_right.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_completion_accept" type="Dictionary" setter="" getter="">
</member>
@@ -679,11 +685,11 @@
</member>
<member name="input/ui_text_delete_all_to_right" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_delete_all_to_right.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_delete_all_to_right.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_delete_word" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_delete_word.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_delete_word.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_indent" type="Dictionary" setter="" getter="">
</member>
@@ -695,11 +701,11 @@
</member>
<member name="input/ui_text_scroll_down" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_scroll_down.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_scroll_down.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_scroll_up" type="Dictionary" setter="" getter="">
</member>
- <member name="input/ui_text_scroll_up.osx" type="Dictionary" setter="" getter="">
+ <member name="input/ui_text_scroll_up.macos" type="Dictionary" setter="" getter="">
</member>
<member name="input/ui_text_select_all" type="Dictionary" setter="" getter="">
</member>
diff --git a/doc/classes/RenderingDevice.xml b/doc/classes/RenderingDevice.xml
index 24f7f4274e..428fa2575c 100644
--- a/doc/classes/RenderingDevice.xml
+++ b/doc/classes/RenderingDevice.xml
@@ -359,6 +359,14 @@
<description>
</description>
</method>
+ <method name="get_driver_resource">
+ <return type="int" />
+ <argument index="0" name="resource" type="int" enum="RenderingDevice.DriverResource" />
+ <argument index="1" name="rid" type="RID" />
+ <argument index="2" name="index" type="int" />
+ <description>
+ </description>
+ </method>
<method name="get_frame_delay" qualifiers="const">
<return type="int" />
<description>
@@ -646,6 +654,32 @@
</constant>
<constant name="BARRIER_MASK_NO_BARRIER" value="8">
</constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_DEVICE" value="0" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE" value="1" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_INSTANCE" value="2" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_QUEUE" value="3" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX" value="4" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_IMAGE" value="5" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_IMAGE_VIEW" value="6" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT" value="7" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_SAMPLER" value="8" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET" value="9" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_BUFFER" value="10" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE" value="11" enum="DriverResource">
+ </constant>
+ <constant name="DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE" value="12" enum="DriverResource">
+ </constant>
<constant name="DATA_FORMAT_R4G4_UNORM_PACK8" value="0" enum="DataFormat">
</constant>
<constant name="DATA_FORMAT_R4G4B4A4_UNORM_PACK16" value="1" enum="DataFormat">
diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml
index 638c657492..b5be04fb01 100644
--- a/doc/classes/RenderingServer.xml
+++ b/doc/classes/RenderingServer.xml
@@ -1156,6 +1156,11 @@
<description>
</description>
</method>
+ <method name="get_rendering_device" qualifiers="const">
+ <return type="RenderingDevice" />
+ <description>
+ </description>
+ </method>
<method name="get_rendering_info">
<return type="int" />
<argument index="0" name="info" type="int" enum="RenderingServer.RenderingInfo" />
@@ -3796,21 +3801,18 @@
<constant name="VIEWPORT_SDF_SCALE_MAX" value="3" enum="ViewportSDFScale">
</constant>
<constant name="VIEWPORT_MSAA_DISABLED" value="0" enum="ViewportMSAA">
- Multisample antialiasing is disabled.
+ Multisample antialiasing for 3D is disabled. This is the default value, and also the fastest setting.
</constant>
<constant name="VIEWPORT_MSAA_2X" value="1" enum="ViewportMSAA">
- Multisample antialiasing uses 2 samples per pixel.
+ Multisample antialiasing uses 2 samples per pixel for 3D. This has a moderate impact on performance.
</constant>
<constant name="VIEWPORT_MSAA_4X" value="2" enum="ViewportMSAA">
- Multisample antialiasing uses 4 samples per pixel.
+ Multisample antialiasing uses 4 samples per pixel for 3D. This has a high impact on performance.
</constant>
<constant name="VIEWPORT_MSAA_8X" value="3" enum="ViewportMSAA">
- Multisample antialiasing uses 8 samples per pixel.
- </constant>
- <constant name="VIEWPORT_MSAA_16X" value="4" enum="ViewportMSAA">
- Multisample antialiasing uses 16 samples per pixel.
+ Multisample antialiasing uses 8 samples per pixel for 3D. This has a very high impact on performance. Likely unsupported on low-end and older hardware.
</constant>
- <constant name="VIEWPORT_MSAA_MAX" value="5" enum="ViewportMSAA">
+ <constant name="VIEWPORT_MSAA_MAX" value="4" enum="ViewportMSAA">
</constant>
<constant name="VIEWPORT_SCREEN_SPACE_AA_DISABLED" value="0" enum="ViewportScreenSpaceAA">
</constant>
diff --git a/doc/classes/SceneTree.xml b/doc/classes/SceneTree.xml
index e81eff35ac..9a38e52b23 100644
--- a/doc/classes/SceneTree.xml
+++ b/doc/classes/SceneTree.xml
@@ -219,7 +219,7 @@
</member>
<member name="paused" type="bool" setter="set_pause" getter="is_paused" default="false">
If [code]true[/code], the [SceneTree] is paused. Doing so will have the following behavior:
- - 2D and 3D physics will be stopped.
+ - 2D and 3D physics will be stopped. This includes signals and collision detection.
- [method Node._process], [method Node._physics_process] and [method Node._input] will not be called anymore in nodes.
</member>
<member name="root" type="Window" setter="" getter="get_root">
diff --git a/doc/classes/StyleBoxFlat.xml b/doc/classes/StyleBoxFlat.xml
index 59ab724f48..40f6075528 100644
--- a/doc/classes/StyleBoxFlat.xml
+++ b/doc/classes/StyleBoxFlat.xml
@@ -120,6 +120,7 @@
<members>
<member name="anti_aliasing" type="bool" setter="set_anti_aliased" getter="is_anti_aliased" default="true">
Antialiasing draws a small ring around the edges, which fades to transparency. As a result, edges look much smoother. This is only noticeable when using rounded corners.
+ [b]Note:[/b] When using beveled corners with 45-degree angles ([member corner_detail] = 1), it is recommended to set [member anti_aliasing] to [code]false[/code] to ensure crisp visuals and avoid possible visual glitches.
</member>
<member name="anti_aliasing_size" type="float" setter="set_aa_size" getter="get_aa_size" default="0.625">
This changes the size of the faded ring. Higher values can be used to achieve a "blurry" effect.
diff --git a/doc/classes/TextServer.xml b/doc/classes/TextServer.xml
index d7af2204cf..661c4f05ef 100644
--- a/doc/classes/TextServer.xml
+++ b/doc/classes/TextServer.xml
@@ -624,7 +624,8 @@
<argument index="0" name="font_rid" type="RID" />
<argument index="1" name="msdf" type="bool" />
<description>
- If set to [code]true[/code], glyphs of all sizes are rendered using single multichannel signed distance field generated from the dynamic font vector data.
+ If set to [code]true[/code], glyphs of all sizes are rendered using single multichannel signed distance field generated from the dynamic font vector data. MSDF rendering allows displaying the font at any scaling factor without blurriness, and without incurring a CPU cost when the font size changes (since the font no longer needs to be rasterized on the CPU). As a downside, font hinting is not available with MSDF. The lack of font hinting may result in less crisp and less readable fonts at small sizes.
+ [b]Note:[/b] MSDF font rendering does not render glyphs with overlapping shapes correctly. Overlapping shapes are not valid per the OpenType standard, but are still commonly found in many font files, especially those converted by Google Fonts. To avoid issues with overlapping glyphs, consider downloading the font file directly from the type foundry instead of relying on Google Fonts.
</description>
</method>
<method name="font_set_oversampling">
diff --git a/doc/classes/Thread.xml b/doc/classes/Thread.xml
index b553aad518..9c9119c664 100644
--- a/doc/classes/Thread.xml
+++ b/doc/classes/Thread.xml
@@ -40,6 +40,8 @@
<return type="Variant" />
<description>
Joins the [Thread] and waits for it to finish. Returns what the method called returned.
+ Should either be used when you want to retrieve the value returned from the method called by the [Thread] or before freeing the instance that contains the [Thread].
+ [b]Note:[/b] After the [Thread] finishes joining it will be disposed. If you want to use it again you will have to create a new instance of it.
</description>
</method>
</methods>
diff --git a/doc/classes/TileData.xml b/doc/classes/TileData.xml
index b5031cfc63..b18ca29a8c 100644
--- a/doc/classes/TileData.xml
+++ b/doc/classes/TileData.xml
@@ -11,6 +11,7 @@
<return type="void" />
<argument index="0" name="layer_id" type="int" />
<description>
+ Adds a collision polygon to the tile on the given TileSet physics layer.
</description>
</method>
<method name="get_collision_polygon_one_way_margin" qualifiers="const">
@@ -18,6 +19,7 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="polygon_index" type="int" />
<description>
+ Returns the one-way margin (for one-way platforms) of the polygon at index [code]polygon_index[/code] for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="get_collision_polygon_points" qualifiers="const">
@@ -25,42 +27,49 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="polygon_index" type="int" />
<description>
+ Returns the points of the polygon at index [code]polygon_index[/code] for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="get_collision_polygons_count" qualifiers="const">
<return type="int" />
<argument index="0" name="layer_id" type="int" />
<description>
+ Returns how many polygons the tile has for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="get_custom_data" qualifiers="const">
<return type="Variant" />
<argument index="0" name="layer_name" type="String" />
<description>
+ Returns the custom data value for custom data layer named [code]layer_name[/code].
</description>
</method>
<method name="get_custom_data_by_layer_id" qualifiers="const">
<return type="Variant" />
<argument index="0" name="layer_id" type="int" />
<description>
+ Returns the custom data value for custom data layer with index [code]layer_id[/code].
</description>
</method>
<method name="get_navigation_polygon" qualifiers="const">
<return type="NavigationPolygon" />
<argument index="0" name="layer_id" type="int" />
<description>
+ Returns the navigation polygon of the tile for the TileSet navigation layer with index [code]layer_id[/code].
</description>
</method>
<method name="get_occluder" qualifiers="const">
<return type="OccluderPolygon2D" />
<argument index="0" name="layer_id" type="int" />
<description>
+ Returns the occluder polygon of the tile for the TileSet occlusion layer with index [code]layer_id[/code].
</description>
</method>
<method name="get_peering_bit_terrain" qualifiers="const">
<return type="int" />
<argument index="0" name="peering_bit" type="int" enum="TileSet.CellNeighbor" />
<description>
+ Returns the tile's terrain bit for the given [code]peering_bit[/code] direction.
</description>
</method>
<method name="is_collision_polygon_one_way" qualifiers="const">
@@ -68,6 +77,7 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="polygon_index" type="int" />
<description>
+ Returns whether one-way collisions are enabled for the polygon at index [code]polygon_index[/code] for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="remove_collision_polygon">
@@ -75,6 +85,7 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="polygon_index" type="int" />
<description>
+ Removes the polygon at index [code]polygon_index[/code] for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_collision_polygon_one_way">
@@ -83,6 +94,7 @@
<argument index="1" name="polygon_index" type="int" />
<argument index="2" name="one_way" type="bool" />
<description>
+ Enables/disables one-way collisions on the polygon at index [code]polygon_index[/code] for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_collision_polygon_one_way_margin">
@@ -91,6 +103,7 @@
<argument index="1" name="polygon_index" type="int" />
<argument index="2" name="one_way_margin" type="float" />
<description>
+ Enables/disables one-way collisions on the polygon at index [code]polygon_index[/code] for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_collision_polygon_points">
@@ -99,6 +112,7 @@
<argument index="1" name="polygon_index" type="int" />
<argument index="2" name="polygon" type="PackedVector2Array" />
<description>
+ Sets the points of the polygon at index [code]polygon_index[/code] for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_collision_polygons_count">
@@ -106,6 +120,7 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="polygons_count" type="int" />
<description>
+ Sets the polygons count for TileSet physics layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_custom_data">
@@ -113,6 +128,7 @@
<argument index="0" name="layer_name" type="String" />
<argument index="1" name="value" type="Variant" />
<description>
+ Sets the tile's custom data value for the TileSet custom data layer with name [code]layer_name[/code].
</description>
</method>
<method name="set_custom_data_by_layer_id">
@@ -120,6 +136,7 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="value" type="Variant" />
<description>
+ Sets the tile's custom data value for the TileSet custom data layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_navigation_polygon">
@@ -127,6 +144,7 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="navigation_polygon" type="NavigationPolygon" />
<description>
+ Sets the navigation polygon for the TileSet navigation layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_occluder">
@@ -134,6 +152,7 @@
<argument index="0" name="layer_id" type="int" />
<argument index="1" name="occluder_polygon" type="OccluderPolygon2D" />
<description>
+ Sets the occluder for the TileSet occlusion layer with index [code]layer_id[/code].
</description>
</method>
<method name="set_peering_bit_terrain">
@@ -141,17 +160,7 @@
<argument index="0" name="peering_bit" type="int" enum="TileSet.CellNeighbor" />
<argument index="1" name="terrain" type="int" />
<description>
- </description>
- </method>
- <method name="tile_get_material" qualifiers="const">
- <return type="ShaderMaterial" />
- <description>
- </description>
- </method>
- <method name="tile_set_material">
- <return type="void" />
- <argument index="0" name="material" type="ShaderMaterial" />
- <description>
+ Sets the tile's terrain bit for the given [code]peering_bit[/code] direction.
</description>
</method>
</methods>
@@ -160,6 +169,8 @@
</member>
<member name="flip_v" type="bool" setter="set_flip_v" getter="get_flip_v" default="false">
</member>
+ <member name="material" type="ShaderMaterial" setter="set_material" getter="get_material">
+ </member>
<member name="modulate" type="Color" setter="set_modulate" getter="get_modulate" default="Color(1, 1, 1, 1)">
</member>
<member name="probability" type="float" setter="set_probability" getter="get_probability" default="1.0">
diff --git a/doc/classes/TileMap.xml b/doc/classes/TileMap.xml
index e92a7331e6..4621d138ac 100644
--- a/doc/classes/TileMap.xml
+++ b/doc/classes/TileMap.xml
@@ -4,8 +4,7 @@
Node for 2D tile-based maps.
</brief_description>
<description>
- Node for 2D tile-based maps. Tilemaps use a [TileSet] which contain a list of tiles (textures plus optional collision, navigation, and/or occluder shapes) which are used to create grid-based maps.
- When doing physics queries against the tilemap, the cell coordinates are encoded as [code]metadata[/code] for each detected collision shape returned by methods such as [method PhysicsDirectSpaceState2D.intersect_shape], [method PhysicsDirectBodyState2D.get_contact_collider_shape_metadata] etc.
+ Node for 2D tile-based maps. Tilemaps use a [TileSet] which contain a list of tiles which are used to create grid-based maps. A TileMap may have several layers, layouting tiles on top of each other.
</description>
<tutorials>
<link title="Using Tilemaps">https://docs.godotengine.org/en/latest/tutorials/2d/using_tilemaps.html</link>
@@ -19,8 +18,9 @@
<methods>
<method name="add_layer">
<return type="void" />
- <argument index="0" name="arg0" type="int" />
+ <argument index="0" name="to_position" type="int" />
<description>
+ Adds a layer at the given position [code]to_position[/code] in the array. If [code]to_position[/code] is -1, adds it at the end of the array.
</description>
</method>
<method name="clear">
@@ -41,6 +41,7 @@
<argument index="1" name="coords" type="Vector2i" />
<argument index="2" name="use_proxies" type="bool" />
<description>
+ Returns the tile alternative ID of the cell on layer [code]layer[/code] at [code]coords[/code]. If [code]use_proxies[/code] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy].
</description>
</method>
<method name="get_cell_atlas_coords" qualifiers="const">
@@ -49,6 +50,7 @@
<argument index="1" name="coords" type="Vector2i" />
<argument index="2" name="use_proxies" type="bool" />
<description>
+ Returns the tile atlas coordinates ID of the cell on layer [code]layer[/code] at coordinates [code]coords[/code]. If [code]use_proxies[/code] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy].
</description>
</method>
<method name="get_cell_source_id" qualifiers="const">
@@ -57,24 +59,28 @@
<argument index="1" name="coords" type="Vector2i" />
<argument index="2" name="use_proxies" type="bool" />
<description>
+ Returns the tile source ID of the cell on layer [code]layer[/code] at coordinates [code]coords[/code]. If [code]use_proxies[/code] is [code]false[/code], ignores the [TileSet]'s tile proxies, returning the raw alternative identifier. See [method TileSet.map_tile_proxy].
</description>
</method>
<method name="get_layer_name" qualifiers="const">
<return type="String" />
<argument index="0" name="layer" type="int" />
<description>
+ Returns a TileMap layer's name.
</description>
</method>
<method name="get_layer_y_sort_origin" qualifiers="const">
<return type="int" />
<argument index="0" name="layer" type="int" />
<description>
+ Returns a TileMap layer's Y sort origin.
</description>
</method>
- <method name="get_layer_z_indexd" qualifiers="const">
+ <method name="get_layer_z_index" qualifiers="const">
<return type="int" />
<argument index="0" name="layer" type="int" />
<description>
+ Returns a TileMap layer's Z-index value.
</description>
</method>
<method name="get_layers_count" qualifiers="const">
@@ -87,37 +93,41 @@
<argument index="0" name="coords" type="Vector2i" />
<argument index="1" name="neighbor" type="int" enum="TileSet.CellNeighbor" />
<description>
+ Returns the neighboring cell to the one at coordinates [code]coords[/code], indentified by the [code]neighbor[/code] direction. This method takes into account the different layouts a TileMap can take.
</description>
</method>
<method name="get_surrounding_tiles">
<return type="Vector2i[]" />
<argument index="0" name="coords" type="Vector2i" />
<description>
+ Returns the list of all neighbourings cells to the one at [code]coords[/code]
</description>
</method>
<method name="get_used_cells" qualifiers="const">
<return type="Vector2i[]" />
<argument index="0" name="layer" type="int" />
<description>
- Returns a [Vector2] array with the positions of all cells containing a tile from the tileset (i.e. a tile index different from [code]-1[/code]).
+ Returns a [Vector2] array with the positions of all cells containing a tile in the given layer. A cell is considered empty if its source identifier equals -1, its atlas coordinates identifiers is [code]Vector2(-1, -1)[/code] and its alternative identifier is -1.
</description>
</method>
<method name="get_used_rect">
<return type="Rect2" />
<description>
- Returns a rectangle enclosing the used (non-empty) tiles of the map.
+ Returns a rectangle enclosing the used (non-empty) tiles of the map, including all layers.
</description>
</method>
<method name="is_layer_enabled" qualifiers="const">
<return type="bool" />
<argument index="0" name="layer" type="int" />
<description>
+ Returns if a layer is enabled.
</description>
</method>
<method name="is_layer_y_sort_enabled" qualifiers="const">
<return type="bool" />
<argument index="0" name="layer" type="int" />
<description>
+ Returns if a layer Y-sorts its tiles.
</description>
</method>
<method name="map_to_world" qualifiers="const">
@@ -129,15 +139,17 @@
</method>
<method name="move_layer">
<return type="void" />
- <argument index="0" name="arg0" type="int" />
- <argument index="1" name="arg1" type="int" />
+ <argument index="0" name="layer" type="int" />
+ <argument index="1" name="to_position" type="int" />
<description>
+ Moves the layer at index [code]layer_index[/code] to the given position [code]to_position[/code] in the array.
</description>
</method>
<method name="remove_layer">
<return type="void" />
- <argument index="0" name="arg0" type="int" />
+ <argument index="0" name="layer" type="int" />
<description>
+ Moves the layer at index [code]layer_index[/code] to the given position [code]to_position[/code] in the array.
</description>
</method>
<method name="set_cell">
@@ -148,7 +160,10 @@
<argument index="3" name="atlas_coords" type="Vector2i" default="Vector2i(-1, -1)" />
<argument index="4" name="alternative_tile" type="int" default="-1" />
<description>
- Sets the tile index for the cell given by a Vector2i.
+ Sets the tile indentifiers for the cell on layer [code]layer[/code] at coordinates [code]coords[/code]. Each tile of the [TileSet] is identified using three parts:
+ - The source indentifier [code]source_id[/code] identifies a [TileSetSource] identifier. See [method TileSet.set_source_id],
+ - The atlas coordinates identifier [code]atlas_coords[/code] identifies a tile coordinates in the atlas (if the source is a [TileSetAtlasSource]. For [TileSetScenesCollectionSource] it should be 0),
+ - The alternative tile identifier [code]alternative_tile[/code] identifies a tile alternative the source is a [TileSetAtlasSource], and the scene for a [TileSetScenesCollectionSource].
</description>
</method>
<method name="set_layer_enabled">
@@ -156,6 +171,7 @@
<argument index="0" name="layer" type="int" />
<argument index="1" name="enabled" type="bool" />
<description>
+ Enables or disables the layer [code]layer[/code]. A disabled layer is not processed at all (no rendering, no physics, etc...).
</description>
</method>
<method name="set_layer_name">
@@ -163,6 +179,7 @@
<argument index="0" name="layer" type="int" />
<argument index="1" name="name" type="String" />
<description>
+ Sets a layer's name. This is mostly useful in the editor.
</description>
</method>
<method name="set_layer_y_sort_enabled">
@@ -170,6 +187,8 @@
<argument index="0" name="layer" type="int" />
<argument index="1" name="y_sort_enabled" type="bool" />
<description>
+ Enables or disables a layer's Y-sorting. If a layer is Y-sorted, the layer will behave as a CanvasItem node where each of its tile gets Y-sorted.
+ Y-sorted layers should usually be on different Z-index values than not Y-sorted layers, otherwise, each of those layer will be Y-sorted as whole with the Y-sorted one. This is usually an undesired behvaior.
</description>
</method>
<method name="set_layer_y_sort_origin">
@@ -177,6 +196,8 @@
<argument index="0" name="layer" type="int" />
<argument index="1" name="y_sort_origin" type="int" />
<description>
+ Sets a layer's Y-sort origin value. This Y-sort origin value is added to each tile's Y-sort origin value.
+ This allows, for example, to fake a different height level on each layer. This can be useful for top-down view games.
</description>
</method>
<method name="set_layer_z_index">
@@ -184,6 +205,7 @@
<argument index="0" name="layer" type="int" />
<argument index="1" name="z_index" type="int" />
<description>
+ Sets a layers Z-index value. This Z-index is added to each tile's Z-index value.
</description>
</method>
<method name="world_to_map" qualifiers="const">
@@ -199,8 +221,10 @@
The TileMap's quadrant size. Optimizes drawing by batching, using chunks of this size.
</member>
<member name="collision_visibility_mode" type="int" setter="set_collision_visibility_mode" getter="get_collision_visibility_mode" enum="TileMap.VisibilityMode" default="0">
+ Show or hide the TileMap's collision shapes. If set to [code]VISIBILITY_MODE_DEFAULT[/code], this depends on the show collision debug settings.
</member>
<member name="navigation_visibility_mode" type="int" setter="set_navigation_visibility_mode" getter="get_navigation_visibility_mode" enum="TileMap.VisibilityMode" default="0">
+ Show or hide the TileMap's collision shapes. If set to [code]VISIBILITY_MODE_DEFAULT[/code], this depends on the show navigation debug settings.
</member>
<member name="tile_set" type="TileSet" setter="set_tileset" getter="get_tileset">
The assigned [TileSet].
@@ -215,10 +239,13 @@
</signals>
<constants>
<constant name="VISIBILITY_MODE_DEFAULT" value="0" enum="VisibilityMode">
+ Use the debug settings to determine visibility.
</constant>
<constant name="VISIBILITY_MODE_FORCE_HIDE" value="2" enum="VisibilityMode">
+ Always hide.
</constant>
<constant name="VISIBILITY_MODE_FORCE_SHOW" value="1" enum="VisibilityMode">
+ Always show.
</constant>
</constants>
</class>
diff --git a/doc/classes/TileSet.xml b/doc/classes/TileSet.xml
index 3e0ab87383..02baded019 100644
--- a/doc/classes/TileSet.xml
+++ b/doc/classes/TileSet.xml
@@ -4,8 +4,13 @@
Tile library for tilemaps.
</brief_description>
<description>
- A TileSet is a library of tiles for a [TileMap]. It contains a list of tiles, each consisting of a sprite and optional collision shapes.
- Tiles are referenced by a unique integer ID.
+ A TileSet is a library of tiles for a [TileMap]. A TileSet handles a list of [TileSetSource], each of them storing a set of tiles.
+ Tiles can either be from a [TileSetAtlasSource], that render tiles out of a texture with support for physics, navigation, etc... or from a [TileSetScenesCollectionSource] which exposes scene-based tiles.
+ Tiles are referenced by using three IDs: their source ID, their atlas coordinates ID and their alternative tile ID.
+
+ A TileSet can be configured so that its tiles expose more or less properties. To do so, the TileSet resources uses property layers, that you can add or remove depending on your needs.
+ For example, adding a physics layer allows giving collision shapes to your tiles. Each layer having dedicated properties (physics layer an mask), you may add several TileSet physics layers for each type of collision you need.
+ See the functions to add new layers for more information.
</description>
<tutorials>
<link title="Using Tilemaps">https://docs.godotengine.org/en/latest/tutorials/2d/using_tilemaps.html</link>
@@ -21,31 +26,41 @@
<return type="void" />
<argument index="0" name="to_position" type="int" default="-1" />
<description>
+ Adds a custom data layer to the TileSet at the given position [code]to_position[/code] in the array. If [code]to_position[/code] is -1, adds it at the end of the array.
+ Custom data layers allow assigning custom properties to atlas tiles.
</description>
</method>
<method name="add_navigation_layer">
<return type="void" />
<argument index="0" name="to_position" type="int" default="-1" />
<description>
+ Adds a navigation layer to the TileSet at the given position [code]to_position[/code] in the array. If [code]to_position[/code] is -1, adds it at the end of the array.
+ Navigation layers allow assigning a navigable area to atlas tiles.
</description>
</method>
<method name="add_occlusion_layer">
<return type="void" />
<argument index="0" name="to_position" type="int" default="-1" />
<description>
+ Adds an occlusion layer to the TileSet at the given position [code]to_position[/code] in the array. If [code]to_position[/code] is -1, adds it at the end of the array.
+ Occlusion layers allow assigning occlusion polygons to atlas tiles.
</description>
</method>
<method name="add_physics_layer">
<return type="void" />
<argument index="0" name="to_position" type="int" default="-1" />
<description>
+ Adds a physics layer to the TileSet at the given position [code]to_position[/code] in the array. If [code]to_position[/code] is -1, adds it at the end of the array.
+ Physics layers allow assigning collision polygons to atlas tiles.
</description>
</method>
<method name="add_source">
<return type="int" />
- <argument index="0" name="atlas_source_id_override" type="TileSetSource" />
- <argument index="1" name="arg1" type="int" default="-1" />
+ <argument index="0" name="source" type="TileSetSource" />
+ <argument index="1" name="atlas_source_id_override" type="int" default="-1" />
<description>
+ Adds a [TileSetSource] to the TileSet. If [code]atlas_source_id_override[/code] is not -1, also set its source ID. Otherwise, a unique identifier is automatically generated.
+ The function returns the added source source ID or -1 if the source could not be added.
</description>
</method>
<method name="add_terrain">
@@ -53,22 +68,26 @@
<argument index="0" name="terrain_set" type="int" />
<argument index="1" name="to_position" type="int" default="-1" />
<description>
+ Adds a new terrain to the given terrain set [code]terrain_set[/code] at the given position [code]to_position[/code] in the array. If [code]to_position[/code] is -1, adds it at the end of the array.
</description>
</method>
<method name="add_terrain_set">
<return type="void" />
<argument index="0" name="to_position" type="int" default="-1" />
<description>
+ Adds a new terrain set at the given position [code]to_position[/code] in the array. If [code]to_position[/code] is -1, adds it at the end of the array.
</description>
</method>
<method name="cleanup_invalid_tile_proxies">
<return type="void" />
<description>
+ Clears tile proxies pointing to invalid tiles.
</description>
</method>
<method name="clear_tile_proxies">
<return type="void" />
<description>
+ Clears all tile proxies.
</description>
</method>
<method name="get_alternative_level_tile_proxy">
@@ -77,6 +96,8 @@
<argument index="1" name="coords_from" type="Vector2i" />
<argument index="2" name="alternative_from" type="int" />
<description>
+ Returns the alternative-level proxy for the given identifiers. The returned array contains the three proxie's target identifiers (source ID, atlas coords ID and alternative tile ID).
+ If the TileSet has no proxy for the given identifiers, returns an empty Array.
</description>
</method>
<method name="get_coords_level_tile_proxy">
@@ -84,90 +105,108 @@
<argument index="0" name="source_from" type="int" />
<argument index="1" name="coords_from" type="Vector2i" />
<description>
+ Returns the coodinate-level proxy for the given identifiers. The returned array contains the two proxie's target identifiers (source ID and atlas coords ID).
+ If the TileSet has no proxy for the given identifiers, returns an empty Array.
</description>
</method>
<method name="get_custom_data_layers_count" qualifiers="const">
<return type="int" />
<description>
+ Returns the custom data layers count.
</description>
</method>
<method name="get_navigation_layer_layers" qualifiers="const">
<return type="int" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Returns the navigation layers (as in the Navigation server) of the gives TileSet navigation layer.
</description>
</method>
<method name="get_navigation_layers_count" qualifiers="const">
<return type="int" />
<description>
+ Returns the navigation layers count.
</description>
</method>
<method name="get_next_source_id" qualifiers="const">
<return type="int" />
<description>
+ Returns a new unused source ID. This generated ID is the same that a call to [code]add_source[/code] would return.
</description>
</method>
<method name="get_occlusion_layer_light_mask" qualifiers="const">
<return type="int" />
- <argument index="0" name="arg0" type="int" />
+ <argument index="0" name="layer_index" type="int" />
<description>
+ Returns the light mask of the occlusion layer.
</description>
</method>
<method name="get_occlusion_layer_sdf_collision" qualifiers="const">
<return type="bool" />
- <argument index="0" name="arg0" type="int" />
+ <argument index="0" name="layer_index" type="int" />
<description>
+ Returns if the occluders from this layer use [code]sdf_collision[/code].
</description>
</method>
<method name="get_occlusion_layers_count" qualifiers="const">
<return type="int" />
<description>
+ Returns the occlusion layers count.
</description>
</method>
<method name="get_physics_layer_collision_layer" qualifiers="const">
<return type="int" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Returns the collision layer (as in the physics server) bodies on the given TileSet's physics layer are in.
</description>
</method>
<method name="get_physics_layer_collision_mask" qualifiers="const">
<return type="int" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Returns the collision mask of bodies on the given TileSet's physics layer.
</description>
</method>
<method name="get_physics_layer_physics_material" qualifiers="const">
<return type="PhysicsMaterial" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Returns the physics material of bodies on the given TileSet's physics layer.
</description>
</method>
<method name="get_physics_layers_count" qualifiers="const">
<return type="int" />
<description>
+ Returns the physics layers count.
</description>
</method>
<method name="get_source" qualifiers="const">
<return type="TileSetSource" />
- <argument index="0" name="index" type="int" />
+ <argument index="0" name="source_id" type="int" />
<description>
+ Returns the [TileSetSource] with ID [code]source_id[/code].
</description>
</method>
<method name="get_source_count" qualifiers="const">
<return type="int" />
<description>
+ Returns the number of [TileSetSource] in this TileSet.
</description>
</method>
<method name="get_source_id" qualifiers="const">
<return type="int" />
<argument index="0" name="index" type="int" />
<description>
+ Returns the source ID for source with index [code]index[/code].
</description>
</method>
<method name="get_source_level_tile_proxy">
<return type="int" />
<argument index="0" name="source_from" type="int" />
<description>
+ Returns the source-level proxy for the given source identifier.
+ If the TileSet has no proxy for the given identifier, returns -1.
</description>
</method>
<method name="get_terrain_color" qualifiers="const">
@@ -175,6 +214,7 @@
<argument index="0" name="terrain_set" type="int" />
<argument index="1" name="terrain_index" type="int" />
<description>
+ Returns a terrain's color.
</description>
</method>
<method name="get_terrain_name" qualifiers="const">
@@ -182,23 +222,27 @@
<argument index="0" name="terrain_set" type="int" />
<argument index="1" name="terrain_index" type="int" />
<description>
+ Returns a terrain's name.
</description>
</method>
<method name="get_terrain_set_mode" qualifiers="const">
<return type="int" enum="TileSet.TerrainMode" />
<argument index="0" name="terrain_set" type="int" />
<description>
+ Returns a terrain set mode.
</description>
</method>
<method name="get_terrain_sets_count" qualifiers="const">
<return type="int" />
<description>
+ Returns the terrain sets count.
</description>
</method>
<method name="get_terrains_count" qualifiers="const">
<return type="int" />
<argument index="0" name="terrain_set" type="int" />
<description>
+ Returns the number of terrains in the given terrain set.
</description>
</method>
<method name="has_alternative_level_tile_proxy">
@@ -207,6 +251,7 @@
<argument index="1" name="coords_from" type="Vector2i" />
<argument index="2" name="alternative_from" type="int" />
<description>
+ Returns if there is and alternative-level proxy for the given identifiers.
</description>
</method>
<method name="has_coords_level_tile_proxy">
@@ -214,18 +259,21 @@
<argument index="0" name="source_from" type="int" />
<argument index="1" name="coords_from" type="Vector2i" />
<description>
+ Returns if there is a coodinates-level proxy for the given identifiers.
</description>
</method>
<method name="has_source" qualifiers="const">
<return type="bool" />
- <argument index="0" name="index" type="int" />
+ <argument index="0" name="source_id" type="int" />
<description>
+ Returns if this TileSet has a source for the given source ID.
</description>
</method>
<method name="has_source_level_tile_proxy">
<return type="bool" />
<argument index="0" name="source_from" type="int" />
<description>
+ Returns if there is a source-level proxy for the given source ID.
</description>
</method>
<method name="map_tile_proxy" qualifiers="const">
@@ -234,6 +282,9 @@
<argument index="1" name="coords_from" type="Vector2i" />
<argument index="2" name="alternative_from" type="int" />
<description>
+ According to the configured proxies, maps the provided indentifiers to a new set of identifiers. The source ID, atlas coordinates ID and alternative tile ID are returned as a 3 elements Array.
+ This function first look for matching alternative-level proxies, then coordinates-level proxies, then source-level proxies.
+ If no proxy corresponding to provided identifiers are found, returns the same values the ones used as arguments.
</description>
</method>
<method name="move_custom_data_layer">
@@ -241,6 +292,7 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="to_position" type="int" />
<description>
+ Moves the custom data layer at index [code]layer_index[/code] to the given position [code]to_position[/code] in the array. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="move_navigation_layer">
@@ -248,6 +300,7 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="to_position" type="int" />
<description>
+ Moves the navigation layer at index [code]layer_index[/code] to the given position [code]to_position[/code] in the array. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="move_occlusion_layer">
@@ -255,6 +308,7 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="to_position" type="int" />
<description>
+ Moves the occlusion layer at index [code]layer_index[/code] to the given position [code]to_position[/code] in the array. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="move_physics_layer">
@@ -262,6 +316,7 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="to_position" type="int" />
<description>
+ Moves the physics layer at index [code]layer_index[/code] to the given position [code]to_position[/code] in the array. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="move_terrain">
@@ -270,13 +325,15 @@
<argument index="1" name="terrain_index" type="int" />
<argument index="2" name="to_position" type="int" />
<description>
+ Moves the terrain at index [code]terrain_index[/code] for terrain set [code]terrain_set[/code] to the given position [code]to_position[/code] in the array. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="move_terrain_set">
<return type="void" />
- <argument index="0" name="layer_index" type="int" />
+ <argument index="0" name="terrain_set" type="int" />
<argument index="1" name="to_position" type="int" />
<description>
+ Moves the terrain set at index [code]terrain_set[/code] to the given position [code]to_position[/code] in the array. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="remove_alternative_level_tile_proxy">
@@ -285,6 +342,7 @@
<argument index="1" name="coords_from" type="Vector2i" />
<argument index="2" name="alternative_from" type="int" />
<description>
+ Removes an alternative-level proxy for the given identifiers.
</description>
</method>
<method name="remove_coords_level_tile_proxy">
@@ -292,42 +350,49 @@
<argument index="0" name="source_from" type="int" />
<argument index="1" name="coords_from" type="Vector2i" />
<description>
+ Removes a coordinates-level proxy for the given identifiers.
</description>
</method>
<method name="remove_custom_data_layer">
<return type="void" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Removes the custom data layer at index [code]layer_index[/code]. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="remove_navigation_layer">
<return type="void" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Removes the navigation layer at index [code]layer_index[/code]. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="remove_occlusion_layer">
<return type="void" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Removes the occlusion layer at index [code]layer_index[/code]. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="remove_physics_layer">
<return type="void" />
<argument index="0" name="layer_index" type="int" />
<description>
+ Removes the physics layer at index [code]layer_index[/code]. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="remove_source">
<return type="void" />
<argument index="0" name="source_id" type="int" />
<description>
+ Removes the source with the given source ID.
</description>
</method>
<method name="remove_source_level_tile_proxy">
<return type="void" />
<argument index="0" name="source_from" type="int" />
<description>
+ Removes a source-level tile proxy.
</description>
</method>
<method name="remove_terrain">
@@ -335,12 +400,14 @@
<argument index="0" name="terrain_set" type="int" />
<argument index="1" name="terrain_index" type="int" />
<description>
+ Removes the terrain at index [code]terrain_index[/code] in the given terrain set [code]terrain_set[/code]. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="remove_terrain_set">
<return type="void" />
- <argument index="0" name="layer_index" type="int" />
+ <argument index="0" name="terrain_set" type="int" />
<description>
+ Removes the terrain set at index [code]terrain_set[/code]. Also updates the atlas tiles accordingly.
</description>
</method>
<method name="set_alternative_level_tile_proxy">
@@ -352,6 +419,9 @@
<argument index="4" name="coords_to" type="Vector2i" />
<argument index="5" name="alternative_to" type="int" />
<description>
+ Create an alternative-level proxy for the given identifiers. A proxy will map set of tile identifiers to another set of identifiers.
+ This can be used to replace a tile in all TileMaps using this TileSet, as TileMap nodes will find and use the proxy's target tile when one is available.
+ Proxied tiles can be automatically replaced in TileMap nodes using the editor.
</description>
</method>
<method name="set_coords_level_tile_proxy">
@@ -361,6 +431,9 @@
<argument index="2" name="source_to" type="int" />
<argument index="3" name="coords_to" type="Vector2i" />
<description>
+ Creates a coordinates-level proxy for the given identifiers. A proxy will map set of tile identifiers to another set of identifiers. The alternative tile ID is kept the same when using coordinates-level proxies.
+ This can be used to replace a tile in all TileMaps using this TileSet, as TileMap nodes will find and use the proxy's target tile when one is available.
+ Proxied tiles can be automatically replaced in TileMap nodes using the editor.
</description>
</method>
<method name="set_navigation_layer_layers">
@@ -368,6 +441,7 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="layers" type="int" />
<description>
+ Sets the navigation layers (as in the navigation server) for navigation regions is the given TileSet navigation layer.
</description>
</method>
<method name="set_occlusion_layer_light_mask">
@@ -375,13 +449,15 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="light_mask" type="int" />
<description>
+ Sets the occlusion layer (as in the rendering server) for occluders in the given TileSet occlusion layer.
</description>
</method>
<method name="set_occlusion_layer_sdf_collision">
<return type="void" />
<argument index="0" name="layer_index" type="int" />
- <argument index="1" name="sdf_collision" type="int" />
+ <argument index="1" name="sdf_collision" type="bool" />
<description>
+ Enables or disables sdf collision for occluders in the given TileSet occlusion layer.
</description>
</method>
<method name="set_physics_layer_collision_layer">
@@ -389,6 +465,7 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="layer" type="int" />
<description>
+ Sets the physics layer (as in the physics server) for bodies in the given TileSet physics layer.
</description>
</method>
<method name="set_physics_layer_collision_mask">
@@ -396,6 +473,7 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="mask" type="int" />
<description>
+ Sets the physics layer (as in the physics server) for bodies in the given TileSet physics layer.
</description>
</method>
<method name="set_physics_layer_physics_material">
@@ -403,13 +481,15 @@
<argument index="0" name="layer_index" type="int" />
<argument index="1" name="physics_material" type="PhysicsMaterial" />
<description>
+ Sets the physics material for bodies in the given TileSet physics layer.
</description>
</method>
<method name="set_source_id">
<return type="void" />
<argument index="0" name="source_id" type="int" />
- <argument index="1" name="arg1" type="int" />
+ <argument index="1" name="new_source_id" type="int" />
<description>
+ Changes a source's ID.
</description>
</method>
<method name="set_source_level_tile_proxy">
@@ -417,6 +497,9 @@
<argument index="0" name="source_from" type="int" />
<argument index="1" name="source_to" type="int" />
<description>
+ Creates a source-level proxy for the given source ID. A proxy will map set of tile identifiers to another set of identifiers. Both the atlac coordinates ID and the alternative tile ID are kept the same when using source-level proxies.
+ This can be used to replace a source in all TileMaps using this TileSet, as TileMap nodes will find and use the proxy's target source when one is available.
+ Proxied tiles can be automatically replaced in TileMap nodes using the editor.
</description>
</method>
<method name="set_terrain_color">
@@ -425,6 +508,7 @@
<argument index="1" name="terrain_index" type="int" />
<argument index="2" name="color" type="Color" />
<description>
+ Sets a terrain's color. This color is used for identifying the different terrains in the TileSet editor.
</description>
</method>
<method name="set_terrain_name">
@@ -433,6 +517,7 @@
<argument index="1" name="terrain_index" type="int" />
<argument index="2" name="name" type="String" />
<description>
+ Sets a terrain's name.
</description>
</method>
<method name="set_terrain_set_mode">
@@ -440,86 +525,120 @@
<argument index="0" name="terrain_set" type="int" />
<argument index="1" name="mode" type="int" enum="TileSet.TerrainMode" />
<description>
+ Sets a terrain mode. Each mode determines which bits of a tile shape is used to match the neighbouring tiles' terrains.
</description>
</method>
</methods>
<members>
<member name="tile_layout" type="int" setter="set_tile_layout" getter="get_tile_layout" enum="TileSet.TileLayout" default="0">
+ For all half-offset shapes (Isometric, Hexagonal and Half-Offset square), changes the way tiles are indexed in the TileMap grid.
</member>
<member name="tile_offset_axis" type="int" setter="set_tile_offset_axis" getter="get_tile_offset_axis" enum="TileSet.TileOffsetAxis" default="0">
+ For all half-offset shapes (Isometric, Hexagonal and Half-Offset square), determines the offset axis.
</member>
<member name="tile_shape" type="int" setter="set_tile_shape" getter="get_tile_shape" enum="TileSet.TileShape" default="0">
+ The tile shape.
</member>
<member name="tile_size" type="Vector2i" setter="set_tile_size" getter="get_tile_size" default="Vector2i(16, 16)">
+ The tile size, in pixels. For all tile shapes, this size corresponds to the encompassing rectangle of the tile shape. This is thus the minimal cell size required in an atlas.
</member>
<member name="uv_clipping" type="bool" setter="set_uv_clipping" getter="is_uv_clipping" default="false">
+ Enables/Disable uv clipping when rendering the tiles.
</member>
</members>
<constants>
<constant name="TILE_SHAPE_SQUARE" value="0" enum="TileShape">
- Orthogonal orientation mode.
+ Rectangular tile shape.
</constant>
<constant name="TILE_SHAPE_ISOMETRIC" value="1" enum="TileShape">
- Isometric orientation mode.
+ Diamond tile shape (for isometric look).
</constant>
<constant name="TILE_SHAPE_HALF_OFFSET_SQUARE" value="2" enum="TileShape">
+ Rectangular tile shape with one row/colum out of two offset by half a tile.
</constant>
<constant name="TILE_SHAPE_HEXAGON" value="3" enum="TileShape">
- Hexagon orientation mode.
+ Hexagonal tile shape.
</constant>
<constant name="TILE_LAYOUT_STACKED" value="0" enum="TileLayout">
+ Tile coordinates layout where both axis stay consistent with their respective local horizontal and vertical axis.
</constant>
<constant name="TILE_LAYOUT_STACKED_OFFSET" value="1" enum="TileLayout">
+ Same as [code]TILE_LAYOUT_STAKED[/code], but the first half-offset is negative instead of positive.
</constant>
<constant name="TILE_LAYOUT_STAIRS_RIGHT" value="2" enum="TileLayout">
+ Tile coordinates layout where the horizontal axis stay horizontal, and the vertical one goes down-right.
</constant>
<constant name="TILE_LAYOUT_STAIRS_DOWN" value="3" enum="TileLayout">
+ Tile coordinates layout where the vertical axis stay vertical, and the horizontal one goes down-right.
</constant>
<constant name="TILE_LAYOUT_DIAMOND_RIGHT" value="4" enum="TileLayout">
+ Tile coordinates layout where the horizontal axis goes up-right, and the vertical one goes down-right.
</constant>
<constant name="TILE_LAYOUT_DIAMOND_DOWN" value="5" enum="TileLayout">
+ Tile coordinates layout where the horizontal axis goes down-right, and the vertical one goes down-left.
</constant>
<constant name="TILE_OFFSET_AXIS_HORIZONTAL" value="0" enum="TileOffsetAxis">
+ Horizontal half-offset.
</constant>
<constant name="TILE_OFFSET_AXIS_VERTICAL" value="1" enum="TileOffsetAxis">
+ Vertical half-offset.
</constant>
<constant name="CELL_NEIGHBOR_RIGHT_SIDE" value="0" enum="CellNeighbor">
+ Neighbor on the right side.
</constant>
<constant name="CELL_NEIGHBOR_RIGHT_CORNER" value="1" enum="CellNeighbor">
+ Neighbor in the right corner.
</constant>
<constant name="CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE" value="2" enum="CellNeighbor">
+ Neighbor on the bottom right side.
</constant>
<constant name="CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER" value="3" enum="CellNeighbor">
+ Neighbor in the bottom right corner.
</constant>
<constant name="CELL_NEIGHBOR_BOTTOM_SIDE" value="4" enum="CellNeighbor">
+ Neighbor on the bottom side.
</constant>
<constant name="CELL_NEIGHBOR_BOTTOM_CORNER" value="5" enum="CellNeighbor">
+ Neighbor in the bottom corner.
</constant>
<constant name="CELL_NEIGHBOR_BOTTOM_LEFT_SIDE" value="6" enum="CellNeighbor">
+ Neighbor on the bottom left side.
</constant>
<constant name="CELL_NEIGHBOR_BOTTOM_LEFT_CORNER" value="7" enum="CellNeighbor">
+ Neighbor in the bottom left corner.
</constant>
<constant name="CELL_NEIGHBOR_LEFT_SIDE" value="8" enum="CellNeighbor">
+ Neighbor on the left side.
</constant>
<constant name="CELL_NEIGHBOR_LEFT_CORNER" value="9" enum="CellNeighbor">
+ Neighbor in the left corner.
</constant>
<constant name="CELL_NEIGHBOR_TOP_LEFT_SIDE" value="10" enum="CellNeighbor">
+ Neighbor on the top left side.
</constant>
<constant name="CELL_NEIGHBOR_TOP_LEFT_CORNER" value="11" enum="CellNeighbor">
+ Neighbor in the top left corner.
</constant>
<constant name="CELL_NEIGHBOR_TOP_SIDE" value="12" enum="CellNeighbor">
+ Neighbor on the top side.
</constant>
<constant name="CELL_NEIGHBOR_TOP_CORNER" value="13" enum="CellNeighbor">
+ Neighbor in the top corner.
</constant>
<constant name="CELL_NEIGHBOR_TOP_RIGHT_SIDE" value="14" enum="CellNeighbor">
+ Neighbor on the top right side.
</constant>
<constant name="CELL_NEIGHBOR_TOP_RIGHT_CORNER" value="15" enum="CellNeighbor">
+ Neighbor in the top right corner.
</constant>
<constant name="TERRAIN_MODE_MATCH_CORNERS_AND_SIDES" value="0" enum="TerrainMode">
+ Requires both corners and side to match with neighboring tiles' terrains.
</constant>
<constant name="TERRAIN_MODE_MATCH_CORNERS" value="1" enum="TerrainMode">
+ Requires corners to match with neighboring tiles' terrains.
</constant>
<constant name="TERRAIN_MODE_MATCH_SIDES" value="2" enum="TerrainMode">
+ Requires sides to match with neighboring tiles' terrains.
</constant>
</constants>
</class>
diff --git a/doc/classes/TileSetAtlasSource.xml b/doc/classes/TileSetAtlasSource.xml
index 8caa3a7c39..fd3dbd1e4d 100644
--- a/doc/classes/TileSetAtlasSource.xml
+++ b/doc/classes/TileSetAtlasSource.xml
@@ -1,8 +1,16 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="TileSetAtlasSource" inherits="TileSetSource" version="4.0">
<brief_description>
+ Exposes a 2D atlas texture as a set of tiles for a [TileSet] resource.
</brief_description>
<description>
+ An atlas is a grid of tiles laid out on a texture. Each tile in the grid must be exposed using [method create_tile]. Those tiles are then indexed using their coordinates in the grid.
+ Each tile can also have a size in the grid coordinates, making it more or less cells in the atlas.
+
+ Alternatives version of a tile can be created using [method create_alternative_tile], which are then indexed using an alternative ID. The main tile (the one in the grid), is accessed with an alternative ID equal to 0.
+
+ Each tile alternate has a set of properties that is defined by the source's [TileSet] layers. Those properties are stored in a TileData object that can be accessed and modified using [method get_tile_data].
+ As TileData properties are stored directly in the TileSetAtlasSource resource, their properties might also be set using [code]TileSetAtlasSource.set("&lt;coords_x&gt;:&lt;coords_y&gt;/&lt;alternative_id&gt;/&lt;tile_data_property&gt;")[/code].
</description>
<tutorials>
</tutorials>
@@ -13,11 +21,14 @@
<argument index="1" name="new_atlas_coords" type="Vector2i" default="Vector2i(-1, -1)" />
<argument index="2" name="new_size" type="Vector2i" default="Vector2i(-1, -1)" />
<description>
+ Returns true if the tile at the [code]atlas_coords[/code] coordinates can be moved to the [code]new_atlas_coords[/code] coordinates with the [code]new_size[/code] size. This functions returns false if a tile is already present in the given area, or if this area is outside the atlas boundaries.
+ If [code]new_atlas_coords[/code] is [code]Vector2i(-1, -1)[/code], keeps the tile's coordinates. If [code]new_size[/code] is [code]Vector2i(-1, -1)[/code], keeps the tile's size.
</description>
</method>
<method name="clear_tiles_outside_texture">
<return type="void" />
<description>
+ Clears all tiles that are defined outside the texture boundaries.
</description>
</method>
<method name="create_alternative_tile">
@@ -25,6 +36,8 @@
<argument index="0" name="atlas_coords" type="Vector2i" />
<argument index="1" name="alternative_id_override" type="int" default="-1" />
<description>
+ Creates an alternative tile for the tile at coords [code]atlas_coords[/code]. If [code]alternative_id_override[/code] is -1, give it an automatically generated unique ID, or assigns it the given ID otherwise.
+ Returns the new alternative identifier, or -1 if the alternative could not be created with a provided [code]alternative_id_override[/code].
</description>
</method>
<method name="create_tile">
@@ -32,84 +45,55 @@
<argument index="0" name="atlas_coords" type="Vector2i" />
<argument index="1" name="size" type="Vector2i" default="Vector2i(1, 1)" />
<description>
- </description>
- </method>
- <method name="get_alternative_tile_id" qualifiers="const">
- <return type="int" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <argument index="1" name="index" type="int" />
- <description>
- </description>
- </method>
- <method name="get_alternative_tiles_count" qualifiers="const">
- <return type="int" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <description>
+ Creates a new tile at coords [code]atlas_coords[/code] with size [code]size[/code].
</description>
</method>
<method name="get_atlas_grid_size" qualifiers="const">
<return type="Vector2i" />
<description>
+ Returns the atlas grid size, which depends on how many tiles can fit in the texture. It thus depends on the Texture's size, the atlas [code]margins[/code] the tiles' [code]texture_region_size[/code].
</description>
</method>
<method name="get_next_alternative_tile_id" qualifiers="const">
<return type="int" />
<argument index="0" name="atlas_coords" type="Vector2i" />
<description>
+ Returns the alternative ID a following call to [method create_alternative_tile] would return.
</description>
</method>
<method name="get_tile_at_coords" qualifiers="const">
<return type="Vector2i" />
<argument index="0" name="atlas_coords" type="Vector2i" />
<description>
+ If there is a tile covering the [code]atlas_coords[/code] coordinates, returns the top-left coordinates of the tile (thus its coordinate ID). Returns [code]Vector2i(-1, -1)[/code] otherwise.
</description>
</method>
<method name="get_tile_data" qualifiers="const">
<return type="Object" />
<argument index="0" name="atlas_coords" type="Vector2i" />
- <argument index="1" name="index" type="int" />
- <description>
- </description>
- </method>
- <method name="get_tile_id" qualifiers="const">
- <return type="Vector2i" />
- <argument index="0" name="index" type="int" />
+ <argument index="1" name="alternative_tile" type="int" />
<description>
+ Returns the [TileData] object for the given atlas coordinates and alternative ID.
</description>
</method>
<method name="get_tile_size_in_atlas" qualifiers="const">
<return type="Vector2i" />
<argument index="0" name="atlas_coords" type="Vector2i" />
<description>
+ Returns the size of the tile (in the grid coordinates system) at coordinates [code]atlas_coords[/code].
</description>
</method>
<method name="get_tile_texture_region" qualifiers="const">
<return type="Rect2i" />
<argument index="0" name="atlas_coords" type="Vector2i" />
<description>
- </description>
- </method>
- <method name="get_tiles_count" qualifiers="const">
- <return type="int" />
- <description>
- </description>
- </method>
- <method name="has_alternative_tile" qualifiers="const">
- <return type="bool" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <argument index="1" name="alternative_tile" type="int" />
- <description>
- </description>
- </method>
- <method name="has_tile" qualifiers="const">
- <return type="bool" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <description>
+ Returns a tile's texture region in the atlas texture.
</description>
</method>
<method name="has_tiles_outside_texture">
<return type="bool" />
<description>
+ Returns if this atlas has tiles outside of its texture.
</description>
</method>
<method name="move_tile_in_atlas">
@@ -118,6 +102,9 @@
<argument index="1" name="new_atlas_coords" type="Vector2i" default="Vector2i(-1, -1)" />
<argument index="2" name="new_size" type="Vector2i" default="Vector2i(-1, -1)" />
<description>
+ Move the tile and its alternatives at the [code]atlas_coords[/code] coordinates to the [code]new_atlas_coords[/code] coordinates with the [code]new_size[/code] size. This functions will fail if a tile is already present in the given area.
+ If [code]new_atlas_coords[/code] is [code]Vector2i(-1, -1)[/code], keeps the tile's coordinates. If [code]new_size[/code] is [code]Vector2i(-1, -1)[/code], keeps the tile's size.
+ To avoid an error, first check if a move is possible using [method can_move_tile_in_atlas].
</description>
</method>
<method name="remove_alternative_tile">
@@ -125,12 +112,15 @@
<argument index="0" name="atlas_coords" type="Vector2i" />
<argument index="1" name="alternative_tile" type="int" />
<description>
+ Remove a tile's alternative with alternative ID [code]alternative_tile[/code].
+ Calling this function with [code]alternative_tile[/code] equals to 0 will fail, as the base tile alternative cannot be removed.
</description>
</method>
<method name="remove_tile">
<return type="void" />
<argument index="0" name="atlas_coords" type="Vector2i" />
<description>
+ Remove a tile and its alternative at coordinates [code]atlas_coords[/code].
</description>
</method>
<method name="set_alternative_tile_id">
@@ -139,17 +129,23 @@
<argument index="1" name="alternative_tile" type="int" />
<argument index="2" name="new_id" type="int" />
<description>
+ Change a tile's alternative ID from [code]alternative_tile[/code] to [code]new_id[/code].
+ Calling this function with [code]alternative_id[/code] equals to 0 will fail, as the base tile alternative cannot be moved.
</description>
</method>
</methods>
<members>
<member name="margins" type="Vector2i" setter="set_margins" getter="get_margins" default="Vector2i(0, 0)">
+ Margins, in pixels, to offset the origin of the grid in the texture.
</member>
<member name="separation" type="Vector2i" setter="set_separation" getter="get_separation" default="Vector2i(0, 0)">
+ Separation, in pixels, between each tile texture region of the grid.
</member>
<member name="texture" type="Texture2D" setter="set_texture" getter="get_texture">
+ The atlas texture.
</member>
- <member name="tile_size" type="Vector2i" setter="set_texture_region_size" getter="get_texture_region_size" default="Vector2i(16, 16)">
+ <member name="texture_region_size" type="Vector2i" setter="set_texture_region_size" getter="get_texture_region_size" default="Vector2i(16, 16)">
+ The base tile size in the texture (in pixel). This size must be bigger than the TileSet's [code]tile_size[/code] value.
</member>
</members>
<constants>
diff --git a/doc/classes/TileSetScenesCollectionSource.xml b/doc/classes/TileSetScenesCollectionSource.xml
index a44f519a4c..119a04c25f 100644
--- a/doc/classes/TileSetScenesCollectionSource.xml
+++ b/doc/classes/TileSetScenesCollectionSource.xml
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="TileSetScenesCollectionSource" inherits="TileSetSource" version="4.0">
<brief_description>
+ Exposes a set of scenes as tiles for a [TileSet] resource.
</brief_description>
<description>
+ When placed on a [TileMap], tiles from [TileSetScenesCollectionSource] will automatically instanciate an assiciated scene at the cell's position in the TileMap.
+ Scenes are instanciated as children of the [TileMap] when it enters the tree. If you add/remove a scene tile in the [TileMap] that is already inside the tree, the [TileMap] will automatically instanciate/free the scene accordingly.
</description>
<tutorials>
</tutorials>
@@ -12,83 +15,55 @@
<argument index="0" name="packed_scene" type="PackedScene" />
<argument index="1" name="id_override" type="int" default="-1" />
<description>
- </description>
- </method>
- <method name="get_alternative_tile_id" qualifiers="const">
- <return type="int" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <argument index="1" name="index" type="int" />
- <description>
- </description>
- </method>
- <method name="get_alternative_tiles_count" qualifiers="const">
- <return type="int" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <description>
+ Creates a scene-based tile out of the given scene.
+ Returns a newly generated unique ID.
</description>
</method>
<method name="get_next_scene_tile_id" qualifiers="const">
<return type="int" />
<description>
+ Returns the scene ID a following call to [method create_scene_tile] would return.
</description>
</method>
<method name="get_scene_tile_display_placeholder" qualifiers="const">
<return type="bool" />
<argument index="0" name="id" type="int" />
<description>
+ Returns whether the scene tile with id [code]id[/code] displays a placeholder in the editor.
</description>
</method>
<method name="get_scene_tile_id">
<return type="int" />
<argument index="0" name="index" type="int" />
<description>
+ Returns the scene tile ID of the scene tile at index [code]index[/code].
</description>
</method>
<method name="get_scene_tile_scene" qualifiers="const">
<return type="PackedScene" />
<argument index="0" name="id" type="int" />
<description>
+ Returns the [PackedScene] resource of scene tile with id [code]id[/code].
</description>
</method>
<method name="get_scene_tiles_count">
<return type="int" />
<description>
- </description>
- </method>
- <method name="get_tile_id" qualifiers="const">
- <return type="Vector2i" />
- <argument index="0" name="index" type="int" />
- <description>
- </description>
- </method>
- <method name="get_tiles_count" qualifiers="const">
- <return type="int" />
- <description>
- </description>
- </method>
- <method name="has_alternative_tile" qualifiers="const">
- <return type="bool" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <argument index="1" name="alternative_tile" type="int" />
- <description>
+ Returns the number or scene tiles this TileSet source has.
</description>
</method>
<method name="has_scene_tile_id">
<return type="bool" />
<argument index="0" name="id" type="int" />
<description>
- </description>
- </method>
- <method name="has_tile" qualifiers="const">
- <return type="bool" />
- <argument index="0" name="atlas_coords" type="Vector2i" />
- <description>
+ Returns whether this TileSet source has a scene tile with id [code]id[/code].
</description>
</method>
<method name="remove_scene_tile">
<return type="void" />
<argument index="0" name="id" type="int" />
<description>
+ Remove the scene tile with id [code]id[/code].
</description>
</method>
<method name="set_scene_tile_display_placeholder">
@@ -96,6 +71,7 @@
<argument index="0" name="id" type="int" />
<argument index="1" name="display_placeholder" type="bool" />
<description>
+ Sets whether or not the scene tile with id [code]id[/code] should display a placeholder in the editor. This might be useful for scenes that are not visible.
</description>
</method>
<method name="set_scene_tile_id">
@@ -103,6 +79,7 @@
<argument index="0" name="id" type="int" />
<argument index="1" name="new_id" type="int" />
<description>
+ Changes a scene tile's ID from [code]id[/code] to [code]new_id[/code]. This will fail if there is already a tile with a ID equal to [code]new_id[/code].
</description>
</method>
<method name="set_scene_tile_scene">
@@ -110,6 +87,7 @@
<argument index="0" name="id" type="int" />
<argument index="1" name="packed_scene" type="PackedScene" />
<description>
+ Assigns a [PackedScene] resource to the scene tile with id [code]id[/code]. This will fail if the scene does not extend CanvasItem, as positionning properties are needed to place the scene on the TileMap.
</description>
</method>
</methods>
diff --git a/doc/classes/TileSetSource.xml b/doc/classes/TileSetSource.xml
index 6a3029bb3f..442d845f6c 100644
--- a/doc/classes/TileSetSource.xml
+++ b/doc/classes/TileSetSource.xml
@@ -1,12 +1,63 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="TileSetSource" inherits="Resource" version="4.0">
<brief_description>
+ Exposes a set of tiles for a [TileSet] resource.
</brief_description>
<description>
+ Exposes a set of tiles for a [TileSet] resource.
+ Tiles in a source are indexed with two IDs, coordinates ID (of type Vector2i) and an alternative ID (of type int), named according to their use in the [TileSetAtlasSource] class.
+ Depending on the TileSet source type, those IDs might have restrictions on their values, this is why the base [TileSetSource] class only exposes getters for them.
+
+ You can iterate over all tiles exposed by a TileSetSource by first iterating over coordinates IDs using [method get_tiles_count] and [method get_tile_id], then over alternative IDs using [method get_alternative_tiles_count] and [method get_alternative_tile_id].
</description>
<tutorials>
</tutorials>
<methods>
+ <method name="get_alternative_tile_id" qualifiers="const">
+ <return type="int" />
+ <argument index="0" name="atlas_coords" type="Vector2i" />
+ <argument index="1" name="index" type="int" />
+ <description>
+ Returns the alternative ID for the tile with coordinates ID [code]atlas_coords[/code] at index [code]index[/code].
+ </description>
+ </method>
+ <method name="get_alternative_tiles_count" qualifiers="const">
+ <return type="int" />
+ <argument index="0" name="atlas_coords" type="Vector2i" />
+ <description>
+ Returns the number of alternatives tiles for the coordinates ID [code]atlas_coords[/code].
+ For [TileSetAtlasSource], this always return at least 1, as the base tile with ID 0 is always part of the alternatives list.
+ Returns -1 if there is not tile at the given coords.
+ </description>
+ </method>
+ <method name="get_tile_id" qualifiers="const">
+ <return type="Vector2i" />
+ <argument index="0" name="index" type="int" />
+ <description>
+ Returns the tile coordinates ID of the tile with index [code]index[/code].
+ </description>
+ </method>
+ <method name="get_tiles_count" qualifiers="const">
+ <return type="int" />
+ <description>
+ Returns how many tiles this atlas source defines (not including alternative tiles).
+ </description>
+ </method>
+ <method name="has_alternative_tile" qualifiers="const">
+ <return type="bool" />
+ <argument index="0" name="atlas_coords" type="Vector2i" />
+ <argument index="1" name="alternative_tile" type="int" />
+ <description>
+ Returns if the base tile at coordinates [code]atlas_coords[/code] has an alternative with ID [code]alternative_tile[/code].
+ </description>
+ </method>
+ <method name="has_tile" qualifiers="const">
+ <return type="bool" />
+ <argument index="0" name="atlas_coords" type="Vector2i" />
+ <description>
+ Returns if this atlas has a tile with coordinates ID [code]atlas_coordinates[/code].
+ </description>
+ </method>
</methods>
<constants>
</constants>
diff --git a/doc/classes/VScrollBar.xml b/doc/classes/VScrollBar.xml
index 98a0aea0c7..519cc9c137 100644
--- a/doc/classes/VScrollBar.xml
+++ b/doc/classes/VScrollBar.xml
@@ -23,6 +23,9 @@
<theme_item name="decrement_highlight" data_type="icon" type="Texture2D">
Displayed when the mouse cursor hovers over the decrement button.
</theme_item>
+ <theme_item name="decrement_pressed" data_type="icon" type="Texture2D">
+ Displayed when the decrement button is being pressed.
+ </theme_item>
<theme_item name="grabber" data_type="style" type="StyleBox">
Used as texture for the grabber, the draggable element representing current scroll.
</theme_item>
@@ -38,6 +41,9 @@
<theme_item name="increment_highlight" data_type="icon" type="Texture2D">
Displayed when the mouse cursor hovers over the increment button.
</theme_item>
+ <theme_item name="increment_pressed" data_type="icon" type="Texture2D">
+ Displayed when the increment button is being pressed.
+ </theme_item>
<theme_item name="scroll" data_type="style" type="StyleBox">
Used as background of this [ScrollBar].
</theme_item>
diff --git a/doc/classes/Vector2.xml b/doc/classes/Vector2.xml
index ab4d0e181a..e61f1fe951 100644
--- a/doc/classes/Vector2.xml
+++ b/doc/classes/Vector2.xml
@@ -56,6 +56,7 @@
<description>
Returns this vector's angle with respect to the positive X axis, or [code](1, 0)[/code] vector, in radians.
For example, [code]Vector2.RIGHT.angle()[/code] will return zero, [code]Vector2.DOWN.angle()[/code] will return [code]PI / 2[/code] (a quarter turn, or 90 degrees), and [code]Vector2(1, -1).angle()[/code] will return [code]-PI / 4[/code] (a negative eighth turn, or -45 degrees).
+ [url=https://raw.githubusercontent.com/godotengine/godot-docs/master/img/vector2_angle.png]Illustration of the returned angle.[/url]
Equivalent to the result of [method @GlobalScope.atan2] when called with the vector's [member y] and [member x] as parameters: [code]atan2(y, x)[/code].
</description>
</method>
@@ -64,6 +65,7 @@
<argument index="0" name="to" type="Vector2" />
<description>
Returns the angle to the given vector, in radians.
+ [url=https://raw.githubusercontent.com/godotengine/godot-docs/master/img/vector2_angle_to.png]Illustration of the returned angle.[/url]
</description>
</method>
<method name="angle_to_point" qualifiers="const">
@@ -71,6 +73,7 @@
<argument index="0" name="to" type="Vector2" />
<description>
Returns the angle between the line connecting the two points and the X axis, in radians.
+ [url=https://raw.githubusercontent.com/godotengine/godot-docs/master/img/vector2_angle_to_point.png]Illustration of the returned angle.[/url]
</description>
</method>
<method name="aspect" qualifiers="const">
diff --git a/doc/classes/Viewport.xml b/doc/classes/Viewport.xml
index 46f38e91f7..06a7177bfc 100644
--- a/doc/classes/Viewport.xml
+++ b/doc/classes/Viewport.xml
@@ -134,6 +134,7 @@
<return type="void" />
<argument index="0" name="text" type="String" />
<description>
+ Returns [code]true[/code] if the viewport is currently embedding windows.
</description>
</method>
<method name="push_unhandled_input">
@@ -320,10 +321,7 @@
<constant name="MSAA_8X" value="3" enum="MSAA">
Use 8× Multisample Antialiasing. This has a very high performance cost. The difference between 4× and 8× MSAA may not always be visible in real gameplay conditions. Likely unsupported on low-end and older hardware.
</constant>
- <constant name="MSAA_16X" value="4" enum="MSAA">
- Use 16× Multisample Antialiasing. This has a very high performance cost. The difference between 8× and 16× MSAA may not always be visible in real gameplay conditions. Likely unsupported on medium and low-end hardware.
- </constant>
- <constant name="MSAA_MAX" value="5" enum="MSAA">
+ <constant name="MSAA_MAX" value="4" enum="MSAA">
Represents the size of the [enum MSAA] enum.
</constant>
<constant name="SCREEN_SPACE_AA_DISABLED" value="0" enum="ScreenSpaceAA">
diff --git a/doc/classes/Window.xml b/doc/classes/Window.xml
index d7b156cc57..15d844aacb 100644
--- a/doc/classes/Window.xml
+++ b/doc/classes/Window.xml
@@ -1,8 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Window" inherits="Viewport" version="4.0">
<brief_description>
+ Base class for all windows.
</brief_description>
<description>
+ A node that creates a window.
</description>
<tutorials>
</tutorials>
@@ -10,6 +12,7 @@
<method name="can_draw" qualifiers="const">
<return type="bool" />
<description>
+ Returns whether the window is being drawn to the screen.
</description>
</method>
<method name="child_controls_changed">
@@ -27,6 +30,7 @@
<return type="bool" />
<argument index="0" name="flag" type="int" enum="Window.Flags" />
<description>
+ Returns [code]true[/code] if the flag is set.
</description>
</method>
<method name="get_layout_direction" qualifiers="const">
@@ -38,6 +42,7 @@
<method name="get_real_size" qualifiers="const">
<return type="Vector2i" />
<description>
+ Returns the window's size including its border.
</description>
</method>
<method name="get_theme_color" qualifiers="const">
@@ -87,11 +92,13 @@
<method name="grab_focus">
<return type="void" />
<description>
+ Causes the window to grab focus, allowing it to receive user input.
</description>
</method>
<method name="has_focus" qualifiers="const">
<return type="bool" />
<description>
+ Returns [code]true[/code] if the window is focused.
</description>
</method>
<method name="has_theme_color" qualifiers="const">
@@ -148,6 +155,7 @@
<method name="is_embedded" qualifiers="const">
<return type="bool" />
<description>
+ Returns [code]true[/code] if the window is currently embedded in another window.
</description>
</method>
<method name="is_layout_rtl" qualifiers="const">
@@ -212,6 +220,7 @@
<argument index="0" name="flag" type="int" enum="Window.Flags" />
<argument index="1" name="enabled" type="bool" />
<description>
+ Sets a specified window flag.
</description>
</method>
<method name="set_ime_active">
@@ -247,11 +256,13 @@
</methods>
<members>
<member name="always_on_top" type="bool" setter="set_flag" getter="get_flag" default="false">
+ If [code]true[/code], the window will be on top of all other windows.
</member>
<member name="auto_translate" type="bool" setter="set_auto_translate" getter="is_auto_translating" default="true">
Toggles if any text should automatically change to its translated version depending on the current locale.
</member>
<member name="borderless" type="bool" setter="set_flag" getter="get_flag" default="false">
+ If [code]true[/code], the window will have no borders.
</member>
<member name="content_scale_aspect" type="int" setter="set_content_scale_aspect" getter="get_content_scale_aspect" enum="Window.ContentScaleAspect" default="0">
</member>
@@ -260,6 +271,7 @@
<member name="content_scale_size" type="Vector2i" setter="set_content_scale_size" getter="get_content_scale_size" default="Vector2i(0, 0)">
</member>
<member name="current_screen" type="int" setter="set_current_screen" getter="get_current_screen" default="0">
+ The screen the window is currently on.
</member>
<member name="exclusive" type="bool" setter="set_exclusive" getter="is_exclusive" default="false">
</member>
@@ -268,16 +280,21 @@
<member name="min_size" type="Vector2i" setter="set_min_size" getter="get_min_size" default="Vector2i(0, 0)">
</member>
<member name="mode" type="int" setter="set_mode" getter="get_mode" enum="Window.Mode" default="0">
+ Set's the window's current mode.
+ [b]Note:[/b] Fullscreen mode is not exclusive fullscreen on Windows and Linux.
</member>
<member name="position" type="Vector2i" setter="set_position" getter="get_position" default="Vector2i(0, 0)">
+ The window's position in pixels.
</member>
<member name="size" type="Vector2i" setter="set_size" getter="get_size" default="Vector2i(100, 100)">
+ The window's size in pixels.
</member>
<member name="theme" type="Theme" setter="set_theme" getter="get_theme">
</member>
<member name="theme_type_variation" type="StringName" setter="set_theme_type_variation" getter="get_theme_type_variation" default="&amp;&quot;&quot;">
</member>
<member name="title" type="String" setter="set_title" getter="get_title" default="&quot;&quot;">
+ The window's title.
</member>
<member name="transient" type="bool" setter="set_transient" getter="is_transient" default="false">
</member>
@@ -286,8 +303,10 @@
<member name="unfocusable" type="bool" setter="set_flag" getter="get_flag" default="false">
</member>
<member name="unresizable" type="bool" setter="set_flag" getter="get_flag" default="false">
+ If [code]true[/code], the window can't be resized.
</member>
<member name="visible" type="bool" setter="set_visible" getter="is_visible" default="true">
+ If [code]true[/code], the window is visible.
</member>
<member name="wrap_controls" type="bool" setter="set_wrap_controls" getter="is_wrapping_controls" default="false">
</member>
@@ -340,20 +359,26 @@
<constant name="NOTIFICATION_VISIBILITY_CHANGED" value="30">
</constant>
<constant name="MODE_WINDOWED" value="0" enum="Mode">
+ Windowed mode.
</constant>
<constant name="MODE_MINIMIZED" value="1" enum="Mode">
+ Minimized window mode.
</constant>
<constant name="MODE_MAXIMIZED" value="2" enum="Mode">
+ Maximized window mode.
</constant>
<constant name="MODE_FULLSCREEN" value="3" enum="Mode">
Fullscreen window mode. Note that this is not [i]exclusive[/i] fullscreen. On Windows and Linux, a borderless window is used to emulate fullscreen. On macOS, a new desktop is used to display the running project.
Regardless of the platform, enabling fullscreen will change the window size to match the monitor's size. Therefore, make sure your project supports [url=https://docs.godotengine.org/en/latest/tutorials/rendering/multiple_resolutions.html]multiple resolutions[/url] when enabling fullscreen mode.
</constant>
<constant name="FLAG_RESIZE_DISABLED" value="0" enum="Flags">
+ The window's ability to be resized.
</constant>
<constant name="FLAG_BORDERLESS" value="1" enum="Flags">
+ Borderless window.
</constant>
<constant name="FLAG_ALWAYS_ON_TOP" value="2" enum="Flags">
+ Flag for making the window always on top of all other windows.
</constant>
<constant name="FLAG_TRANSPARENT" value="3" enum="Flags">
</constant>
diff --git a/doc/classes/XRInterfaceExtension.xml b/doc/classes/XRInterfaceExtension.xml
index 66440d4bb4..fb79926043 100644
--- a/doc/classes/XRInterfaceExtension.xml
+++ b/doc/classes/XRInterfaceExtension.xml
@@ -121,6 +121,12 @@
Blits our render results to screen optionally applying lens distortion. This can only be called while processing [code]_commit_views[/code].
</description>
</method>
+ <method name="get_render_target_texture">
+ <return type="RID" />
+ <argument index="0" name="render_target" type="RID" />
+ <description>
+ </description>
+ </method>
</methods>
<constants>
</constants>
diff --git a/drivers/register_driver_types.cpp b/drivers/register_driver_types.cpp
index 83702ea2cc..4a163b7c10 100644
--- a/drivers/register_driver_types.cpp
+++ b/drivers/register_driver_types.cpp
@@ -30,6 +30,7 @@
#include "register_driver_types.h"
+#include "core/extension/native_extension_manager.h"
#include "drivers/png/image_loader_png.h"
#include "drivers/png/resource_saver_png.h"
@@ -54,7 +55,9 @@ void unregister_core_driver_types() {
}
void register_driver_types() {
+ NativeExtensionManager::get_singleton()->initialize_extensions(NativeExtension::INITIALIZATION_LEVEL_DRIVER);
}
void unregister_driver_types() {
+ NativeExtensionManager::get_singleton()->deinitialize_extensions(NativeExtension::INITIALIZATION_LEVEL_DRIVER);
}
diff --git a/drivers/vulkan/rendering_device_vulkan.cpp b/drivers/vulkan/rendering_device_vulkan.cpp
index 6ad24f255f..a4324f0a2c 100644
--- a/drivers/vulkan/rendering_device_vulkan.cpp
+++ b/drivers/vulkan/rendering_device_vulkan.cpp
@@ -7588,7 +7588,7 @@ Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint3
VkCommandPoolCreateInfo cmd_pool_info;
cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmd_pool_info.pNext = nullptr;
- cmd_pool_info.queueFamilyIndex = context->get_graphics_queue();
+ cmd_pool_info.queueFamilyIndex = context->get_graphics_queue_family_index();
cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &split_draw_list_allocators.write[i].command_pool);
@@ -8846,7 +8846,7 @@ void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_de
VkCommandPoolCreateInfo cmd_pool_info;
cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmd_pool_info.pNext = nullptr;
- cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue();
+ cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue_family_index();
cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &frames[i].command_pool);
@@ -9016,6 +9016,92 @@ void RenderingDeviceVulkan::capture_timestamp(const String &p_name) {
frames[frame].timestamp_count++;
}
+uint64_t RenderingDeviceVulkan::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) {
+ _THREAD_SAFE_METHOD_
+
+ switch (p_resource) {
+ case DRIVER_RESOURCE_VULKAN_DEVICE: {
+ return (uint64_t)context->get_device();
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE: {
+ return (uint64_t)context->get_physical_device();
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_INSTANCE: {
+ return (uint64_t)context->get_instance();
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_QUEUE: {
+ return (uint64_t)context->get_graphics_queue();
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX: {
+ return context->get_graphics_queue_family_index();
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_IMAGE: {
+ Texture *tex = texture_owner.getornull(p_rid);
+ ERR_FAIL_NULL_V(tex, 0);
+
+ return (uint64_t)tex->image;
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_IMAGE_VIEW: {
+ Texture *tex = texture_owner.getornull(p_rid);
+ ERR_FAIL_NULL_V(tex, 0);
+
+ return (uint64_t)tex->view;
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT: {
+ Texture *tex = texture_owner.getornull(p_rid);
+ ERR_FAIL_NULL_V(tex, 0);
+
+ return vulkan_formats[tex->format];
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_SAMPLER: {
+ VkSampler *sampler = sampler_owner.getornull(p_rid);
+ ERR_FAIL_NULL_V(sampler, 0);
+
+ return uint64_t(*sampler);
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET: {
+ UniformSet *uniform_set = uniform_set_owner.getornull(p_rid);
+ ERR_FAIL_NULL_V(uniform_set, 0);
+
+ return uint64_t(uniform_set->descriptor_set);
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_BUFFER: {
+ Buffer *buffer = nullptr;
+ if (vertex_buffer_owner.owns(p_rid)) {
+ buffer = vertex_buffer_owner.getornull(p_rid);
+ } else if (index_buffer_owner.owns(p_rid)) {
+ buffer = index_buffer_owner.getornull(p_rid);
+ } else if (uniform_buffer_owner.owns(p_rid)) {
+ buffer = uniform_buffer_owner.getornull(p_rid);
+ } else if (texture_buffer_owner.owns(p_rid)) {
+ buffer = &texture_buffer_owner.getornull(p_rid)->buffer;
+ } else if (storage_buffer_owner.owns(p_rid)) {
+ buffer = storage_buffer_owner.getornull(p_rid);
+ }
+
+ ERR_FAIL_NULL_V(buffer, 0);
+
+ return uint64_t(buffer->buffer);
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE: {
+ ComputePipeline *compute_pipeline = compute_pipeline_owner.getornull(p_rid);
+ ERR_FAIL_NULL_V(compute_pipeline, 0);
+
+ return uint64_t(compute_pipeline->pipeline);
+ }; break;
+ case DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE: {
+ RenderPipeline *render_pipeline = render_pipeline_owner.getornull(p_rid);
+ ERR_FAIL_NULL_V(render_pipeline, 0);
+
+ return uint64_t(render_pipeline->pipeline);
+ }; break;
+ default: {
+ // not supported for this driver
+ return 0;
+ }; break;
+ }
+}
+
uint32_t RenderingDeviceVulkan::get_captured_timestamps_count() const {
return frames[frame].timestamp_result_count;
}
diff --git a/drivers/vulkan/rendering_device_vulkan.h b/drivers/vulkan/rendering_device_vulkan.h
index dc1b78c1d5..cf0b725cfc 100644
--- a/drivers/vulkan/rendering_device_vulkan.h
+++ b/drivers/vulkan/rendering_device_vulkan.h
@@ -813,7 +813,7 @@ class RenderingDeviceVulkan : public RenderingDevice {
// When using split command lists, this is
// implemented internally using secondary command
// buffers. As they can be created in threads,
- // each needs it's own command pool.
+ // each needs its own command pool.
struct SplitDrawListAllocator {
VkCommandPool command_pool = VK_NULL_HANDLE;
@@ -1227,6 +1227,8 @@ public:
virtual String get_device_name() const;
virtual String get_device_pipeline_cache_uuid() const;
+ virtual uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0);
+
RenderingDeviceVulkan();
~RenderingDeviceVulkan();
};
diff --git a/drivers/vulkan/vulkan_context.cpp b/drivers/vulkan/vulkan_context.cpp
index 625c222b67..bb0123e536 100644
--- a/drivers/vulkan/vulkan_context.cpp
+++ b/drivers/vulkan/vulkan_context.cpp
@@ -275,22 +275,21 @@ Error VulkanContext::_obtain_vulkan_version() {
if (res == VK_SUCCESS) {
vulkan_major = VK_VERSION_MAJOR(api_version);
vulkan_minor = VK_VERSION_MINOR(api_version);
- uint32_t vulkan_patch = VK_VERSION_PATCH(api_version);
-
- print_line("Vulkan API " + itos(vulkan_major) + "." + itos(vulkan_minor) + "." + itos(vulkan_patch));
+ vulkan_patch = VK_VERSION_PATCH(api_version);
} else {
// according to the documentation this shouldn't fail with anything except a memory allocation error
// in which case we're in deep trouble anyway
ERR_FAIL_V(ERR_CANT_CREATE);
}
} else {
- print_line("vkEnumerateInstanceVersion not available, assuming Vulkan 1.0");
+ print_line("vkEnumerateInstanceVersion not available, assuming Vulkan 1.0.");
}
// we don't go above 1.2
if ((vulkan_major > 1) || (vulkan_major == 1 && vulkan_minor > 2)) {
vulkan_major = 1;
vulkan_minor = 2;
+ vulkan_patch = 0;
}
return OK;
@@ -759,7 +758,9 @@ Error VulkanContext::_create_physical_device() {
}
}
- print_line("Using Vulkan Device #" + itos(device_index) + ": " + device_vendor + " - " + device_name);
+ print_line(
+ "Vulkan API " + itos(vulkan_major) + "." + itos(vulkan_minor) + "." + itos(vulkan_patch) +
+ " - " + "Using Vulkan Device #" + itos(device_index) + ": " + device_vendor + " - " + device_name);
device_api_version = gpu_props.apiVersion;
@@ -2028,7 +2029,11 @@ int VulkanContext::get_swapchain_image_count() const {
return swapchainImageCount;
}
-uint32_t VulkanContext::get_graphics_queue() const {
+VkQueue VulkanContext::get_graphics_queue() const {
+ return graphics_queue;
+}
+
+uint32_t VulkanContext::get_graphics_queue_family_index() const {
return graphics_queue_family_index;
}
diff --git a/drivers/vulkan/vulkan_context.h b/drivers/vulkan/vulkan_context.h
index fe09d4c497..ae7c697be8 100644
--- a/drivers/vulkan/vulkan_context.h
+++ b/drivers/vulkan/vulkan_context.h
@@ -85,6 +85,7 @@ private:
// Vulkan 1.0 doesn't return version info so we assume this by default until we know otherwise
uint32_t vulkan_major = 1;
uint32_t vulkan_minor = 0;
+ uint32_t vulkan_patch = 0;
SubgroupCapabilities subgroup_capabilities;
MultiviewCapabilities multiview_capabilities;
@@ -243,7 +244,8 @@ public:
VkPhysicalDevice get_physical_device();
VkInstance get_instance() { return inst; }
int get_swapchain_image_count() const;
- uint32_t get_graphics_queue() const;
+ VkQueue get_graphics_queue() const;
+ uint32_t get_graphics_queue_family_index() const;
void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height);
int window_get_width(DisplayServer::WindowID p_window = 0);
diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp
index 0b5cfceadc..276fda2a8f 100644
--- a/drivers/wasapi/audio_driver_wasapi.cpp
+++ b/drivers/wasapi/audio_driver_wasapi.cpp
@@ -499,7 +499,7 @@ Error AudioDriverWASAPI::finish_capture_device() {
Error AudioDriverWASAPI::init() {
mix_rate = GLOBAL_GET("audio/driver/mix_rate");
- target_latency_ms = GLOBAL_GET("audio/output_latency");
+ target_latency_ms = GLOBAL_GET("audio/driver/output_latency");
Error err = init_render_device();
if (err != OK) {
diff --git a/editor/action_map_editor.cpp b/editor/action_map_editor.cpp
index 7aa63f899b..6789b5be00 100644
--- a/editor/action_map_editor.cpp
+++ b/editor/action_map_editor.cpp
@@ -248,10 +248,8 @@ void InputEventConfigurationDialog::_listen_window_input(const Ref<InputEvent> &
k->set_pressed(false); // to avoid serialisation of 'pressed' property - doesn't matter for actions anyway.
// Maintain physical keycode option state
if (physical_key_checkbox->is_pressed()) {
- k->set_physical_keycode(k->get_keycode());
k->set_keycode(KEY_NONE);
} else {
- k->set_keycode((Key)k->get_physical_keycode());
k->set_physical_keycode(KEY_NONE);
}
}
diff --git a/editor/code_editor.cpp b/editor/code_editor.cpp
index 89c2e49814..5599076c40 100644
--- a/editor/code_editor.cpp
+++ b/editor/code_editor.cpp
@@ -715,7 +715,27 @@ void CodeTextEditor::input(const Ref<InputEvent> &event) {
ERR_FAIL_COND(event.is_null());
const Ref<InputEventKey> key_event = event;
- if (!key_event.is_valid() || !key_event->is_pressed() || !text_editor->has_focus()) {
+
+ if (!key_event.is_valid()) {
+ return;
+ }
+ if (!key_event->is_pressed()) {
+ return;
+ }
+
+ if (!text_editor->has_focus()) {
+ if ((find_replace_bar != nullptr && find_replace_bar->is_visible()) && (find_replace_bar->has_focus() || find_replace_bar->is_ancestor_of(get_focus_owner()))) {
+ if (ED_IS_SHORTCUT("script_text_editor/find_next", key_event)) {
+ find_replace_bar->search_next();
+ accept_event();
+ return;
+ }
+ if (ED_IS_SHORTCUT("script_text_editor/find_previous", key_event)) {
+ find_replace_bar->search_prev();
+ accept_event();
+ return;
+ }
+ }
return;
}
@@ -1282,7 +1302,9 @@ void CodeTextEditor::_delete_line(int p_line) {
text_editor->set_caret_column(0);
}
text_editor->backspace();
- text_editor->unfold_line(p_line);
+ if (p_line < text_editor->get_line_count()) {
+ text_editor->unfold_line(p_line);
+ }
text_editor->set_caret_line(p_line);
}
@@ -1735,7 +1757,7 @@ void CodeTextEditor::goto_prev_bookmark() {
text_editor->set_caret_line(bmarks[bmarks.size() - 1]);
text_editor->center_viewport_to_caret();
} else {
- for (int i = bmarks.size(); i >= 0; i--) {
+ for (int i = bmarks.size() - 1; i >= 0; i--) {
int bmark_line = bmarks[i];
if (bmark_line < line) {
text_editor->unfold_line(bmark_line);
diff --git a/editor/debugger/editor_debugger_node.cpp b/editor/debugger/editor_debugger_node.cpp
index 07c02eb022..be84e8dec5 100644
--- a/editor/debugger/editor_debugger_node.cpp
+++ b/editor/debugger/editor_debugger_node.cpp
@@ -183,16 +183,16 @@ ScriptEditorDebugger *EditorDebuggerNode::get_default_debugger() const {
return Object::cast_to<ScriptEditorDebugger>(tabs->get_tab_control(0));
}
-Error EditorDebuggerNode::start(const String &p_protocol) {
+Error EditorDebuggerNode::start(const String &p_uri) {
stop();
+ ERR_FAIL_COND_V(p_uri.find("://") < 0, ERR_INVALID_PARAMETER);
if (EDITOR_GET("run/output/always_open_output_on_play")) {
EditorNode::get_singleton()->make_bottom_panel_item_visible(EditorNode::get_log());
} else {
EditorNode::get_singleton()->make_bottom_panel_item_visible(this);
}
-
- server = Ref<EditorDebuggerServer>(EditorDebuggerServer::create(p_protocol));
- const Error err = server->start();
+ server = Ref<EditorDebuggerServer>(EditorDebuggerServer::create(p_uri.substr(0, p_uri.find("://") + 3)));
+ const Error err = server->start(p_uri);
if (err != OK) {
return err;
}
diff --git a/editor/debugger/editor_debugger_node.h b/editor/debugger/editor_debugger_node.h
index 39a95326be..4d9e846834 100644
--- a/editor/debugger/editor_debugger_node.h
+++ b/editor/debugger/editor_debugger_node.h
@@ -188,7 +188,7 @@ public:
void set_camera_override(CameraOverride p_override);
CameraOverride get_camera_override();
- Error start(const String &p_protocol = "tcp://");
+ Error start(const String &p_uri = "tcp://");
void stop();
diff --git a/editor/debugger/editor_debugger_server.cpp b/editor/debugger/editor_debugger_server.cpp
index e8524e0702..8c3833af50 100644
--- a/editor/debugger/editor_debugger_server.cpp
+++ b/editor/debugger/editor_debugger_server.cpp
@@ -45,7 +45,7 @@ private:
public:
static EditorDebuggerServer *create(const String &p_protocol);
virtual void poll() {}
- virtual Error start();
+ virtual Error start(const String &p_uri);
virtual void stop();
virtual bool is_active() const;
virtual bool is_connection_available() const;
@@ -63,11 +63,18 @@ EditorDebuggerServerTCP::EditorDebuggerServerTCP() {
server.instantiate();
}
-Error EditorDebuggerServerTCP::start() {
- int remote_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
- const Error err = server->listen(remote_port);
+Error EditorDebuggerServerTCP::start(const String &p_uri) {
+ int bind_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
+ String bind_host = (String)EditorSettings::get_singleton()->get("network/debug/remote_host");
+ if (!p_uri.is_empty() && p_uri != "tcp://") {
+ String scheme, path;
+ Error err = p_uri.parse_url(scheme, bind_host, bind_port, path);
+ ERR_FAIL_COND_V(err != OK, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!bind_host.is_valid_ip_address() && bind_host != "*", ERR_INVALID_PARAMETER);
+ }
+ const Error err = server->listen(bind_port, bind_host);
if (err != OK) {
- EditorNode::get_log()->add_message(String("Error listening on port ") + itos(remote_port), EditorLog::MSG_TYPE_ERROR);
+ EditorNode::get_log()->add_message(String("Error listening on port ") + itos(bind_port), EditorLog::MSG_TYPE_ERROR);
return err;
}
return err;
diff --git a/editor/debugger/editor_debugger_server.h b/editor/debugger/editor_debugger_server.h
index 6216d0df3d..844d1a9e5a 100644
--- a/editor/debugger/editor_debugger_server.h
+++ b/editor/debugger/editor_debugger_server.h
@@ -48,7 +48,7 @@ public:
static void register_protocol_handler(const String &p_protocol, CreateServerFunc p_func);
static EditorDebuggerServer *create(const String &p_protocol);
virtual void poll() = 0;
- virtual Error start() = 0;
+ virtual Error start(const String &p_uri = "") = 0;
virtual void stop() = 0;
virtual bool is_active() const = 0;
virtual bool is_connection_available() const = 0;
diff --git a/editor/editor_autoload_settings.cpp b/editor/editor_autoload_settings.cpp
index fad76682b5..fcf79a80a7 100644
--- a/editor/editor_autoload_settings.cpp
+++ b/editor/editor_autoload_settings.cpp
@@ -64,7 +64,12 @@ void EditorAutoloadSettings::_notification(int p_what) {
bool EditorAutoloadSettings::_autoload_name_is_valid(const String &p_name, String *r_error) {
if (!p_name.is_valid_identifier()) {
if (r_error) {
- *r_error = TTR("Invalid name.") + "\n" + TTR("Valid characters:") + " a-z, A-Z, 0-9 or _";
+ *r_error = TTR("Invalid name.") + " ";
+ if (p_name.size() > 0 && p_name.left(1).is_numeric()) {
+ *r_error += TTR("Cannot begin with a digit.");
+ } else {
+ *r_error += TTR("Valid characters:") + " a-z, A-Z, 0-9 or _";
+ }
}
return false;
@@ -72,7 +77,15 @@ bool EditorAutoloadSettings::_autoload_name_is_valid(const String &p_name, Strin
if (ClassDB::class_exists(p_name)) {
if (r_error) {
- *r_error = TTR("Invalid name.") + "\n" + TTR("Must not collide with an existing engine class name.");
+ *r_error = TTR("Invalid name.") + " " + TTR("Must not collide with an existing engine class name.");
+ }
+
+ return false;
+ }
+
+ if (ScriptServer::is_global_class(p_name)) {
+ if (r_error) {
+ *r_error = TTR("Invalid name.") + "\n" + TTR("Must not collide with an existing global script class name.");
}
return false;
@@ -81,7 +94,7 @@ bool EditorAutoloadSettings::_autoload_name_is_valid(const String &p_name, Strin
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
if (Variant::get_type_name(Variant::Type(i)) == p_name) {
if (r_error) {
- *r_error = TTR("Invalid name.") + "\n" + TTR("Must not collide with an existing built-in type name.");
+ *r_error = TTR("Invalid name.") + " " + TTR("Must not collide with an existing built-in type name.");
}
return false;
@@ -91,7 +104,7 @@ bool EditorAutoloadSettings::_autoload_name_is_valid(const String &p_name, Strin
for (int i = 0; i < CoreConstants::get_global_constant_count(); i++) {
if (CoreConstants::get_global_constant_name(i) == p_name) {
if (r_error) {
- *r_error = TTR("Invalid name.") + "\n" + TTR("Must not collide with an existing global constant name.");
+ *r_error = TTR("Invalid name.") + " " + TTR("Must not collide with an existing global constant name.");
}
return false;
@@ -104,7 +117,7 @@ bool EditorAutoloadSettings::_autoload_name_is_valid(const String &p_name, Strin
for (const String &E : keywords) {
if (E == p_name) {
if (r_error) {
- *r_error = TTR("Invalid name.") + "\n" + TTR("Keyword cannot be used as an autoload name.");
+ *r_error = TTR("Invalid name.") + " " + TTR("Keyword cannot be used as an autoload name.");
}
return false;
@@ -338,8 +351,11 @@ void EditorAutoloadSettings::_autoload_path_text_changed(const String p_path) {
}
void EditorAutoloadSettings::_autoload_text_changed(const String p_name) {
- add_autoload->set_disabled(
- autoload_add_path->get_text() == "" || !_autoload_name_is_valid(p_name, nullptr));
+ String error_string;
+ bool is_name_valid = _autoload_name_is_valid(p_name, &error_string);
+ add_autoload->set_disabled(autoload_add_path->get_text() == "" || !is_name_valid);
+ error_message->set_text(error_string);
+ error_message->set_visible(autoload_add_name->get_text() != "" && !is_name_valid);
}
Node *EditorAutoloadSettings::_create_autoload(const String &p_path) {
@@ -820,6 +836,12 @@ EditorAutoloadSettings::EditorAutoloadSettings() {
HBoxContainer *hbc = memnew(HBoxContainer);
add_child(hbc);
+ error_message = memnew(Label);
+ error_message->hide();
+ error_message->set_align(Label::Align::ALIGN_RIGHT);
+ error_message->add_theme_color_override("font_color", EditorNode::get_singleton()->get_gui_base()->get_theme_color(SNAME("error_color"), SNAME("Editor")));
+ add_child(error_message);
+
Label *l = memnew(Label);
l->set_text(TTR("Path:"));
hbc->add_child(l);
diff --git a/editor/editor_autoload_settings.h b/editor/editor_autoload_settings.h
index b709728856..b8e054cd14 100644
--- a/editor/editor_autoload_settings.h
+++ b/editor/editor_autoload_settings.h
@@ -70,6 +70,7 @@ class EditorAutoloadSettings : public VBoxContainer {
LineEdit *autoload_add_name;
Button *add_autoload;
LineEdit *autoload_add_path;
+ Label *error_message;
Button *browse_button;
EditorFileDialog *file_dialog;
diff --git a/editor/editor_command_palette.cpp b/editor/editor_command_palette.cpp
index 25250e231e..4ad45f9649 100644
--- a/editor/editor_command_palette.cpp
+++ b/editor/editor_command_palette.cpp
@@ -70,6 +70,7 @@ void EditorCommandPalette::_update_command_search(const String &search_text) {
r.key_name = command_keys[i];
r.display_name = commands[r.key_name].name;
r.shortcut_text = commands[r.key_name].shortcut;
+ r.last_used = commands[r.key_name].last_used;
if (search_text.is_subsequence_ofi(r.display_name)) {
if (!search_text.is_empty()) {
@@ -94,6 +95,9 @@ void EditorCommandPalette::_update_command_search(const String &search_text) {
if (!search_text.is_empty()) {
SortArray<CommandEntry, CommandEntryComparator> sorter;
sorter.sort(entries.ptrw(), entries.size());
+ } else {
+ SortArray<CommandEntry, CommandHistoryComparator> sorter;
+ sorter.sort(entries.ptrw(), entries.size());
}
const int entry_limit = MIN(entries.size(), 300);
@@ -213,7 +217,9 @@ void EditorCommandPalette::_add_command(String p_command_name, String p_key_name
void EditorCommandPalette::execute_command(String &p_command_key) {
ERR_FAIL_COND_MSG(!commands.has(p_command_key), p_command_key + " not found.");
+ commands[p_command_key].last_used = OS::get_singleton()->get_unix_time();
commands[p_command_key].callable.call_deferred(nullptr, 0);
+ _save_history();
}
void EditorCommandPalette::register_shortcuts_as_command() {
@@ -230,6 +236,14 @@ void EditorCommandPalette::register_shortcuts_as_command() {
key = unregistered_shortcuts.next(key);
}
unregistered_shortcuts.clear();
+
+ // Load command use history.
+ Dictionary command_history = EditorSettings::get_singleton()->get_project_metadata("command_palette", "command_history", Dictionary());
+ Array history_entries = command_history.keys();
+ for (int i = 0; i < history_entries.size(); i++) {
+ const String &history_key = history_entries[i];
+ commands[history_key].last_used = command_history[history_key];
+ }
}
Ref<Shortcut> EditorCommandPalette::add_shortcut_command(const String &p_command, const String &p_key, Ref<Shortcut> p_shortcut) {
@@ -252,6 +266,19 @@ void EditorCommandPalette::_theme_changed() {
command_search_box->set_right_icon(search_options->get_theme_icon("Search", "EditorIcons"));
}
+void EditorCommandPalette::_save_history() const {
+ Dictionary command_history;
+ List<String> command_keys;
+ commands.get_key_list(&command_keys);
+
+ for (const String &key : command_keys) {
+ if (commands[key].last_used > 0) {
+ command_history[key] = commands[key].last_used;
+ }
+ }
+ EditorSettings::get_singleton()->set_project_metadata("command_palette", "command_history", command_history);
+}
+
EditorCommandPalette *EditorCommandPalette::get_singleton() {
if (singleton == nullptr) {
singleton = memnew(EditorCommandPalette);
diff --git a/editor/editor_command_palette.h b/editor/editor_command_palette.h
index 093f4b797d..39821a1169 100644
--- a/editor/editor_command_palette.h
+++ b/editor/editor_command_palette.h
@@ -47,13 +47,15 @@ class EditorCommandPalette : public ConfirmationDialog {
Callable callable;
String name;
String shortcut;
+ int last_used = 0; // Store time as int, because doubles have problems with text serialization.
};
struct CommandEntry {
String key_name;
String display_name;
String shortcut_text;
- float score;
+ int last_used = 0;
+ float score = 0;
};
struct CommandEntryComparator {
@@ -62,6 +64,12 @@ class EditorCommandPalette : public ConfirmationDialog {
}
};
+ struct CommandHistoryComparator {
+ _FORCE_INLINE_ bool operator()(const CommandEntry &A, const CommandEntry &B) const {
+ return A.last_used > B.last_used;
+ }
+ };
+
HashMap<String, Command> commands;
HashMap<String, Pair<String, Ref<Shortcut>>> unregistered_shortcuts;
@@ -74,6 +82,7 @@ class EditorCommandPalette : public ConfirmationDialog {
void _update_command_keys();
void _add_command(String p_command_name, String p_key_name, Callable p_binded_action, String p_shortcut_text = "None");
void _theme_changed();
+ void _save_history() const;
EditorCommandPalette();
protected:
diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp
index aa89a14725..8523833d52 100644
--- a/editor/editor_file_system.cpp
+++ b/editor/editor_file_system.cpp
@@ -444,6 +444,10 @@ bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_impo
Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
+ if (importer.is_null()) {
+ return true; // the importer has possibly changed, try to reimport.
+ }
+
if (importer->get_format_version() > version) {
return true; // version changed, reimport
}
diff --git a/editor/editor_help.cpp b/editor/editor_help.cpp
index 490c8f287f..8c935b846a 100644
--- a/editor/editor_help.cpp
+++ b/editor/editor_help.cpp
@@ -117,7 +117,7 @@ void EditorHelp::_class_desc_select(const String &p_select) {
} else {
if (table->has(link)) {
// Found in the current page
- class_desc->scroll_to_line((*table)[link]);
+ class_desc->scroll_to_paragraph((*table)[link]);
} else {
if (topic == "class_enum") {
// Try to find the enum in @GlobalScope
@@ -1345,7 +1345,7 @@ void EditorHelp::_help_callback(const String &p_topic) {
}
}
- class_desc->call_deferred(SNAME("scroll_to_line"), line);
+ class_desc->call_deferred(SNAME("scroll_to_paragraph"), line);
}
static void _add_text_to_rt(const String &p_bbcode, RichTextLabel *p_rt) {
@@ -1653,7 +1653,7 @@ Vector<Pair<String, int>> EditorHelp::get_sections() {
void EditorHelp::scroll_to_section(int p_section_index) {
int line = section_line[p_section_index].second;
- class_desc->scroll_to_line(line);
+ class_desc->scroll_to_paragraph(line);
}
void EditorHelp::popup_search() {
diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp
index d3841ad6c0..7631e425e8 100644
--- a/editor/editor_inspector.cpp
+++ b/editor/editor_inspector.cpp
@@ -799,7 +799,7 @@ void EditorProperty::gui_input(const Ref<InputEvent> &p_event) {
}
void EditorProperty::unhandled_key_input(const Ref<InputEvent> &p_event) {
- if (!selected) {
+ if (!selected || !p_event->is_pressed()) {
return;
}
@@ -815,6 +815,19 @@ void EditorProperty::unhandled_key_input(const Ref<InputEvent> &p_event) {
}
}
+const Color *EditorProperty::_get_property_colors() {
+ const Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const float saturation = base.get_s() * 0.75;
+ const float value = base.get_v();
+
+ static Color c[4];
+ c[0].set_hsv(0.0 / 3.0 + 0.05, saturation, value);
+ c[1].set_hsv(1.0 / 3.0 + 0.05, saturation, value);
+ c[2].set_hsv(2.0 / 3.0 + 0.05, saturation, value);
+ c[3].set_hsv(1.5 / 3.0 + 0.05, saturation, value);
+ return c;
+}
+
void EditorProperty::set_label_reference(Control *p_control) {
label_reference = p_control;
}
@@ -1266,9 +1279,13 @@ void EditorInspectorSection::_notification(int p_what) {
}
header_height += get_theme_constant(SNAME("vseparation"), SNAME("Tree"));
+ Rect2 header_rect = Rect2(Vector2(), Vector2(get_size().width, header_height));
Color c = bg_color;
c.a *= 0.4;
- draw_rect(Rect2(Vector2(), Vector2(get_size().width, header_height)), c);
+ if (foldable && header_rect.has_point(get_local_mouse_position())) {
+ c = c.lightened(Input::get_singleton()->is_mouse_button_pressed(MOUSE_BUTTON_LEFT) ? -0.05 : 0.2);
+ }
+ draw_rect(header_rect, c);
const int arrow_margin = 2;
const int arrow_width = arrow.is_valid() ? arrow->get_width() : 0;
@@ -1315,12 +1332,14 @@ void EditorInspectorSection::_notification(int p_what) {
if (dropping) {
dropping_unfold_timer->start();
}
+ update();
} break;
case NOTIFICATION_MOUSE_EXIT: {
if (dropping) {
dropping_unfold_timer->stop();
}
+ update();
} break;
}
}
@@ -1395,6 +1414,8 @@ void EditorInspectorSection::gui_input(const Ref<InputEvent> &p_event) {
} else {
fold();
}
+ } else if (mb.is_valid() && !mb->is_pressed()) {
+ update();
}
}
diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h
index 5992c23f8c..b71efe8f19 100644
--- a/editor/editor_inspector.h
+++ b/editor/editor_inspector.h
@@ -123,6 +123,7 @@ protected:
virtual void gui_input(const Ref<InputEvent> &p_event) override;
virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override;
+ const Color *_get_property_colors();
public:
void emit_changed(const StringName &p_property, const Variant &p_value, const StringName &p_field = StringName(), bool p_changing = false);
diff --git a/editor/editor_log.cpp b/editor/editor_log.cpp
index 296a33d917..f91cb7f607 100644
--- a/editor/editor_log.cpp
+++ b/editor/editor_log.cpp
@@ -195,7 +195,7 @@ void EditorLog::add_message(const String &p_msg, MessageType p_type) {
// get grouped together and sent to the editor log as one message. This can mess with the
// search functionality (see the comments on the PR above for more details). This behaviour
// also matches that of other IDE's.
- Vector<String> lines = p_msg.split("\n", false);
+ Vector<String> lines = p_msg.split("\n", true);
for (int i = 0; i < lines.size(); i++) {
_process_message(lines[i], p_type);
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index f86a36df2f..812bbd9b7d 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -524,6 +524,26 @@ void EditorNode::_update_from_settings() {
RS::get_singleton()->light_projectors_set_filter(RS::LightProjectorFilter(int(GLOBAL_GET("rendering/textures/light_projectors/filter"))));
}
+void EditorNode::_select_default_main_screen_plugin() {
+ if (EDITOR_3D < main_editor_buttons.size() && main_editor_buttons[EDITOR_3D]->is_visible()) {
+ // If the 3D editor is enabled, use this as the default.
+ _editor_select(EDITOR_3D);
+ return;
+ }
+
+ // Switch to the first main screen plugin that is enabled. Usually this is
+ // 2D, but may be subsequent ones if 2D is disabled in the feature profile.
+ for (int i = 0; i < main_editor_buttons.size(); i++) {
+ Button *editor_button = main_editor_buttons[i];
+ if (editor_button->is_visible()) {
+ _editor_select(i);
+ return;
+ }
+ }
+
+ _editor_select(-1);
+}
+
void EditorNode::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_PROCESS: {
@@ -595,29 +615,12 @@ void EditorNode::_notification(int p_what) {
} break;
case NOTIFICATION_READY: {
- {
- _initializing_addons = true;
- Vector<String> addons;
- if (ProjectSettings::get_singleton()->has_setting("editor_plugins/enabled")) {
- addons = ProjectSettings::get_singleton()->get("editor_plugins/enabled");
- }
-
- for (int i = 0; i < addons.size(); i++) {
- set_addon_plugin_enabled(addons[i], true);
- }
- _initializing_addons = false;
- }
-
RenderingServer::get_singleton()->viewport_set_disable_2d(get_scene_root()->get_viewport_rid(), true);
RenderingServer::get_singleton()->viewport_set_disable_environment(get_viewport()->get_viewport_rid(), true);
feature_profile_manager->notify_changed();
- if (!main_editor_buttons[EDITOR_3D]->is_visible()) { //may be hidden due to feature profile
- _editor_select(EDITOR_2D);
- } else {
- _editor_select(EDITOR_3D);
- }
+ _select_default_main_screen_plugin();
// Save the project after opening to mark it as last modified, except in headless mode.
if (DisplayServer::get_singleton()->window_can_draw()) {
@@ -970,6 +973,18 @@ void EditorNode::_sources_changed(bool p_exist) {
load_scene(defer_load_scene);
defer_load_scene = "";
}
+
+ // Only enable addons once resources have been imported
+ _initializing_addons = true;
+ Vector<String> addons;
+ if (ProjectSettings::get_singleton()->has_setting("editor_plugins/enabled")) {
+ addons = ProjectSettings::get_singleton()->get("editor_plugins/enabled");
+ }
+
+ for (int i = 0; i < addons.size(); i++) {
+ set_addon_plugin_enabled(addons[i], true);
+ }
+ _initializing_addons = false;
}
}
@@ -1856,7 +1871,7 @@ void EditorNode::_dialog_action(String p_file) {
ml = Ref<MeshLibrary>(memnew(MeshLibrary));
}
- MeshLibraryEditor::update_library_file(editor_data.get_edited_scene_root(), ml, true);
+ MeshLibraryEditor::update_library_file(editor_data.get_edited_scene_root(), ml, true, file_export_lib_apply_xforms->is_pressed());
Error err = ResourceSaver::save(p_file, ml);
if (err) {
@@ -3100,9 +3115,10 @@ void EditorNode::add_editor_plugin(EditorPlugin *p_editor, bool p_config_changed
tb->set_flat(true);
tb->set_toggle_mode(true);
tb->connect("pressed", callable_mp(singleton, &EditorNode::_editor_select), varray(singleton->main_editor_buttons.size()));
+ tb->set_name(p_editor->get_name());
tb->set_text(p_editor->get_name());
- Ref<Texture2D> icon = p_editor->get_icon();
+ Ref<Texture2D> icon = p_editor->get_icon();
if (icon.is_valid()) {
tb->set_icon(icon);
} else if (singleton->gui_base->has_theme_icon(p_editor->get_name(), "EditorIcons")) {
@@ -3112,7 +3128,6 @@ void EditorNode::add_editor_plugin(EditorPlugin *p_editor, bool p_config_changed
tb->add_theme_font_override("font", singleton->gui_base->get_theme_font(SNAME("main_button_font"), SNAME("EditorFonts")));
tb->add_theme_font_size_override("font_size", singleton->gui_base->get_theme_font_size(SNAME("main_button_font_size"), SNAME("EditorFonts")));
- tb->set_name(p_editor->get_name());
singleton->main_editor_buttons.push_back(tb);
singleton->main_editor_button_vb->add_child(tb);
singleton->editor_table.push_back(p_editor);
@@ -6811,6 +6826,10 @@ EditorNode::EditorNode() {
file_export_lib_merge->set_text(TTR("Merge With Existing"));
file_export_lib_merge->set_pressed(true);
file_export_lib->get_vbox()->add_child(file_export_lib_merge);
+ file_export_lib_apply_xforms = memnew(CheckBox);
+ file_export_lib_apply_xforms->set_text(TTR("Apply MeshInstance Transforms"));
+ file_export_lib_apply_xforms->set_pressed(false);
+ file_export_lib->get_vbox()->add_child(file_export_lib_apply_xforms);
gui_base->add_child(file_export_lib);
file_script = memnew(EditorFileDialog);
diff --git a/editor/editor_node.h b/editor/editor_node.h
index 03c18a8972..2e8b850c7b 100644
--- a/editor/editor_node.h
+++ b/editor/editor_node.h
@@ -32,7 +32,6 @@
#define EDITOR_NODE_H
#include "core/templates/safe_refcount.h"
-#include "editor/editor_command_palette.h"
#include "editor/editor_data.h"
#include "editor/editor_export.h"
#include "editor/editor_folding.h"
@@ -335,6 +334,7 @@ private:
EditorFileDialog *file_script;
EditorFileDialog *file_android_build_source;
CheckBox *file_export_lib_merge;
+ CheckBox *file_export_lib_apply_xforms;
String current_path;
MenuButton *update_spinner;
@@ -681,6 +681,8 @@ private:
bool immediate_dialog_confirmed = false;
void _immediate_dialog_confirmed();
+ void _select_default_main_screen_plugin();
+
protected:
void _notification(int p_what);
diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp
index 73ea4fb5ef..5baffb6f9d 100644
--- a/editor/editor_plugin.cpp
+++ b/editor/editor_plugin.cpp
@@ -30,6 +30,7 @@
#include "editor_plugin.h"
+#include "editor/editor_command_palette.h"
#include "editor/editor_export.h"
#include "editor/editor_node.h"
#include "editor/editor_paths.h"
diff --git a/editor/editor_properties.cpp b/editor/editor_properties.cpp
index 1729705be5..c1e60e141c 100644
--- a/editor/editor_properties.cpp
+++ b/editor/editor_properties.cpp
@@ -1510,11 +1510,9 @@ void EditorPropertyVector2::update_property() {
void EditorPropertyVector2::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 2; i++) {
- Color c = base;
- c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i]);
}
}
}
@@ -1603,11 +1601,9 @@ void EditorPropertyRect2::update_property() {
void EditorPropertyRect2::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 4; i++) {
- Color c = base;
- c.set_hsv(float(i % 2) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i % 2]);
}
}
}
@@ -1731,11 +1727,9 @@ Vector3 EditorPropertyVector3::get_vector() {
void EditorPropertyVector3::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 3; i++) {
- Color c = base;
- c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i]);
}
}
}
@@ -1820,11 +1814,9 @@ void EditorPropertyVector2i::update_property() {
void EditorPropertyVector2i::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 2; i++) {
- Color c = base;
- c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i]);
}
}
}
@@ -1913,11 +1905,9 @@ void EditorPropertyRect2i::update_property() {
void EditorPropertyRect2i::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 4; i++) {
- Color c = base;
- c.set_hsv(float(i % 2) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i % 2]);
}
}
}
@@ -2014,11 +2004,9 @@ void EditorPropertyVector3i::update_property() {
void EditorPropertyVector3i::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 3; i++) {
- Color c = base;
- c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i]);
}
}
}
@@ -2106,11 +2094,9 @@ void EditorPropertyPlane::update_property() {
void EditorPropertyPlane::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
- for (int i = 0; i < 3; i++) {
- Color c = base;
- c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ const Color *colors = _get_property_colors();
+ for (int i = 0; i < 4; i++) {
+ spin[i]->set_custom_label_color(true, colors[i]);
}
}
}
@@ -2199,11 +2185,9 @@ void EditorPropertyQuaternion::update_property() {
void EditorPropertyQuaternion::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
- for (int i = 0; i < 3; i++) {
- Color c = base;
- c.set_hsv(float(i) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ const Color *colors = _get_property_colors();
+ for (int i = 0; i < 4; i++) {
+ spin[i]->set_custom_label_color(true, colors[i]);
}
}
}
@@ -2295,11 +2279,9 @@ void EditorPropertyAABB::update_property() {
void EditorPropertyAABB::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 6; i++) {
- Color c = base;
- c.set_hsv(float(i % 3) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i % 3]);
}
}
}
@@ -2354,10 +2336,10 @@ void EditorPropertyTransform2D::_value_changed(double val, const String &p_name)
Transform2D p;
p[0][0] = spin[0]->get_value();
- p[0][1] = spin[1]->get_value();
- p[1][0] = spin[2]->get_value();
- p[1][1] = spin[3]->get_value();
- p[2][0] = spin[4]->get_value();
+ p[1][0] = spin[1]->get_value();
+ p[2][0] = spin[2]->get_value();
+ p[0][1] = spin[3]->get_value();
+ p[1][1] = spin[4]->get_value();
p[2][1] = spin[5]->get_value();
emit_changed(get_edited_property(), p, p_name);
@@ -2367,10 +2349,10 @@ void EditorPropertyTransform2D::update_property() {
Transform2D val = get_edited_object()->get(get_edited_property());
setting = true;
spin[0]->set_value(val[0][0]);
- spin[1]->set_value(val[0][1]);
- spin[2]->set_value(val[1][0]);
- spin[3]->set_value(val[1][1]);
- spin[4]->set_value(val[2][0]);
+ spin[1]->set_value(val[1][0]);
+ spin[2]->set_value(val[2][0]);
+ spin[3]->set_value(val[0][1]);
+ spin[4]->set_value(val[1][1]);
spin[5]->set_value(val[2][1]);
setting = false;
@@ -2378,11 +2360,14 @@ void EditorPropertyTransform2D::update_property() {
void EditorPropertyTransform2D::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 6; i++) {
- Color c = base;
- c.set_hsv(float(i % 2) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ // For Transform2D, use the 4th color (cyan) for the origin vector.
+ if (i % 3 == 2) {
+ spin[i]->set_custom_label_color(true, colors[3]);
+ } else {
+ spin[i]->set_custom_label_color(true, colors[i % 3]);
+ }
}
}
}
@@ -2402,17 +2387,19 @@ void EditorPropertyTransform2D::setup(double p_min, double p_max, double p_step,
}
}
-EditorPropertyTransform2D::EditorPropertyTransform2D() {
+EditorPropertyTransform2D::EditorPropertyTransform2D(bool p_include_origin) {
GridContainer *g = memnew(GridContainer);
- g->set_columns(2);
+ g->set_columns(p_include_origin ? 3 : 2);
add_child(g);
- static const char *desc[6] = { "x", "y", "x", "y", "x", "y" };
+ static const char *desc[6] = { "xx", "xy", "xo", "yx", "yy", "yo" };
for (int i = 0; i < 6; i++) {
spin[i] = memnew(EditorSpinSlider);
spin[i]->set_label(desc[i]);
spin[i]->set_flat(true);
- g->add_child(spin[i]);
+ if (p_include_origin || i % 3 != 2) {
+ g->add_child(spin[i]);
+ }
spin[i]->set_h_size_flags(SIZE_EXPAND_FILL);
add_focusable(spin[i]);
spin[i]->connect("value_changed", callable_mp(this, &EditorPropertyTransform2D::_value_changed), varray(desc[i]));
@@ -2436,13 +2423,13 @@ void EditorPropertyBasis::_value_changed(double val, const String &p_name) {
Basis p;
p[0][0] = spin[0]->get_value();
- p[1][0] = spin[1]->get_value();
- p[2][0] = spin[2]->get_value();
- p[0][1] = spin[3]->get_value();
+ p[0][1] = spin[1]->get_value();
+ p[0][2] = spin[2]->get_value();
+ p[1][0] = spin[3]->get_value();
p[1][1] = spin[4]->get_value();
- p[2][1] = spin[5]->get_value();
- p[0][2] = spin[6]->get_value();
- p[1][2] = spin[7]->get_value();
+ p[1][2] = spin[5]->get_value();
+ p[2][0] = spin[6]->get_value();
+ p[2][1] = spin[7]->get_value();
p[2][2] = spin[8]->get_value();
emit_changed(get_edited_property(), p, p_name);
@@ -2452,13 +2439,13 @@ void EditorPropertyBasis::update_property() {
Basis val = get_edited_object()->get(get_edited_property());
setting = true;
spin[0]->set_value(val[0][0]);
- spin[1]->set_value(val[1][0]);
- spin[2]->set_value(val[2][0]);
- spin[3]->set_value(val[0][1]);
+ spin[1]->set_value(val[0][1]);
+ spin[2]->set_value(val[0][2]);
+ spin[3]->set_value(val[1][0]);
spin[4]->set_value(val[1][1]);
- spin[5]->set_value(val[2][1]);
- spin[6]->set_value(val[0][2]);
- spin[7]->set_value(val[1][2]);
+ spin[5]->set_value(val[1][2]);
+ spin[6]->set_value(val[2][0]);
+ spin[7]->set_value(val[2][1]);
spin[8]->set_value(val[2][2]);
setting = false;
@@ -2466,11 +2453,9 @@ void EditorPropertyBasis::update_property() {
void EditorPropertyBasis::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 9; i++) {
- Color c = base;
- c.set_hsv(float(i % 3) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i % 3]);
}
}
}
@@ -2495,7 +2480,7 @@ EditorPropertyBasis::EditorPropertyBasis() {
g->set_columns(3);
add_child(g);
- static const char *desc[9] = { "x", "y", "z", "x", "y", "z", "x", "y", "z" };
+ static const char *desc[9] = { "xx", "xy", "xz", "yx", "yy", "yz", "zx", "zy", "zz" };
for (int i = 0; i < 9; i++) {
spin[i] = memnew(EditorSpinSlider);
spin[i]->set_label(desc[i]);
@@ -2524,16 +2509,16 @@ void EditorPropertyTransform3D::_value_changed(double val, const String &p_name)
Transform3D p;
p.basis[0][0] = spin[0]->get_value();
- p.basis[1][0] = spin[1]->get_value();
- p.basis[2][0] = spin[2]->get_value();
- p.basis[0][1] = spin[3]->get_value();
- p.basis[1][1] = spin[4]->get_value();
- p.basis[2][1] = spin[5]->get_value();
- p.basis[0][2] = spin[6]->get_value();
- p.basis[1][2] = spin[7]->get_value();
- p.basis[2][2] = spin[8]->get_value();
- p.origin[0] = spin[9]->get_value();
- p.origin[1] = spin[10]->get_value();
+ p.basis[0][1] = spin[1]->get_value();
+ p.basis[0][2] = spin[2]->get_value();
+ p.origin[0] = spin[3]->get_value();
+ p.basis[1][0] = spin[4]->get_value();
+ p.basis[1][1] = spin[5]->get_value();
+ p.basis[1][2] = spin[6]->get_value();
+ p.origin[1] = spin[7]->get_value();
+ p.basis[2][0] = spin[8]->get_value();
+ p.basis[2][1] = spin[9]->get_value();
+ p.basis[2][2] = spin[10]->get_value();
p.origin[2] = spin[11]->get_value();
emit_changed(get_edited_property(), p, p_name);
@@ -2546,27 +2531,25 @@ void EditorPropertyTransform3D::update_property() {
void EditorPropertyTransform3D::update_using_transform(Transform3D p_transform) {
setting = true;
spin[0]->set_value(p_transform.basis[0][0]);
- spin[1]->set_value(p_transform.basis[1][0]);
- spin[2]->set_value(p_transform.basis[2][0]);
- spin[3]->set_value(p_transform.basis[0][1]);
- spin[4]->set_value(p_transform.basis[1][1]);
- spin[5]->set_value(p_transform.basis[2][1]);
- spin[6]->set_value(p_transform.basis[0][2]);
- spin[7]->set_value(p_transform.basis[1][2]);
- spin[8]->set_value(p_transform.basis[2][2]);
- spin[9]->set_value(p_transform.origin[0]);
- spin[10]->set_value(p_transform.origin[1]);
+ spin[1]->set_value(p_transform.basis[0][1]);
+ spin[2]->set_value(p_transform.basis[0][2]);
+ spin[3]->set_value(p_transform.origin[0]);
+ spin[4]->set_value(p_transform.basis[1][0]);
+ spin[5]->set_value(p_transform.basis[1][1]);
+ spin[6]->set_value(p_transform.basis[1][2]);
+ spin[7]->set_value(p_transform.origin[1]);
+ spin[8]->set_value(p_transform.basis[2][0]);
+ spin[9]->set_value(p_transform.basis[2][1]);
+ spin[10]->set_value(p_transform.basis[2][2]);
spin[11]->set_value(p_transform.origin[2]);
setting = false;
}
void EditorPropertyTransform3D::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- Color base = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
+ const Color *colors = _get_property_colors();
for (int i = 0; i < 12; i++) {
- Color c = base;
- c.set_hsv(float(i % 3) / 3.0 + 0.05, c.get_s() * 0.75, c.get_v());
- spin[i]->set_custom_label_color(true, c);
+ spin[i]->set_custom_label_color(true, colors[i % 4]);
}
}
}
@@ -2588,10 +2571,10 @@ void EditorPropertyTransform3D::setup(double p_min, double p_max, double p_step,
EditorPropertyTransform3D::EditorPropertyTransform3D() {
GridContainer *g = memnew(GridContainer);
- g->set_columns(3);
+ g->set_columns(4);
add_child(g);
- static const char *desc[12] = { "x", "y", "z", "x", "y", "z", "x", "y", "z", "x", "y", "z" };
+ static const char *desc[12] = { "xx", "xy", "xz", "xo", "yx", "yy", "yz", "yo", "zx", "zy", "zz", "zo" };
for (int i = 0; i < 12; i++) {
spin[i] = memnew(EditorSpinSlider);
spin[i]->set_label(desc[i]);
@@ -3448,7 +3431,6 @@ EditorProperty *EditorInspectorDefaultPlugin::get_editor_for_property(Object *p_
EditorPropertyRangeHint hint = _parse_range_hint(p_hint, p_hint_text, default_float_step);
editor->setup(hint.min, hint.max, hint.step, hint.hide_slider, hint.suffix);
return editor;
-
} break;
case Variant::PLANE: {
EditorPropertyPlane *editor = memnew(EditorPropertyPlane(p_wide));
diff --git a/editor/editor_properties.h b/editor/editor_properties.h
index cee5ab96a7..9a687f1a72 100644
--- a/editor/editor_properties.h
+++ b/editor/editor_properties.h
@@ -554,7 +554,7 @@ protected:
public:
virtual void update_property() override;
void setup(double p_min, double p_max, double p_step, bool p_no_slider, const String &p_suffix = String());
- EditorPropertyTransform2D();
+ EditorPropertyTransform2D(bool p_include_origin = true);
};
class EditorPropertyBasis : public EditorProperty {
diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp
index 8a08f4e450..6e5b94dc07 100644
--- a/editor/editor_themes.cpp
+++ b/editor/editor_themes.cpp
@@ -1154,8 +1154,10 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
theme->set_icon("increment", "HScrollBar", empty_icon);
theme->set_icon("increment_highlight", "HScrollBar", empty_icon);
+ theme->set_icon("increment_pressed", "HScrollBar", empty_icon);
theme->set_icon("decrement", "HScrollBar", empty_icon);
theme->set_icon("decrement_highlight", "HScrollBar", empty_icon);
+ theme->set_icon("decrement_pressed", "HScrollBar", empty_icon);
// VScrollBar
theme->set_stylebox("scroll", "VScrollBar", make_stylebox(theme->get_icon("GuiScrollBg", "EditorIcons"), 5, 5, 5, 5, 0, 0, 0, 0));
@@ -1166,8 +1168,10 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
theme->set_icon("increment", "VScrollBar", empty_icon);
theme->set_icon("increment_highlight", "VScrollBar", empty_icon);
+ theme->set_icon("increment_pressed", "VScrollBar", empty_icon);
theme->set_icon("decrement", "VScrollBar", empty_icon);
theme->set_icon("decrement_highlight", "VScrollBar", empty_icon);
+ theme->set_icon("decrement_pressed", "VScrollBar", empty_icon);
// HSlider
theme->set_icon("grabber_highlight", "HSlider", theme->get_icon("GuiSliderGrabberHl", "EditorIcons"));
diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp
index daee61c2dd..5dd5c050e0 100644
--- a/editor/filesystem_dock.cpp
+++ b/editor/filesystem_dock.cpp
@@ -2158,6 +2158,14 @@ bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_da
return true;
}
+ if (drag_data.has("type") && String(drag_data["type"]) == "nodes") {
+ // Save branch as scene.
+ String to_dir;
+ bool favorite;
+ _get_drag_target_folder(to_dir, favorite, p_point, p_from);
+ return !favorite && Array(drag_data["nodes"]).size() == 1;
+ }
+
return false;
}
@@ -2296,6 +2304,13 @@ void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data,
_update_tree(_compute_uncollapsed_paths());
}
}
+
+ if (drag_data.has("type") && String(drag_data["type"]) == "nodes") {
+ String to_dir;
+ bool favorite;
+ _get_drag_target_folder(to_dir, favorite, p_point, p_from);
+ EditorNode::get_singleton()->get_scene_tree_dock()->save_branch_to_file(to_dir);
+ }
}
void FileSystemDock::_get_drag_target_folder(String &target, bool &target_favorites, const Point2 &p_point, Control *p_from) const {
diff --git a/editor/icons/Listener2D.svg b/editor/icons/Listener2D.svg
new file mode 100644
index 0000000000..db84dcfed7
--- /dev/null
+++ b/editor/icons/Listener2D.svg
@@ -0,0 +1 @@
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m6 1a5 5 0 0 0 -5 5h2a3 3 0 0 1 3-3 3 3 0 0 1 3 3c0 1.75-.54175 2.3583-1.1406 2.8574-.29944.2495-.62954.44071-.97656.69141-.17351.1253-.35729.26529-.53711.49219-.17982.227-.3457.58398-.3457.95898 0 1.2778-.31632 1.5742-.63867 1.7676-.32236.1934-.86133.23242-1.3613.23242h-1v2h1c.5 0 1.461.038922 2.3887-.51758.87316-.5239 1.4826-1.6633 1.5566-3.2266.011365-.0098.027247-.024684.10938-.083984.21547-.1556.63537-.40194 1.0859-.77734.90112-.751 1.8594-2.1445 1.8594-4.3945a5 5 0 0 0 -5-5zm7.9277 1-1.7383 1.0039a6 6 0 0 1 .81055 2.9961 6 6 0 0 1 -.80859 2.998l1.7363 1.002a8 8 0 0 0 0-8z" fill="#a5b7f3"/></svg>
diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp
index 84cb1f7325..753dcb1275 100644
--- a/editor/import/resource_importer_scene.cpp
+++ b/editor/import/resource_importer_scene.cpp
@@ -233,13 +233,14 @@ static String _fixstr(const String &p_what, const String &p_str) {
return what;
}
-static void _pre_gen_shape_list(const Ref<EditorSceneImporterMesh> &mesh, List<Ref<Shape3D>> &r_shape_list, bool p_convex) {
+static void _pre_gen_shape_list(Ref<EditorSceneImporterMesh> &mesh, Vector<Ref<Shape3D>> &r_shape_list, bool p_convex) {
ERR_FAIL_NULL_MSG(mesh, "Cannot generate shape list with null mesh value");
if (!p_convex) {
Ref<Shape3D> shape = mesh->create_trimesh_shape();
r_shape_list.push_back(shape);
} else {
- Vector<Ref<Shape3D>> cd = mesh->convex_decompose();
+ Vector<Ref<Shape3D>> cd;
+ cd.push_back(mesh->get_mesh()->create_convex_shape(true, /*Passing false, otherwise VHACD will be used to simplify (Decompose) the Mesh.*/ false));
if (cd.size()) {
for (int i = 0; i < cd.size(); i++) {
r_shape_list.push_back(cd[i]);
@@ -248,7 +249,7 @@ static void _pre_gen_shape_list(const Ref<EditorSceneImporterMesh> &mesh, List<R
}
}
-Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, List<Ref<Shape3D>>> &collision_map) {
+Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map) {
// children first
for (int i = 0; i < p_node->get_child_count(); i++) {
Node *r = _pre_fix_node(p_node->get_child(i), p_root, collision_map);
@@ -335,7 +336,7 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E
Ref<EditorSceneImporterMesh> mesh = mi->get_mesh();
if (mesh.is_valid()) {
- List<Ref<Shape3D>> shapes;
+ Vector<Ref<Shape3D>> shapes;
String fixed_name;
if (collision_map.has(mesh)) {
shapes = collision_map[mesh];
@@ -406,7 +407,7 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E
Ref<EditorSceneImporterMesh> mesh = mi->get_mesh();
if (mesh.is_valid()) {
- List<Ref<Shape3D>> shapes;
+ Vector<Ref<Shape3D>> shapes;
if (collision_map.has(mesh)) {
shapes = collision_map[mesh];
} else {
@@ -431,7 +432,7 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E
Ref<EditorSceneImporterMesh> mesh = mi->get_mesh();
if (mesh.is_valid()) {
- List<Ref<Shape3D>> shapes;
+ Vector<Ref<Shape3D>> shapes;
String fixed_name;
if (collision_map.has(mesh)) {
shapes = collision_map[mesh];
@@ -490,7 +491,7 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E
Ref<EditorSceneImporterMesh> mesh = mi->get_mesh();
if (!mesh.is_null()) {
- List<Ref<Shape3D>> shapes;
+ Vector<Ref<Shape3D>> shapes;
if (collision_map.has(mesh)) {
shapes = collision_map[mesh];
} else if (_teststr(mesh->get_name(), "col")) {
@@ -516,7 +517,7 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<E
return p_node;
}
-Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, List<Ref<Shape3D>>> &collision_map, Set<Ref<EditorSceneImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps) {
+Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map, Set<Ref<EditorSceneImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps) {
// children first
for (int i = 0; i < p_node->get_child_count(); i++) {
Node *r = _post_fix_node(p_node->get_child(i), p_root, collision_map, r_scanned_meshes, p_node_data, p_material_data, p_animation_data, p_animation_fps);
@@ -579,28 +580,35 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<
}
if (node_settings.has("generate/physics")) {
- int mesh_physics_mode = node_settings["generate/physics"];
-
- if (mesh_physics_mode != MESH_PHYSICS_DISABLED) {
- List<Ref<Shape3D>> shapes;
+ int mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_DISABLED;
+
+ const bool generate_collider = node_settings["generate/physics"];
+ if (generate_collider) {
+ mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_MESH_AND_STATIC_COLLIDER;
+ if (node_settings.has("physics/body_type")) {
+ const BodyType body_type = (BodyType)node_settings["physics/body_type"].operator int();
+ switch (body_type) {
+ case BODY_TYPE_STATIC:
+ mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_MESH_AND_STATIC_COLLIDER;
+ break;
+ case BODY_TYPE_DYNAMIC:
+ mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_RIGID_BODY_AND_MESH;
+ break;
+ case BODY_TYPE_AREA:
+ mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_AREA_ONLY;
+ break;
+ }
+ }
+ }
+ if (mesh_physics_mode != MeshPhysicsMode::MESH_PHYSICS_DISABLED) {
+ Vector<Ref<Shape3D>> shapes;
if (collision_map.has(m)) {
shapes = collision_map[m];
} else {
- switch (mesh_physics_mode) {
- case MESH_PHYSICS_MESH_AND_STATIC_COLLIDER: {
- _pre_gen_shape_list(m, shapes, false);
- } break;
- case MESH_PHYSICS_RIGID_BODY_AND_MESH: {
- _pre_gen_shape_list(m, shapes, true);
- } break;
- case MESH_PHYSICS_STATIC_COLLIDER_ONLY: {
- _pre_gen_shape_list(m, shapes, false);
- } break;
- case MESH_PHYSICS_AREA_ONLY: {
- _pre_gen_shape_list(m, shapes, true);
- } break;
- }
+ shapes = get_collision_shapes(
+ m->get_mesh(),
+ node_settings);
}
if (shapes.size()) {
@@ -609,13 +617,15 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<
case MESH_PHYSICS_MESH_AND_STATIC_COLLIDER: {
StaticBody3D *col = memnew(StaticBody3D);
p_node->add_child(col);
+ col->set_owner(p_node->get_owner());
+ col->set_transform(get_collision_shapes_transform(node_settings));
base = col;
} break;
case MESH_PHYSICS_RIGID_BODY_AND_MESH: {
RigidBody3D *rigid_body = memnew(RigidBody3D);
rigid_body->set_name(p_node->get_name());
p_node->replace_by(rigid_body);
- rigid_body->set_transform(mi->get_transform());
+ rigid_body->set_transform(mi->get_transform() * get_collision_shapes_transform(node_settings));
p_node = rigid_body;
mi->set_transform(Transform3D());
rigid_body->add_child(mi);
@@ -624,7 +634,7 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<
} break;
case MESH_PHYSICS_STATIC_COLLIDER_ONLY: {
StaticBody3D *col = memnew(StaticBody3D);
- col->set_transform(mi->get_transform());
+ col->set_transform(mi->get_transform() * get_collision_shapes_transform(node_settings));
col->set_name(p_node->get_name());
p_node->replace_by(col);
memdelete(p_node);
@@ -633,7 +643,7 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref<
} break;
case MESH_PHYSICS_AREA_ONLY: {
Area3D *area = memnew(Area3D);
- area->set_transform(mi->get_transform());
+ area->set_transform(mi->get_transform() * get_collision_shapes_transform(node_settings));
area->set_name(p_node->get_name());
p_node->replace_by(area);
memdelete(p_node);
@@ -933,8 +943,35 @@ void ResourceImporterScene::get_internal_import_options(InternalImportCategory p
} break;
case INTERNAL_IMPORT_CATEGORY_MESH_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));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/physics", PROPERTY_HINT_ENUM, "Disabled,Mesh + Static Collider,Rigid Body + Mesh,Static Collider Only,Area Only"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate/physics", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/navmesh", PROPERTY_HINT_ENUM, "Disabled,Mesh + NavMesh,NavMesh Only"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "physics/body_type", PROPERTY_HINT_ENUM, "Static,Dynamic,Area"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "physics/shape_type", PROPERTY_HINT_ENUM, "Decompose Convex,Simple Convex,Trimesh,Box,Sphere,Cylinder,Capsule", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
+
+ // Decomposition
+ Mesh::ConvexDecompositionSettings decomposition_default;
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/advanced", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/precision", PROPERTY_HINT_RANGE, "1,10,1"), 5));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/max_concavity", PROPERTY_HINT_RANGE, "0.0,1.0,0.001", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.max_concavity));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/symmetry_planes_clipping_bias", PROPERTY_HINT_RANGE, "0.0,1.0,0.001", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.symmetry_planes_clipping_bias));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/revolution_axes_clipping_bias", PROPERTY_HINT_RANGE, "0.0,1.0,0.001", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.revolution_axes_clipping_bias));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/min_volume_per_convex_hull", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.min_volume_per_convex_hull));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/resolution", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.resolution));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/max_num_vertices_per_convex_hull", PROPERTY_HINT_RANGE, "5,512,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.max_num_vertices_per_convex_hull));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/plane_downsampling", PROPERTY_HINT_RANGE, "1,16,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.plane_downsampling));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/convexhull_downsampling", PROPERTY_HINT_RANGE, "1,16,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.convexhull_downsampling));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/normalize_mesh", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.normalize_mesh));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/mode", PROPERTY_HINT_ENUM, "Voxel,Tetrahedron", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), static_cast<int>(decomposition_default.mode)));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/convexhull_approximation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.convexhull_approximation));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/max_convex_hulls", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.max_convex_hulls));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/project_hull_vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default.project_hull_vertices));
+
+ // Primitives: Box, Sphere, Cylinder, Capsule.
+ r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3(2.0, 2.0, 2.0)));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "primitive/height", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1.0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "primitive/radius", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1.0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3()));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3()));
} break;
case INTERNAL_IMPORT_CATEGORY_MESH: {
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));
@@ -985,6 +1022,65 @@ bool ResourceImporterScene::get_internal_option_visibility(InternalImportCategor
case INTERNAL_IMPORT_CATEGORY_NODE: {
} break;
case INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE: {
+ const bool generate_physics =
+ p_options.has("generate/physics") &&
+ p_options["generate/physics"].operator bool();
+
+ if (
+ p_option == "physics/body_type" ||
+ p_option == "physics/shape_type") {
+ // Show if need to generate collisions.
+ return generate_physics;
+ }
+
+ if (p_option.find("decomposition/") >= 0) {
+ // Show if need to generate collisions.
+ if (generate_physics &&
+ // Show if convex is enabled.
+ p_options["physics/shape_type"] == Variant(SHAPE_TYPE_DECOMPOSE_CONVEX)) {
+ if (p_option == "decomposition/advanced") {
+ return true;
+ }
+
+ const bool decomposition_advanced =
+ p_options.has("decomposition/advanced") &&
+ p_options["decomposition/advanced"].operator bool();
+
+ if (p_option == "decomposition/precision") {
+ return !decomposition_advanced;
+ } else {
+ return decomposition_advanced;
+ }
+ }
+
+ return false;
+ }
+
+ if (p_option == "primitive/position" || p_option == "primitive/rotation") {
+ const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
+ return generate_physics &&
+ physics_shape >= SHAPE_TYPE_BOX;
+ }
+
+ if (p_option == "primitive/size") {
+ const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
+ return generate_physics &&
+ physics_shape == SHAPE_TYPE_BOX;
+ }
+
+ if (p_option == "primitive/radius") {
+ const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
+ return generate_physics && (physics_shape == SHAPE_TYPE_SPHERE ||
+ physics_shape == SHAPE_TYPE_CYLINDER ||
+ physics_shape == SHAPE_TYPE_CAPSULE);
+ }
+
+ if (p_option == "primitive/height") {
+ const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
+ return generate_physics &&
+ (physics_shape == SHAPE_TYPE_CYLINDER ||
+ physics_shape == SHAPE_TYPE_CAPSULE);
+ }
} break;
case INTERNAL_IMPORT_CATEGORY_MESH: {
if (p_option == "save_to_file/path" || p_option == "save_to_file/make_streamable") {
@@ -1021,6 +1117,33 @@ bool ResourceImporterScene::get_internal_option_visibility(InternalImportCategor
return true;
}
+bool ResourceImporterScene::get_internal_option_update_view_required(InternalImportCategory p_category, const String &p_option, const Map<StringName, Variant> &p_options) const {
+ switch (p_category) {
+ case INTERNAL_IMPORT_CATEGORY_NODE: {
+ } break;
+ case INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE: {
+ if (
+ p_option == "generate/physics" ||
+ p_option == "physics/shape_type" ||
+ p_option.find("decomposition/") >= 0 ||
+ p_option.find("primitive/") >= 0) {
+ return true;
+ }
+ } break;
+ case INTERNAL_IMPORT_CATEGORY_MESH: {
+ } break;
+ case INTERNAL_IMPORT_CATEGORY_MATERIAL: {
+ } break;
+ case INTERNAL_IMPORT_CATEGORY_ANIMATION: {
+ } break;
+ case INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE: {
+ } break;
+ default: {
+ }
+ }
+ return false;
+}
+
void ResourceImporterScene::get_import_options(List<ImportOption> *r_options, int p_preset) const {
r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_type", PROPERTY_HINT_TYPE_STRING, "Node"), "Node3D"));
r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_name"), "Scene Root"));
@@ -1275,7 +1398,7 @@ void ResourceImporterScene::_generate_meshes(Node *p_node, const Dictionary &p_m
}
}
-void ResourceImporterScene::_add_shapes(Node *p_node, const List<Ref<Shape3D>> &p_shapes) {
+void ResourceImporterScene::_add_shapes(Node *p_node, const Vector<Ref<Shape3D>> &p_shapes) {
for (const Ref<Shape3D> &E : p_shapes) {
CollisionShape3D *cshape = memnew(CollisionShape3D);
cshape->set_shape(E);
@@ -1316,7 +1439,7 @@ Node *ResourceImporterScene::pre_import(const String &p_source_file) {
return nullptr;
}
- Map<Ref<EditorSceneImporterMesh>, List<Ref<Shape3D>>> collision_map;
+ Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> collision_map;
_pre_fix_node(scene, scene, collision_map);
@@ -1392,7 +1515,7 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p
}
Set<Ref<EditorSceneImporterMesh>> scanned_meshes;
- Map<Ref<EditorSceneImporterMesh>, List<Ref<Shape3D>>> collision_map;
+ Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> collision_map;
_pre_fix_node(scene, scene, collision_map);
_post_fix_node(scene, scene, collision_map, scanned_meshes, node_data, material_data, animation_data, fps);
diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h
index 542959be02..e232b715be 100644
--- a/editor/import/resource_importer_scene.h
+++ b/editor/import/resource_importer_scene.h
@@ -63,7 +63,6 @@ public:
IMPORT_FAIL_ON_MISSING_DEPENDENCIES = 4,
IMPORT_GENERATE_TANGENT_ARRAYS = 8,
IMPORT_USE_NAMED_SKIN_BINDS = 16,
-
};
virtual uint32_t get_import_flags() const;
@@ -125,9 +124,25 @@ class ResourceImporterScene : public ResourceImporter {
MESH_OVERRIDE_DISABLE,
};
+ enum BodyType {
+ BODY_TYPE_STATIC,
+ BODY_TYPE_DYNAMIC,
+ BODY_TYPE_AREA
+ };
+
+ enum ShapeType {
+ SHAPE_TYPE_DECOMPOSE_CONVEX,
+ SHAPE_TYPE_SIMPLE_CONVEX,
+ SHAPE_TYPE_TRIMESH,
+ SHAPE_TYPE_BOX,
+ SHAPE_TYPE_SPHERE,
+ SHAPE_TYPE_CYLINDER,
+ SHAPE_TYPE_CAPSULE,
+ };
+
void _replace_owner(Node *p_node, Node *p_scene, Node *p_new_owner);
void _generate_meshes(Node *p_node, const Dictionary &p_mesh_data, bool p_generate_lods, bool p_create_shadow_meshes, LightBakeMode p_light_bake_mode, float p_lightmap_texel_size, const Vector<uint8_t> &p_src_lightmap_cache, Vector<Vector<uint8_t>> &r_lightmap_caches);
- void _add_shapes(Node *p_node, const List<Ref<Shape3D>> &p_shapes);
+ void _add_shapes(Node *p_node, const Vector<Ref<Shape3D>> &p_shapes);
public:
static ResourceImporterScene *get_singleton() { return singleton; }
@@ -159,14 +174,15 @@ public:
void get_internal_import_options(InternalImportCategory p_category, List<ImportOption> *r_options) const;
bool get_internal_option_visibility(InternalImportCategory p_category, const String &p_option, const Map<StringName, Variant> &p_options) const;
+ bool get_internal_option_update_view_required(InternalImportCategory p_category, const String &p_option, const Map<StringName, Variant> &p_options) const;
virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const override;
virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const override;
// Import scenes *after* everything else (such as textures).
virtual int get_import_order() const override { return ResourceImporter::IMPORT_ORDER_SCENE; }
- Node *_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, List<Ref<Shape3D>>> &collision_map);
- Node *_post_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, List<Ref<Shape3D>>> &collision_map, Set<Ref<EditorSceneImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps);
+ Node *_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map);
+ Node *_post_fix_node(Node *p_node, Node *p_root, Map<Ref<EditorSceneImporterMesh>, Vector<Ref<Shape3D>>> &collision_map, Set<Ref<EditorSceneImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps);
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);
@@ -184,6 +200,12 @@ public:
virtual bool can_import_threaded() const override { return false; }
ResourceImporterScene();
+
+ template <class M>
+ static Vector<Ref<Shape3D>> get_collision_shapes(const Ref<Mesh> &p_mesh, const M &p_options);
+
+ template <class M>
+ static Transform3D get_collision_shapes_transform(const M &p_options);
};
class EditorSceneImporterESCN : public EditorSceneImporter {
@@ -196,4 +218,176 @@ public:
virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) override;
};
+#include "scene/resources/box_shape_3d.h"
+#include "scene/resources/capsule_shape_3d.h"
+#include "scene/resources/cylinder_shape_3d.h"
+#include "scene/resources/sphere_shape_3d.h"
+
+template <class M>
+Vector<Ref<Shape3D>> ResourceImporterScene::get_collision_shapes(const Ref<Mesh> &p_mesh, const M &p_options) {
+ ShapeType generate_shape_type = SHAPE_TYPE_DECOMPOSE_CONVEX;
+ if (p_options.has(SNAME("physics/shape_type"))) {
+ generate_shape_type = (ShapeType)p_options[SNAME("physics/shape_type")].operator int();
+ }
+
+ if (generate_shape_type == SHAPE_TYPE_DECOMPOSE_CONVEX) {
+ Mesh::ConvexDecompositionSettings decomposition_settings;
+ bool advanced = false;
+ if (p_options.has(SNAME("decomposition/advanced"))) {
+ advanced = p_options[SNAME("decomposition/advanced")];
+ }
+
+ if (advanced) {
+ if (p_options.has(SNAME("decomposition/max_concavity"))) {
+ decomposition_settings.max_concavity = p_options[SNAME("decomposition/max_concavity")];
+ }
+
+ if (p_options.has(SNAME("decomposition/symmetry_planes_clipping_bias"))) {
+ decomposition_settings.symmetry_planes_clipping_bias = p_options[SNAME("decomposition/symmetry_planes_clipping_bias")];
+ }
+
+ if (p_options.has(SNAME("decomposition/revolution_axes_clipping_bias"))) {
+ decomposition_settings.revolution_axes_clipping_bias = p_options[SNAME("decomposition/revolution_axes_clipping_bias")];
+ }
+
+ if (p_options.has(SNAME("decomposition/min_volume_per_convex_hull"))) {
+ decomposition_settings.min_volume_per_convex_hull = p_options[SNAME("decomposition/min_volume_per_convex_hull")];
+ }
+
+ if (p_options.has(SNAME("decomposition/resolution"))) {
+ decomposition_settings.resolution = p_options[SNAME("decomposition/resolution")];
+ }
+
+ if (p_options.has(SNAME("decomposition/max_num_vertices_per_convex_hull"))) {
+ decomposition_settings.max_num_vertices_per_convex_hull = p_options[SNAME("decomposition/max_num_vertices_per_convex_hull")];
+ }
+
+ if (p_options.has(SNAME("decomposition/plane_downsampling"))) {
+ decomposition_settings.plane_downsampling = p_options[SNAME("decomposition/plane_downsampling")];
+ }
+
+ if (p_options.has(SNAME("decomposition/convexhull_downsampling"))) {
+ decomposition_settings.convexhull_downsampling = p_options[SNAME("decomposition/convexhull_downsampling")];
+ }
+
+ if (p_options.has(SNAME("decomposition/normalize_mesh"))) {
+ decomposition_settings.normalize_mesh = p_options[SNAME("decomposition/normalize_mesh")];
+ }
+
+ if (p_options.has(SNAME("decomposition/mode"))) {
+ decomposition_settings.mode = (Mesh::ConvexDecompositionSettings::Mode)p_options[SNAME("decomposition/mode")].operator int();
+ }
+
+ if (p_options.has(SNAME("decomposition/convexhull_approximation"))) {
+ decomposition_settings.convexhull_approximation = p_options[SNAME("decomposition/convexhull_approximation")];
+ }
+
+ if (p_options.has(SNAME("decomposition/max_convex_hulls"))) {
+ decomposition_settings.max_convex_hulls = p_options[SNAME("decomposition/max_convex_hulls")];
+ }
+
+ if (p_options.has(SNAME("decomposition/project_hull_vertices"))) {
+ decomposition_settings.project_hull_vertices = p_options[SNAME("decomposition/project_hull_vertices")];
+ }
+ } else {
+ int precision_level = 5;
+ if (p_options.has(SNAME("decomposition/precision"))) {
+ precision_level = p_options[SNAME("decomposition/precision")];
+ }
+
+ const real_t precision = real_t(precision_level - 1) / 9.0;
+
+ decomposition_settings.max_concavity = Math::lerp(real_t(1.0), real_t(0.001), precision);
+ decomposition_settings.min_volume_per_convex_hull = Math::lerp(real_t(0.01), real_t(0.0001), precision);
+ decomposition_settings.resolution = Math::lerp(10'000, 100'000, precision);
+ decomposition_settings.max_num_vertices_per_convex_hull = Math::lerp(32, 64, precision);
+ decomposition_settings.plane_downsampling = Math::lerp(3, 16, precision);
+ decomposition_settings.convexhull_downsampling = Math::lerp(3, 16, precision);
+ decomposition_settings.max_convex_hulls = Math::lerp(1, 32, precision);
+ }
+
+ return p_mesh->convex_decompose(decomposition_settings);
+ } else if (generate_shape_type == SHAPE_TYPE_SIMPLE_CONVEX) {
+ Vector<Ref<Shape3D>> shapes;
+ shapes.push_back(p_mesh->create_convex_shape(true, /*Passing false, otherwise VHACD will be used to simplify (Decompose) the Mesh.*/ false));
+ return shapes;
+ } else if (generate_shape_type == SHAPE_TYPE_TRIMESH) {
+ Vector<Ref<Shape3D>> shapes;
+ shapes.push_back(p_mesh->create_trimesh_shape());
+ return shapes;
+ } else if (generate_shape_type == SHAPE_TYPE_BOX) {
+ Ref<BoxShape3D> box;
+ box.instantiate();
+ if (p_options.has(SNAME("primitive/size"))) {
+ box->set_size(p_options[SNAME("primitive/size")]);
+ }
+
+ Vector<Ref<Shape3D>> shapes;
+ shapes.push_back(box);
+ return shapes;
+
+ } else if (generate_shape_type == SHAPE_TYPE_SPHERE) {
+ Ref<SphereShape3D> sphere;
+ sphere.instantiate();
+ if (p_options.has(SNAME("primitive/radius"))) {
+ sphere->set_radius(p_options[SNAME("primitive/radius")]);
+ }
+
+ Vector<Ref<Shape3D>> shapes;
+ shapes.push_back(sphere);
+ return shapes;
+ } else if (generate_shape_type == SHAPE_TYPE_CYLINDER) {
+ Ref<CylinderShape3D> cylinder;
+ cylinder.instantiate();
+ if (p_options.has(SNAME("primitive/height"))) {
+ cylinder->set_height(p_options[SNAME("primitive/height")]);
+ }
+ if (p_options.has(SNAME("primitive/radius"))) {
+ cylinder->set_radius(p_options[SNAME("primitive/radius")]);
+ }
+
+ Vector<Ref<Shape3D>> shapes;
+ shapes.push_back(cylinder);
+ return shapes;
+ } else if (generate_shape_type == SHAPE_TYPE_CAPSULE) {
+ Ref<CapsuleShape3D> capsule;
+ capsule.instantiate();
+ if (p_options.has(SNAME("primitive/height"))) {
+ capsule->set_height(p_options[SNAME("primitive/height")]);
+ }
+ if (p_options.has(SNAME("primitive/radius"))) {
+ capsule->set_radius(p_options[SNAME("primitive/radius")]);
+ }
+
+ Vector<Ref<Shape3D>> shapes;
+ shapes.push_back(capsule);
+ return shapes;
+ }
+ return Vector<Ref<Shape3D>>();
+}
+
+template <class M>
+Transform3D ResourceImporterScene::get_collision_shapes_transform(const M &p_options) {
+ Transform3D transform;
+
+ ShapeType generate_shape_type = SHAPE_TYPE_DECOMPOSE_CONVEX;
+ if (p_options.has(SNAME("physics/shape_type"))) {
+ generate_shape_type = (ShapeType)p_options[SNAME("physics/shape_type")].operator int();
+ }
+
+ if (generate_shape_type == SHAPE_TYPE_BOX ||
+ generate_shape_type == SHAPE_TYPE_SPHERE ||
+ generate_shape_type == SHAPE_TYPE_CYLINDER ||
+ generate_shape_type == SHAPE_TYPE_CAPSULE) {
+ if (p_options.has(SNAME("primitive/position"))) {
+ transform.origin = p_options[SNAME("primitive/position")];
+ }
+
+ if (p_options.has(SNAME("primitive/rotation"))) {
+ transform.basis.set_euler((p_options[SNAME("primitive/rotation")].operator Vector3() / 180.0) * Math_PI);
+ }
+ }
+ return transform;
+}
+
#endif // RESOURCEIMPORTERSCENE_H
diff --git a/editor/import/scene_import_settings.cpp b/editor/import/scene_import_settings.cpp
index 19a8f209bb..4bcb6863fb 100644
--- a/editor/import/scene_import_settings.cpp
+++ b/editor/import/scene_import_settings.cpp
@@ -53,6 +53,11 @@ class SceneImportSettingsData : public Object {
}
current[p_name] = p_value;
+
+ if (ResourceImporterScene::get_singleton()->get_internal_option_update_view_required(category, p_name, current)) {
+ SceneImportSettings::get_singleton()->update_view();
+ }
+
return true;
}
return false;
@@ -317,6 +322,13 @@ void SceneImportSettings::_fill_scene(Node *p_node, TreeItem *p_parent_item) {
if (mesh_node && mesh_node->get_mesh().is_valid()) {
_fill_mesh(scene_tree, mesh_node->get_mesh(), item);
+ // Add the collider view.
+ MeshInstance3D *collider_view = memnew(MeshInstance3D);
+ collider_view->set_name("collider_view");
+ collider_view->set_visible(false);
+ mesh_node->add_child(collider_view);
+ collider_view->set_owner(mesh_node);
+
Transform3D accum_xform;
Node3D *base = mesh_node;
while (base) {
@@ -346,6 +358,54 @@ void SceneImportSettings::_update_scene() {
_fill_scene(scene, nullptr);
}
+void SceneImportSettings::_update_view_gizmos() {
+ for (const KeyValue<String, NodeData> &e : node_map) {
+ bool generate_collider = false;
+ if (e.value.settings.has(SNAME("generate/physics"))) {
+ generate_collider = e.value.settings[SNAME("generate/physics")];
+ }
+
+ MeshInstance3D *mesh_node = Object::cast_to<MeshInstance3D>(e.value.node);
+ if (mesh_node == nullptr || mesh_node->get_mesh().is_null()) {
+ // Nothing to do
+ continue;
+ }
+
+ MeshInstance3D *collider_view = static_cast<MeshInstance3D *>(mesh_node->find_node("collider_view"));
+ CRASH_COND_MSG(collider_view == nullptr, "This is unreachable, since the collider view is always created even when the collision is not used! If this is triggered there is a bug on the function `_fill_scene`.");
+
+ collider_view->set_visible(generate_collider);
+ if (generate_collider) {
+ // This collider_view doesn't have a mesh so we need to generate a new one.
+
+ // Generate the mesh collider.
+ Vector<Ref<Shape3D>> shapes = ResourceImporterScene::get_collision_shapes(mesh_node->get_mesh(), e.value.settings);
+ const Transform3D transform = ResourceImporterScene::get_collision_shapes_transform(e.value.settings);
+
+ Ref<ArrayMesh> collider_view_mesh;
+ collider_view_mesh.instantiate();
+ for (Ref<Shape3D> shape : shapes) {
+ Ref<ArrayMesh> debug_shape_mesh;
+ if (shape.is_valid()) {
+ debug_shape_mesh = shape->get_debug_mesh();
+ }
+ if (debug_shape_mesh.is_valid()) {
+ collider_view_mesh->add_surface_from_arrays(
+ debug_shape_mesh->surface_get_primitive_type(0),
+ debug_shape_mesh->surface_get_arrays(0));
+
+ collider_view_mesh->surface_set_material(
+ collider_view_mesh->get_surface_count() - 1,
+ collider_mat);
+ }
+ }
+
+ collider_view->set_mesh(collider_view_mesh);
+ collider_view->set_transform(transform);
+ }
+ }
+}
+
void SceneImportSettings::_update_camera() {
AABB camera_aabb;
@@ -404,11 +464,16 @@ void SceneImportSettings::_load_default_subresource_settings(Map<StringName, Var
}
}
+void SceneImportSettings::update_view() {
+ _update_view_gizmos();
+}
+
void SceneImportSettings::open_settings(const String &p_path) {
if (scene) {
memdelete(scene);
scene = nullptr;
}
+ scene_import_settings_data->settings = nullptr;
scene = ResourceImporterScene::get_singleton()->pre_import(p_path);
if (scene == nullptr) {
EditorNode::get_singleton()->show_warning(TTR("Error opening scene"));
@@ -463,6 +528,7 @@ void SceneImportSettings::open_settings(const String &p_path) {
}
popup_centered_ratio();
+ _update_view_gizmos();
_update_camera();
set_title(vformat(TTR("Advanced Import Settings for '%s'"), base_path.get_file()));
@@ -629,6 +695,7 @@ void SceneImportSettings::_material_tree_selected() {
_select(material_tree, type, import_id);
}
+
void SceneImportSettings::_mesh_tree_selected() {
if (selecting) {
return;
@@ -640,6 +707,7 @@ void SceneImportSettings::_mesh_tree_selected() {
_select(mesh_tree, type, import_id);
}
+
void SceneImportSettings::_scene_tree_selected() {
if (selecting) {
return;
@@ -1144,6 +1212,12 @@ SceneImportSettings::SceneImportSettings() {
material_preview.instantiate();
}
+ {
+ collider_mat.instantiate();
+ collider_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
+ collider_mat->set_albedo(Color(0.5, 0.5, 1.0));
+ }
+
inspector = memnew(EditorInspector);
inspector->set_custom_minimum_size(Size2(300 * EDSCALE, 0));
diff --git a/editor/import/scene_import_settings.h b/editor/import/scene_import_settings.h
index ddcf4a6d5d..c7c94af493 100644
--- a/editor/import/scene_import_settings.h
+++ b/editor/import/scene_import_settings.h
@@ -84,6 +84,8 @@ class SceneImportSettings : public ConfirmationDialog {
MeshInstance3D *mesh_preview;
Ref<SphereMesh> material_preview;
+ Ref<StandardMaterial3D> collider_mat;
+
float cam_rot_x;
float cam_rot_y;
float cam_zoom;
@@ -145,6 +147,7 @@ class SceneImportSettings : public ConfirmationDialog {
bool selecting = false;
+ void _update_view_gizmos();
void _update_camera();
void _select(Tree *p_from, String p_type, String p_id);
void _material_tree_selected();
@@ -190,6 +193,7 @@ protected:
void _notification(int p_what);
public:
+ void update_view();
void open_settings(const String &p_path);
static SceneImportSettings *get_singleton();
SceneImportSettings();
diff --git a/editor/import/scene_importer_mesh.cpp b/editor/import/scene_importer_mesh.cpp
index 06f373c54f..5e6dd08e79 100644
--- a/editor/import/scene_importer_mesh.cpp
+++ b/editor/import/scene_importer_mesh.cpp
@@ -33,6 +33,8 @@
#include "core/math/math_defs.h"
#include "scene/resources/surface_tool.h"
+#include <cstdint>
+
void EditorSceneImporterMesh::add_blend_shape(const String &p_name) {
ERR_FAIL_COND(surfaces.size() > 0);
blend_shapes.push_back(p_name);
@@ -55,13 +57,14 @@ Mesh::BlendShapeMode EditorSceneImporterMesh::get_blend_shape_mode() const {
return blend_shape_mode;
}
-void EditorSceneImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_name) {
+void EditorSceneImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_name, const uint32_t p_flags) {
ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);
Surface s;
s.primitive = p_primitive;
s.arrays = p_arrays;
s.name = p_name;
+ s.flags = p_flags;
Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];
int vertex_count = vertex_array.size();
@@ -138,6 +141,11 @@ float EditorSceneImporterMesh::get_surface_lod_size(int p_surface, int p_lod) co
return surfaces[p_surface].lods[p_lod].distance;
}
+uint32_t EditorSceneImporterMesh::get_surface_format(int p_surface) const {
+ ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
+ return surfaces[p_surface].flags;
+}
+
Ref<Material> EditorSceneImporterMesh::get_surface_material(int p_surface) const {
ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());
return surfaces[p_surface].material;
@@ -283,7 +291,7 @@ Ref<ArrayMesh> EditorSceneImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {
}
}
- mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods);
+ mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);
if (surfaces[i].material.is_valid()) {
mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
}
@@ -398,7 +406,7 @@ void EditorSceneImporterMesh::create_shadow_mesh() {
}
}
- shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name);
+ shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);
}
}
@@ -436,7 +444,11 @@ void EditorSceneImporterMesh::_set_data(const Dictionary &p_data) {
if (s.has("material")) {
material = s["material"];
}
- add_surface(prim, arr, blend_shapes, lods, material, name);
+ uint32_t flags = 0;
+ if (s.has("flags")) {
+ flags = s["flags"];
+ }
+ add_surface(prim, arr, blend_shapes, lods, material, name, flags);
}
}
}
@@ -473,6 +485,10 @@ Dictionary EditorSceneImporterMesh::_get_data() const {
d["name"] = surfaces[i].name;
}
+ if (surfaces[i].flags != 0) {
+ d["flags"] = surfaces[i].flags;
+ }
+
surface_arr.push_back(d);
}
data["surfaces"] = surface_arr;
@@ -508,36 +524,47 @@ Vector<Face3> EditorSceneImporterMesh::get_faces() const {
return faces;
}
-Vector<Ref<Shape3D>> EditorSceneImporterMesh::convex_decompose() const {
- ERR_FAIL_COND_V(!Mesh::convex_composition_function, Vector<Ref<Shape3D>>());
+Vector<Ref<Shape3D>> EditorSceneImporterMesh::convex_decompose(const Mesh::ConvexDecompositionSettings &p_settings) const {
+ ERR_FAIL_COND_V(!Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());
const Vector<Face3> faces = get_faces();
+ int face_count = faces.size();
+
+ Vector<Vector3> vertices;
+ uint32_t vertex_count = 0;
+ vertices.resize(face_count * 3);
+ Vector<uint32_t> indices;
+ indices.resize(face_count * 3);
+ {
+ Map<Vector3, uint32_t> vertex_map;
+ Vector3 *vertex_w = vertices.ptrw();
+ uint32_t *index_w = indices.ptrw();
+ for (int i = 0; i < face_count; i++) {
+ for (int j = 0; j < 3; j++) {
+ const Vector3 &vertex = faces[i].vertex[j];
+ Map<Vector3, uint32_t>::Element *found_vertex = vertex_map.find(vertex);
+ uint32_t index;
+ if (found_vertex) {
+ index = found_vertex->get();
+ } else {
+ index = ++vertex_count;
+ vertex_map[vertex] = index;
+ vertex_w[index] = vertex;
+ }
+ index_w[i * 3 + j] = index;
+ }
+ }
+ }
+ vertices.resize(vertex_count);
- Vector<Vector<Face3>> decomposed = Mesh::convex_composition_function(faces, -1);
+ Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);
Vector<Ref<Shape3D>> ret;
for (int i = 0; i < decomposed.size(); i++) {
- Set<Vector3> points;
- for (int j = 0; j < decomposed[i].size(); j++) {
- points.insert(decomposed[i][j].vertex[0]);
- points.insert(decomposed[i][j].vertex[1]);
- points.insert(decomposed[i][j].vertex[2]);
- }
-
- Vector<Vector3> convex_points;
- convex_points.resize(points.size());
- {
- Vector3 *w = convex_points.ptrw();
- int idx = 0;
- for (Set<Vector3>::Element *E = points.front(); E; E = E->next()) {
- w[idx++] = E->get();
- }
- }
-
Ref<ConvexPolygonShape3D> shape;
shape.instantiate();
- shape->set_points(convex_points);
+ shape->set_points(decomposed[i]);
ret.push_back(shape);
}
@@ -833,7 +860,7 @@ void EditorSceneImporterMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &EditorSceneImporterMesh::set_blend_shape_mode);
ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &EditorSceneImporterMesh::get_blend_shape_mode);
- ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name"), &EditorSceneImporterMesh::add_surface, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()));
+ ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name", "flags"), &EditorSceneImporterMesh::add_surface, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()), DEFVAL(0));
ClassDB::bind_method(D_METHOD("get_surface_count"), &EditorSceneImporterMesh::get_surface_count);
ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &EditorSceneImporterMesh::get_surface_primitive_type);
@@ -844,6 +871,7 @@ void EditorSceneImporterMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &EditorSceneImporterMesh::get_surface_lod_size);
ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &EditorSceneImporterMesh::get_surface_lod_indices);
ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &EditorSceneImporterMesh::get_surface_material);
+ ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &EditorSceneImporterMesh::get_surface_format);
ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &EditorSceneImporterMesh::set_surface_name);
ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &EditorSceneImporterMesh::set_surface_material);
diff --git a/editor/import/scene_importer_mesh.h b/editor/import/scene_importer_mesh.h
index e57e479d8e..d32b1fdf74 100644
--- a/editor/import/scene_importer_mesh.h
+++ b/editor/import/scene_importer_mesh.h
@@ -36,6 +36,9 @@
#include "scene/resources/convex_polygon_shape_3d.h"
#include "scene/resources/mesh.h"
#include "scene/resources/navigation_mesh.h"
+
+#include <cstdint>
+
// The following classes are used by importers instead of ArrayMesh and MeshInstance3D
// so the data is not registered (hence, quality loss), importing happens faster and
// its easier to modify before saving
@@ -57,6 +60,7 @@ class EditorSceneImporterMesh : public Resource {
Vector<LOD> lods;
Ref<Material> material;
String name;
+ uint32_t flags = 0;
};
Vector<Surface> surfaces;
Vector<String> blend_shapes;
@@ -80,7 +84,7 @@ public:
int get_blend_shape_count() const;
String get_blend_shape_name(int p_blend_shape) const;
- void add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), const Dictionary &p_lods = Dictionary(), const Ref<Material> &p_material = Ref<Material>(), const String &p_name = String());
+ void add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), const Dictionary &p_lods = Dictionary(), const Ref<Material> &p_material = Ref<Material>(), const String &p_name = String(), const uint32_t p_flags = 0);
int get_surface_count() const;
void set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode);
@@ -95,6 +99,7 @@ public:
Vector<int> get_surface_lod_indices(int p_surface, int p_lod) const;
float get_surface_lod_size(int p_surface, int p_lod) const;
Ref<Material> get_surface_material(int p_surface) const;
+ uint32_t get_surface_format(int p_surface) const;
void set_surface_material(int p_surface, const Ref<Material> &p_material);
@@ -104,7 +109,7 @@ public:
Ref<EditorSceneImporterMesh> get_shadow_mesh() const;
Vector<Face3> get_faces() const;
- Vector<Ref<Shape3D>> convex_decompose() const;
+ Vector<Ref<Shape3D>> convex_decompose(const Mesh::ConvexDecompositionSettings &p_settings) const;
Ref<Shape3D> create_trimesh_shape() const;
Ref<NavigationMesh> create_navigation_mesh();
Error lightmap_unwrap_cached(const Transform3D &p_base_transform, float p_texel_size, const Vector<uint8_t> &p_src_cache, Vector<uint8_t> &r_dst_cache);
diff --git a/editor/multi_node_edit.cpp b/editor/multi_node_edit.cpp
index fd4a4334fc..1e707c1a60 100644
--- a/editor/multi_node_edit.cpp
+++ b/editor/multi_node_edit.cpp
@@ -49,6 +49,11 @@ bool MultiNodeEdit::_set_impl(const StringName &p_name, const Variant &p_value,
name = "script";
}
+ Node *node_path_target = nullptr;
+ if (p_value.get_type() == Variant::NODE_PATH && p_value != NodePath()) {
+ node_path_target = es->get_node(p_value);
+ }
+
UndoRedo *ur = EditorNode::get_undo_redo();
ur->create_action(TTR("MultiNode Set") + " " + String(name), UndoRedo::MERGE_ENDS);
@@ -63,9 +68,11 @@ bool MultiNodeEdit::_set_impl(const StringName &p_name, const Variant &p_value,
}
if (p_value.get_type() == Variant::NODE_PATH) {
- Node *tonode = n->get_node(p_value);
- NodePath p_path = n->get_path_to(tonode);
- ur->add_do_property(n, name, p_path);
+ NodePath path;
+ if (node_path_target) {
+ path = n->get_path_to(node_path_target);
+ }
+ ur->add_do_property(n, name, path);
} else {
Variant new_value;
if (p_field == "") {
diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp
index 830b010d01..18b4966f80 100644
--- a/editor/plugins/animation_player_editor_plugin.cpp
+++ b/editor/plugins/animation_player_editor_plugin.cpp
@@ -904,7 +904,7 @@ void AnimationPlayerEditor::edit(AnimationPlayer *p_player) {
}
}
-void AnimationPlayerEditor::forward_canvas_force_draw_over_viewport(Control *p_overlay) {
+void AnimationPlayerEditor::forward_force_draw_over_viewport(Control *p_overlay) {
if (!onion.can_overlay) {
return;
}
diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h
index be80b7f4e3..0a514d3ff1 100644
--- a/editor/plugins/animation_player_editor_plugin.h
+++ b/editor/plugins/animation_player_editor_plugin.h
@@ -238,7 +238,7 @@ public:
void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
void edit(AnimationPlayer *p_player);
- void forward_canvas_force_draw_over_viewport(Control *p_overlay);
+ void forward_force_draw_over_viewport(Control *p_overlay);
AnimationPlayerEditor(EditorNode *p_editor, AnimationPlayerEditorPlugin *p_plugin);
};
@@ -262,7 +262,8 @@ public:
virtual bool handles(Object *p_object) const override;
virtual void make_visible(bool p_visible) override;
- virtual void forward_canvas_force_draw_over_viewport(Control *p_overlay) override { anim_editor->forward_canvas_force_draw_over_viewport(p_overlay); }
+ virtual void forward_canvas_force_draw_over_viewport(Control *p_overlay) override { anim_editor->forward_force_draw_over_viewport(p_overlay); }
+ virtual void forward_spatial_force_draw_over_viewport(Control *p_overlay) override { anim_editor->forward_force_draw_over_viewport(p_overlay); }
AnimationPlayerEditorPlugin(EditorNode *p_node);
~AnimationPlayerEditorPlugin();
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index d96cc1cd18..f11e51960c 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -5204,7 +5204,9 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
snap_rotation = false;
snap_scale = false;
snap_relative = false;
- snap_pixel = false;
+ // Enable pixel snapping even if pixel snap rendering is disabled in the Project Settings.
+ // This results in crisper visuals by preventing 2D nodes from being placed at subpixel coordinates.
+ snap_pixel = true;
snap_target[0] = SNAP_TARGET_NONE;
snap_target[1] = SNAP_TARGET_NONE;
diff --git a/editor/plugins/mesh_instance_3d_editor_plugin.cpp b/editor/plugins/mesh_instance_3d_editor_plugin.cpp
index 9a2b222f21..574d3ef27e 100644
--- a/editor/plugins/mesh_instance_3d_editor_plugin.cpp
+++ b/editor/plugins/mesh_instance_3d_editor_plugin.cpp
@@ -202,7 +202,8 @@ void MeshInstance3DEditor::_menu_option(int p_option) {
return;
}
- Vector<Ref<Shape3D>> shapes = mesh->convex_decompose();
+ Mesh::ConvexDecompositionSettings settings;
+ Vector<Ref<Shape3D>> shapes = mesh->convex_decompose(settings);
if (!shapes.size()) {
err_dialog->set_text(TTR("Couldn't create any collision shapes."));
diff --git a/editor/plugins/mesh_library_editor_plugin.cpp b/editor/plugins/mesh_library_editor_plugin.cpp
index b3f92c9d95..18e7480287 100644
--- a/editor/plugins/mesh_library_editor_plugin.cpp
+++ b/editor/plugins/mesh_library_editor_plugin.cpp
@@ -47,23 +47,25 @@ void MeshLibraryEditor::edit(const Ref<MeshLibrary> &p_mesh_library) {
}
}
-void MeshLibraryEditor::_menu_confirm() {
+void MeshLibraryEditor::_menu_remove_confirm() {
switch (option) {
case MENU_OPTION_REMOVE_ITEM: {
mesh_library->remove_item(to_erase);
} break;
- case MENU_OPTION_UPDATE_FROM_SCENE: {
- String existing = mesh_library->get_meta("_editor_source_scene");
- ERR_FAIL_COND(existing == "");
- _import_scene_cbk(existing);
-
- } break;
default: {
};
}
}
-void MeshLibraryEditor::_import_scene(Node *p_scene, Ref<MeshLibrary> p_library, bool p_merge) {
+void MeshLibraryEditor::_menu_update_confirm(bool p_apply_xforms) {
+ cd_update->hide();
+ apply_xforms = p_apply_xforms;
+ String existing = mesh_library->get_meta("_editor_source_scene");
+ ERR_FAIL_COND(existing == "");
+ _import_scene_cbk(existing);
+}
+
+void MeshLibraryEditor::_import_scene(Node *p_scene, Ref<MeshLibrary> p_library, bool p_merge, bool p_apply_xforms) {
if (!p_merge) {
p_library->clear();
}
@@ -108,6 +110,13 @@ void MeshLibraryEditor::_import_scene(Node *p_scene, Ref<MeshLibrary> p_library,
}
p_library->set_item_mesh(id, mesh);
+
+ if (p_apply_xforms) {
+ p_library->set_item_mesh_transform(id, mi->get_transform());
+ } else {
+ p_library->set_item_mesh_transform(id, Transform3D());
+ }
+
mesh_instances[id] = mi;
Vector<MeshLibrary::ShapeData> collisions;
@@ -197,15 +206,16 @@ void MeshLibraryEditor::_import_scene_cbk(const String &p_str) {
ERR_FAIL_COND_MSG(!scene, "Cannot create an instance from PackedScene '" + p_str + "'.");
- _import_scene(scene, mesh_library, option == MENU_OPTION_UPDATE_FROM_SCENE);
+ _import_scene(scene, mesh_library, option == MENU_OPTION_UPDATE_FROM_SCENE, apply_xforms);
memdelete(scene);
mesh_library->set_meta("_editor_source_scene", p_str);
+
menu->get_popup()->set_item_disabled(menu->get_popup()->get_item_index(MENU_OPTION_UPDATE_FROM_SCENE), false);
}
-Error MeshLibraryEditor::update_library_file(Node *p_base_scene, Ref<MeshLibrary> ml, bool p_merge) {
- _import_scene(p_base_scene, ml, p_merge);
+Error MeshLibraryEditor::update_library_file(Node *p_base_scene, Ref<MeshLibrary> ml, bool p_merge, bool p_apply_xforms) {
+ _import_scene(p_base_scene, ml, p_merge, p_apply_xforms);
return OK;
}
@@ -219,16 +229,21 @@ void MeshLibraryEditor::_menu_cbk(int p_option) {
String p = editor->get_inspector()->get_selected_path();
if (p.begins_with("/MeshLibrary/item") && p.get_slice_count("/") >= 3) {
to_erase = p.get_slice("/", 3).to_int();
- cd->set_text(vformat(TTR("Remove item %d?"), to_erase));
- cd->popup_centered(Size2(300, 60));
+ cd_remove->set_text(vformat(TTR("Remove item %d?"), to_erase));
+ cd_remove->popup_centered(Size2(300, 60));
}
} break;
case MENU_OPTION_IMPORT_FROM_SCENE: {
+ apply_xforms = false;
+ file->popup_file_dialog();
+ } break;
+ case MENU_OPTION_IMPORT_FROM_SCENE_APPLY_XFORMS: {
+ apply_xforms = true;
file->popup_file_dialog();
} break;
case MENU_OPTION_UPDATE_FROM_SCENE: {
- cd->set_text(vformat(TTR("Update from existing scene?:\n%s"), String(mesh_library->get_meta("_editor_source_scene"))));
- cd->popup_centered(Size2(500, 60));
+ cd_update->set_text(vformat(TTR("Update from existing scene?:\n%s"), String(mesh_library->get_meta("_editor_source_scene"))));
+ cd_update->popup_centered(Size2(500, 60));
} break;
}
}
@@ -258,16 +273,22 @@ MeshLibraryEditor::MeshLibraryEditor(EditorNode *p_editor) {
menu->get_popup()->add_item(TTR("Add Item"), MENU_OPTION_ADD_ITEM);
menu->get_popup()->add_item(TTR("Remove Selected Item"), MENU_OPTION_REMOVE_ITEM);
menu->get_popup()->add_separator();
- menu->get_popup()->add_item(TTR("Import from Scene"), MENU_OPTION_IMPORT_FROM_SCENE);
+ menu->get_popup()->add_item(TTR("Import from Scene (Ignore Transforms)"), MENU_OPTION_IMPORT_FROM_SCENE);
+ menu->get_popup()->add_item(TTR("Import from Scene (Apply Transforms)"), MENU_OPTION_IMPORT_FROM_SCENE_APPLY_XFORMS);
menu->get_popup()->add_item(TTR("Update from Scene"), MENU_OPTION_UPDATE_FROM_SCENE);
menu->get_popup()->set_item_disabled(menu->get_popup()->get_item_index(MENU_OPTION_UPDATE_FROM_SCENE), true);
menu->get_popup()->connect("id_pressed", callable_mp(this, &MeshLibraryEditor::_menu_cbk));
menu->hide();
editor = p_editor;
- cd = memnew(ConfirmationDialog);
- add_child(cd);
- cd->get_ok_button()->connect("pressed", callable_mp(this, &MeshLibraryEditor::_menu_confirm));
+ cd_remove = memnew(ConfirmationDialog);
+ add_child(cd_remove);
+ cd_remove->get_ok_button()->connect("pressed", callable_mp(this, &MeshLibraryEditor::_menu_remove_confirm));
+ cd_update = memnew(ConfirmationDialog);
+ add_child(cd_update);
+ cd_update->get_ok_button()->set_text("Apply without Transforms");
+ cd_update->get_ok_button()->connect("pressed", callable_mp(this, &MeshLibraryEditor::_menu_update_confirm), varray(false));
+ cd_update->add_button("Apply with Transforms")->connect("pressed", callable_mp(this, &MeshLibraryEditor::_menu_update_confirm), varray(true));
}
void MeshLibraryEditorPlugin::edit(Object *p_node) {
diff --git a/editor/plugins/mesh_library_editor_plugin.h b/editor/plugins/mesh_library_editor_plugin.h
index 6c33c8bb9e..9e225ffb9b 100644
--- a/editor/plugins/mesh_library_editor_plugin.h
+++ b/editor/plugins/mesh_library_editor_plugin.h
@@ -41,23 +41,27 @@ class MeshLibraryEditor : public Control {
EditorNode *editor;
MenuButton *menu;
- ConfirmationDialog *cd;
+ ConfirmationDialog *cd_remove;
+ ConfirmationDialog *cd_update;
EditorFileDialog *file;
+ bool apply_xforms;
int to_erase;
enum {
MENU_OPTION_ADD_ITEM,
MENU_OPTION_REMOVE_ITEM,
MENU_OPTION_UPDATE_FROM_SCENE,
- MENU_OPTION_IMPORT_FROM_SCENE
+ MENU_OPTION_IMPORT_FROM_SCENE,
+ MENU_OPTION_IMPORT_FROM_SCENE_APPLY_XFORMS
};
int option;
void _import_scene_cbk(const String &p_str);
void _menu_cbk(int p_option);
- void _menu_confirm();
+ void _menu_remove_confirm();
+ void _menu_update_confirm(bool p_apply_xforms);
- static void _import_scene(Node *p_scene, Ref<MeshLibrary> p_library, bool p_merge);
+ static void _import_scene(Node *p_scene, Ref<MeshLibrary> p_library, bool p_merge, bool p_apply_xforms);
protected:
static void _bind_methods();
@@ -66,7 +70,7 @@ public:
MenuButton *get_menu_button() const { return menu; }
void edit(const Ref<MeshLibrary> &p_mesh_library);
- static Error update_library_file(Node *p_base_scene, Ref<MeshLibrary> ml, bool p_merge = true);
+ static Error update_library_file(Node *p_base_scene, Ref<MeshLibrary> ml, bool p_merge = true, bool p_apply_xforms = false);
MeshLibraryEditor(EditorNode *p_editor);
};
diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp
index 291cafab2b..be5d756444 100644
--- a/editor/plugins/node_3d_editor_plugin.cpp
+++ b/editor/plugins/node_3d_editor_plugin.cpp
@@ -1831,6 +1831,8 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
motion = Vector3(scale, scale, scale);
}
+ motion /= click.distance_to(_edit.center);
+
// Disable local transformation for TRANSFORM_VIEW
bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
diff --git a/editor/plugins/packed_scene_translation_parser_plugin.cpp b/editor/plugins/packed_scene_translation_parser_plugin.cpp
index 0a949c8610..53c5b8dd70 100644
--- a/editor/plugins/packed_scene_translation_parser_plugin.cpp
+++ b/editor/plugins/packed_scene_translation_parser_plugin.cpp
@@ -31,6 +31,7 @@
#include "packed_scene_translation_parser_plugin.h"
#include "core/io/resource_loader.h"
+#include "scene/gui/option_button.h"
#include "scene/resources/packed_scene.h"
void PackedSceneEditorTranslationParserPlugin::get_recognized_extensions(List<String> *r_extensions) const {
@@ -50,21 +51,31 @@ Error PackedSceneEditorTranslationParserPlugin::parse_file(const String &p_path,
Ref<SceneState> state = Ref<PackedScene>(loaded_res)->get_state();
Vector<String> parsed_strings;
- String property_name;
- Variant property_value;
for (int i = 0; i < state->get_node_count(); i++) {
- if (!ClassDB::is_parent_class(state->get_node_type(i), "Control") && !ClassDB::is_parent_class(state->get_node_type(i), "Viewport")) {
+ String node_type = state->get_node_type(i);
+ if (!ClassDB::is_parent_class(node_type, "Control") && !ClassDB::is_parent_class(node_type, "Window")) {
continue;
}
+ // Find the `auto_translate` property, and abort the string parsing of the node if disabled.
+ bool auto_translating = true;
for (int j = 0; j < state->get_node_property_count(i); j++) {
- property_name = state->get_node_property_name(i, j);
- if (!lookup_properties.has(property_name)) {
- continue;
+ if (state->get_node_property_name(i, j) == "auto_translate" && (bool)state->get_node_property_value(i, j) == false) {
+ auto_translating = false;
+ break;
}
+ }
+ if (!auto_translating) {
+ continue;
+ }
- property_value = state->get_node_property_value(i, j);
+ for (int j = 0; j < state->get_node_property_count(i); j++) {
+ String property_name = state->get_node_property_name(i, j);
+ if (!lookup_properties.has(property_name) || (exception_list.has(node_type) && exception_list[node_type].has(property_name))) {
+ continue;
+ }
+ Variant property_value = state->get_node_property_value(i, j);
if (property_name == "script" && property_value.get_type() == Variant::OBJECT && !property_value.is_null()) {
// Parse built-in script.
Ref<Script> s = Object::cast_to<Script>(property_value);
@@ -76,7 +87,16 @@ Error PackedSceneEditorTranslationParserPlugin::parse_file(const String &p_path,
parsed_strings.append_array(temp);
r_ids_ctx_plural->append_array(ids_context_plural);
}
- } else if (property_name == "filters") {
+ } else if ((node_type == "MenuButton" || node_type == "OptionButton") && property_name == "items") {
+ Vector<String> str_values = property_value;
+ int incr_value = node_type == "MenuButton" ? PopupMenu::ITEM_PROPERTY_SIZE : OptionButton::ITEM_PROPERTY_SIZE;
+ for (int k = 0; k < str_values.size(); k += incr_value) {
+ String desc = str_values[k].get_slice(";", 1).strip_edges();
+ if (!desc.is_empty()) {
+ parsed_strings.push_back(desc);
+ }
+ }
+ } else if (node_type == "FileDialog" && property_name == "filters") {
// Extract FileDialog's filters property with values in format "*.png ; PNG Images","*.gd ; GDScript Files".
Vector<String> str_values = property_value;
for (int k = 0; k < str_values.size(); k++) {
@@ -105,12 +125,17 @@ PackedSceneEditorTranslationParserPlugin::PackedSceneEditorTranslationParserPlug
lookup_properties.insert("text");
lookup_properties.insert("hint_tooltip");
lookup_properties.insert("placeholder_text");
+ lookup_properties.insert("items");
+ lookup_properties.insert("title");
lookup_properties.insert("dialog_text");
lookup_properties.insert("filters");
lookup_properties.insert("script");
- //Add exception list (to prevent false positives)
- //line edit, text edit, richtextlabel
- //Set<String> exception_list;
- //exception_list.insert("RichTextLabel");
+ // Exception list (to prevent false positives).
+ exception_list.insert("LineEdit", Vector<StringName>());
+ exception_list["LineEdit"].append("text");
+ exception_list.insert("TextEdit", Vector<StringName>());
+ exception_list["TextEdit"].append("text");
+ exception_list.insert("CodeEdit", Vector<StringName>());
+ exception_list["CodeEdit"].append("text");
}
diff --git a/editor/plugins/packed_scene_translation_parser_plugin.h b/editor/plugins/packed_scene_translation_parser_plugin.h
index e51d65414e..af0291b69c 100644
--- a/editor/plugins/packed_scene_translation_parser_plugin.h
+++ b/editor/plugins/packed_scene_translation_parser_plugin.h
@@ -37,7 +37,9 @@ class PackedSceneEditorTranslationParserPlugin : public EditorTranslationParserP
GDCLASS(PackedSceneEditorTranslationParserPlugin, EditorTranslationParserPlugin);
// Scene Node's properties that contain translation strings.
- Set<String> lookup_properties;
+ Set<StringName> lookup_properties;
+ // Properties from specific Nodes that should be ignored.
+ Map<StringName, Vector<StringName>> exception_list;
public:
virtual Error parse_file(const String &p_path, Vector<String> *r_ids, Vector<Vector<String>> *r_ids_ctx_plural) override;
diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp
index 48239a5d99..89d91cc079 100644
--- a/editor/plugins/script_text_editor.cpp
+++ b/editor/plugins/script_text_editor.cpp
@@ -1242,7 +1242,7 @@ void ScriptTextEditor::_edit_option(int p_op) {
tx->set_caret_line(bpoints[bpoints.size() - 1]);
tx->center_viewport_to_caret();
} else {
- for (int i = bpoints.size(); i >= 0; i--) {
+ for (int i = bpoints.size() - 1; i >= 0; i--) {
int bline = bpoints[i];
if (bline < line) {
tx->unfold_line(bline);
diff --git a/editor/plugins/skeleton_2d_editor_plugin.cpp b/editor/plugins/skeleton_2d_editor_plugin.cpp
index 7ef680d7ef..c350004f0f 100644
--- a/editor/plugins/skeleton_2d_editor_plugin.cpp
+++ b/editor/plugins/skeleton_2d_editor_plugin.cpp
@@ -98,9 +98,10 @@ Skeleton2DEditor::Skeleton2DEditor() {
options->set_text(TTR("Skeleton2D"));
options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Skeleton2D"), SNAME("EditorIcons")));
- options->get_popup()->add_item(TTR("Make Rest Pose (From Bones)"), MENU_OPTION_MAKE_REST);
+ options->get_popup()->add_item(TTR("Reset to Rest Pose"), MENU_OPTION_MAKE_REST);
options->get_popup()->add_separator();
- options->get_popup()->add_item(TTR("Set Bones to Rest Pose"), MENU_OPTION_SET_REST);
+ // Use the "Overwrite" word to highlight that this is a destructive operation.
+ options->get_popup()->add_item(TTR("Overwrite Rest Pose"), MENU_OPTION_SET_REST);
options->set_switch_on_hover(true);
options->get_popup()->connect("id_pressed", callable_mp(this, &Skeleton2DEditor::_menu_option));
diff --git a/editor/plugins/tiles/tile_atlas_view.cpp b/editor/plugins/tiles/tile_atlas_view.cpp
index 0add83f64d..6e0a5b00b9 100644
--- a/editor/plugins/tiles/tile_atlas_view.cpp
+++ b/editor/plugins/tiles/tile_atlas_view.cpp
@@ -327,10 +327,12 @@ void TileAtlasView::_draw_base_tiles_shape_grid() {
Vector2i tile_id = tile_set_atlas_source->get_tile_id(i);
Vector2 in_tile_base_offset = tile_set_atlas_source->get_tile_effective_texture_offset(tile_id, 0);
Rect2i texture_region = tile_set_atlas_source->get_tile_texture_region(tile_id);
- Vector2 origin = texture_region.position + (texture_region.size - tile_shape_size) / 2 + in_tile_base_offset;
// Draw only if the tile shape fits in the texture region
- tile_set->draw_tile_shape(base_tiles_shape_grid, Rect2(origin, tile_shape_size), grid_color);
+ Transform2D tile_xform;
+ tile_xform.set_origin(texture_region.position + texture_region.size / 2 + in_tile_base_offset);
+ tile_xform.set_scale(tile_shape_size);
+ tile_set->draw_tile_shape(base_tiles_shape_grid, tile_xform, grid_color);
}
}
diff --git a/editor/plugins/tiles/tile_data_editors.cpp b/editor/plugins/tiles/tile_data_editors.cpp
index fd5c59af34..2a75a743a7 100644
--- a/editor/plugins/tiles/tile_data_editors.cpp
+++ b/editor/plugins/tiles/tile_data_editors.cpp
@@ -124,7 +124,9 @@ void GenericTilePolygonEditor::_base_control_draw() {
base_control->draw_set_transform_matrix(xform);
// Draw the tile shape filled.
- tile_set->draw_tile_shape(base_control, Rect2(-tile_size / 2, tile_size), Color(1.0, 1.0, 1.0, 0.3), true);
+ Transform2D tile_xform;
+ tile_xform.set_scale(tile_size);
+ tile_set->draw_tile_shape(base_control, tile_xform, Color(1.0, 1.0, 1.0, 0.3), true);
// Draw the background.
if (background_texture.is_valid()) {
@@ -213,7 +215,7 @@ void GenericTilePolygonEditor::_base_control_draw() {
// Draw the tile shape line.
base_control->draw_set_transform_matrix(xform);
- tile_set->draw_tile_shape(base_control, Rect2(-tile_size / 2, tile_size), grid_color, false);
+ tile_set->draw_tile_shape(base_control, tile_xform, grid_color, false);
base_control->draw_set_transform_matrix(Transform2D());
}
@@ -1072,14 +1074,15 @@ void TileDataTextureOffsetEditor::draw_over_tile(CanvasItem *p_canvas_item, Tran
ERR_FAIL_COND(!tile_data);
Vector2i tile_set_tile_size = tile_set->get_tile_size();
- Rect2i rect = Rect2i(-tile_set_tile_size / 2, tile_set_tile_size);
Color color = Color(1.0, 0.0, 0.0);
if (p_selected) {
Color grid_color = EditorSettings::get_singleton()->get("editors/tiles_editor/grid_color");
Color selection_color = Color().from_hsv(Math::fposmod(grid_color.get_h() + 0.5, 1.0), grid_color.get_s(), grid_color.get_v(), 1.0);
color = selection_color;
}
- tile_set->draw_tile_shape(p_canvas_item, p_transform.xform(rect), color);
+ Transform2D tile_xform;
+ tile_xform.set_scale(tile_set_tile_size);
+ tile_set->draw_tile_shape(p_canvas_item, p_transform * tile_xform, color);
}
void TileDataPositionEditor::draw_over_tile(CanvasItem *p_canvas_item, Transform2D p_transform, TileMapCell p_cell, bool p_selected) {
@@ -1514,9 +1517,10 @@ void TileDataTerrainsEditor::forward_draw_over_atlas(TileAtlasView *p_tile_atlas
}
} else {
// Draw hovered tile.
- Vector2i tile_size = tile_set->get_tile_size();
- Rect2i rect = p_transform.xform(Rect2i(position - tile_size / 2, tile_size));
- tile_set->draw_tile_shape(p_canvas_item, rect, Color(1.0, 1.0, 1.0, 0.5), true);
+ Transform2D tile_xform;
+ tile_xform.set_origin(position);
+ tile_xform.set_scale(tile_set->get_tile_size());
+ tile_set->draw_tile_shape(p_canvas_item, p_transform * tile_xform, Color(1.0, 1.0, 1.0, 0.5), true);
}
}
}
@@ -1686,9 +1690,10 @@ void TileDataTerrainsEditor::forward_draw_over_alternatives(TileAtlasView *p_til
}
} else {
// Draw hovered tile.
- Vector2i tile_size = tile_set->get_tile_size();
- Rect2i rect = p_transform.xform(Rect2i(position - tile_size / 2, tile_size));
- tile_set->draw_tile_shape(p_canvas_item, rect, Color(1.0, 1.0, 1.0, 0.5), true);
+ Transform2D tile_xform;
+ tile_xform.set_origin(position);
+ tile_xform.set_scale(tile_set->get_tile_size());
+ tile_set->draw_tile_shape(p_canvas_item, p_transform * tile_xform, Color(1.0, 1.0, 1.0, 0.5), true);
}
}
}
diff --git a/editor/plugins/tiles/tile_map_editor.cpp b/editor/plugins/tiles/tile_map_editor.cpp
index b5e070b4d6..acbd5d70ff 100644
--- a/editor/plugins/tiles/tile_map_editor.cpp
+++ b/editor/plugins/tiles/tile_map_editor.cpp
@@ -636,8 +636,10 @@ void TileMapEditorTilesPlugin::forward_canvas_draw_over_viewport(Control *p_over
for (int y = rect.position.y; y < rect.get_end().y; y++) {
Vector2i coords = Vector2i(x, y);
if (tile_map->get_cell_source_id(tile_map_layer, coords) != TileSet::INVALID_SOURCE) {
- Rect2 cell_region = xform.xform(Rect2(tile_map->map_to_world(coords) - tile_shape_size / 2, tile_shape_size));
- tile_set->draw_tile_shape(p_overlay, cell_region, Color(1.0, 1.0, 1.0), false);
+ Transform2D tile_xform;
+ tile_xform.set_origin(tile_map->map_to_world(coords));
+ tile_xform.set_scale(tile_shape_size);
+ tile_set->draw_tile_shape(p_overlay, xform * tile_xform, Color(1.0, 1.0, 1.0), false);
}
}
}
@@ -734,10 +736,12 @@ void TileMapEditorTilesPlugin::forward_canvas_draw_over_viewport(Control *p_over
float bottom_opacity = CLAMP(Math::inverse_lerp((float)drawn_grid_rect.size.y, (float)(drawn_grid_rect.size.y - fading), (float)pos_in_rect.y), 0.0f, 1.0f);
float opacity = CLAMP(MIN(left_opacity, MIN(right_opacity, MIN(top_opacity, bottom_opacity))) + 0.1, 0.0f, 1.0f);
- Rect2 cell_region = xform.xform(Rect2(tile_map->map_to_world(Vector2(x, y)) - tile_shape_size / 2, tile_shape_size));
+ Transform2D tile_xform;
+ tile_xform.set_origin(tile_map->map_to_world(Vector2(x, y)));
+ tile_xform.set_scale(tile_shape_size);
Color color = grid_color;
color.a = color.a * opacity;
- tile_set->draw_tile_shape(p_overlay, cell_region, color, false);
+ tile_set->draw_tile_shape(p_overlay, xform * tile_xform, color, false);
}
}
}
@@ -745,11 +749,11 @@ void TileMapEditorTilesPlugin::forward_canvas_draw_over_viewport(Control *p_over
// Draw the preview.
for (Map<Vector2i, TileMapCell>::Element *E = preview.front(); E; E = E->next()) {
- Vector2i size = tile_set->get_tile_size();
- Vector2 position = tile_map->map_to_world(E->key()) - size / 2;
- Rect2 cell_region = xform.xform(Rect2(position, size));
+ Transform2D tile_xform;
+ tile_xform.set_origin(tile_map->map_to_world(E->key()));
+ tile_xform.set_scale(tile_set->get_tile_size());
if (!erase_button->is_pressed() && random_tile_checkbox->is_pressed()) {
- tile_set->draw_tile_shape(p_overlay, cell_region, Color(1.0, 1.0, 1.0, 0.5), true);
+ tile_set->draw_tile_shape(p_overlay, xform * tile_xform, Color(1.0, 1.0, 1.0, 0.5), true);
} else {
if (tile_set->has_source(E->get().source_id)) {
TileSetSource *source = *tile_set->get_source(E->get().source_id);
@@ -791,10 +795,10 @@ void TileMapEditorTilesPlugin::forward_canvas_draw_over_viewport(Control *p_over
// Draw the tile.
p_overlay->draw_texture_rect_region(atlas_source->get_texture(), dest_rect, source_rect, modulate * Color(1.0, 1.0, 1.0, 0.5), transpose, tile_set->is_uv_clipping());
} else {
- tile_set->draw_tile_shape(p_overlay, cell_region, Color(1.0, 1.0, 1.0, 0.5), true);
+ tile_set->draw_tile_shape(p_overlay, xform * tile_xform, Color(1.0, 1.0, 1.0, 0.5), true);
}
} else {
- tile_set->draw_tile_shape(p_overlay, cell_region, Color(0.0, 0.0, 0.0, 0.5), true);
+ tile_set->draw_tile_shape(p_overlay, xform * tile_xform, Color(0.0, 0.0, 0.0, 0.5), true);
}
}
}
@@ -3689,8 +3693,10 @@ void TileMapEditor::forward_canvas_draw_over_viewport(Control *p_overlay) {
0.8);
// Draw the scaled tile.
- Rect2 cell_region = xform.xform(Rect2(tile_map->map_to_world(coords) - Vector2(tile_shape_size) / 2, Vector2(tile_shape_size)));
- tile_set->draw_tile_shape(p_overlay, cell_region, color, true, warning_pattern_texture);
+ Transform2D tile_xform;
+ tile_xform.set_origin(tile_map->map_to_world(coords));
+ tile_xform.set_scale(tile_shape_size);
+ tile_set->draw_tile_shape(p_overlay, xform * tile_xform, color, true, warning_pattern_texture);
}
// Draw the warning icon.
@@ -3746,10 +3752,12 @@ void TileMapEditor::forward_canvas_draw_over_viewport(Control *p_overlay) {
float bottom_opacity = CLAMP(Math::inverse_lerp((float)displayed_rect.size.y, (float)(displayed_rect.size.y - fading), (float)pos_in_rect.y), 0.0f, 1.0f);
float opacity = CLAMP(MIN(left_opacity, MIN(right_opacity, MIN(top_opacity, bottom_opacity))) + 0.1, 0.0f, 1.0f);
- Rect2 cell_region = xform.xform(Rect2(tile_map->map_to_world(Vector2(x, y)) - tile_shape_size / 2, tile_shape_size));
+ Transform2D tile_xform;
+ tile_xform.set_origin(tile_map->map_to_world(Vector2(x, y)));
+ tile_xform.set_scale(tile_shape_size);
Color color = grid_color;
color.a = color.a * opacity;
- tile_set->draw_tile_shape(p_overlay, cell_region, color, false);
+ tile_set->draw_tile_shape(p_overlay, xform * tile_xform, color, false);
}
}
}
diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp
index 50808a25af..aaa085675c 100644
--- a/editor/plugins/visual_shader_editor_plugin.cpp
+++ b/editor/plugins/visual_shader_editor_plugin.cpp
@@ -4042,7 +4042,7 @@ VisualShaderEditor::VisualShaderEditor() {
graph->get_zoom_hbox()->add_child(add_node);
add_node->set_text(TTR("Add Node..."));
graph->get_zoom_hbox()->move_child(add_node, 0);
- add_node->connect("pressed", callable_mp(this, &VisualShaderEditor::_show_members_dialog), varray(false));
+ add_node->connect("pressed", callable_mp(this, &VisualShaderEditor::_show_members_dialog), varray(false, VisualShaderNode::PORT_TYPE_MAX, VisualShaderNode::PORT_TYPE_MAX));
preview_shader = memnew(Button);
preview_shader->set_flat(true);
diff --git a/editor/pot_generator.cpp b/editor/pot_generator.cpp
index b58b7e4cac..d57345cac1 100644
--- a/editor/pot_generator.cpp
+++ b/editor/pot_generator.cpp
@@ -108,7 +108,6 @@ void POTGenerator::_write_to_pot(const String &p_file) {
const String header =
"# LANGUAGE translation for " + project_name + " for the following files:\n" + extracted_files +
"#\n"
- "#\n"
"# FIRST AUTHOR < EMAIL @ADDRESS>, YEAR.\n"
"#\n"
"#, fuzzy\n"
@@ -116,8 +115,9 @@ void POTGenerator::_write_to_pot(const String &p_file) {
"msgstr \"\"\n"
"\"Project-Id-Version: " +
project_name + "\\n\"\n"
+ "\"MIME-Version: 1.0\\n\"\n"
"\"Content-Type: text/plain; charset=UTF-8\\n\"\n"
- "\"Content-Transfer-Encoding: 8-bit\\n\"\n\n";
+ "\"Content-Transfer-Encoding: 8-bit\\n\"\n";
file->store_string(header);
@@ -129,6 +129,9 @@ void POTGenerator::_write_to_pot(const String &p_file) {
String plural = v_msgid_data[i].plural;
const Set<String> &locations = v_msgid_data[i].locations;
+ // Put the blank line at the start, to avoid a double at the end when closing the file.
+ file->store_line("");
+
// Write file locations.
for (Set<String>::Element *E = locations.front(); E; E = E->next()) {
file->store_line("#: " + E->get().trim_prefix("res://"));
@@ -142,13 +145,13 @@ void POTGenerator::_write_to_pot(const String &p_file) {
// Write msgid.
_write_msgid(file, msgid, false);
- // Write msgid_plural
+ // Write msgid_plural.
if (!plural.is_empty()) {
_write_msgid(file, plural, true);
file->store_line("msgstr[0] \"\"");
- file->store_line("msgstr[1] \"\"\n");
+ file->store_line("msgstr[1] \"\"");
} else {
- file->store_line("msgstr \"\"\n");
+ file->store_line("msgstr \"\"");
}
}
}
diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp
index 05cf3791f4..81554c9550 100644
--- a/editor/project_manager.cpp
+++ b/editor/project_manager.cpp
@@ -2051,6 +2051,10 @@ void ProjectManager::_open_selected_projects() {
args.push_back("--disable-crash-handler");
}
+ if (OS::get_singleton()->is_single_window()) {
+ args.push_back("--single-window");
+ }
+
String exec = OS::get_singleton()->get_executable_path();
Error err = OS::get_singleton()->create_process(exec, args);
ERR_FAIL_COND(err);
diff --git a/editor/rename_dialog.cpp b/editor/rename_dialog.cpp
index d86e2656d4..9063b5c6f8 100644
--- a/editor/rename_dialog.cpp
+++ b/editor/rename_dialog.cpp
@@ -30,23 +30,19 @@
#include "rename_dialog.h"
+#ifdef MODULE_REGEX_ENABLED
+
#include "core/string/print_string.h"
#include "editor_node.h"
#include "editor_scale.h"
#include "editor_settings.h"
#include "editor_themes.h"
+#include "modules/regex/regex.h"
#include "plugins/script_editor_plugin.h"
#include "scene/gui/control.h"
#include "scene/gui/label.h"
#include "scene/gui/tab_container.h"
-#include "modules/modules_enabled.gen.h"
-#ifdef MODULE_REGEX_ENABLED
-#include "modules/regex/regex.h"
-#else
-#error "Can't build editor rename dialog without RegEx module."
-#endif
-
RenameDialog::RenameDialog(SceneTreeEditor *p_scene_tree_editor, UndoRedo *p_undo_redo) {
scene_tree_editor = p_scene_tree_editor;
undo_redo = p_undo_redo;
@@ -655,3 +651,5 @@ void RenameDialog::_features_toggled(bool pressed) {
size.y = 0;
set_size(size);
}
+
+#endif // MODULE_REGEX_ENABLED
diff --git a/editor/rename_dialog.h b/editor/rename_dialog.h
index 76e99e3b66..7990862b37 100644
--- a/editor/rename_dialog.h
+++ b/editor/rename_dialog.h
@@ -31,6 +31,9 @@
#ifndef RENAME_DIALOG_H
#define RENAME_DIALOG_H
+#include "modules/modules_enabled.gen.h"
+#ifdef MODULE_REGEX_ENABLED
+
#include "scene/gui/check_box.h"
#include "scene/gui/dialogs.h"
#include "scene/gui/option_button.h"
@@ -113,4 +116,6 @@ public:
~RenameDialog() {}
};
-#endif
+#endif // MODULE_REGEX_ENABLED
+
+#endif // RENAME_DIALOG_H
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index 2ec4a088a2..4bc0905163 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -83,10 +83,12 @@ void SceneTreeDock::unhandled_key_input(const Ref<InputEvent> &p_event) {
return;
}
- if (ED_IS_SHORTCUT("scene_tree/batch_rename", p_event)) {
- _tool_selected(TOOL_BATCH_RENAME);
- } else if (ED_IS_SHORTCUT("scene_tree/rename", p_event)) {
+ if (ED_IS_SHORTCUT("scene_tree/rename", p_event)) {
_tool_selected(TOOL_RENAME);
+#ifdef MODULE_REGEX_ENABLED
+ } else if (ED_IS_SHORTCUT("scene_tree/batch_rename", p_event)) {
+ _tool_selected(TOOL_BATCH_RENAME);
+#endif // MODULE_REGEX_ENABLED
} else if (ED_IS_SHORTCUT("scene_tree/add_child_node", p_event)) {
_tool_selected(TOOL_NEW);
} else if (ED_IS_SHORTCUT("scene_tree/instance_scene", p_event)) {
@@ -336,6 +338,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
current_option = p_tool;
switch (p_tool) {
+#ifdef MODULE_REGEX_ENABLED
case TOOL_BATCH_RENAME: {
if (!profile_allow_editing) {
break;
@@ -344,6 +347,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
rename_dialog->popup_centered();
}
} break;
+#endif // MODULE_REGEX_ENABLED
case TOOL_RENAME: {
if (!profile_allow_editing) {
break;
@@ -2807,11 +2811,13 @@ void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) {
}
}
+#ifdef MODULE_REGEX_ENABLED
if (profile_allow_editing && selection.size() > 1) {
//this is not a commonly used action, it makes no sense for it to be where it was nor always present.
menu->add_separator();
menu->add_icon_shortcut(get_theme_icon(SNAME("Rename"), SNAME("EditorIcons")), ED_GET_SHORTCUT("scene_tree/batch_rename"), TOOL_BATCH_RENAME);
}
+#endif // MODULE_REGEX_ENABLED
menu->add_separator();
menu->add_icon_item(get_theme_icon(SNAME("Help"), SNAME("EditorIcons")), TTR("Open Documentation"), TOOL_OPEN_DOCUMENTATION);
@@ -2837,6 +2843,11 @@ void SceneTreeDock::set_filter(const String &p_filter) {
scene_tree->set_filter(p_filter);
}
+void SceneTreeDock::save_branch_to_file(String p_directory) {
+ new_scene_from_dialog->set_current_dir(p_directory);
+ _tool_selected(TOOL_NEW_SCENE_FROM);
+}
+
void SceneTreeDock::_focus_node() {
Node *node = scene_tree->get_selected();
ERR_FAIL_COND(!node);
@@ -3316,8 +3327,10 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel
create_dialog->connect("create", callable_mp(this, &SceneTreeDock::_create));
create_dialog->connect("favorites_updated", callable_mp(this, &SceneTreeDock::_update_create_root_dialog));
+#ifdef MODULE_REGEX_ENABLED
rename_dialog = memnew(RenameDialog(scene_tree, &editor_data->get_undo_redo()));
add_child(rename_dialog);
+#endif // MODULE_REGEX_ENABLED
script_create_dialog = memnew(ScriptCreateDialog);
script_create_dialog->set_inheritance_base_type("Node");
diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h
index 387a35acbb..ece0ca5ca4 100644
--- a/editor/scene_tree_dock.h
+++ b/editor/scene_tree_dock.h
@@ -62,7 +62,9 @@ class SceneTreeDock : public VBoxContainer {
TOOL_COPY,
TOOL_PASTE,
TOOL_RENAME,
+#ifdef MODULE_REGEX_ENABLED
TOOL_BATCH_RENAME,
+#endif // MODULE_REGEX_ENABLED
TOOL_REPLACE,
TOOL_EXTEND_SCRIPT,
TOOL_ATTACH_SCRIPT,
@@ -105,7 +107,9 @@ class SceneTreeDock : public VBoxContainer {
int current_option;
CreateDialog *create_dialog;
+#ifdef MODULE_REGEX_ENABLED
RenameDialog *rename_dialog;
+#endif // MODULE_REGEX_ENABLED
Button *button_add;
Button *button_instance;
@@ -269,6 +273,7 @@ protected:
public:
String get_filter();
void set_filter(const String &p_filter);
+ void save_branch_to_file(String p_directory);
void _focus_node();
diff --git a/editor/translations/el.po b/editor/translations/el.po
index e773b011a4..93b5941f64 100644
--- a/editor/translations/el.po
+++ b/editor/translations/el.po
@@ -6,7 +6,7 @@
# Georgios Katsanakis <geo.elgeo@gmail.com>, 2019.
# Overloaded <manoschool@yahoo.gr>, 2019.
# Eternal Death <eternaldeath0001@gmail.com>, 2019.
-# Overloaded @ Orama Interactive https://orama-interactive.com/ <manoschool@yahoo.gr>, 2020.
+# Overloaded @ Orama Interactive http://orama-interactive.com/ <manoschool@yahoo.gr>, 2020.
# pandektis <pandektis@gmail.com>, 2020.
# KostasMSC <kargyris@athtech.gr>, 2020.
# lawfulRobot <czavantias@gmail.com>, 2020, 2021.
diff --git a/main/main.cpp b/main/main.cpp
index ece194b0f1..5513e571d6 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -135,7 +135,6 @@ static int audio_driver_idx = -1;
// Engine config/tools
-static bool single_window = false;
static bool editor = false;
static bool project_manager = false;
static bool cmdline_tool = false;
@@ -145,6 +144,7 @@ static bool auto_quit = false;
static OS::ProcessID allow_focus_steal_pid = 0;
#ifdef TOOLS_ENABLED
static bool auto_build_solutions = false;
+static String debug_server_uri;
#endif
// Display
@@ -286,6 +286,7 @@ void Main::print_help(const char *p_binary) {
#ifdef TOOLS_ENABLED
OS::get_singleton()->print(" -e, --editor Start the editor instead of running the scene.\n");
OS::get_singleton()->print(" -p, --project-manager Start the project manager, even if a project is auto-detected.\n");
+ OS::get_singleton()->print(" --debug-server <uri> Start the editor debug server (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007)\n");
#endif
OS::get_singleton()->print(" -q, --quit Quit after the first iteration.\n");
OS::get_singleton()->print(" -l, --language <locale> Use a specific locale (<locale> being a two-letter code).\n");
@@ -403,6 +404,7 @@ Error Main::test_setup() {
GLOBAL_DEF("debug/settings/crash_handler/message",
String("Please include this when reporting the bug on https://github.com/godotengine/godot/issues"));
+ GLOBAL_DEF_RST("rendering/occlusion_culling/bvh_build_quality", 2);
translation_server = memnew(TranslationServer);
@@ -752,7 +754,7 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
}
} else if (I->get() == "--single-window") { // force single window
- single_window = true;
+ OS::get_singleton()->_single_window = true;
} else if (I->get() == "-t" || I->get() == "--always-on-top") { // force always-on-top window
init_always_on_top = true;
@@ -874,6 +876,18 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph
} else if (I->get() == "-p" || I->get() == "--project-manager") { // starts project manager
project_manager = true;
+ } else if (I->get() == "--debug-server") {
+ if (I->next()) {
+ debug_server_uri = I->next()->get();
+ if (debug_server_uri.find("://") == -1) { // wrong address
+ OS::get_singleton()->print("Invalid debug server uri. It should be of the form <protocol>://<bind_address>:<port>.\n");
+ goto error;
+ }
+ N = I->next()->next();
+ } else {
+ OS::get_singleton()->print("Missing remote debug server uri, aborting.\n");
+ goto error;
+ }
} else if (I->get() == "--build-solutions") { // Build the scripting solution such C#
auto_build_solutions = true;
@@ -2116,7 +2130,7 @@ bool Main::start() {
bool embed_subwindows = GLOBAL_DEF("display/window/subwindows/embed_subwindows", false);
- if (single_window || (!project_manager && !editor && embed_subwindows)) {
+ if (OS::get_singleton()->is_single_window() || (!project_manager && !editor && embed_subwindows)) {
sml->get_root()->set_embed_subwindows_hint(true);
}
ResourceLoader::add_custom_loaders();
@@ -2346,6 +2360,9 @@ bool Main::start() {
}
}
DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_EDITOR);
+ if (!debug_server_uri.is_empty()) {
+ EditorDebuggerNode::get_singleton()->start(debug_server_uri);
+ }
}
#endif
if (!editor) {
@@ -2669,18 +2686,19 @@ void Main::cleanup(bool p_force) {
//clear global shader variables before scene and other graphics stuff are deinitialized.
rendering_server->global_variables_clear();
-#ifdef TOOLS_ENABLED
- EditorNode::unregister_editor_types();
-#endif
-
if (xr_server) {
// cleanup now before we pull the rug from underneath...
memdelete(xr_server);
}
+ unregister_driver_types();
+
+#ifdef TOOLS_ENABLED
+ EditorNode::unregister_editor_types();
+#endif
+
ImageLoader::cleanup();
- unregister_driver_types();
unregister_module_types();
unregister_platform_apis();
unregister_scene_types();
diff --git a/misc/scripts/file_format.sh b/misc/scripts/file_format.sh
index 0b49b175f2..b241f3da70 100755
--- a/misc/scripts/file_format.sh
+++ b/misc/scripts/file_format.sh
@@ -20,6 +20,9 @@ while IFS= read -rd '' f; do
continue
elif [[ "$f" == *"sln" ]]; then
continue
+ elif [[ "$f" == *".out" ]]; then
+ # GDScript integration testing files.
+ continue
elif [[ "$f" == *"patch" ]]; then
continue
elif [[ "$f" == *"pot" ]]; then
diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp
index bf11cc7f68..452fb32d9d 100644
--- a/modules/csg/csg_shape.cpp
+++ b/modules/csg/csg_shape.cpp
@@ -280,7 +280,7 @@ void CSGShape3D::mikktSetTSpaceDefault(const SMikkTSpaceContext *pContext, const
}
void CSGShape3D::_update_shape() {
- if (parent) {
+ if (parent || !is_inside_tree()) {
return;
}
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index 5409b3ff79..bc8801b8b9 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -87,6 +87,19 @@ Object *GDScriptNativeClass::instantiate() {
return ClassDB::instantiate(name);
}
+GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) {
+ if (p_script->initializer) {
+ return p_script->initializer;
+ } else {
+ GDScript *base = p_script->_base;
+ if (base != nullptr) {
+ return _super_constructor(base);
+ } else {
+ return nullptr;
+ }
+ }
+}
+
void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) {
GDScript *base = p_script->_base;
if (base != nullptr) {
@@ -135,6 +148,8 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco
if (p_argcount < 0) {
return instance;
}
+
+ initializer = _super_constructor(this);
if (initializer != nullptr) {
initializer->call(instance, p_args, p_argcount, r_error);
if (r_error.error != Callable::CallError::CALL_OK) {
diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h
index a6fd7b3b5d..791f8a1431 100644
--- a/modules/gdscript/gdscript.h
+++ b/modules/gdscript/gdscript.h
@@ -130,6 +130,7 @@ class GDScript : public Script {
SelfList<GDScriptFunctionState>::List pending_func_states;
+ GDScriptFunction *_super_constructor(GDScript *p_script);
void _super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error);
GDScriptInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error);
diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
index f2b601dc2c..e785151a6b 100644
--- a/modules/gdscript/gdscript_analyzer.cpp
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -171,7 +171,7 @@ Error GDScriptAnalyzer::check_native_member_name_conflict(const StringName &p_me
}
if (class_exists(p_member_name)) {
- push_error(vformat(R"(The class "%s" shadows a native class.)", p_member_name), p_member_node);
+ push_error(vformat(R"(The member "%s" shadows a native class.)", p_member_name), p_member_node);
return ERR_PARSE_ERROR;
}
@@ -218,6 +218,17 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class,
p_class->fqcn = p_class->outer->fqcn + "::" + String(p_class->identifier->name);
}
+ if (p_class->identifier) {
+ StringName class_name = p_class->identifier->name;
+ if (class_exists(class_name)) {
+ push_error(vformat(R"(Class "%s" hides a native class.)", class_name), p_class->identifier);
+ } else if (ScriptServer::is_global_class(class_name) && (ScriptServer::get_global_class_path(class_name) != parser->script_path || p_class != parser->head)) {
+ push_error(vformat(R"(Class "%s" hides a global script class.)", class_name), p_class->identifier);
+ } else if (ProjectSettings::get_singleton()->has_autoload(class_name) && ProjectSettings::get_singleton()->get_autoload(class_name).is_singleton) {
+ push_error(vformat(R"(Class "%s" hides an autoload singleton.)", class_name), p_class->identifier);
+ }
+ }
+
GDScriptParser::DataType result;
// Set datatype for class.
@@ -242,6 +253,9 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class,
int extends_index = 0;
if (!p_class->extends_path.is_empty()) {
+ if (p_class->extends_path.is_relative_path()) {
+ p_class->extends_path = class_type.script_path.get_base_dir().plus_file(p_class->extends_path).simplify_path();
+ }
Ref<GDScriptParserRef> parser = get_parser_for(p_class->extends_path);
if (parser.is_null()) {
push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
@@ -681,8 +695,9 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas
specified_type.is_meta_type = false;
}
- GDScriptParser::DataType datatype = member.constant->get_datatype();
+ GDScriptParser::DataType datatype;
if (member.constant->initializer) {
+ datatype = member.constant->initializer->get_datatype();
if (member.constant->initializer->type == GDScriptParser::Node::ARRAY) {
GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(member.constant->initializer);
const_fold_array(array);
@@ -1478,6 +1493,10 @@ void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parame
}
}
+ if (result.builtin_type == Variant::Type::NIL && result.type_source == GDScriptParser::DataType::ANNOTATED_INFERRED && p_parameter->datatype_specifier == nullptr) {
+ push_error(vformat(R"(Could not infer the type of the variable "%s" because the initial value is "null".)", p_parameter->identifier->name), p_parameter->default_value);
+ }
+
p_parameter->set_datatype(result);
}
@@ -2516,14 +2535,29 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod
while (outer != nullptr) {
if (outer->has_member(name)) {
const GDScriptParser::ClassNode::Member &member = outer->get_member(name);
- if (member.type == GDScriptParser::ClassNode::Member::CONSTANT) {
- // TODO: Make sure loops won't cause problem. And make special error message for those.
- // For out-of-order resolution:
- reduce_expression(member.constant->initializer);
- p_identifier->set_datatype(member.get_datatype());
- p_identifier->is_constant = true;
- p_identifier->reduced_value = member.constant->initializer->reduced_value;
- return;
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::CONSTANT: {
+ // TODO: Make sure loops won't cause problem. And make special error message for those.
+ // For out-of-order resolution:
+ reduce_expression(member.constant->initializer);
+ p_identifier->set_datatype(member.get_datatype());
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = member.constant->initializer->reduced_value;
+ return;
+ } break;
+ case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
+ p_identifier->set_datatype(member.get_datatype());
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = member.enum_value.value;
+ return;
+ } break;
+ case GDScriptParser::ClassNode::Member::ENUM: {
+ p_identifier->set_datatype(member.get_datatype());
+ p_identifier->is_constant = false;
+ return;
+ } break;
+ default:
+ break;
}
}
outer = outer->outer;
@@ -2837,6 +2871,9 @@ void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
}
void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
+ if (p_subscript->base == nullptr) {
+ return;
+ }
if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
} else {
diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp
index bed67b55f0..1127488db8 100644
--- a/modules/gdscript/gdscript_byte_codegen.cpp
+++ b/modules/gdscript/gdscript_byte_codegen.cpp
@@ -864,6 +864,12 @@ void GDScriptByteCodeGenerator::write_assign_default_parameter(const Address &p_
function->default_arguments.push_back(opcodes.size());
}
+void GDScriptByteCodeGenerator::write_store_global(const Address &p_dst, int p_global_index) {
+ append(GDScriptFunction::OPCODE_STORE_GLOBAL, 1);
+ append(p_dst);
+ append(p_global_index);
+}
+
void GDScriptByteCodeGenerator::write_store_named_global(const Address &p_dst, const StringName &p_global) {
append(GDScriptFunction::OPCODE_STORE_NAMED_GLOBAL, 1);
append(p_dst);
diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h
index ce1a043b28..dcc11ebdce 100644
--- a/modules/gdscript/gdscript_byte_codegen.h
+++ b/modules/gdscript/gdscript_byte_codegen.h
@@ -454,6 +454,7 @@ public:
virtual void write_assign_true(const Address &p_target) override;
virtual void write_assign_false(const Address &p_target) override;
virtual void write_assign_default_parameter(const Address &p_dst, const Address &p_src) override;
+ virtual void write_store_global(const Address &p_dst, int p_global_index) override;
virtual void write_store_named_global(const Address &p_dst, const StringName &p_global) override;
virtual void write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) override;
virtual void write_call(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h
index 7713d13bc8..e6ecc92d55 100644
--- a/modules/gdscript/gdscript_codegen.h
+++ b/modules/gdscript/gdscript_codegen.h
@@ -115,6 +115,7 @@ public:
virtual void write_assign_true(const Address &p_target) = 0;
virtual void write_assign_false(const Address &p_target) = 0;
virtual void write_assign_default_parameter(const Address &dst, const Address &src) = 0;
+ virtual void write_store_global(const Address &p_dst, int p_global_index) = 0;
virtual void write_store_named_global(const Address &p_dst, const StringName &p_global) = 0;
virtual void write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) = 0;
virtual void write_call(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp
index 736f6eae79..a8aef84db3 100644
--- a/modules/gdscript/gdscript_compiler.cpp
+++ b/modules/gdscript/gdscript_compiler.cpp
@@ -35,6 +35,8 @@
#include "gdscript_cache.h"
#include "gdscript_utility_functions.h"
+#include "core/config/project_settings.h"
+
bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) {
if (codegen.function_node && codegen.function_node->is_static) {
return false;
@@ -316,10 +318,21 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code
}
}
+ // Try globals.
if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
- int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
- Variant global = GDScriptLanguage::get_singleton()->get_global_array()[idx];
- return codegen.add_constant(global); // TODO: Get type.
+ // If it's an autoload singleton, we postpone to load it at runtime.
+ // This is so one autoload doesn't try to load another before it's compiled.
+ OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
+ if (autoloads.has(identifier) && autoloads[identifier].is_singleton) {
+ GDScriptCodeGenerator::Address global = codegen.add_temporary(_gdtype_from_datatype(in->get_datatype()));
+ int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
+ gen->write_store_global(global, idx);
+ return global;
+ } else {
+ int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
+ Variant global = GDScriptLanguage::get_singleton()->get_global_array()[idx];
+ return codegen.add_constant(global);
+ }
}
// Try global classes.
@@ -427,7 +440,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code
break;
case GDScriptParser::DictionaryNode::LUA_TABLE:
// Lua-style: key is an identifier interpreted as StringName.
- StringName key = static_cast<const GDScriptParser::IdentifierNode *>(dn->elements[i].key)->name;
+ StringName key = dn->elements[i].key->reduced_value.operator StringName();
element = codegen.add_constant(key);
break;
}
@@ -951,7 +964,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code
// Perform operator if any.
if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
- GDScriptCodeGenerator::Address value = codegen.add_temporary();
+ GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype()));
if (subscript->is_attribute) {
gen->write_get_named(value, name, prev_base);
} else {
diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp
index 1acb9ceddc..9287df2ea0 100644
--- a/modules/gdscript/gdscript_disassembler.cpp
+++ b/modules/gdscript/gdscript_disassembler.cpp
@@ -914,6 +914,14 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const {
incr += 5;
} break;
DISASSEMBLE_ITERATE_TYPES(DISASSEMBLE_ITERATE);
+ case OPCODE_STORE_GLOBAL: {
+ text += "store global ";
+ text += DADDR(1);
+ text += " = ";
+ text += String::num_int64(_code_ptr[ip + 2]);
+
+ incr += 3;
+ } break;
case OPCODE_STORE_NAMED_GLOBAL: {
text += "store named global ";
text += DADDR(1);
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index f809a4dab8..f79e5726ce 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -1733,7 +1733,7 @@ static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context,
}
}
- if (is_function_parameter && p_context.current_function && p_context.current_class) {
+ if (is_function_parameter && p_context.current_function && p_context.current_function->source_lambda == nullptr && p_context.current_class) {
// Check if it's override of native function, then we can assume the type from the signature.
GDScriptParser::DataType base_type = p_context.current_class->base_type;
while (base_type.is_set()) {
diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h
index b21cb47910..9d076a8e4c 100644
--- a/modules/gdscript/gdscript_function.h
+++ b/modules/gdscript/gdscript_function.h
@@ -348,6 +348,7 @@ public:
OPCODE_ITERATE_PACKED_VECTOR3_ARRAY,
OPCODE_ITERATE_PACKED_COLOR_ARRAY,
OPCODE_ITERATE_OBJECT,
+ OPCODE_STORE_GLOBAL,
OPCODE_STORE_NAMED_GLOBAL,
OPCODE_TYPE_ADJUST_BOOL,
OPCODE_TYPE_ADJUST_INT,
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index 64a393f90c..d555be1e8d 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -337,12 +337,29 @@ Error GDScriptParser::parse(const String &p_source_code, const String &p_script_
tokenizer.set_cursor_position(cursor_line, cursor_column);
script_path = p_script_path;
current = tokenizer.scan();
- // Avoid error as the first token.
- while (current.type == GDScriptTokenizer::Token::ERROR) {
- push_error(current.literal);
+ // Avoid error or newline as the first token.
+ // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
+ while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
+ if (current.type == GDScriptTokenizer::Token::ERROR) {
+ push_error(current.literal);
+ }
current = tokenizer.scan();
}
+#ifdef DEBUG_ENABLED
+ // Warn about parsing an empty script file:
+ if (current.type == GDScriptTokenizer::Token::TK_EOF) {
+ // Create a dummy Node for the warning, pointing to the very beginning of the file
+ Node *nd = alloc_node<PassNode>();
+ nd->start_line = 1;
+ nd->start_column = 0;
+ nd->end_line = 1;
+ nd->leftmost_column = 0;
+ nd->rightmost_column = 0;
+ push_warning(nd, GDScriptWarning::EMPTY_FILE);
+ }
+#endif
+
push_multiline(false); // Keep one for the whole parsing.
parse_program();
pop_multiline();
@@ -1682,6 +1699,7 @@ GDScriptParser::MatchNode *GDScriptParser::parse_match() {
while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
MatchBranchNode *branch = parse_match_branch();
if (branch == nullptr) {
+ advance();
continue;
}
@@ -1745,7 +1763,9 @@ GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
push_error(R"(No pattern found for "match" branch.)");
}
- consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)");
+ if (!consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)")) {
+ return nullptr;
+ }
// Save continue state.
bool could_continue = can_continue;
@@ -1778,15 +1798,6 @@ GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_
PatternNode *pattern = alloc_node<PatternNode>();
switch (current.type) {
- case GDScriptTokenizer::Token::LITERAL:
- advance();
- pattern->pattern_type = PatternNode::PT_LITERAL;
- pattern->literal = parse_literal();
- if (pattern->literal == nullptr) {
- // Error happened.
- return nullptr;
- }
- break;
case GDScriptTokenizer::Token::VAR: {
// Bind.
advance();
@@ -1849,44 +1860,44 @@ GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_
// Dictionary.
advance();
pattern->pattern_type = PatternNode::PT_DICTIONARY;
-
- if (!check(GDScriptTokenizer::Token::BRACE_CLOSE) && !is_at_end()) {
- do {
- if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
- // Rest.
+ do {
+ if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
+ break;
+ }
+ if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
+ // Rest.
+ if (pattern->rest_used) {
+ push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
+ } else {
+ PatternNode *sub_pattern = alloc_node<PatternNode>();
+ sub_pattern->pattern_type = PatternNode::PT_REST;
+ pattern->dictionary.push_back({ nullptr, sub_pattern });
+ pattern->rest_used = true;
+ }
+ } else {
+ ExpressionNode *key = parse_expression(false);
+ if (key == nullptr) {
+ push_error(R"(Expected expression as key for dictionary pattern.)");
+ }
+ if (match(GDScriptTokenizer::Token::COLON)) {
+ // Value pattern.
+ PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
+ if (sub_pattern == nullptr) {
+ continue;
+ }
if (pattern->rest_used) {
push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
+ } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
+ push_error(R"(The ".." pattern cannot be used as a value.)");
} else {
- PatternNode *sub_pattern = alloc_node<PatternNode>();
- sub_pattern->pattern_type = PatternNode::PT_REST;
- pattern->dictionary.push_back({ nullptr, sub_pattern });
- pattern->rest_used = true;
+ pattern->dictionary.push_back({ key, sub_pattern });
}
} else {
- ExpressionNode *key = parse_expression(false);
- if (key == nullptr) {
- push_error(R"(Expected expression as key for dictionary pattern.)");
- }
- if (match(GDScriptTokenizer::Token::COLON)) {
- // Value pattern.
- PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
- if (sub_pattern == nullptr) {
- continue;
- }
- if (pattern->rest_used) {
- push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
- } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
- push_error(R"(The ".." pattern cannot be used as a value.)");
- } else {
- pattern->dictionary.push_back({ key, sub_pattern });
- }
- } else {
- // Key match only.
- pattern->dictionary.push_back({ key, nullptr });
- }
+ // Key match only.
+ pattern->dictionary.push_back({ key, nullptr });
}
- } while (match(GDScriptTokenizer::Token::COMMA));
- }
+ }
+ } while (match(GDScriptTokenizer::Token::COMMA));
consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
break;
}
@@ -1895,8 +1906,13 @@ GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_
ExpressionNode *expression = parse_expression(false);
if (expression == nullptr) {
push_error(R"(Expected expression for match pattern.)");
+ return nullptr;
} else {
- pattern->pattern_type = PatternNode::PT_EXPRESSION;
+ if (expression->type == GDScriptParser::Node::LITERAL) {
+ pattern->pattern_type = PatternNode::PT_LITERAL;
+ } else {
+ pattern->pattern_type = PatternNode::PT_EXPRESSION;
+ }
pattern->expression = expression;
}
break;
@@ -2107,22 +2123,34 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionN
operation->operation = UnaryOpNode::OP_NEGATIVE;
operation->variant_op = Variant::OP_NEGATE;
operation->operand = parse_precedence(PREC_SIGN, false);
+ if (operation->operand == nullptr) {
+ push_error(R"(Expected expression after "-" operator.)");
+ }
break;
case GDScriptTokenizer::Token::PLUS:
operation->operation = UnaryOpNode::OP_POSITIVE;
operation->variant_op = Variant::OP_POSITIVE;
operation->operand = parse_precedence(PREC_SIGN, false);
+ if (operation->operand == nullptr) {
+ push_error(R"(Expected expression after "+" operator.)");
+ }
break;
case GDScriptTokenizer::Token::TILDE:
operation->operation = UnaryOpNode::OP_COMPLEMENT;
operation->variant_op = Variant::OP_BIT_NEGATE;
operation->operand = parse_precedence(PREC_BIT_NOT, false);
+ if (operation->operand == nullptr) {
+ push_error(R"(Expected expression after "~" operator.)");
+ }
break;
case GDScriptTokenizer::Token::NOT:
case GDScriptTokenizer::Token::BANG:
operation->operation = UnaryOpNode::OP_LOGIC_NOT;
operation->variant_op = Variant::OP_NOT;
operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
+ if (operation->operand == nullptr) {
+ push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
+ }
break;
default:
return nullptr; // Unreachable.
@@ -2259,6 +2287,10 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(Expressio
operation->false_expr = parse_precedence(PREC_TERNARY, false);
+ if (operation->false_expr == nullptr) {
+ push_error(R"(Expected expression after "else".)");
+ }
+
return operation;
}
@@ -2370,8 +2402,12 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode
}
#ifdef DEBUG_ENABLED
- if (has_operator && source_variable != nullptr && source_variable->assignments == 0) {
- push_warning(assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, source_variable->identifier->name);
+ if (source_variable != nullptr) {
+ if (has_operator && source_variable->assignments == 0) {
+ push_warning(assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, source_variable->identifier->name);
+ }
+
+ source_variable->assignments += 1;
}
#endif
@@ -2386,7 +2422,9 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_pr
}
await->to_await = element;
- current_function->is_coroutine = true;
+ if (current_function) { // Might be null in a getter or setter.
+ current_function->is_coroutine = true;
+ }
return await;
}
@@ -2450,8 +2488,13 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode
switch (dictionary->style) {
case DictionaryNode::LUA_TABLE:
- if (key != nullptr && key->type != Node::IDENTIFIER) {
- push_error("Expected identifier as LUA-style dictionary key.");
+ if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
+ push_error("Expected identifier or string as LUA-style dictionary key.");
+ advance();
+ break;
+ }
+ if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
+ push_error("Expected identifier or string as LUA-style dictionary key.");
advance();
break;
}
@@ -2463,8 +2506,14 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode
push_error(R"(Expected "=" after dictionary key.)");
}
}
- key->is_constant = true;
- key->reduced_value = static_cast<IdentifierNode *>(key)->name;
+ if (key != nullptr) {
+ key->is_constant = true;
+ if (key->type == Node::IDENTIFIER) {
+ key->reduced_value = static_cast<IdentifierNode *>(key)->name;
+ } else if (key->type == Node::LITERAL) {
+ key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
+ }
+ }
break;
case DictionaryNode::PYTHON_DICT:
if (!match(GDScriptTokenizer::Token::COLON)) {
diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp
index 882256b7e3..bf21c8510a 100644
--- a/modules/gdscript/gdscript_vm.cpp
+++ b/modules/gdscript/gdscript_vm.cpp
@@ -322,6 +322,7 @@ void (*type_init_function_table[])(Variant *) = {
&&OPCODE_ITERATE_PACKED_VECTOR3_ARRAY, \
&&OPCODE_ITERATE_PACKED_COLOR_ARRAY, \
&&OPCODE_ITERATE_OBJECT, \
+ &&OPCODE_STORE_GLOBAL, \
&&OPCODE_STORE_NAMED_GLOBAL, \
&&OPCODE_TYPE_ADJUST_BOOL, \
&&OPCODE_TYPE_ADJUST_INT, \
@@ -1231,6 +1232,13 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
GD_ERR_BREAK(to_type < 0 || to_type >= Variant::VARIANT_MAX);
+#ifdef DEBUG_ENABLED
+ if (src->get_type() == Variant::OBJECT && !src->operator ObjectID().is_ref_counted() && ObjectDB::get_instance(src->operator ObjectID()) == nullptr) {
+ err_text = "Trying to cast a freed object.";
+ OPCODE_BREAK;
+ }
+#endif
+
Callable::CallError err;
Variant::construct(to_type, *dst, (const Variant **)&src, 1, err);
@@ -1255,6 +1263,10 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
GD_ERR_BREAK(!nc);
#ifdef DEBUG_ENABLED
+ if (src->get_type() == Variant::OBJECT && !src->operator ObjectID().is_ref_counted() && ObjectDB::get_instance(src->operator ObjectID()) == nullptr) {
+ err_text = "Trying to cast a freed object.";
+ OPCODE_BREAK;
+ }
if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
err_text = "Invalid cast: can't convert a non-object value to an object type.";
OPCODE_BREAK;
@@ -1283,6 +1295,10 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
GD_ERR_BREAK(!base_type);
#ifdef DEBUG_ENABLED
+ if (src->get_type() == Variant::OBJECT && !src->operator ObjectID().is_ref_counted() && ObjectDB::get_instance(src->operator ObjectID()) == nullptr) {
+ err_text = "Trying to cast a freed object.";
+ OPCODE_BREAK;
+ }
if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'.";
OPCODE_BREAK;
@@ -3116,6 +3132,18 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
}
DISPATCH_OPCODE;
+ OPCODE(OPCODE_STORE_GLOBAL) {
+ CHECK_SPACE(3);
+ int global_idx = _code_ptr[ip + 2];
+ GD_ERR_BREAK(global_idx < 0 || global_idx >= GDScriptLanguage::get_singleton()->get_global_array_size());
+
+ GET_INSTRUCTION_ARG(dst, 0);
+ *dst = GDScriptLanguage::get_singleton()->get_global_array()[global_idx];
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
OPCODE(OPCODE_STORE_NAMED_GLOBAL) {
CHECK_SPACE(3);
int globalname_idx = _code_ptr[ip + 2];
diff --git a/modules/gdscript/gdscript_warning.cpp b/modules/gdscript/gdscript_warning.cpp
index ad41b60a4e..7a483a16ba 100644
--- a/modules/gdscript/gdscript_warning.cpp
+++ b/modules/gdscript/gdscript_warning.cpp
@@ -145,6 +145,9 @@ String GDScriptWarning::get_message() const {
case REDUNDANT_AWAIT: {
return R"("await" keyword not needed in this case, because the expression isn't a coroutine nor a signal.)";
}
+ case EMPTY_FILE: {
+ return "Empty script file.";
+ }
case WARNING_MAX:
break; // Can't happen, but silences warning
}
@@ -190,6 +193,7 @@ String GDScriptWarning::get_name_from_code(Code p_code) {
"ASSERT_ALWAYS_TRUE",
"ASSERT_ALWAYS_FALSE",
"REDUNDANT_AWAIT",
+ "EMPTY_FILE",
};
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 4b295b5eb8..8de46b08c1 100644
--- a/modules/gdscript/gdscript_warning.h
+++ b/modules/gdscript/gdscript_warning.h
@@ -68,6 +68,7 @@ public:
ASSERT_ALWAYS_TRUE, // Expression for assert argument is always true.
ASSERT_ALWAYS_FALSE, // Expression for assert argument is always false.
REDUNDANT_AWAIT, // await is used but expression is synchronous (not a signal nor a coroutine).
+ EMPTY_FILE, // A script file is empty.
WARNING_MAX,
};
diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp
index 6225e5d1eb..c383830c82 100644
--- a/modules/gdscript/tests/gdscript_test_runner.cpp
+++ b/modules/gdscript/tests/gdscript_test_runner.cpp
@@ -415,6 +415,7 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) {
TestResult result;
result.status = GDTEST_OK;
result.output = String();
+ result.passed = false;
Error err = OK;
@@ -496,7 +497,12 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) {
}
return result;
}
-
+ // Script files matching this pattern are allowed to not contain a test() function.
+ if (source_file.match("*.notest.gd")) {
+ enable_stdout();
+ result.passed = check_output(result.output);
+ return result;
+ }
// Test running.
const Map<StringName, GDScriptFunction *>::Element *test_function_element = script->get_member_functions().find(GDScriptTestRunner::test_function_name);
if (test_function_element == nullptr) {
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.gd b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.gd
new file mode 100644
index 0000000000..9b722ea50a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.gd
@@ -0,0 +1,3 @@
+func test():
+ # Error here.
+ print(2.2 << 4)
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.out b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.out
new file mode 100644
index 0000000000..7dee854d1a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_left_operand.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Invalid operands to operator <<, float and int.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.gd b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.gd
new file mode 100644
index 0000000000..4502960105
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.gd
@@ -0,0 +1,3 @@
+func test():
+ # Error here.
+ print(2 << 4.4)
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.out b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.out
new file mode 100644
index 0000000000..1879fc1adf
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/bitwise_float_right_operand.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Invalid operands to operator <<, int and float.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.gd b/modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.gd
new file mode 100644
index 0000000000..0ad2337c15
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.gd
@@ -0,0 +1,5 @@
+const CONSTANT = 25
+
+
+func test():
+ CONSTANT(123)
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.out b/modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.out
new file mode 100644
index 0000000000..f4051cd02c
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/constant_used_as_function.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Member "CONSTANT" is not a function.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.gd b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.gd
new file mode 100644
index 0000000000..7a922cd73e
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.gd
@@ -0,0 +1,6 @@
+func test():
+ var lua_dict = {
+ a = 1,
+ b = 2,
+ a = 3, # Duplicate isn't allowed.
+ }
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.out b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.out
new file mode 100644
index 0000000000..ffdfa56645
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Key "a" was already used in this dictionary (at line 3).
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.gd b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.gd
new file mode 100644
index 0000000000..933e737ac7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.gd
@@ -0,0 +1,6 @@
+func test():
+ var lua_dict_with_string = {
+ a = 1,
+ b = 2,
+ "a" = 3, # Duplicate isn't allowed.
+ }
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.out b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.out
new file mode 100644
index 0000000000..ffdfa56645
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_lua_with_string.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Key "a" was already used in this dictionary (at line 3).
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.gd b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.gd
new file mode 100644
index 0000000000..3b8c83e9cb
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.gd
@@ -0,0 +1,6 @@
+func test():
+ var python_dict = {
+ "a": 1,
+ "b": 2,
+ "a": 3, # Duplicate isn't allowed.
+ }
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.out b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.out
new file mode 100644
index 0000000000..ffdfa56645
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/dictionary_duplicate_key_python.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Key "a" was already used in this dictionary (at line 3).
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.gd b/modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.gd
new file mode 100644
index 0000000000..cf9a0ce038
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.gd
@@ -0,0 +1,7 @@
+enum Size {
+ # Error here. Enum values must be integers.
+ S = 0.0,
+}
+
+func test():
+ pass
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.out b/modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.out
new file mode 100644
index 0000000000..b315d20508
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/enum_float_value.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Enum values must be integers.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.gd b/modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.gd
new file mode 100644
index 0000000000..cd9b8fabc4
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.gd
@@ -0,0 +1,7 @@
+enum Size {
+ # Error here. Enum values must be integers.
+ S = "hello",
+}
+
+func test():
+ pass
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.out b/modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.out
new file mode 100644
index 0000000000..b315d20508
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/enum_string_value.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Enum values must be integers.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.gd b/modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.gd
new file mode 100644
index 0000000000..4346503fc2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.gd
@@ -0,0 +1,6 @@
+func function():
+ pass
+
+
+func test():
+ function = 25
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.out b/modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.out
new file mode 100644
index 0000000000..5275183da2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/function_used_as_property.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Cannot assign a new value to a constant.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.gd b/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.gd
new file mode 100644
index 0000000000..b8c0b7a8d3
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.gd
@@ -0,0 +1,3 @@
+func test():
+ # Error here. Array indices must be integers.
+ print([0, 1][true])
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out b/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out
new file mode 100644
index 0000000000..015ad756f8
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_array_index.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Invalid index type "bool" for a base of type "Array".
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.gd b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.gd
new file mode 100644
index 0000000000..c159e03140
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.gd
@@ -0,0 +1,2 @@
+func test():
+ print(true + true)
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.out b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.out
new file mode 100644
index 0000000000..c1dc7c7d08
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_bool.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Invalid operands to operator +, bool and bool.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.gd b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.gd
new file mode 100644
index 0000000000..6aec2e0796
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.gd
@@ -0,0 +1,2 @@
+func test():
+ print({"hello": "world"} + {"godot": "engine"})
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.out b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.out
new file mode 100644
index 0000000000..1b4451edbe
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_dictionary.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Invalid operands "Dictionary" and "Dictionary" for "+" operator.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.gd b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.gd
new file mode 100644
index 0000000000..eb2a6a0ce7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.gd
@@ -0,0 +1,2 @@
+func test():
+ print("hello" + ["world"])
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.out b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.out
new file mode 100644
index 0000000000..6d44c6c1bd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_concatenation_mixed.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Invalid operands "String" and "Array" for "+" operator.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.gd b/modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.gd
new file mode 100644
index 0000000000..a7426e88da
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.gd
@@ -0,0 +1,5 @@
+func test():
+ var i = 12
+ # Constants must be made of a constant, deterministic expression.
+ # A constant that depends on a variable's value is not a constant expression.
+ const TEST = 13 + i
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.out b/modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.out
new file mode 100644
index 0000000000..c40830f123
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/invalid_constant.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Assigned value for constant "TEST" isn't a constant expression.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.gd b/modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.gd
new file mode 100644
index 0000000000..d88c02d6ee
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.gd
@@ -0,0 +1,3 @@
+func test():
+ # Number separators may not be placed at the beginning of a number.
+ var __ = _123
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.out b/modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.out
new file mode 100644
index 0000000000..cfb558bf45
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/leading_number_separator.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Identifier "_123" not declared in the current scope.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/missing_argument.gd b/modules/gdscript/tests/scripts/analyzer/errors/missing_argument.gd
new file mode 100644
index 0000000000..70bdadf291
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/missing_argument.gd
@@ -0,0 +1,6 @@
+func args(a, b):
+ print(a)
+ print(b)
+
+func test():
+ args(1,)
diff --git a/modules/gdscript/tests/scripts/parser/errors/missing_argument.out b/modules/gdscript/tests/scripts/analyzer/errors/missing_argument.out
index fc2a891109..fc2a891109 100644
--- a/modules/gdscript/tests/scripts/parser/errors/missing_argument.out
+++ b/modules/gdscript/tests/scripts/analyzer/errors/missing_argument.out
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.gd b/modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.gd
new file mode 100644
index 0000000000..059d774927
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.gd
@@ -0,0 +1,4 @@
+var property = 25
+
+func test():
+ property()
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.out b/modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.out
new file mode 100644
index 0000000000..94d6c26a1a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/property_used_as_function.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Member "property" is not a function.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.gd b/modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.gd
new file mode 100644
index 0000000000..91401d32fc
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.gd
@@ -0,0 +1,7 @@
+# See also `parser-warnings/shadowed-constant.gd`.
+const TEST = 25
+
+
+func test():
+ # Error here (trying to set a new value to a constant).
+ TEST = 50
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.out b/modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.out
new file mode 100644
index 0000000000..5275183da2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/redefine_class_constant.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Cannot assign a new value to a constant.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.gd b/modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.gd
new file mode 100644
index 0000000000..97f3e55e81
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.gd
@@ -0,0 +1,5 @@
+func test():
+ const TEST = 25
+
+ # Error here (can't assign a new value to a constant).
+ TEST = 50
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.out b/modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.out
new file mode 100644
index 0000000000..5275183da2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/redefine_local_constant.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Cannot assign a new value to a constant.
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.gd b/modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.gd
new file mode 100644
index 0000000000..722a8fcdb7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.gd
@@ -0,0 +1,11 @@
+# `class` extends RefCounted by default.
+class Say:
+ func say():
+ super()
+ print("say something")
+
+
+func test():
+ # RefCounted doesn't have a `say()` method, so the `super()` call in the method
+ # definition will cause a run-time error.
+ Say.new().say()
diff --git a/modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.out b/modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.out
new file mode 100644
index 0000000000..e3dbf81850
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/errors/super_nonexistent_base_method.out
@@ -0,0 +1,2 @@
+GDTEST_ANALYZER_ERROR
+Function "say()" not found in base RefCounted.
diff --git a/modules/gdscript/tests/scripts/analyzer/features/as.gd b/modules/gdscript/tests/scripts/analyzer/features/as.gd
new file mode 100644
index 0000000000..13a36147c0
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/as.gd
@@ -0,0 +1,16 @@
+func test():
+ var some_bool = 5 as bool
+ var some_int = 5 as int
+ var some_float = 5 as float
+ print(typeof(some_bool))
+ print(typeof(some_int))
+ print(typeof(some_float))
+
+ print()
+
+ var some_bool_typed := 5 as bool
+ var some_int_typed := 5 as int
+ var some_float_typed := 5 as float
+ print(typeof(some_bool_typed))
+ print(typeof(some_int_typed))
+ print(typeof(some_float_typed))
diff --git a/modules/gdscript/tests/scripts/analyzer/features/as.out b/modules/gdscript/tests/scripts/analyzer/features/as.out
new file mode 100644
index 0000000000..bcf84aa6f6
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/as.out
@@ -0,0 +1,8 @@
+GDTEST_OK
+1
+2
+3
+
+1
+2
+3
diff --git a/modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.gd b/modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.gd
new file mode 100644
index 0000000000..135b6c3d85
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.gd
@@ -0,0 +1,16 @@
+extends Node
+
+const NO_TYPE_CONST = 0
+const TYPE_CONST: int = 1
+const GUESS_TYPE_CONST := 2
+
+class Test:
+ var a = NO_TYPE_CONST
+ var b = TYPE_CONST
+ var c = GUESS_TYPE_CONST
+
+func test():
+ var test_instance = Test.new()
+ prints("a", test_instance.a, test_instance.a == NO_TYPE_CONST)
+ prints("b", test_instance.b, test_instance.b == TYPE_CONST)
+ prints("c", test_instance.c, test_instance.c == GUESS_TYPE_CONST)
diff --git a/modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.out b/modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.out
new file mode 100644
index 0000000000..a96bb84246
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/constants_from_parent.out
@@ -0,0 +1,4 @@
+GDTEST_OK
+a 0 true
+b 1 true
+c 2 true
diff --git a/modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.gd b/modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.gd
new file mode 100644
index 0000000000..5f57c5b8c2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.gd
@@ -0,0 +1,14 @@
+extends Node
+
+enum Named { VALUE_A, VALUE_B, VALUE_C = 42 }
+
+class Test:
+ var a = Named.VALUE_A
+ var b = Named.VALUE_B
+ var c = Named.VALUE_C
+
+func test():
+ var test_instance = Test.new()
+ prints("a", test_instance.a, test_instance.a == Named.VALUE_A)
+ prints("b", test_instance.b, test_instance.b == Named.VALUE_B)
+ prints("c", test_instance.c, test_instance.c == Named.VALUE_C)
diff --git a/modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.out b/modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.out
new file mode 100644
index 0000000000..c160839da3
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/enum_from_parent.out
@@ -0,0 +1,4 @@
+GDTEST_OK
+a 0 true
+b 1 true
+c 42 true
diff --git a/modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.gd b/modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.gd
new file mode 100644
index 0000000000..26edce353d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.gd
@@ -0,0 +1,14 @@
+extends Node
+
+enum { VALUE_A, VALUE_B, VALUE_C = 42 }
+
+class Test:
+ var a = VALUE_A
+ var b = VALUE_B
+ var c = VALUE_C
+
+func test():
+ var test_instance = Test.new()
+ prints("a", test_instance.a, test_instance.a == VALUE_A)
+ prints("b", test_instance.b, test_instance.b == VALUE_B)
+ prints("c", test_instance.c, test_instance.c == VALUE_C)
diff --git a/modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.out b/modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.out
new file mode 100644
index 0000000000..c160839da3
--- /dev/null
+++ b/modules/gdscript/tests/scripts/analyzer/features/enum_value_from_parent.out
@@ -0,0 +1,4 @@
+GDTEST_OK
+a 0 true
+b 1 true
+c 42 true
diff --git a/modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.gd b/modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.gd
new file mode 100644
index 0000000000..b45f99fdd0
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.gd
@@ -0,0 +1,3 @@
+func test():
+ # Arrays with consecutive commas are not allowed.
+ var array = ["arrays",,,,]
diff --git a/modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.out b/modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.out
new file mode 100644
index 0000000000..4ef8526065
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/array_consecutive_commas.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression as array element.
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.gd b/modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.gd
new file mode 100644
index 0000000000..17d5e078e5
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.gd
@@ -0,0 +1,2 @@
+func test():
+ var hello == "world"
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.out b/modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.out
new file mode 100644
index 0000000000..b150fc0d16
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_2_equal_signs.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected end of statement after variable declaration, found "==" instead.
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.gd b/modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.gd
new file mode 100644
index 0000000000..8b5f620889
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.gd
@@ -0,0 +1,2 @@
+func test():
+ var hello === "world"
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.out b/modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.out
new file mode 100644
index 0000000000..b150fc0d16
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_3_equal_signs.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected end of statement after variable declaration, found "==" instead.
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_in_if.gd b/modules/gdscript/tests/scripts/parser/errors/assignment_in_if.gd
new file mode 100644
index 0000000000..8c3a908532
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_in_if.gd
@@ -0,0 +1,4 @@
+func test():
+ # Error here.
+ if foo = 25:
+ print(foo)
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_in_if.out b/modules/gdscript/tests/scripts/parser/errors/assignment_in_if.out
new file mode 100644
index 0000000000..e8f9130706
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_in_if.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Assignment is not allowed inside an expression.
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_in_var.gd b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var.gd
new file mode 100644
index 0000000000..126a3227ea
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var.gd
@@ -0,0 +1,2 @@
+func test():
+ var hello = "world" = "test"
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_in_var.out b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var.out
new file mode 100644
index 0000000000..e8f9130706
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Assignment is not allowed inside an expression.
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.gd b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.gd
new file mode 100644
index 0000000000..a99557fa3c
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.gd
@@ -0,0 +1,4 @@
+func test():
+ # Error here.
+ if var foo = 25:
+ print(foo)
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.out b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.out
new file mode 100644
index 0000000000..e84f4652ac
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_in_var_if.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected conditional expression after "if".
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.gd b/modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.gd
new file mode 100644
index 0000000000..031ea523c8
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.gd
@@ -0,0 +1,2 @@
+func test():
+ var = "world"
diff --git a/modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.out b/modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.out
new file mode 100644
index 0000000000..a4bd8beef1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/assignment_without_identifier.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected variable name after "var".
diff --git a/modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.gd b/modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.gd
new file mode 100644
index 0000000000..b52a6defcb
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.gd
@@ -0,0 +1,2 @@
+func test():
+ print(~)
diff --git a/modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.out b/modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.out
new file mode 100644
index 0000000000..ceabe42d3c
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/binary_complement_without_argument.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression after "~" operator.
diff --git a/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.gd b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.gd
new file mode 100644
index 0000000000..b3ea1ba1f6
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.gd
@@ -0,0 +1,2 @@
+func test():
+ print(not)
diff --git a/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.out b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.out
new file mode 100644
index 0000000000..6cf191ea98
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression after "not" operator.
diff --git a/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.gd b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.gd
new file mode 100644
index 0000000000..8a33079193
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.gd
@@ -0,0 +1,2 @@
+func test():
+ print(!)
diff --git a/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.out b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.out
new file mode 100644
index 0000000000..87fcc5e2b0
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/boolean_negation_without_argument_using_bang.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression after "!" operator.
diff --git a/modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.gd b/modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.gd
new file mode 100644
index 0000000000..d13d713454
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.gd
@@ -0,0 +1,6 @@
+# Error here. `class_name` should be used *before* annotations, not after.
+@icon("res://path/to/optional/icon.svg")
+class_name HelloWorld
+
+func test():
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.out b/modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.out
new file mode 100644
index 0000000000..0bcc8acc55
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/class_name_after_annotation.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+"class_name" should be used before annotations.
diff --git a/modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.gd b/modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.gd
new file mode 100644
index 0000000000..49fb4ffedf
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.gd
@@ -0,0 +1,3 @@
+func test():
+ var TEST = 50
+ const TEST = 25
diff --git a/modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.out b/modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.out
new file mode 100644
index 0000000000..407f094ca0
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/constant_conflicts_variable.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+There is already a variable named "TEST" declared in this scope.
diff --git a/modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.gd b/modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.gd
new file mode 100644
index 0000000000..2581d873dd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.gd
@@ -0,0 +1,7 @@
+func hello(arg1):
+ print(arg1)
+
+
+func test():
+ # Error here.
+ hello(arg1 = 25)
diff --git a/modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.out b/modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.out
new file mode 100644
index 0000000000..e8f9130706
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/default_value_in_function_call.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Assignment is not allowed inside an expression.
diff --git a/modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.gd b/modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.gd
new file mode 100644
index 0000000000..92dfb2366d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.gd
@@ -0,0 +1,2 @@
+func test():
+ var dictionary = { hello = "world",, }
diff --git a/modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.out b/modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.out
new file mode 100644
index 0000000000..d1dcd1cb4b
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/double_dictionary_comma.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression as dictionary key.
diff --git a/modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.gd b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.gd
new file mode 100644
index 0000000000..a8f7cf1810
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.gd
@@ -0,0 +1,5 @@
+const test = 25
+
+
+func test():
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.out b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.out
new file mode 100644
index 0000000000..c614acd094
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_constant.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Function "test" has the same name as a previously declared constant.
diff --git a/modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.gd b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.gd
new file mode 100644
index 0000000000..5c86710a40
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.gd
@@ -0,0 +1,7 @@
+func test():
+ pass
+
+
+# Error here. The difference with `variable-conflicts-function.gd` is that here,
+# the function is defined *before* the variable.
+var test = 25
diff --git a/modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.out b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.out
new file mode 100644
index 0000000000..551db61531
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/function_conflicts_variable.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Variable "test" has the same name as a previously declared function.
diff --git a/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.gd b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.gd
new file mode 100644
index 0000000000..081b9faf4b
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.gd
@@ -0,0 +1,3 @@
+func test():
+ # Error here.
+ var 23test = "is not a valid identifier"
diff --git a/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.out b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.out
new file mode 100644
index 0000000000..a4bd8beef1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_number.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected variable name after "var".
diff --git a/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.gd b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.gd
new file mode 100644
index 0000000000..fa4d6b5cac
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.gd
@@ -0,0 +1,3 @@
+func test():
+ # Error here.
+ var "yes" = "is not a valid identifier"
diff --git a/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.out b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.out
new file mode 100644
index 0000000000..a4bd8beef1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/invalid_identifier_string.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected variable name after "var".
diff --git a/modules/gdscript/tests/scripts/parser/errors/missing_argument.gd b/modules/gdscript/tests/scripts/parser/errors/missing_argument.gd
deleted file mode 100644
index c56ad94095..0000000000
--- a/modules/gdscript/tests/scripts/parser/errors/missing_argument.gd
+++ /dev/null
@@ -1,6 +0,0 @@
-func args(a, b):
- print(a)
- print(b)
-
-func test():
- args(1,)
diff --git a/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.gd b/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.gd
index a1077e1985..8af5f123cc 100644
--- a/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.gd
+++ b/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.gd
@@ -1,2 +1,2 @@
func test():
- var a = ("missing paren ->"
+ var a = ("missing paren ->"
diff --git a/modules/gdscript/tests/scripts/parser/errors/missing_colon.gd b/modules/gdscript/tests/scripts/parser/errors/missing_colon.gd
index 62cb633e9e..0e5e5ce060 100644
--- a/modules/gdscript/tests/scripts/parser/errors/missing_colon.gd
+++ b/modules/gdscript/tests/scripts/parser/errors/missing_colon.gd
@@ -1,3 +1,3 @@
func test():
- if true # Missing colon here.
- print("true")
+ if true # Missing colon here.
+ print("true")
diff --git a/modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.gd b/modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.gd
new file mode 100644
index 0000000000..1f66935329
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.gd
@@ -0,0 +1,4 @@
+func test():
+ var x = 1 if false else
+ print("oops")
+ print(x)
diff --git a/modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.out b/modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.out
new file mode 100644
index 0000000000..dab6b0a1ad
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/missing_expression_after_ternary_else.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression after "else".
diff --git a/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.gd b/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.gd
index 116b0151da..7a35bf688c 100644
--- a/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.gd
+++ b/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.gd
@@ -1,6 +1,6 @@
func args(a, b):
- print(a)
- print(b)
+ print(a)
+ print(b)
func test():
- args(1,2
+ args(1,2
diff --git a/modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.gd b/modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.gd
new file mode 100644
index 0000000000..193f824702
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.gd
@@ -0,0 +1,3 @@
+func test():
+ var a = 0
+ print(a--)
diff --git a/modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.out b/modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.out
new file mode 100644
index 0000000000..b6b577a277
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/mistaken_decrement_operator.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression after "-" operator.
diff --git a/modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.gd b/modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.gd
new file mode 100644
index 0000000000..035d27638c
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.gd
@@ -0,0 +1,3 @@
+func test():
+ var a = 0
+ print(a++)
diff --git a/modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.out b/modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.out
new file mode 100644
index 0000000000..24eb76593a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/mistaken_increment_operator.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected expression after "+" operator.
diff --git a/modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.gd b/modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.gd
new file mode 100644
index 0000000000..71a03fbc0d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.gd
@@ -0,0 +1,3 @@
+func test():
+ # Number separators may not be placed right next to each other.
+ var __ = 1__23
diff --git a/modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.out b/modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.out
new file mode 100644
index 0000000000..71a3c2fd6a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/multiple_number_separators.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Only one underscore can be used as a numeric separator.
diff --git a/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.gd b/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.gd
index 3875ce3936..df388a21de 100644
--- a/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.gd
+++ b/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.gd
@@ -1,3 +1,5 @@
extends Node
+
+
func test():
- var a = $ # Expected some node path.
+ var a = $ # Expected some node path.
diff --git a/modules/gdscript/tests/scripts/parser/errors/redefine_keyword.gd b/modules/gdscript/tests/scripts/parser/errors/redefine_keyword.gd
new file mode 100644
index 0000000000..c289c9d976
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/redefine_keyword.gd
@@ -0,0 +1,2 @@
+func test():
+ var while = "it's been a while"
diff --git a/modules/gdscript/tests/scripts/parser/errors/redefine_keyword.out b/modules/gdscript/tests/scripts/parser/errors/redefine_keyword.out
new file mode 100644
index 0000000000..a4bd8beef1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/redefine_keyword.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Expected variable name after "var".
diff --git a/modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.gd b/modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.gd
new file mode 100644
index 0000000000..204259f981
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.gd
@@ -0,0 +1,5 @@
+func test():
+ const TEST = 25
+
+ # Error here (can't redeclare a constant on the same scope).
+ const TEST = 50
diff --git a/modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.out b/modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.out
new file mode 100644
index 0000000000..d67cc92953
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/redefine_local_constant_with_keyword.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+There is already a constant named "TEST" declared in this scope.
diff --git a/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.gd b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.gd
new file mode 100644
index 0000000000..0d8843df20
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.gd
@@ -0,0 +1,3 @@
+func test():
+ const TEST = 25
+ var TEST = 50
diff --git a/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.out b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.out
new file mode 100644
index 0000000000..d67cc92953
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_constant.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+There is already a constant named "TEST" declared in this scope.
diff --git a/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.gd b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.gd
new file mode 100644
index 0000000000..ce2c8784d6
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.gd
@@ -0,0 +1,6 @@
+var test = 25
+
+# Error here. The difference with `variable-conflicts-function.gd` is that here,
+# the function is defined *before* the variable.
+func test():
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.out b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.out
new file mode 100644
index 0000000000..daeaca40ec
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/errors/variable_conflicts_function.out
@@ -0,0 +1,2 @@
+GDTEST_PARSER_ERROR
+Function "test" has the same name as a previously declared variable.
diff --git a/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.gd b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.gd
index 6fd2692d47..babe39068c 100644
--- a/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.gd
+++ b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.gd
@@ -1,3 +1,5 @@
extends Node
+
+
func test():
- $23 # Can't use number here.
+ $23 # Can't use number here.
diff --git a/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.gd b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.gd
index 1836d42226..b6b1cf3e52 100644
--- a/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.gd
+++ b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.gd
@@ -1,3 +1,5 @@
extends Node
+
+
func test():
- $MyNode/23 # Can't use number here.
+ $MyNode/23 # Can't use number here.
diff --git a/modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.gd b/modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.gd
new file mode 100644
index 0000000000..43b513045b
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.gd
@@ -0,0 +1,34 @@
+func foo(x):
+ match x:
+ 1 + 1:
+ print("1+1")
+ [1,2,[1,{1:2,2:var z,..}]]:
+ print("[1,2,[1,{1:2,2:var z,..}]]")
+ print(z)
+ 1 if true else 2:
+ print("1 if true else 2")
+ 1 < 2:
+ print("1 < 2")
+ 1 or 2 and 1:
+ print("1 or 2 and 1")
+ 6 | 1:
+ print("1 | 1")
+ 1 >> 1:
+ print("1 >> 1")
+ 1, 2 or 3, 4:
+ print("1, 2 or 3, 4")
+ _:
+ print("wildcard")
+
+func test():
+ foo(6 | 1)
+ foo(1 >> 1)
+ foo(2)
+ foo(1)
+ foo(1+1)
+ foo(1 < 2)
+ foo([2, 1])
+ foo(4)
+ foo([1, 2, [1, {1 : 2, 2:3}]])
+ foo([1, 2, [1, {1 : 2, 2:[1,3,5, "123"], 4:2}]])
+ foo([1, 2, [1, {1 : 2}]])
diff --git a/modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.out b/modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.out
new file mode 100644
index 0000000000..67c7e28046
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/advanced_expression_matching.out
@@ -0,0 +1,14 @@
+GDTEST_OK
+1 | 1
+1 >> 1
+1+1
+1 if true else 2
+1+1
+1 < 2
+wildcard
+1, 2 or 3, 4
+[1,2,[1,{1:2,2:var z,..}]]
+3
+[1,2,[1,{1:2,2:var z,..}]]
+[1, 3, 5, 123]
+wildcard
diff --git a/modules/gdscript/tests/scripts/parser/features/array.gd b/modules/gdscript/tests/scripts/parser/features/array.gd
new file mode 100644
index 0000000000..828ce8d134
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/array.gd
@@ -0,0 +1,16 @@
+func test():
+ # Indexing from the beginning:
+ print([1, 2, 3][0])
+ print([1, 2, 3][1])
+ print([1, 2, 3][2])
+
+ # Indexing from the end:
+ print([1, 2, 3][-1])
+ print([1, 2, 3][-2])
+ print([1, 2, 3][-3])
+
+ # Float indices are currently allowed, but should probably be an error?
+ print([1, 2, 3][0.4])
+ print([1, 2, 3][0.8])
+ print([1, 2, 3][1.0])
+ print([1, 2, 3][-1.0])
diff --git a/modules/gdscript/tests/scripts/parser/features/array.out b/modules/gdscript/tests/scripts/parser/features/array.out
new file mode 100644
index 0000000000..cf576c59e0
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/array.out
@@ -0,0 +1,11 @@
+GDTEST_OK
+1
+2
+3
+3
+2
+1
+1
+1
+2
+3
diff --git a/modules/gdscript/tests/scripts/parser/features/basic_expression_matching.gd b/modules/gdscript/tests/scripts/parser/features/basic_expression_matching.gd
new file mode 100644
index 0000000000..2b46f1e88a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/basic_expression_matching.gd
@@ -0,0 +1,27 @@
+func foo(x):
+ match x:
+ 1:
+ print("1")
+ 2:
+ print("2")
+ [1, 2]:
+ print("[1, 2]")
+ 3 or 4:
+ print("3 or 4")
+ 4:
+ print("4")
+ {1 : 2, 2 : 3}:
+ print("{1 : 2, 2 : 3}")
+ _:
+ print("wildcard")
+
+func test():
+ foo(0)
+ foo(1)
+ foo(2)
+ foo([1, 2])
+ foo(3)
+ foo(4)
+ foo([4,4])
+ foo({1 : 2, 2 : 3})
+ foo({1 : 2, 4 : 3})
diff --git a/modules/gdscript/tests/scripts/parser/features/basic_expression_matching.out b/modules/gdscript/tests/scripts/parser/features/basic_expression_matching.out
new file mode 100644
index 0000000000..46ee4b04da
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/basic_expression_matching.out
@@ -0,0 +1,10 @@
+GDTEST_OK
+wildcard
+1
+2
+[1, 2]
+wildcard
+4
+wildcard
+{1 : 2, 2 : 3}
+wildcard
diff --git a/modules/gdscript/tests/scripts/parser/features/bitwise_operators.gd b/modules/gdscript/tests/scripts/parser/features/bitwise_operators.gd
new file mode 100644
index 0000000000..de502c6ed1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/bitwise_operators.gd
@@ -0,0 +1,50 @@
+enum Flags {
+ FIRE = 1 << 1,
+ ICE = 1 << 2,
+ SLIPPERY = 1 << 3,
+ STICKY = 1 << 4,
+ NONSOLID = 1 << 5,
+
+ ALL = FIRE | ICE | SLIPPERY | STICKY | NONSOLID,
+}
+
+
+func test():
+ var flags = Flags.FIRE | Flags.SLIPPERY
+ print(flags)
+
+ flags = Flags.FIRE & Flags.SLIPPERY
+ print(flags)
+
+ flags = Flags.FIRE ^ Flags.SLIPPERY
+ print(flags)
+
+ flags = Flags.ALL & (Flags.FIRE | Flags.ICE)
+ print(flags)
+
+ flags = (Flags.ALL & Flags.FIRE) | Flags.ICE
+ print(flags)
+
+ flags = Flags.ALL & Flags.FIRE | Flags.ICE
+ print(flags)
+
+ # Enum value must be casted to an integer. Otherwise, a parser error is emitted.
+ flags &= int(Flags.ICE)
+ print(flags)
+
+ flags ^= int(Flags.ICE)
+ print(flags)
+
+ flags |= int(Flags.STICKY | Flags.SLIPPERY)
+ print(flags)
+
+ print()
+
+ var num = 2 << 4
+ print(num)
+
+ num <<= 2
+ print(num)
+
+ num >>= 2
+ print(num)
diff --git a/modules/gdscript/tests/scripts/parser/features/bitwise_operators.out b/modules/gdscript/tests/scripts/parser/features/bitwise_operators.out
new file mode 100644
index 0000000000..410e358a05
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/bitwise_operators.out
@@ -0,0 +1,14 @@
+GDTEST_OK
+10
+0
+10
+6
+6
+6
+4
+0
+24
+
+32
+128
+32
diff --git a/modules/gdscript/tests/scripts/parser/features/class.gd b/modules/gdscript/tests/scripts/parser/features/class.gd
new file mode 100644
index 0000000000..6652f85ad9
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/class.gd
@@ -0,0 +1,25 @@
+# Test non-nested/slightly nested class architecture.
+class Test:
+ var number = 25
+ var string = "hello"
+
+
+class TestSub extends Test:
+ var other_string = "bye"
+
+
+class TestConstructor:
+ func _init(argument = 10):
+ print(str("constructor with argument ", argument))
+
+
+func test():
+ var test_instance = Test.new()
+ test_instance.number = 42
+
+ var test_sub = TestSub.new()
+ assert(test_sub.number == 25) # From Test.
+ assert(test_sub.other_string == "bye") # From TestSub.
+
+ TestConstructor.new()
+ TestConstructor.new(500)
diff --git a/modules/gdscript/tests/scripts/parser/features/class.out b/modules/gdscript/tests/scripts/parser/features/class.out
new file mode 100644
index 0000000000..94dc2d6003
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/class.out
@@ -0,0 +1,3 @@
+GDTEST_OK
+constructor with argument 10
+constructor with argument 500
diff --git a/modules/gdscript/tests/scripts/parser/features/class_inheritance.gd b/modules/gdscript/tests/scripts/parser/features/class_inheritance.gd
new file mode 100644
index 0000000000..3f9b4ea86e
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/class_inheritance.gd
@@ -0,0 +1,33 @@
+# Test deeply nested class architectures.
+class Test:
+ var depth = 1
+
+ class Nested:
+ var depth_nested = 10
+
+
+class Test2 extends Test:
+ var depth2 = 2
+
+
+class Test3 extends Test2:
+ var depth3 = 3
+
+
+class Test4 extends Test3:
+ var depth4 = 4
+
+ class Nested2:
+ var depth4_nested = 100
+
+
+func test():
+ print(Test.new().depth)
+ print(Test2.new().depth)
+ print(Test2.new().depth2)
+ print(Test3.new().depth)
+ print(Test3.new().depth3)
+ print(Test4.new().depth)
+ print(Test4.new().depth4)
+ print(Test.Nested.new().depth_nested)
+ print(Test4.Nested2.new().depth4_nested)
diff --git a/modules/gdscript/tests/scripts/parser/features/class_inheritance.out b/modules/gdscript/tests/scripts/parser/features/class_inheritance.out
new file mode 100644
index 0000000000..75bdde3d94
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/class_inheritance.out
@@ -0,0 +1,10 @@
+GDTEST_OK
+1
+1
+2
+1
+3
+1
+4
+10
+100
diff --git a/modules/gdscript/tests/scripts/parser/features/class_name.gd b/modules/gdscript/tests/scripts/parser/features/class_name.gd
new file mode 100644
index 0000000000..8bd188e247
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/class_name.gd
@@ -0,0 +1,5 @@
+class_name HelloWorld
+@icon("res://path/to/optional/icon.svg")
+
+func test():
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/features/class_name.out b/modules/gdscript/tests/scripts/parser/features/class_name.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/class_name.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/concatenation.gd b/modules/gdscript/tests/scripts/parser/features/concatenation.gd
new file mode 100644
index 0000000000..e8335c9823
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/concatenation.gd
@@ -0,0 +1,4 @@
+func test():
+ print(20 + 20)
+ print("hello" + "world")
+ print([1, 2] + [3, 4])
diff --git a/modules/gdscript/tests/scripts/parser/features/concatenation.out b/modules/gdscript/tests/scripts/parser/features/concatenation.out
new file mode 100644
index 0000000000..23bff08f49
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/concatenation.out
@@ -0,0 +1,4 @@
+GDTEST_OK
+40
+helloworld
+[1, 2, 3, 4]
diff --git a/modules/gdscript/tests/scripts/parser/features/constants.gd b/modules/gdscript/tests/scripts/parser/features/constants.gd
new file mode 100644
index 0000000000..013c9c074f
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/constants.gd
@@ -0,0 +1,11 @@
+func test():
+ const _TEST = 12 + 34 - 56 * 78
+ const _STRING = "yes"
+ const _VECTOR = Vector2(5, 6)
+ const _ARRAY = []
+ const _DICTIONARY = {"this": "dictionary"}
+
+ # Create user constants from built-in constants.
+ const _HELLO = PI + TAU
+ const _INFINITY = INF
+ const _NOT_A_NUMBER = NAN
diff --git a/modules/gdscript/tests/scripts/parser/features/constants.out b/modules/gdscript/tests/scripts/parser/features/constants.out
new file mode 100644
index 0000000000..6093e4a6ca
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/constants.out
@@ -0,0 +1,33 @@
+GDTEST_OK
+>> WARNING
+>> Line: 2
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_TEST' is declared but never used in the block. If this is intended, prefix it with an underscore: '__TEST'
+>> WARNING
+>> Line: 3
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_STRING' is declared but never used in the block. If this is intended, prefix it with an underscore: '__STRING'
+>> WARNING
+>> Line: 4
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_VECTOR' is declared but never used in the block. If this is intended, prefix it with an underscore: '__VECTOR'
+>> WARNING
+>> Line: 5
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_ARRAY' is declared but never used in the block. If this is intended, prefix it with an underscore: '__ARRAY'
+>> WARNING
+>> Line: 6
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_DICTIONARY' is declared but never used in the block. If this is intended, prefix it with an underscore: '__DICTIONARY'
+>> WARNING
+>> Line: 9
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_HELLO' is declared but never used in the block. If this is intended, prefix it with an underscore: '__HELLO'
+>> WARNING
+>> Line: 10
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_INFINITY' is declared but never used in the block. If this is intended, prefix it with an underscore: '__INFINITY'
+>> WARNING
+>> Line: 11
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_NOT_A_NUMBER' is declared but never used in the block. If this is intended, prefix it with an underscore: '__NOT_A_NUMBER'
diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary.gd b/modules/gdscript/tests/scripts/parser/features/dictionary.gd
new file mode 100644
index 0000000000..99afe166c7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dictionary.gd
@@ -0,0 +1,37 @@
+func test():
+ # Non-string keys are valid.
+ print({ 12: "world" }[12])
+
+ var contents = {
+ 0: "zero",
+ 0.0: "zero point zero",
+ null: "null",
+ false: "false",
+ []: "empty array",
+ Vector2i(): "zero Vector2i",
+ 15: {
+ 22: {
+ 4: ["nesting", "arrays"],
+ },
+ },
+ }
+
+ print(contents[0.0])
+ # Making sure declaration order doesn't affect things...
+ print({ 0.0: "zero point zero", 0: "zero", null: "null", false: "false", []: "empty array" }[0])
+ print({ 0.0: "zero point zero", 0: "zero", null: "null", false: "false", []: "empty array" }[0.0])
+
+ print(contents[null])
+ print(contents[false])
+ print(contents[[]])
+ print(contents[Vector2i()])
+ print(contents[15])
+ print(contents[15][22])
+ print(contents[15][22][4])
+ print(contents[15][22][4][0])
+ print(contents[15][22][4][1])
+
+ # Currently fails with "invalid get index 'hello' on base Dictionary".
+ # Both syntaxes are valid however.
+ #print({ "hello": "world" }["hello"])
+ #print({ "hello": "world" }.hello)
diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary.out b/modules/gdscript/tests/scripts/parser/features/dictionary.out
new file mode 100644
index 0000000000..54083c1afc
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dictionary.out
@@ -0,0 +1,14 @@
+GDTEST_OK
+world
+zero point zero
+zero
+zero point zero
+null
+false
+empty array
+zero Vector2i
+{22:{4:[nesting, arrays]}}
+{4:[nesting, arrays]}
+[nesting, arrays]
+nesting
+arrays
diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.gd b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.gd
new file mode 100644
index 0000000000..fdd6de2348
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.gd
@@ -0,0 +1,9 @@
+func test():
+ var lua_dict = {
+ a = 1,
+ "b" = 2, # Using strings are allowed too.
+ "with spaces" = 3, # Especially useful when key has spaces...
+ "2" = 4, # ... or invalid identifiers.
+ }
+
+ print(lua_dict)
diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out
new file mode 100644
index 0000000000..447d7e223c
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dictionary_lua_style.out
@@ -0,0 +1,2 @@
+GDTEST_OK
+{2:4, a:1, b:2, with spaces:3}
diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.gd b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.gd
new file mode 100644
index 0000000000..cce8538ddd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.gd
@@ -0,0 +1,12 @@
+func test():
+ # Mixing Python-style and Lua-style syntax in the same dictionary declaration
+ # is allowed.
+ var dict = {
+ "hello": {
+ world = {
+ "is": "beautiful",
+ },
+ },
+ }
+
+ print(dict)
diff --git a/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out
new file mode 100644
index 0000000000..62be807a1f
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dictionary_mixed_syntax.out
@@ -0,0 +1,2 @@
+GDTEST_OK
+{hello:{world:{is:beautiful}}}
diff --git a/modules/gdscript/tests/scripts/parser/features/dollar_node_paths.gd b/modules/gdscript/tests/scripts/parser/features/dollar_node_paths.gd
new file mode 100644
index 0000000000..8ba558e91d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dollar_node_paths.gd
@@ -0,0 +1,20 @@
+extends Node
+
+
+func test():
+ # Create the required node structure.
+ var hello = Node.new()
+ hello.name = "Hello"
+ add_child(hello)
+ var world = Node.new()
+ world.name = "World"
+ hello.add_child(world)
+
+ # All the ways of writing node paths below with the `$` operator are valid.
+ # Results are assigned to variables to avoid warnings.
+ var __ = $Hello
+ __ = $"Hello"
+ __ = $Hello/World
+ __ = $"Hello/World"
+ __ = $"Hello/.."
+ __ = $"Hello/../Hello/World"
diff --git a/modules/gdscript/tests/scripts/parser/features/dollar_node_paths.out b/modules/gdscript/tests/scripts/parser/features/dollar_node_paths.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/dollar_node_paths.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/enum.gd b/modules/gdscript/tests/scripts/parser/features/enum.gd
new file mode 100644
index 0000000000..bbc66f6f3d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/enum.gd
@@ -0,0 +1,14 @@
+enum Size {
+ S = -10,
+ M,
+ L = 0,
+ XL = 10,
+ XXL,
+}
+
+func test():
+ print(Size.S)
+ print(Size.M)
+ print(Size.L)
+ print(Size.XL)
+ print(Size.XXL)
diff --git a/modules/gdscript/tests/scripts/parser/features/enum.out b/modules/gdscript/tests/scripts/parser/features/enum.out
new file mode 100644
index 0000000000..6f3a4a3e49
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/enum.out
@@ -0,0 +1,6 @@
+GDTEST_OK
+-10
+-9
+0
+10
+11
diff --git a/modules/gdscript/tests/scripts/parser/features/export_variable.gd b/modules/gdscript/tests/scripts/parser/features/export_variable.gd
new file mode 100644
index 0000000000..51e7d4a8ed
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/export_variable.gd
@@ -0,0 +1,11 @@
+@export var example = 99
+@export_range(0, 100) var example_range = 100
+@export_range(0, 100, 1) var example_range_step = 101
+@export_range(0, 100, 1, "or_greater") var example_range_step_or_greater = 102
+
+
+func test():
+ print(example)
+ print(example_range)
+ print(example_range_step)
+ print(example_range_step_or_greater)
diff --git a/modules/gdscript/tests/scripts/parser/features/export_variable.out b/modules/gdscript/tests/scripts/parser/features/export_variable.out
new file mode 100644
index 0000000000..b455196359
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/export_variable.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+99
+100
+101
+102
diff --git a/modules/gdscript/tests/scripts/parser/features/float_notation.gd b/modules/gdscript/tests/scripts/parser/features/float_notation.gd
new file mode 100644
index 0000000000..b207b88820
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/float_notation.gd
@@ -0,0 +1,24 @@
+func test():
+ # The following floating-point notations are all valid:
+ print(is_equal_approx(123., 123))
+ print(is_equal_approx(.123, 0.123))
+ print(is_equal_approx(.123e4, 1230))
+ print(is_equal_approx(123.e4, 1.23e6))
+ print(is_equal_approx(.123e-1, 0.0123))
+ print(is_equal_approx(123.e-1, 12.3))
+
+ # Same as above, but with negative numbers.
+ print(is_equal_approx(-123., -123))
+ print(is_equal_approx(-.123, -0.123))
+ print(is_equal_approx(-.123e4, -1230))
+ print(is_equal_approx(-123.e4, -1.23e6))
+ print(is_equal_approx(-.123e-1, -0.0123))
+ print(is_equal_approx(-123.e-1, -12.3))
+
+ # Same as above, but with explicit positive numbers (which is redundant).
+ print(is_equal_approx(+123., +123))
+ print(is_equal_approx(+.123, +0.123))
+ print(is_equal_approx(+.123e4, +1230))
+ print(is_equal_approx(+123.e4, +1.23e6))
+ print(is_equal_approx(+.123e-1, +0.0123))
+ print(is_equal_approx(+123.e-1, +12.3))
diff --git a/modules/gdscript/tests/scripts/parser/features/float_notation.out b/modules/gdscript/tests/scripts/parser/features/float_notation.out
new file mode 100644
index 0000000000..041c4439b0
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/float_notation.out
@@ -0,0 +1,19 @@
+GDTEST_OK
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
diff --git a/modules/gdscript/tests/scripts/parser/features/for_range.gd b/modules/gdscript/tests/scripts/parser/features/for_range.gd
new file mode 100644
index 0000000000..fd1d002b82
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/for_range.gd
@@ -0,0 +1,39 @@
+func test():
+ for i in range(5):
+ print(i)
+
+ print()
+
+ # Equivalent to the above `for` loop:
+ for i in 5:
+ print(i)
+
+ print()
+
+ for i in range(1, 5):
+ print(i)
+
+ print()
+
+ for i in range(1, -5, -1):
+ print(i)
+
+ print()
+
+ for i in [2, 4, 6, -8]:
+ print(i)
+
+ print()
+
+ for i in [true, false]:
+ print(i)
+
+ print()
+
+ for i in [Vector2i(10, 20), Vector2i(-30, -40)]:
+ print(i)
+
+ print()
+
+ for i in "Hello_Unicôde_world!_🦄":
+ print(i)
diff --git a/modules/gdscript/tests/scripts/parser/features/for_range.out b/modules/gdscript/tests/scripts/parser/features/for_range.out
new file mode 100644
index 0000000000..50b2c856c5
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/for_range.out
@@ -0,0 +1,58 @@
+GDTEST_OK
+0
+1
+2
+3
+4
+
+0
+1
+2
+3
+4
+
+1
+2
+3
+4
+
+1
+0
+-1
+-2
+-3
+-4
+
+2
+4
+6
+-8
+
+true
+false
+
+(10, 20)
+(-30, -40)
+
+H
+e
+l
+l
+o
+_
+U
+n
+i
+c
+ô
+d
+e
+_
+w
+o
+r
+l
+d
+!
+_
+🦄
diff --git a/modules/gdscript/tests/scripts/parser/features/in.gd b/modules/gdscript/tests/scripts/parser/features/in.gd
new file mode 100644
index 0000000000..f7296017c5
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/in.gd
@@ -0,0 +1,14 @@
+func test():
+ print("dot" in "Godot")
+ print(not "i" in "team")
+
+ print(true in [true, false])
+ print(not null in [true, false])
+ print(null in [null])
+
+ print(26 in [8, 26, 64, 100])
+ print(not Vector2i(10, 20) in [Vector2i(20, 10)])
+
+ print("apple" in { "apple": "fruit" })
+ print("apple" in { "apple": null })
+ print(not "apple" in { "fruit": "apple" })
diff --git a/modules/gdscript/tests/scripts/parser/features/in.out b/modules/gdscript/tests/scripts/parser/features/in.out
new file mode 100644
index 0000000000..7533f6ff54
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/in.out
@@ -0,0 +1,11 @@
+GDTEST_OK
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
diff --git a/modules/gdscript/tests/scripts/parser/features/match.gd b/modules/gdscript/tests/scripts/parser/features/match.gd
new file mode 100644
index 0000000000..4d05490aa5
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/match.gd
@@ -0,0 +1,18 @@
+func test():
+ var i = "Hello"
+ match i:
+ "Hello":
+ print("hello")
+ # This will fall through to the default case below.
+ continue
+ "Good bye":
+ print("bye")
+ _:
+ print("default")
+
+ var j = 25
+ match j:
+ 26:
+ print("This won't match")
+ _:
+ print("This will match")
diff --git a/modules/gdscript/tests/scripts/parser/features/match.out b/modules/gdscript/tests/scripts/parser/features/match.out
new file mode 100644
index 0000000000..732885c7a2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/match.out
@@ -0,0 +1,4 @@
+GDTEST_OK
+hello
+default
+This will match
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_arrays.gd b/modules/gdscript/tests/scripts/parser/features/multiline_arrays.gd
new file mode 100644
index 0000000000..3b30998853
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_arrays.gd
@@ -0,0 +1,7 @@
+func test():
+ var __ = [
+ "this",
+ "is", "a","multiline",
+
+ "array", "with mixed indentation and trailing comma",
+ ]
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_arrays.out b/modules/gdscript/tests/scripts/parser/features/multiline_arrays.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_arrays.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.gd b/modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.gd
new file mode 100644
index 0000000000..e108cd23d4
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.gd
@@ -0,0 +1,10 @@
+func test():
+ var __ = {
+ "multiline": "dictionary","should": "work",
+ "even with": "a trailing comma",
+ }
+
+ __ = {
+ this_also_applies = "to the",
+ lua_style_syntax = null, foo = null,
+ }
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.out b/modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_dictionaries.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_if.gd b/modules/gdscript/tests/scripts/parser/features/multiline_if.gd
new file mode 100644
index 0000000000..86152f4543
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_if.gd
@@ -0,0 +1,14 @@
+func test():
+ # Line breaks are allowed within parentheses.
+ if (
+ 1 == 1
+ and 2 == 2 and
+ 3 == 3
+ ):
+ pass
+
+ # Alternatively, backslashes can be used.
+ if 1 == 1 \
+ and 2 == 2 and \
+ 3 == 3:
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_if.out b/modules/gdscript/tests/scripts/parser/features/multiline_if.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_if.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_strings.gd b/modules/gdscript/tests/scripts/parser/features/multiline_strings.gd
new file mode 100644
index 0000000000..7f5bba85e7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_strings.gd
@@ -0,0 +1,15 @@
+func test():
+ var __ = """
+ This is a standalone string, not a multiline comment.
+ Writing both "double" quotes and 'simple' quotes is fine as
+ long as there is only ""one"" or ''two'' of those in a row, not more.
+
+ If you have more quotes, they need to be escaped like this: \"\"\"
+ """
+ __ = '''
+ Another standalone string, this time with single quotes.
+ Writing both "double" quotes and 'simple' quotes is fine as
+ long as there is only ""one"" or ''two'' of those in a row, not more.
+
+ If you have more quotes, they need to be escaped like this: \'\'\'
+ '''
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_strings.out b/modules/gdscript/tests/scripts/parser/features/multiline_strings.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_strings.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_vector.gd b/modules/gdscript/tests/scripts/parser/features/multiline_vector.gd
new file mode 100644
index 0000000000..11a40fc00e
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_vector.gd
@@ -0,0 +1,17 @@
+func test():
+ Vector2(
+ 1,
+ 2
+ )
+
+ Vector3(
+ 3,
+ 3.5,
+ 4, # Trailing comma should work.
+ )
+
+ Vector2i(1, 2,) # Trailing comma should work.
+
+ Vector3i(6,
+ 9,
+ 12)
diff --git a/modules/gdscript/tests/scripts/parser/features/multiline_vector.out b/modules/gdscript/tests/scripts/parser/features/multiline_vector.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/multiline_vector.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_arithmetic.gd b/modules/gdscript/tests/scripts/parser/features/nested_arithmetic.gd
new file mode 100644
index 0000000000..b9bd19c9c5
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_arithmetic.gd
@@ -0,0 +1,22 @@
+func test():
+ print(+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++2.718)
+
+ print()
+
+ print(------------------------------------------------------------------2.718)
+ print(-------------------------------------------------------------------2.718)
+
+ print()
+
+ print(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~999)
+
+ print()
+
+ print(+-+-+-----+------------+++++++---++--++--+--+---+--++2.718)
+
+ print()
+
+ print(2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 0.444)
+ print(153023902390239 % 550 % 29 % 27 % 23 % 17)
+ print(2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 << 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2 >> 2)
+ print(8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8 ^ -8 ^ 8 ^ 8 ^ 8 ^ 8 ^ 8)
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_arithmetic.out b/modules/gdscript/tests/scripts/parser/features/nested_arithmetic.out
new file mode 100644
index 0000000000..048cfbdfae
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_arithmetic.out
@@ -0,0 +1,82 @@
+GDTEST_OK
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+>> WARNING
+>> Line: 19
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
+2.718
+
+2.718
+-2.718
+
+-1000
+
+-2.718
+
+36900.9009009009
+2
+8192
+-8
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_array.gd b/modules/gdscript/tests/scripts/parser/features/nested_array.gd
new file mode 100644
index 0000000000..3caef96391
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_array.gd
@@ -0,0 +1,5 @@
+func test():
+ var array = [[[[[[[[[[15]]]]]]]]]]
+ print(array[0][0][0][0][0][0][0][0])
+ print(array[0][0][0][0][0][0][0][0][0])
+ print(array[0][0][0][0][0][0][0][0][0][0])
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_array.out b/modules/gdscript/tests/scripts/parser/features/nested_array.out
new file mode 100644
index 0000000000..46c6ce3874
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_array.out
@@ -0,0 +1,4 @@
+GDTEST_OK
+[[15]]
+[15]
+15
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_dictionary.gd b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.gd
new file mode 100644
index 0000000000..d67e142156
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.gd
@@ -0,0 +1,6 @@
+func test():
+ var dictionary = {1: {2: {3: {4: {5: {6: {7: {8: {"key": "value"}}}}}}}}}
+ print(dictionary[1][2][3][4][5][6][7])
+ print(dictionary[1][2][3][4][5][6][7][8])
+ print(dictionary[1][2][3][4][5][6][7][8].key)
+ print(dictionary[1][2][3][4][5][6][7][8]["key"])
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out
new file mode 100644
index 0000000000..4009160439
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_dictionary.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+{8:{key:value}}
+{key:value}
+value
+value
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_if.gd b/modules/gdscript/tests/scripts/parser/features/nested_if.gd
new file mode 100644
index 0000000000..7282d08497
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_if.gd
@@ -0,0 +1,57 @@
+func test():
+ # 20 levels of nesting (and then some).
+ if true:
+ print("1")
+ if true:
+ print("2")
+ if true:
+ print("3")
+ if true:
+ print("4")
+ if true:
+ print("5")
+ if true:
+ print("6")
+ if true:
+ print("7")
+ if true:
+ print("8")
+ if true:
+ print("9")
+ if true:
+ print("10")
+ if true:
+ print("11")
+ if true:
+ print("12")
+ if true:
+ print("13")
+ if true:
+ print("14")
+ if true:
+ print("15")
+ if true:
+ print("16")
+ if true:
+ print("17")
+ if true:
+ print("18")
+ if true:
+ print("19")
+ if true:
+ print("20")
+ if false:
+ print("End")
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ if true:
+ print("This won't be printed")
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_if.out b/modules/gdscript/tests/scripts/parser/features/nested_if.out
new file mode 100644
index 0000000000..c2d2e29a06
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_if.out
@@ -0,0 +1,21 @@
+GDTEST_OK
+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_match.gd b/modules/gdscript/tests/scripts/parser/features/nested_match.gd
new file mode 100644
index 0000000000..aaddcc7e83
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_match.gd
@@ -0,0 +1,79 @@
+func test():
+ # 20 levels of nesting (and then some).
+ var number = 1234
+ match number:
+ 1234:
+ print("1")
+ match number:
+ 1234:
+ print("2")
+ match number:
+ 1234:
+ print("3")
+ continue
+ _:
+ print("Should also be printed")
+ match number:
+ 1234:
+ print("4")
+ match number:
+ _:
+ print("5")
+ match number:
+ false:
+ print("Should not be printed")
+ true:
+ print("Should not be printed")
+ "hello":
+ print("Should not be printed")
+ 1234:
+ print("6")
+ match number:
+ _:
+ print("7")
+ match number:
+ 1234:
+ print("8")
+ match number:
+ _:
+ print("9")
+ match number:
+ 1234:
+ print("10")
+ match number:
+ _:
+ print("11")
+ match number:
+ 1234:
+ print("12")
+ match number:
+ _:
+ print("13")
+ match number:
+ 1234:
+ print("14")
+ match number:
+ _:
+ print("15")
+ match number:
+ _:
+ print("16")
+ match number:
+ 1234:
+ print("17")
+ match number:
+ _:
+ print("18")
+ match number:
+ 1234:
+ print("19")
+ match number:
+ _:
+ print("20")
+ match number:
+ []:
+ print("Should not be printed")
+ _:
+ print("Should not be printed")
+ 5678:
+ print("Should not be printed either")
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_match.out b/modules/gdscript/tests/scripts/parser/features/nested_match.out
new file mode 100644
index 0000000000..651d76cc59
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_match.out
@@ -0,0 +1,22 @@
+GDTEST_OK
+1
+2
+3
+Should also be printed
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_parentheses.gd b/modules/gdscript/tests/scripts/parser/features/nested_parentheses.gd
new file mode 100644
index 0000000000..3fef73b9be
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_parentheses.gd
@@ -0,0 +1,65 @@
+func test():
+ (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((print("Hello world!"))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
+
+ print(((((((((((((((((((((((((((((((((((((((((((((((((((((((((("Hello world 2!"))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
+
+ print(
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (
+ (2)) + ((4))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
diff --git a/modules/gdscript/tests/scripts/parser/features/nested_parentheses.out b/modules/gdscript/tests/scripts/parser/features/nested_parentheses.out
new file mode 100644
index 0000000000..27221a56bb
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/nested_parentheses.out
@@ -0,0 +1,4 @@
+GDTEST_OK
+Hello world!
+Hello world 2!
+6
diff --git a/modules/gdscript/tests/scripts/parser/features/number_separators.gd b/modules/gdscript/tests/scripts/parser/features/number_separators.gd
new file mode 100644
index 0000000000..f5f5661cae
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/number_separators.gd
@@ -0,0 +1,12 @@
+func test():
+ # `_` can be used as a separator for numbers in GDScript.
+ # It can be placed anywhere in the number, except at the beginning.
+ # Currently, GDScript in the `master` branch only allows using one separator
+ # per number.
+ # Results are assigned to variables to avoid warnings.
+ var __ = 1_23
+ __ = 123_ # Trailing number separators are OK.
+ __ = 12_3
+ __ = 123_456
+ __ = 0x1234_5678
+ __ = 0b1001_0101
diff --git a/modules/gdscript/tests/scripts/parser/features/number_separators.out b/modules/gdscript/tests/scripts/parser/features/number_separators.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/number_separators.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/operator_assign.gd b/modules/gdscript/tests/scripts/parser/features/operator_assign.gd
new file mode 100644
index 0000000000..b5f07675ca
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/operator_assign.gd
@@ -0,0 +1,8 @@
+func test():
+ var i = 0
+ i += 5
+ i -= 4
+ i *= 10
+ i %= 8
+ i /= 0.25
+ print(round(i))
diff --git a/modules/gdscript/tests/scripts/parser/features/operator_assign.out b/modules/gdscript/tests/scripts/parser/features/operator_assign.out
new file mode 100644
index 0000000000..b0cb63ef59
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/operator_assign.out
@@ -0,0 +1,2 @@
+GDTEST_OK
+8
diff --git a/modules/gdscript/tests/scripts/parser/features/property_setter_getter.gd b/modules/gdscript/tests/scripts/parser/features/property_setter_getter.gd
new file mode 100644
index 0000000000..9e4b360fb2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/property_setter_getter.gd
@@ -0,0 +1,37 @@
+# 4.0+ replacement for `setget`:
+var _backing: int = 0
+var property:
+ get:
+ return _backing + 1000
+ set(value):
+ _backing = value - 1000
+
+
+func test():
+ print("Not using self:")
+ print(property)
+ print(_backing)
+ property = 5000
+ print(property)
+ print(_backing)
+ _backing = -50
+ print(property)
+ print(_backing)
+ property = 5000
+ print(property)
+ print(_backing)
+
+ # In Godot 4.0 and later, using `self` no longer makes a difference for
+ # getter/setter execution in GDScript.
+ print("Using self:")
+ print(self.property)
+ print(self._backing)
+ self.property = 5000
+ print(self.property)
+ print(self._backing)
+ self._backing = -50
+ print(self.property)
+ print(self._backing)
+ self.property = 5000
+ print(self.property)
+ print(self._backing)
diff --git a/modules/gdscript/tests/scripts/parser/features/property_setter_getter.out b/modules/gdscript/tests/scripts/parser/features/property_setter_getter.out
new file mode 100644
index 0000000000..560e0c3bd7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/property_setter_getter.out
@@ -0,0 +1,19 @@
+GDTEST_OK
+Not using self:
+1000
+0
+5000
+4000
+950
+-50
+5000
+4000
+Using self:
+5000
+4000
+5000
+4000
+950
+-50
+5000
+4000
diff --git a/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.gd b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.gd
index 08f2eedb2d..d50776c25c 100644
--- a/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.gd
+++ b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.gd
@@ -1,2 +1,5 @@
func test():
- print("A"); print("B")
+ print("A"); print("B")
+
+ # Multiple semicolons and whitespace between them is also valid.
+ print("A"); ;;;;; ; print("B");;
diff --git a/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.out b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.out
index fc03f3efe8..bd7f38f516 100644
--- a/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.out
+++ b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.out
@@ -1,3 +1,5 @@
GDTEST_OK
A
B
+A
+B
diff --git a/modules/gdscript/tests/scripts/parser/features/space_indentation.gd b/modules/gdscript/tests/scripts/parser/features/space_indentation.gd
new file mode 100644
index 0000000000..0a4887c199
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/space_indentation.gd
@@ -0,0 +1,4 @@
+func test():
+ # 2-space indentation should work, even though the GDScript style guide recommends tabs.
+ if true:
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/features/space_indentation.out b/modules/gdscript/tests/scripts/parser/features/space_indentation.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/space_indentation.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/features/static_typing.gd b/modules/gdscript/tests/scripts/parser/features/static_typing.gd
new file mode 100644
index 0000000000..d42632c82d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/static_typing.gd
@@ -0,0 +1,13 @@
+func test():
+ # The following lines are equivalent:
+ var _integer: int = 1
+ var _integer2 : int = 1
+ var _inferred := 1
+ var _inferred2 : = 1
+
+ # Type inference is automatic for constants.
+ const _INTEGER = 1
+ const _INTEGER_REDUNDANT_TYPED : int = 1
+ const _INTEGER_REDUNDANT_TYPED2 : int = 1
+ const _INTEGER_REDUNDANT_INFERRED := 1
+ const _INTEGER_REDUNDANT_INFERRED2 : = 1
diff --git a/modules/gdscript/tests/scripts/parser/features/static_typing.out b/modules/gdscript/tests/scripts/parser/features/static_typing.out
new file mode 100644
index 0000000000..92ce7bc0e0
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/static_typing.out
@@ -0,0 +1,21 @@
+GDTEST_OK
+>> WARNING
+>> Line: 9
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_INTEGER' is declared but never used in the block. If this is intended, prefix it with an underscore: '__INTEGER'
+>> WARNING
+>> Line: 10
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_INTEGER_REDUNDANT_TYPED' is declared but never used in the block. If this is intended, prefix it with an underscore: '__INTEGER_REDUNDANT_TYPED'
+>> WARNING
+>> Line: 11
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_INTEGER_REDUNDANT_TYPED2' is declared but never used in the block. If this is intended, prefix it with an underscore: '__INTEGER_REDUNDANT_TYPED2'
+>> WARNING
+>> Line: 12
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_INTEGER_REDUNDANT_INFERRED' is declared but never used in the block. If this is intended, prefix it with an underscore: '__INTEGER_REDUNDANT_INFERRED'
+>> WARNING
+>> Line: 13
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant '_INTEGER_REDUNDANT_INFERRED2' is declared but never used in the block. If this is intended, prefix it with an underscore: '__INTEGER_REDUNDANT_INFERRED2'
diff --git a/modules/gdscript/tests/scripts/parser/features/string_formatting.gd b/modules/gdscript/tests/scripts/parser/features/string_formatting.gd
new file mode 100644
index 0000000000..a91837145d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/string_formatting.gd
@@ -0,0 +1,18 @@
+func test():
+ print("hello %s" % "world" == "hello world")
+ print("hello %s" % true == "hello true")
+ print("hello %s" % false == "hello false")
+
+ print("hello %d" % 25 == "hello 25")
+ print("hello %d %d" % [25, 42] == "hello 25 42")
+ # Pad with spaces.
+ print("hello %3d" % 25 == "hello 25")
+ # Pad with zeroes.
+ print("hello %03d" % 25 == "hello 025")
+
+ print("hello %.02f" % 0.123456 == "hello 0.12")
+
+ # Dynamic padding:
+ # <https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/gdscript_format_string.html#dynamic-padding>
+ print("hello %*.*f" % [7, 3, 0.123456] == "hello 0.123")
+ print("hello %0*.*f" % [7, 3, 0.123456] == "hello 000.123")
diff --git a/modules/gdscript/tests/scripts/parser/features/string_formatting.out b/modules/gdscript/tests/scripts/parser/features/string_formatting.out
new file mode 100644
index 0000000000..7533f6ff54
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/string_formatting.out
@@ -0,0 +1,11 @@
+GDTEST_OK
+true
+true
+true
+true
+true
+true
+true
+true
+true
+true
diff --git a/modules/gdscript/tests/scripts/parser/features/super.gd b/modules/gdscript/tests/scripts/parser/features/super.gd
new file mode 100644
index 0000000000..f5ae2a74a7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/super.gd
@@ -0,0 +1,60 @@
+class Say:
+ var prefix = "S"
+
+ func greet():
+ prefix = "S Greeted"
+ print("hello")
+
+ func say(name):
+ print(prefix, " say something ", name)
+
+
+class SayAnotherThing extends Say:
+ # This currently crashes the engine.
+ #var prefix = "SAT"
+
+ func greet():
+ prefix = "SAT Greeted"
+ print("hi")
+
+ func say(name):
+ print(prefix, " say another thing ", name)
+
+
+class SayNothing extends Say:
+ # This currently crashes the engine.
+ #var prefix = "SN"
+
+ func greet():
+ super()
+ prefix = "SN Greeted"
+ print("howdy, see above")
+
+ func greet_prefix_before_super():
+ prefix = "SN Greeted"
+ super.greet()
+ print("howdy, see above")
+
+ func say(name):
+ super(name + " super'd")
+ print(prefix, " say nothing... or not? ", name)
+
+
+func test():
+ var say = Say.new()
+ say.greet()
+ say.say("foo")
+ print()
+
+ var say_another_thing = SayAnotherThing.new()
+ say_another_thing.greet()
+ say_another_thing.say("bar")
+ print()
+
+ var say_nothing = SayNothing.new()
+ say_nothing.greet()
+ print(say_nothing.prefix)
+ say_nothing.greet_prefix_before_super()
+ print(say_nothing.prefix)
+ # This currently triggers a compiler bug: "compiler bug, function name not found"
+ #say_nothing.say("baz")
diff --git a/modules/gdscript/tests/scripts/parser/features/super.out b/modules/gdscript/tests/scripts/parser/features/super.out
new file mode 100644
index 0000000000..e0d4f4f098
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/super.out
@@ -0,0 +1,13 @@
+GDTEST_OK
+hello
+S Greeted say something foo
+
+hi
+SAT Greeted say another thing bar
+
+hello
+howdy, see above
+SN Greeted
+hello
+howdy, see above
+S Greeted
diff --git a/modules/gdscript/tests/scripts/parser/features/truthiness.gd b/modules/gdscript/tests/scripts/parser/features/truthiness.gd
new file mode 100644
index 0000000000..9c67a152f5
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/truthiness.gd
@@ -0,0 +1,30 @@
+func test():
+ # The assertions below should all evaluate to `true` for this test to pass.
+ assert(true)
+ assert(not false)
+ assert(500)
+ assert(not 0)
+ assert(500.5)
+ assert(not 0.0)
+ assert("non-empty string")
+ assert(["non-empty array"])
+ assert({"non-empty": "dictionary"})
+ assert(Vector2(1, 0))
+ assert(Vector2i(-1, -1))
+ assert(Vector3(0, 0, 0.0001))
+ assert(Vector3i(0, 0, 10000))
+
+ # Zero position is `true` only if the Rect2's size is non-zero.
+ assert(Rect2(0, 0, 0, 1))
+
+ # Zero size is `true` only if the position is non-zero.
+ assert(Rect2(1, 1, 0, 0))
+
+ # Zero position is `true` only if the Rect2's size is non-zero.
+ assert(Rect2i(0, 0, 0, 1))
+
+ # Zero size is `true` only if the position is non-zero.
+ assert(Rect2i(1, 1, 0, 0))
+
+ # A fully black color is only truthy if its alpha component is not equal to `1`.
+ assert(Color(0, 0, 0, 0.5))
diff --git a/modules/gdscript/tests/scripts/parser/features/truthiness.out b/modules/gdscript/tests/scripts/parser/features/truthiness.out
new file mode 100644
index 0000000000..705524857b
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/truthiness.out
@@ -0,0 +1,65 @@
+GDTEST_OK
+>> WARNING
+>> Line: 3
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 4
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 5
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 6
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 7
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 8
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 9
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 12
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 13
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 14
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 15
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 18
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 21
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 24
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 27
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 30
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
diff --git a/modules/gdscript/tests/scripts/parser/features/variable_declaration.gd b/modules/gdscript/tests/scripts/parser/features/variable_declaration.gd
index 3b48f10ca7..65013c4301 100644
--- a/modules/gdscript/tests/scripts/parser/features/variable_declaration.gd
+++ b/modules/gdscript/tests/scripts/parser/features/variable_declaration.gd
@@ -1,12 +1,20 @@
-var a # No init.
-var b = 42 # Init.
+var m1 # No init.
+var m2 = 22 # Init.
+var m3: String # No init, typed.
+var m4: String = "44" # Init, typed.
+
func test():
- var c # No init, local.
- var d = 23 # Init, local.
+ var loc5 # No init, local.
+ var loc6 = 66 # Init, local.
+ var loc7: String # No init, typed.
+ var loc8: String = "88" # Init, typed.
+
+ m1 = 11
+ m3 = "33"
- a = 1
- c = 2
+ loc5 = 55
+ loc7 = "77"
- prints(a, b, c, d)
+ prints(m1, m2, m3, m4, loc5, loc6, loc7, loc8)
print("OK")
diff --git a/modules/gdscript/tests/scripts/parser/features/variable_declaration.out b/modules/gdscript/tests/scripts/parser/features/variable_declaration.out
index 2e0a63c024..7817dd3169 100644
--- a/modules/gdscript/tests/scripts/parser/features/variable_declaration.out
+++ b/modules/gdscript/tests/scripts/parser/features/variable_declaration.out
@@ -1,7 +1,3 @@
GDTEST_OK
->> WARNING
->> Line: 5
->> UNASSIGNED_VARIABLE
->> The variable 'c' was used but never assigned a value.
-1 42 2 23
+11 22 33 44 55 66 77 88
OK
diff --git a/modules/gdscript/tests/scripts/parser/features/while.gd b/modules/gdscript/tests/scripts/parser/features/while.gd
new file mode 100644
index 0000000000..17dd4fbad2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/while.gd
@@ -0,0 +1,5 @@
+func test():
+ var i = 0
+ while i < 5:
+ print(i)
+ i += 1
diff --git a/modules/gdscript/tests/scripts/parser/features/while.out b/modules/gdscript/tests/scripts/parser/features/while.out
new file mode 100644
index 0000000000..b4a50885c7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/features/while.out
@@ -0,0 +1,6 @@
+GDTEST_OK
+0
+1
+2
+3
+4
diff --git a/modules/gdscript/tests/scripts/parser/warnings/assert_always_true.gd b/modules/gdscript/tests/scripts/parser/warnings/assert_always_true.gd
new file mode 100644
index 0000000000..8feaed899f
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/assert_always_true.gd
@@ -0,0 +1,5 @@
+func test():
+ # These statements always evaluate to `true`, and therefore emit a warning.
+ assert(true)
+ assert(-1.234)
+ assert(2 + 3 == 5)
diff --git a/modules/gdscript/tests/scripts/parser/warnings/assert_always_true.out b/modules/gdscript/tests/scripts/parser/warnings/assert_always_true.out
new file mode 100644
index 0000000000..5132792cb7
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/assert_always_true.out
@@ -0,0 +1,13 @@
+GDTEST_OK
+>> WARNING
+>> Line: 3
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 4
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
+>> WARNING
+>> Line: 5
+>> ASSERT_ALWAYS_TRUE
+>> Assert statement is redundant because the expression is always true.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.gd b/modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.gd
new file mode 100644
index 0000000000..f72b10213f
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.gd
@@ -0,0 +1,8 @@
+func test():
+ # `and` should be used instead.
+ if true && true:
+ pass
+
+ # `or` should be used instead.
+ if false || true:
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.out b/modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/deprecated_operators.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.gd b/modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.gd
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.gd
@@ -0,0 +1 @@
+
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.out b/modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.out
new file mode 100644
index 0000000000..20eec212ba
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file.notest.out
@@ -0,0 +1,4 @@
+>> WARNING
+>> Line: 1
+>> EMPTY_FILE
+>> Empty script file.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.gd b/modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.gd
new file mode 100644
index 0000000000..15cd95ff2b
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.gd
@@ -0,0 +1 @@
+#a comment
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.out b/modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.out
new file mode 100644
index 0000000000..20eec212ba
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file_comment.notest.out
@@ -0,0 +1,4 @@
+>> WARNING
+>> Line: 1
+>> EMPTY_FILE
+>> Empty script file.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.gd b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.gd
new file mode 100644
index 0000000000..b28b04f643
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.gd
@@ -0,0 +1,3 @@
+
+
+
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.out b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.out
new file mode 100644
index 0000000000..20eec212ba
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline.notest.out
@@ -0,0 +1,4 @@
+>> WARNING
+>> Line: 1
+>> EMPTY_FILE
+>> Empty script file.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.gd b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.gd
new file mode 100644
index 0000000000..ecdba44d21
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.gd
@@ -0,0 +1,4 @@
+#a comment, followed by a bunch of newlines
+
+
+
diff --git a/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.out b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.out
new file mode 100644
index 0000000000..20eec212ba
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/empty_file_newline_comment.notest.out
@@ -0,0 +1,4 @@
+>> WARNING
+>> Line: 1
+>> EMPTY_FILE
+>> Empty script file.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.gd b/modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.gd
new file mode 100644
index 0000000000..a93ecb66b1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.gd
@@ -0,0 +1,8 @@
+func test():
+ # The ternary operator below returns values of different types and the
+ # result is assigned to a typed variable. This will cause a run-time error
+ # if the branch with the incompatible type is picked. Here, it won't happen
+ # since the `false` condition never evaluates to `true`. Instead, a warning
+ # will be emitted.
+ var __: int = 25
+ __ = "hello" if false else -2
diff --git a/modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.out b/modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.out
new file mode 100644
index 0000000000..7d1558c6fc
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/incompatible_ternary.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 8
+>> INCOMPATIBLE_TERNARY
+>> Values of the ternary conditional are not mutually compatible.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/integer_division.gd b/modules/gdscript/tests/scripts/parser/warnings/integer_division.gd
new file mode 100644
index 0000000000..6117425528
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/integer_division.gd
@@ -0,0 +1,10 @@
+func test():
+ # This should emit a warning.
+ var __ = 5 / 2
+
+ # These should not emit warnings.
+ __ = float(5) / 2
+ __ = 5 / float(2)
+ __ = 5.0 / 2
+ __ = 5 / 2.0
+ __ = 5.0 / 2.0
diff --git a/modules/gdscript/tests/scripts/parser/warnings/integer_division.out b/modules/gdscript/tests/scripts/parser/warnings/integer_division.out
new file mode 100644
index 0000000000..40eb63ffcb
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/integer_division.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 3
+>> INTEGER_DIVISION
+>> Integer division, decimal part will be discarded.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.gd b/modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.gd
new file mode 100644
index 0000000000..1eb54059dd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.gd
@@ -0,0 +1,9 @@
+func test():
+ var i = 25
+ # The default branch (`_`) should be at the end of the `match` statement.
+ # Otherwise, a warning will be emitted
+ match i:
+ _:
+ print("default")
+ 25:
+ print("is 25")
diff --git a/modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.out b/modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.out
new file mode 100644
index 0000000000..8630fab420
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/match_default_not_at_end.out
@@ -0,0 +1,6 @@
+GDTEST_OK
+>> WARNING
+>> Line: 8
+>> UNREACHABLE_PATTERN
+>> Unreachable pattern (pattern after wildcard or bind).
+default
diff --git a/modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.gd b/modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.gd
new file mode 100644
index 0000000000..954e697145
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.gd
@@ -0,0 +1,5 @@
+func i_accept_ints_only(_i: int):
+ pass
+
+func test():
+ i_accept_ints_only(12.345)
diff --git a/modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.out b/modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.out
new file mode 100644
index 0000000000..6fb592117b
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/narrowing_conversion.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 5
+>> NARROWING_CONVERSION
+>> Narrowing conversion (float is converted to int and loses precision).
diff --git a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.gd b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.gd
new file mode 100644
index 0000000000..00598e4d50
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.gd
@@ -0,0 +1,6 @@
+func i_return_int() -> int:
+ return 4
+
+
+func test():
+ i_return_int()
diff --git a/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out
new file mode 100644
index 0000000000..d73c5eb7cd
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/return_value_discarded.out
@@ -0,0 +1 @@
+GDTEST_OK
diff --git a/modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.gd b/modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.gd
new file mode 100644
index 0000000000..d565d38365
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.gd
@@ -0,0 +1,8 @@
+# See also `parser-errors/redefine-class-constant.gd`.
+const TEST = 25
+
+
+func test():
+ # Warning here. This is not an error because a new constant is created,
+ # rather than attempting to set the value of an existing constant.
+ const TEST = 50
diff --git a/modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.out b/modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.out
new file mode 100644
index 0000000000..9c9417e11d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/shadowed_constant.out
@@ -0,0 +1,9 @@
+GDTEST_OK
+>> WARNING
+>> Line: 8
+>> UNUSED_LOCAL_CONSTANT
+>> The local constant 'TEST' is declared but never used in the block. If this is intended, prefix it with an underscore: '_TEST'
+>> WARNING
+>> Line: 8
+>> SHADOWED_VARIABLE
+>> The local constant "TEST" is shadowing an already-declared constant at line 2.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.gd b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.gd
new file mode 100644
index 0000000000..66dcf309e8
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.gd
@@ -0,0 +1,8 @@
+var foo = 123
+
+
+func test():
+ # Notice the `var` keyword. Without this keyword, no warning would be emitted
+ # because no new variable would be created. Instead, the class variable's value
+ # would be overwritten.
+ var foo = 456
diff --git a/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.out b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.out
new file mode 100644
index 0000000000..82e467b368
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_class.out
@@ -0,0 +1,9 @@
+GDTEST_OK
+>> WARNING
+>> Line: 8
+>> UNUSED_VARIABLE
+>> The local variable 'foo' is declared but never used in the block. If this is intended, prefix it with an underscore: '_foo'
+>> WARNING
+>> Line: 8
+>> SHADOWED_VARIABLE
+>> The local variable "foo" is shadowing an already-declared variable at line 1.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.gd b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.gd
new file mode 100644
index 0000000000..2c55d68be8
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.gd
@@ -0,0 +1,2 @@
+func test():
+ var test = "This variable has the same name as the test() function."
diff --git a/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.out b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.out
new file mode 100644
index 0000000000..26ce0465b1
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/shadowed_variable_function.out
@@ -0,0 +1,9 @@
+GDTEST_OK
+>> WARNING
+>> Line: 2
+>> UNUSED_VARIABLE
+>> The local variable 'test' is declared but never used in the block. If this is intended, prefix it with an underscore: '_test'
+>> WARNING
+>> Line: 2
+>> SHADOWED_VARIABLE
+>> The local variable "test" is shadowing an already-declared function at line 1.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/standalone_expression.gd b/modules/gdscript/tests/scripts/parser/warnings/standalone_expression.gd
new file mode 100644
index 0000000000..18ea260fa2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/standalone_expression.gd
@@ -0,0 +1,9 @@
+func test():
+ # The following statements should all be reported as standalone expressions:
+ "This is a standalone expression"
+ 1234
+ 0.0 + 0.0
+ Color(1, 1, 1)
+ Vector3.ZERO
+ [true, false]
+ float(125)
diff --git a/modules/gdscript/tests/scripts/parser/warnings/standalone_expression.out b/modules/gdscript/tests/scripts/parser/warnings/standalone_expression.out
new file mode 100644
index 0000000000..99ec87438e
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/standalone_expression.out
@@ -0,0 +1,21 @@
+GDTEST_OK
+>> WARNING
+>> Line: 3
+>> STANDALONE_EXPRESSION
+>> Standalone expression (the line has no effect).
+>> WARNING
+>> Line: 4
+>> STANDALONE_EXPRESSION
+>> Standalone expression (the line has no effect).
+>> WARNING
+>> Line: 5
+>> STANDALONE_EXPRESSION
+>> Standalone expression (the line has no effect).
+>> WARNING
+>> Line: 7
+>> STANDALONE_EXPRESSION
+>> Standalone expression (the line has no effect).
+>> WARNING
+>> Line: 8
+>> STANDALONE_EXPRESSION
+>> Standalone expression (the line has no effect).
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.gd b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.gd
new file mode 100644
index 0000000000..afb5059eea
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.gd
@@ -0,0 +1,2 @@
+func test():
+ var __
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.out b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.out
new file mode 100644
index 0000000000..cf14502e9a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 2
+>> UNASSIGNED_VARIABLE
+>> The variable '__' was used but never assigned a value.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.gd b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.gd
new file mode 100644
index 0000000000..d77791f4c5
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.gd
@@ -0,0 +1,4 @@
+func test():
+ var __: int
+ # Variable has no set value at this point (even though it's implicitly `0` here).
+ __ += 15
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.out b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.out
new file mode 100644
index 0000000000..ba55a4e0f8
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unassigned_variable_op_assign.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 4
+>> UNASSIGNED_VARIABLE_OP_ASSIGN
+>> Using assignment with operation but the variable '__' was not previously assigned a value.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.gd b/modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.gd
new file mode 100644
index 0000000000..3311f342ab
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.gd
@@ -0,0 +1,7 @@
+func test():
+ var i = 25
+
+ return
+
+ # This will never be run due to the `return` statement above.
+ print(i)
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.out b/modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.out
new file mode 100644
index 0000000000..9316abd5eb
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unreachable_code_after_return.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 7
+>> UNREACHABLE_CODE
+>> Unreachable code (statement after return) in function 'test()'.
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unused_argument.gd b/modules/gdscript/tests/scripts/parser/warnings/unused_argument.gd
new file mode 100644
index 0000000000..e6e24dc6f2
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unused_argument.gd
@@ -0,0 +1,12 @@
+# This should emit a warning since the unused argument is not prefixed with an underscore.
+func function_with_unused_argument(p_arg1, p_arg2):
+ print(p_arg1)
+
+
+# This shouldn't emit a warning since the unused argument is prefixed with an underscore.
+func function_with_ignored_unused_argument(p_arg1, _p_arg2):
+ print(p_arg1)
+
+
+func test():
+ pass
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unused_argument.out b/modules/gdscript/tests/scripts/parser/warnings/unused_argument.out
new file mode 100644
index 0000000000..92f3308f85
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/unused_argument.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 2
+>> UNUSED_PARAMETER
+>> The parameter 'p_arg2' is never used in the function 'function_with_unused_argument'. If this is intended, prefix it with an underscore: '_p_arg2'
diff --git a/modules/gdscript/tests/scripts/parser/warnings/unused_variable.gd b/modules/gdscript/tests/scripts/parser/warnings/unused_variable.gd
index 68e3bd424f..013a2e4beb 100644
--- a/modules/gdscript/tests/scripts/parser/warnings/unused_variable.gd
+++ b/modules/gdscript/tests/scripts/parser/warnings/unused_variable.gd
@@ -1,2 +1,4 @@
func test():
- var unused = "not used"
+ var unused = "not used"
+
+ var _unused = "not used, but no warning since the variable name starts with an underscore"
diff --git a/modules/gdscript/tests/scripts/parser/warnings/void_assignment.gd b/modules/gdscript/tests/scripts/parser/warnings/void_assignment.gd
new file mode 100644
index 0000000000..b4a42b3e3d
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/void_assignment.gd
@@ -0,0 +1,6 @@
+func i_return_void() -> void:
+ return
+
+
+func test():
+ var __ = i_return_void()
diff --git a/modules/gdscript/tests/scripts/parser/warnings/void_assignment.out b/modules/gdscript/tests/scripts/parser/warnings/void_assignment.out
new file mode 100644
index 0000000000..84c9598f9a
--- /dev/null
+++ b/modules/gdscript/tests/scripts/parser/warnings/void_assignment.out
@@ -0,0 +1,5 @@
+GDTEST_OK
+>> WARNING
+>> Line: 6
+>> VOID_ASSIGNMENT
+>> Assignment operation, but the function 'i_return_void()' returns void.
diff --git a/modules/gltf/config.py b/modules/gltf/config.py
index a4ee871eff..52a97c93aa 100644
--- a/modules/gltf/config.py
+++ b/modules/gltf/config.py
@@ -22,7 +22,6 @@ def get_doc_classes():
"GLTFSpecGloss",
"GLTFState",
"GLTFTexture",
- "PackedSceneGLTF",
]
diff --git a/modules/gltf/doc_classes/GLTFCamera.xml b/modules/gltf/doc_classes/GLTFCamera.xml
index 0b95f2c802..ec25d84756 100644
--- a/modules/gltf/doc_classes/GLTFCamera.xml
+++ b/modules/gltf/doc_classes/GLTFCamera.xml
@@ -9,13 +9,13 @@
<methods>
</methods>
<members>
- <member name="fov_size" type="float" setter="set_fov_size" getter="get_fov_size" default="75.0">
+ <member name="depth_far" type="float" setter="set_depth_far" getter="get_depth_far" default="4000.0">
</member>
- <member name="perspective" type="bool" setter="set_perspective" getter="get_perspective" default="true">
+ <member name="depth_near" type="float" setter="set_depth_near" getter="get_depth_near" default="0.05">
</member>
- <member name="zfar" type="float" setter="set_zfar" getter="get_zfar" default="4000.0">
+ <member name="fov_size" type="float" setter="set_fov_size" getter="get_fov_size" default="75.0">
</member>
- <member name="znear" type="float" setter="set_znear" getter="get_znear" default="0.05">
+ <member name="perspective" type="bool" setter="set_perspective" getter="get_perspective" default="true">
</member>
</members>
<constants>
diff --git a/modules/gltf/doc_classes/GLTFDocument.xml b/modules/gltf/doc_classes/GLTFDocument.xml
index 04c40dd752..f8e0007684 100644
--- a/modules/gltf/doc_classes/GLTFDocument.xml
+++ b/modules/gltf/doc_classes/GLTFDocument.xml
@@ -7,6 +7,28 @@
<tutorials>
</tutorials>
<methods>
+ <method name="import_scene">
+ <return type="Node" />
+ <argument index="0" name="path" type="String" />
+ <argument index="1" name="flags" type="int" default="0" />
+ <argument index="2" name="bake_fps" type="int" default="30" />
+ <argument index="3" name="state" type="GLTFState" default="null" />
+ <description>
+ Import a scene from glTF2 ".gltf" or ".glb" file.
+ </description>
+ </method>
+ <method name="save_scene">
+ <return type="int" enum="Error" />
+ <argument index="0" name="node" type="Node" />
+ <argument index="1" name="path" type="String" />
+ <argument index="2" name="src_path" type="String" />
+ <argument index="3" name="flags" type="int" default="0" />
+ <argument index="4" name="bake_fps" type="float" default="30" />
+ <argument index="5" name="state" type="GLTFState" default="null" />
+ <description>
+ Save a scene as a glTF2 ".glb" or ".gltf" file.
+ </description>
+ </method>
</methods>
<constants>
</constants>
diff --git a/modules/gltf/doc_classes/GLTFLight.xml b/modules/gltf/doc_classes/GLTFLight.xml
index f51d287685..2eb5ee9070 100644
--- a/modules/gltf/doc_classes/GLTFLight.xml
+++ b/modules/gltf/doc_classes/GLTFLight.xml
@@ -15,12 +15,12 @@
</member>
<member name="intensity" type="float" setter="set_intensity" getter="get_intensity" default="0.0">
</member>
+ <member name="light_type" type="String" setter="set_light_type" getter="get_light_type" default="&quot;&quot;">
+ </member>
<member name="outer_cone_angle" type="float" setter="set_outer_cone_angle" getter="get_outer_cone_angle" default="0.0">
</member>
<member name="range" type="float" setter="set_range" getter="get_range" default="0.0">
</member>
- <member name="type" type="String" setter="set_type" getter="get_type" default="&quot;&quot;">
- </member>
</members>
<constants>
</constants>
diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml
index bfbb12df4d..95d7283398 100644
--- a/modules/gltf/doc_classes/GLTFNode.xml
+++ b/modules/gltf/doc_classes/GLTFNode.xml
@@ -23,6 +23,8 @@
</member>
<member name="parent" type="int" setter="set_parent" getter="get_parent" default="-1">
</member>
+ <member name="position" type="Vector3" setter="set_position" getter="get_position" default="Vector3(0, 0, 0)">
+ </member>
<member name="rotation" type="Quaternion" setter="set_rotation" getter="get_rotation" default="Quaternion(0, 0, 0, 1)">
</member>
<member name="scale" type="Vector3" setter="set_scale" getter="get_scale" default="Vector3(1, 1, 1)">
@@ -31,8 +33,6 @@
</member>
<member name="skin" type="int" setter="set_skin" getter="get_skin" default="-1">
</member>
- <member name="translation" type="Vector3" setter="set_translation" getter="get_translation" default="Vector3(0, 0, 0)">
- </member>
<member name="xform" type="Transform3D" setter="set_xform" getter="get_xform" default="Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)">
</member>
</members>
diff --git a/modules/gltf/doc_classes/PackedSceneGLTF.xml b/modules/gltf/doc_classes/PackedSceneGLTF.xml
deleted file mode 100644
index d0136c6402..0000000000
--- a/modules/gltf/doc_classes/PackedSceneGLTF.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="PackedSceneGLTF" inherits="PackedScene" version="4.0">
- <brief_description>
- </brief_description>
- <description>
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="export_gltf">
- <return type="int" enum="Error" />
- <argument index="0" name="node" type="Node" />
- <argument index="1" name="path" type="String" />
- <argument index="2" name="flags" type="int" default="0" />
- <argument index="3" name="bake_fps" type="float" default="1000.0" />
- <description>
- </description>
- </method>
- <method name="import_gltf_scene">
- <return type="Node" />
- <argument index="0" name="path" type="String" />
- <argument index="1" name="flags" type="int" default="0" />
- <argument index="2" name="bake_fps" type="float" default="1000.0" />
- <argument index="3" name="state" type="GLTFState" default="null" />
- <description>
- </description>
- </method>
- <method name="pack_gltf">
- <return type="void" />
- <argument index="0" name="path" type="String" />
- <argument index="1" name="flags" type="int" default="0" />
- <argument index="2" name="bake_fps" type="float" default="1000.0" />
- <argument index="3" name="state" type="GLTFState" default="null" />
- <description>
- </description>
- </method>
- </methods>
- <members>
- <member name="_bundled" type="Dictionary" setter="_set_bundled_scene" getter="_get_bundled_scene" override="true" default="{&quot;conn_count&quot;: 0,&quot;conns&quot;: PackedInt32Array(),&quot;editable_instances&quot;: [],&quot;names&quot;: PackedStringArray(),&quot;node_count&quot;: 0,&quot;node_paths&quot;: [],&quot;nodes&quot;: PackedInt32Array(),&quot;variants&quot;: [],&quot;version&quot;: 2}" />
- </members>
- <constants>
- </constants>
-</class>
diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp
index ae080bcc9a..fd9f758f10 100644
--- a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp
+++ b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp
@@ -30,9 +30,11 @@
#include "editor_scene_exporter_gltf_plugin.h"
#include "core/config/project_settings.h"
+#include "core/error/error_list.h"
#include "core/object/object.h"
#include "core/templates/vector.h"
#include "editor/editor_file_system.h"
+#include "gltf_document.h"
#include "scene/3d/mesh_instance_3d.h"
#include "scene/gui/check_box.h"
#include "scene/main/node.h"
@@ -49,7 +51,6 @@ bool SceneExporterGLTFPlugin::has_main_screen() const {
SceneExporterGLTFPlugin::SceneExporterGLTFPlugin(EditorNode *p_node) {
editor = p_node;
- convert_gltf2.instantiate();
file_export_lib = memnew(EditorFileDialog);
editor->get_gui_base()->add_child(file_export_lib);
file_export_lib->connect("file_selected", callable_mp(this, &SceneExporterGLTFPlugin::_gltf2_dialog_action));
@@ -71,8 +72,12 @@ void SceneExporterGLTFPlugin::_gltf2_dialog_action(String p_file) {
return;
}
List<String> deps;
- convert_gltf2->save_scene(root, p_file, p_file, 0, 1000.0f, &deps);
- EditorFileSystem::get_singleton()->scan_changes();
+ Ref<GLTFDocument> doc;
+ doc.instantiate();
+ Error err = doc->save_scene(root, p_file, p_file, 0, 30.0f, Ref<GLTFState>());
+ if (err != OK) {
+ ERR_PRINT(vformat("glTF2 save scene error %s.", itos(err)));
+ }
}
void SceneExporterGLTFPlugin::convert_scene_to_gltf2() {
diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.h b/modules/gltf/editor_scene_exporter_gltf_plugin.h
index d952894c16..c4f277fca2 100644
--- a/modules/gltf/editor_scene_exporter_gltf_plugin.h
+++ b/modules/gltf/editor_scene_exporter_gltf_plugin.h
@@ -37,7 +37,6 @@
class SceneExporterGLTFPlugin : public EditorPlugin {
GDCLASS(SceneExporterGLTFPlugin, EditorPlugin);
- Ref<PackedSceneGLTF> convert_gltf2;
EditorNode *editor = nullptr;
EditorFileDialog *file_export_lib = nullptr;
void _gltf2_dialog_action(String p_file);
diff --git a/modules/gltf/editor_scene_importer_gltf.cpp b/modules/gltf/editor_scene_importer_gltf.cpp
index eca1c85bf3..12796c41d7 100644
--- a/modules/gltf/editor_scene_importer_gltf.cpp
+++ b/modules/gltf/editor_scene_importer_gltf.cpp
@@ -50,9 +50,9 @@ Node *EditorSceneImporterGLTF::import_scene(const String &p_path,
uint32_t p_flags, int p_bake_fps,
List<String> *r_missing_deps,
Error *r_err) {
- Ref<PackedSceneGLTF> importer;
- importer.instantiate();
- return importer->import_scene(p_path, p_flags, p_bake_fps, r_missing_deps, r_err, Ref<GLTFState>());
+ Ref<GLTFDocument> doc;
+ doc.instantiate();
+ return doc->import_scene_gltf(p_path, p_flags, p_bake_fps, Ref<GLTFState>(), r_missing_deps, r_err);
}
Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path,
@@ -60,114 +60,3 @@ Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path,
int p_bake_fps) {
return Ref<Animation>();
}
-
-void PackedSceneGLTF::_bind_methods() {
- ClassDB::bind_method(
- D_METHOD("export_gltf", "node", "path", "flags", "bake_fps"),
- &PackedSceneGLTF::export_gltf, DEFVAL(0), DEFVAL(1000.0f));
- ClassDB::bind_method(D_METHOD("pack_gltf", "path", "flags", "bake_fps", "state"),
- &PackedSceneGLTF::pack_gltf, DEFVAL(0), DEFVAL(1000.0f), DEFVAL(Ref<GLTFState>()));
- ClassDB::bind_method(D_METHOD("import_gltf_scene", "path", "flags", "bake_fps", "state"),
- &PackedSceneGLTF::import_gltf_scene, DEFVAL(0), DEFVAL(1000.0f), DEFVAL(Ref<GLTFState>()));
-}
-Node *PackedSceneGLTF::import_gltf_scene(const String &p_path, uint32_t p_flags, float p_bake_fps, Ref<GLTFState> r_state) {
- Error err = FAILED;
- List<String> deps;
- return import_scene(p_path, p_flags, p_bake_fps, &deps, &err, r_state);
-}
-
-Node *PackedSceneGLTF::import_scene(const String &p_path, uint32_t p_flags,
- int p_bake_fps,
- List<String> *r_missing_deps,
- Error *r_err,
- Ref<GLTFState> r_state) {
- if (r_state == Ref<GLTFState>()) {
- r_state.instantiate();
- }
- r_state->use_named_skin_binds =
- p_flags & EditorSceneImporter::IMPORT_USE_NAMED_SKIN_BINDS;
-
- Ref<GLTFDocument> gltf_document;
- gltf_document.instantiate();
- Error err = gltf_document->parse(r_state, p_path);
- if (r_err) {
- *r_err = err;
- }
- ERR_FAIL_COND_V(err != Error::OK, nullptr);
-
- Node3D *root = memnew(Node3D);
- for (int32_t root_i = 0; root_i < r_state->root_nodes.size(); root_i++) {
- gltf_document->_generate_scene_node(r_state, root, root, r_state->root_nodes[root_i]);
- }
- gltf_document->_process_mesh_instances(r_state, root);
- if (r_state->animations.size()) {
- AnimationPlayer *ap = memnew(AnimationPlayer);
- root->add_child(ap);
- ap->set_owner(root);
- for (int i = 0; i < r_state->animations.size(); i++) {
- gltf_document->_import_animation(r_state, ap, i, p_bake_fps);
- }
- }
-
- return cast_to<Node3D>(root);
-}
-
-void PackedSceneGLTF::pack_gltf(String p_path, int32_t p_flags,
- real_t p_bake_fps, Ref<GLTFState> r_state) {
- Error err = FAILED;
- List<String> deps;
- Node *root = import_scene(p_path, p_flags, p_bake_fps, &deps, &err, r_state);
- ERR_FAIL_COND(err != OK);
- pack(root);
-}
-
-void PackedSceneGLTF::save_scene(Node *p_node, const String &p_path,
- const String &p_src_path, uint32_t p_flags,
- int p_bake_fps, List<String> *r_missing_deps,
- Error *r_err) {
- Error err = FAILED;
- if (r_err) {
- *r_err = err;
- }
- Ref<GLTFDocument> gltf_document;
- gltf_document.instantiate();
- Ref<GLTFState> state;
- state.instantiate();
- err = gltf_document->serialize(state, p_node, p_path);
- if (r_err) {
- *r_err = err;
- }
-}
-
-void PackedSceneGLTF::_build_parent_hierachy(Ref<GLTFState> state) {
- // build the hierarchy
- for (GLTFNodeIndex node_i = 0; node_i < state->nodes.size(); node_i++) {
- for (int j = 0; j < state->nodes[node_i]->children.size(); j++) {
- GLTFNodeIndex child_i = state->nodes[node_i]->children[j];
- ERR_FAIL_INDEX(child_i, state->nodes.size());
- if (state->nodes.write[child_i]->parent != -1) {
- continue;
- }
- state->nodes.write[child_i]->parent = node_i;
- }
- }
-}
-
-Error PackedSceneGLTF::export_gltf(Node *p_root, String p_path,
- int32_t p_flags,
- real_t p_bake_fps) {
- ERR_FAIL_COND_V(!p_root, FAILED);
- List<String> deps;
- Error err;
- String path = p_path;
- int32_t flags = p_flags;
- real_t baked_fps = p_bake_fps;
- Ref<PackedSceneGLTF> exporter;
- exporter.instantiate();
- exporter->save_scene(p_root, path, "", flags, baked_fps, &deps, &err);
- int32_t error_code = err;
- if (error_code != 0) {
- return Error(error_code);
- }
- return OK;
-}
diff --git a/modules/gltf/editor_scene_importer_gltf.h b/modules/gltf/editor_scene_importer_gltf.h
index 7bc5f594ed..eb8775b137 100644
--- a/modules/gltf/editor_scene_importer_gltf.h
+++ b/modules/gltf/editor_scene_importer_gltf.h
@@ -46,35 +46,9 @@ class EditorSceneImporterGLTF : public EditorSceneImporter {
public:
virtual uint32_t get_import_flags() const override;
virtual void get_extensions(List<String> *r_extensions) const override;
- virtual Node *import_scene(const String &p_path, uint32_t p_flags,
- int p_bake_fps,
- List<String> *r_missing_deps = nullptr,
- Error *r_err = nullptr) override;
+ virtual Node *import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr) override;
virtual Ref<Animation> import_animation(const String &p_path,
uint32_t p_flags, int p_bake_fps) override;
};
#endif
-
-class PackedSceneGLTF : public PackedScene {
- GDCLASS(PackedSceneGLTF, PackedScene);
-
-protected:
- static void _bind_methods();
-
-public:
- virtual void save_scene(Node *p_node, const String &p_path, const String &p_src_path,
- uint32_t p_flags, int p_bake_fps,
- List<String> *r_missing_deps, Error *r_err = nullptr);
- virtual void _build_parent_hierachy(Ref<GLTFState> state);
- virtual Error export_gltf(Node *p_root, String p_path, int32_t p_flags = 0,
- real_t p_bake_fps = 1000.0f);
- virtual Node *import_scene(const String &p_path, uint32_t p_flags,
- int p_bake_fps,
- List<String> *r_missing_deps,
- Error *r_err,
- Ref<GLTFState> r_state);
- virtual Node *import_gltf_scene(const String &p_path, uint32_t p_flags, float p_bake_fps, Ref<GLTFState> r_state = Ref<GLTFState>());
- virtual void pack_gltf(String p_path, int32_t p_flags = 0,
- real_t p_bake_fps = 1000.0f, Ref<GLTFState> r_state = Ref<GLTFState>());
-};
#endif // EDITOR_SCENE_IMPORTER_GLTF_H
diff --git a/modules/gltf/gltf_accessor.h b/modules/gltf/gltf_accessor.h
index 949a601730..57aea1026c 100644
--- a/modules/gltf/gltf_accessor.h
+++ b/modules/gltf/gltf_accessor.h
@@ -44,8 +44,7 @@ private:
int component_type = 0;
bool normalized = false;
int count = 0;
- GLTFDocument::GLTFType
- type = GLTFDocument::TYPE_SCALAR;
+ GLTFDocument::GLTFType type = GLTFDocument::TYPE_SCALAR;
Vector<double> min;
Vector<double> max;
int sparse_count = 0;
diff --git a/modules/gltf/gltf_animation.h b/modules/gltf/gltf_animation.h
index 216d2161c4..be0ed2d4c6 100644
--- a/modules/gltf/gltf_animation.h
+++ b/modules/gltf/gltf_animation.h
@@ -55,7 +55,7 @@ public:
};
struct Track {
- Channel<Vector3> translation_track;
+ Channel<Vector3> position_track;
Channel<Quaternion> rotation_track;
Channel<Vector3> scale_track;
Vector<Channel<float>> weight_tracks;
diff --git a/modules/gltf/gltf_camera.cpp b/modules/gltf/gltf_camera.cpp
index efa7c5d6d7..0f895fb989 100644
--- a/modules/gltf/gltf_camera.cpp
+++ b/modules/gltf/gltf_camera.cpp
@@ -35,13 +35,13 @@ void GLTFCamera::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_perspective", "perspective"), &GLTFCamera::set_perspective);
ClassDB::bind_method(D_METHOD("get_fov_size"), &GLTFCamera::get_fov_size);
ClassDB::bind_method(D_METHOD("set_fov_size", "fov_size"), &GLTFCamera::set_fov_size);
- ClassDB::bind_method(D_METHOD("get_zfar"), &GLTFCamera::get_zfar);
- ClassDB::bind_method(D_METHOD("set_zfar", "zfar"), &GLTFCamera::set_zfar);
- ClassDB::bind_method(D_METHOD("get_znear"), &GLTFCamera::get_znear);
- ClassDB::bind_method(D_METHOD("set_znear", "znear"), &GLTFCamera::set_znear);
+ ClassDB::bind_method(D_METHOD("get_depth_far"), &GLTFCamera::get_depth_far);
+ ClassDB::bind_method(D_METHOD("set_depth_far", "zdepth_far"), &GLTFCamera::set_depth_far);
+ ClassDB::bind_method(D_METHOD("get_depth_near"), &GLTFCamera::get_depth_near);
+ ClassDB::bind_method(D_METHOD("set_depth_near", "zdepth_near"), &GLTFCamera::set_depth_near);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "perspective"), "set_perspective", "get_perspective"); // bool
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov_size"), "set_fov_size", "get_fov_size"); // float
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "zfar"), "set_zfar", "get_zfar"); // float
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "znear"), "set_znear", "get_znear"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_far"), "set_depth_far", "get_depth_far"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_near"), "set_depth_near", "get_depth_near"); // float
}
diff --git a/modules/gltf/gltf_camera.h b/modules/gltf/gltf_camera.h
index bf94b80bef..843ff417a4 100644
--- a/modules/gltf/gltf_camera.h
+++ b/modules/gltf/gltf_camera.h
@@ -39,8 +39,8 @@ class GLTFCamera : public Resource {
private:
bool perspective = true;
float fov_size = 75.0;
- float zfar = 4000.0;
- float znear = 0.05;
+ float depth_far = 4000.0;
+ float depth_near = 0.05;
protected:
static void _bind_methods();
@@ -50,9 +50,9 @@ public:
void set_perspective(bool p_val) { perspective = p_val; }
float get_fov_size() const { return fov_size; }
void set_fov_size(float p_val) { fov_size = p_val; }
- float get_zfar() const { return zfar; }
- void set_zfar(float p_val) { zfar = p_val; }
- float get_znear() const { return znear; }
- void set_znear(float p_val) { znear = p_val; }
+ float get_depth_far() const { return depth_far; }
+ void set_depth_far(float p_val) { depth_far = p_val; }
+ float get_depth_near() const { return depth_near; }
+ void set_depth_near(float p_val) { depth_near = p_val; }
};
#endif // GLTF_CAMERA_H
diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp
index ff0579a11c..d4f4221663 100644
--- a/modules/gltf/gltf_document.cpp
+++ b/modules/gltf/gltf_document.cpp
@@ -48,6 +48,7 @@
#include "core/io/file_access.h"
#include "core/io/json.h"
#include "core/math/disjoint_set.h"
+#include "core/math/vector2.h"
#include "core/variant/typed_array.h"
#include "core/variant/variant.h"
#include "core/version.h"
@@ -61,6 +62,7 @@
#include "scene/resources/surface_tool.h"
#include "modules/modules_enabled.gen.h"
+
#ifdef MODULE_CSG_ENABLED
#include "modules/csg/csg_shape.h"
#endif // MODULE_CSG_ENABLED
@@ -70,6 +72,7 @@
#include <stdio.h>
#include <stdlib.h>
+#include <cstdint>
#include <limits>
Error GLTFDocument::serialize(Ref<GLTFState> state, Node *p_root, const String &p_path) {
@@ -426,8 +429,8 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) {
node["scale"] = _vec3_to_arr(n->scale);
}
- if (!n->translation.is_equal_approx(Vector3())) {
- node["translation"] = _vec3_to_arr(n->translation);
+ if (!n->position.is_equal_approx(Vector3())) {
+ node["translation"] = _vec3_to_arr(n->position);
}
if (n->children.size()) {
Array children;
@@ -581,7 +584,7 @@ Error GLTFDocument::_parse_nodes(Ref<GLTFState> state) {
node->xform = _arr_to_xform(n["matrix"]);
} else {
if (n.has("translation")) {
- node->translation = _arr_to_vec3(n["translation"]);
+ node->position = _arr_to_vec3(n["translation"]);
}
if (n.has("rotation")) {
node->rotation = _arr_to_quaternion(n["rotation"]);
@@ -591,7 +594,7 @@ Error GLTFDocument::_parse_nodes(Ref<GLTFState> state) {
}
node->xform.basis.set_quaternion_scale(node->rotation, node->scale);
- node->xform.origin = node->translation;
+ node->xform.origin = node->position;
}
if (n.has("extensions")) {
@@ -2170,11 +2173,14 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) {
}
Array array = import_mesh->get_surface_arrays(surface_i);
+ uint32_t format = import_mesh->get_surface_format(surface_i);
+ int32_t vertex_num = 0;
Dictionary attributes;
{
Vector<Vector3> a = array[Mesh::ARRAY_VERTEX];
ERR_FAIL_COND_V(!a.size(), ERR_INVALID_DATA);
attributes["POSITION"] = _encode_accessor_as_vec3(state, a, true);
+ vertex_num = a.size();
}
{
Vector<real_t> a = array[Mesh::ARRAY_TANGENT];
@@ -2217,6 +2223,58 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) {
attributes["TEXCOORD_1"] = _encode_accessor_as_vec2(state, a, true);
}
}
+ for (int custom_i = 0; custom_i < 3; custom_i++) {
+ Vector<float> a = array[Mesh::ARRAY_CUSTOM0 + custom_i];
+ if (a.size()) {
+ int num_channels = 4;
+ int custom_shift = Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT + custom_i * Mesh::ARRAY_FORMAT_CUSTOM_BITS;
+ switch ((format >> custom_shift) & Mesh::ARRAY_FORMAT_CUSTOM_MASK) {
+ case Mesh::ARRAY_CUSTOM_R_FLOAT:
+ num_channels = 1;
+ break;
+ case Mesh::ARRAY_CUSTOM_RG_FLOAT:
+ num_channels = 2;
+ break;
+ case Mesh::ARRAY_CUSTOM_RGB_FLOAT:
+ num_channels = 3;
+ break;
+ case Mesh::ARRAY_CUSTOM_RGBA_FLOAT:
+ num_channels = 4;
+ break;
+ }
+ int texcoord_i = 2 + 2 * custom_i;
+ String gltf_texcoord_key;
+ for (int prev_texcoord_i = 0; prev_texcoord_i < texcoord_i; prev_texcoord_i++) {
+ gltf_texcoord_key = vformat("TEXCOORD_%d", prev_texcoord_i);
+ if (!attributes.has(gltf_texcoord_key)) {
+ Vector<Vector2> empty;
+ empty.resize(vertex_num);
+ attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(state, empty, true);
+ }
+ }
+
+ LocalVector<Vector2> first_channel;
+ first_channel.resize(vertex_num);
+ LocalVector<Vector2> second_channel;
+ second_channel.resize(vertex_num);
+ for (int32_t vert_i = 0; vert_i < vertex_num; vert_i++) {
+ float u = a[vert_i * num_channels + 0];
+ float v = (num_channels == 1 ? 0.0f : a[vert_i * num_channels + 1]);
+ first_channel[vert_i] = Vector2(u, v);
+ u = 0;
+ v = 0;
+ if (num_channels >= 3) {
+ u = a[vert_i * num_channels + 2];
+ v = (num_channels == 3 ? 0.0f : a[vert_i * num_channels + 3]);
+ second_channel[vert_i] = Vector2(u, v);
+ }
+ }
+ gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i);
+ attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(state, first_channel, true);
+ gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i + 1);
+ attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(state, second_channel, true);
+ }
+ }
{
Vector<Color> a = array[Mesh::ARRAY_COLOR];
if (a.size()) {
@@ -2252,13 +2310,12 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) {
}
attributes["JOINTS_0"] = _encode_accessor_as_joints(state, attribs, true);
} else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
- int32_t vertex_count = vertex_array.size();
Vector<Color> joints_0;
- joints_0.resize(vertex_count);
+ joints_0.resize(vertex_num);
Vector<Color> joints_1;
- joints_1.resize(vertex_count);
+ joints_1.resize(vertex_num);
int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
- for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
Color joint_0;
joint_0.r = a[vertex_i * weights_8_count + 0];
joint_0.g = a[vertex_i * weights_8_count + 1];
@@ -2288,13 +2345,12 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) {
}
attributes["WEIGHTS_0"] = _encode_accessor_as_weights(state, attribs, true);
} else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
- int32_t vertex_count = vertex_array.size();
Vector<Color> weights_0;
- weights_0.resize(vertex_count);
+ weights_0.resize(vertex_num);
Vector<Color> weights_1;
- weights_1.resize(vertex_count);
+ weights_1.resize(vertex_num);
int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
- for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
Color weight_0;
weight_0.r = a[vertex_i * weights_8_count + 0];
weight_0.g = a[vertex_i * weights_8_count + 1];
@@ -2458,7 +2514,8 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR);
Array primitives = d["primitives"];
- const Dictionary &extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary();
+ const Dictionary &extras = d.has("extras") ? (Dictionary)d["extras"] :
+ Dictionary();
Ref<EditorSceneImporterMesh> import_mesh;
import_mesh.instantiate();
String mesh_name = "mesh";
@@ -2468,6 +2525,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
import_mesh->set_name(_gen_unique_name(state, vformat("%s_%s", state->scene_name, mesh_name)));
for (int j = 0; j < primitives.size(); j++) {
+ uint32_t flags = 0;
Dictionary p = primitives[j];
Array array;
@@ -2499,8 +2557,11 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
}
ERR_FAIL_COND_V(!a.has("POSITION"), ERR_PARSE_ERROR);
+ int32_t vertex_num = 0;
if (a.has("POSITION")) {
- array[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(state, a["POSITION"], true);
+ PackedVector3Array vertices = _decode_accessor_as_vec3(state, a["POSITION"], true);
+ array[Mesh::ARRAY_VERTEX] = vertices;
+ vertex_num = vertices.size();
}
if (a.has("NORMAL")) {
array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(state, a["NORMAL"], true);
@@ -2514,6 +2575,60 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
if (a.has("TEXCOORD_1")) {
array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(state, a["TEXCOORD_1"], true);
}
+ for (int custom_i = 0; custom_i < 3; custom_i++) {
+ Vector<float> cur_custom;
+ Vector<Vector2> texcoord_first;
+ Vector<Vector2> texcoord_second;
+
+ int texcoord_i = 2 + 2 * custom_i;
+ String gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i);
+ int num_channels = 0;
+ if (a.has(gltf_texcoord_key)) {
+ texcoord_first = _decode_accessor_as_vec2(state, a[gltf_texcoord_key], true);
+ num_channels = 2;
+ }
+ gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i + 1);
+ if (a.has(gltf_texcoord_key)) {
+ texcoord_second = _decode_accessor_as_vec2(state, a[gltf_texcoord_key], true);
+ num_channels = 4;
+ }
+ if (!num_channels) {
+ break;
+ }
+ if (num_channels == 2 || num_channels == 4) {
+ cur_custom.resize(vertex_num * num_channels);
+ for (int32_t uv_i = 0; uv_i < texcoord_first.size() && uv_i < vertex_num; uv_i++) {
+ cur_custom.write[uv_i * num_channels + 0] = texcoord_first[uv_i].x;
+ cur_custom.write[uv_i * num_channels + 1] = texcoord_first[uv_i].y;
+ }
+ // Vector.resize seems to not zero-initialize. Ensure all unused elements are 0:
+ for (int32_t uv_i = texcoord_first.size(); uv_i < vertex_num; uv_i++) {
+ cur_custom.write[uv_i * num_channels + 0] = 0;
+ cur_custom.write[uv_i * num_channels + 1] = 0;
+ }
+ }
+ if (num_channels == 4) {
+ for (int32_t uv_i = 0; uv_i < texcoord_second.size() && uv_i < vertex_num; uv_i++) {
+ // num_channels must be 4
+ cur_custom.write[uv_i * num_channels + 2] = texcoord_second[uv_i].x;
+ cur_custom.write[uv_i * num_channels + 3] = texcoord_second[uv_i].y;
+ }
+ // Vector.resize seems to not zero-initialize. Ensure all unused elements are 0:
+ for (int32_t uv_i = texcoord_second.size(); uv_i < vertex_num; uv_i++) {
+ cur_custom.write[uv_i * num_channels + 2] = 0;
+ cur_custom.write[uv_i * num_channels + 3] = 0;
+ }
+ }
+ if (cur_custom.size() > 0) {
+ array[Mesh::ARRAY_CUSTOM0 + custom_i] = cur_custom;
+ int custom_shift = Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT + custom_i * Mesh::ARRAY_FORMAT_CUSTOM_BITS;
+ if (num_channels == 2) {
+ flags |= Mesh::ARRAY_CUSTOM_RG_FLOAT << custom_shift;
+ } else {
+ flags |= Mesh::ARRAY_CUSTOM_RGBA_FLOAT << custom_shift;
+ }
+ }
+ }
if (a.has("COLOR_0")) {
array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(state, a["COLOR_0"], true);
has_vertex_color = true;
@@ -2525,10 +2640,9 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
PackedInt32Array joints_1 = _decode_accessor_as_ints(state, a["JOINTS_1"], true);
ERR_FAIL_COND_V(joints_0.size() != joints_0.size(), ERR_INVALID_DATA);
int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
- int32_t vertex_count = joints_0.size() / JOINT_GROUP_SIZE;
Vector<int> joints;
- joints.resize(vertex_count * weight_8_count);
- for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ joints.resize(vertex_num * weight_8_count);
+ for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
joints.write[vertex_i * weight_8_count + 0] = joints_0[vertex_i * JOINT_GROUP_SIZE + 0];
joints.write[vertex_i * weight_8_count + 1] = joints_0[vertex_i * JOINT_GROUP_SIZE + 1];
joints.write[vertex_i * weight_8_count + 2] = joints_0[vertex_i * JOINT_GROUP_SIZE + 2];
@@ -2567,9 +2681,8 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
Vector<float> weights;
ERR_FAIL_COND_V(weights_0.size() != weights_1.size(), ERR_INVALID_DATA);
int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
- int32_t vertex_count = weights_0.size() / JOINT_GROUP_SIZE;
- weights.resize(vertex_count * weight_8_count);
- for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ weights.resize(vertex_num * weight_8_count);
+ for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
weights.write[vertex_i * weight_8_count + 0] = weights_0[vertex_i * JOINT_GROUP_SIZE + 0];
weights.write[vertex_i * weight_8_count + 1] = weights_0[vertex_i * JOINT_GROUP_SIZE + 1];
weights.write[vertex_i * weight_8_count + 2] = weights_0[vertex_i * JOINT_GROUP_SIZE + 2];
@@ -2797,7 +2910,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
mat = mat3d;
}
- import_mesh->add_surface(primitive, array, morphs, Dictionary(), mat, mat.is_valid() ? mat->get_name() : String());
+ import_mesh->add_surface(primitive, array, morphs, Dictionary(), mat, mat.is_valid() ? mat->get_name() : String(), flags);
}
Vector<float> blend_weights;
@@ -2953,6 +3066,7 @@ Error GLTFDocument::_parse_images(Ref<GLTFState> state, const String &p_base_pat
}
}
} else { // Relative path to an external image file.
+ uri = uri.uri_decode();
uri = p_base_path.plus_file(uri).replace("\\", "/"); // Fix for Windows.
// ResourceLoader will rely on the file extension to use the relevant loader.
// The spec says that if mimeType is defined, it should take precedence (e.g.
@@ -4356,8 +4470,8 @@ Error GLTFDocument::_serialize_lights(Ref<GLTFState> state) {
color[1] = light->color.g;
color[2] = light->color.b;
d["color"] = color;
- d["type"] = light->type;
- if (light->type == "spot") {
+ d["type"] = light->light_type;
+ if (light->light_type == "spot") {
Dictionary s;
float inner_cone_angle = light->inner_cone_angle;
s["innerConeAngle"] = inner_cone_angle;
@@ -4403,16 +4517,16 @@ Error GLTFDocument::_serialize_cameras(Ref<GLTFState> state) {
Dictionary og;
og["ymag"] = Math::deg2rad(camera->get_fov_size());
og["xmag"] = Math::deg2rad(camera->get_fov_size());
- og["zfar"] = camera->get_zfar();
- og["znear"] = camera->get_znear();
+ og["zfar"] = camera->get_depth_far();
+ og["znear"] = camera->get_depth_near();
d["orthographic"] = og;
d["type"] = "orthographic";
} else if (camera->get_perspective()) {
Dictionary ppt;
// GLTF spec is in radians, Godot's camera is in degrees.
ppt["yfov"] = Math::deg2rad(camera->get_fov_size());
- ppt["zfar"] = camera->get_zfar();
- ppt["znear"] = camera->get_znear();
+ ppt["zfar"] = camera->get_depth_far();
+ ppt["znear"] = camera->get_depth_near();
d["perspective"] = ppt;
d["type"] = "perspective";
}
@@ -4452,7 +4566,7 @@ Error GLTFDocument::_parse_lights(Ref<GLTFState> state) {
light.instantiate();
ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
const String &type = d["type"];
- light->type = type;
+ light->light_type = type;
if (d.has("color")) {
const Array &arr = d["color"];
@@ -4503,8 +4617,8 @@ Error GLTFDocument::_parse_cameras(Ref<GLTFState> state) {
const Dictionary &og = d["orthographic"];
// GLTF spec is in radians, Godot's camera is in degrees.
camera->set_fov_size(Math::rad2deg(real_t(og["ymag"])));
- camera->set_zfar(og["zfar"]);
- camera->set_znear(og["znear"]);
+ camera->set_depth_far(og["zfar"]);
+ camera->set_depth_near(og["znear"]);
} else {
camera->set_fov_size(10);
}
@@ -4514,8 +4628,8 @@ Error GLTFDocument::_parse_cameras(Ref<GLTFState> state) {
const Dictionary &ppt = d["perspective"];
// GLTF spec is in radians, Godot's camera is in degrees.
camera->set_fov_size(Math::rad2deg(real_t(ppt["yfov"])));
- camera->set_zfar(ppt["zfar"]);
- camera->set_znear(ppt["znear"]);
+ camera->set_depth_far(ppt["zfar"]);
+ camera->set_depth_near(ppt["znear"]);
} else {
camera->set_fov_size(10);
}
@@ -4576,15 +4690,15 @@ Error GLTFDocument::_serialize_animations(Ref<GLTFState> state) {
for (Map<int, GLTFAnimation::Track>::Element *track_i = gltf_animation->get_tracks().front(); track_i; track_i = track_i->next()) {
GLTFAnimation::Track track = track_i->get();
- if (track.translation_track.times.size()) {
+ if (track.position_track.times.size()) {
Dictionary t;
t["sampler"] = samplers.size();
Dictionary s;
- s["interpolation"] = interpolation_to_string(track.translation_track.interpolation);
- Vector<real_t> times = Variant(track.translation_track.times);
+ s["interpolation"] = interpolation_to_string(track.position_track.interpolation);
+ Vector<real_t> times = Variant(track.position_track.times);
s["input"] = _encode_accessor_as_floats(state, times, false);
- Vector<Vector3> values = Variant(track.translation_track.values);
+ Vector<Vector3> values = Variant(track.position_track.values);
s["output"] = _encode_accessor_as_vec3(state, values, false);
samplers.push_back(s);
@@ -4769,10 +4883,10 @@ Error GLTFDocument::_parse_animations(Ref<GLTFState> state) {
const Vector<float> times = _decode_accessor_as_floats(state, input, false);
if (path == "translation") {
- const Vector<Vector3> translations = _decode_accessor_as_vec3(state, output, false);
- track->translation_track.interpolation = interp;
- track->translation_track.times = Variant(times); //convert via variant
- track->translation_track.values = Variant(translations); //convert via variant
+ const Vector<Vector3> positions = _decode_accessor_as_vec3(state, output, false);
+ track->position_track.interpolation = interp;
+ track->position_track.times = Variant(times); //convert via variant
+ track->position_track.values = Variant(positions); //convert via variant
} else if (path == "rotation") {
const Vector<Quaternion> rotations = _decode_accessor_as_quaternion(state, output, false);
track->rotation_track.interpolation = interp;
@@ -4896,7 +5010,7 @@ GLTFMeshIndex GLTFDocument::_convert_mesh_instance(Ref<GLTFState> state, MeshIns
if (p_mesh_instance->get_material_override().is_valid()) {
mat = p_mesh_instance->get_material_override();
}
- import_mesh->add_surface(primitive_type, arrays, blend_shape_arrays, Dictionary(), mat, surface_name);
+ import_mesh->add_surface(primitive_type, arrays, blend_shape_arrays, Dictionary(), mat, surface_name, godot_mesh->surface_get_format(surface_i));
}
for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) {
blend_weights.write[blend_i] = 0.0f;
@@ -4950,7 +5064,7 @@ Node3D *GLTFDocument::_generate_light(Ref<GLTFState> state, Node *scene_parent,
intensity /= 100;
}
- if (l->type == "directional") {
+ if (l->light_type == "directional") {
DirectionalLight3D *light = memnew(DirectionalLight3D);
light->set_param(Light3D::PARAM_ENERGY, intensity);
light->set_color(l->color);
@@ -4961,14 +5075,14 @@ Node3D *GLTFDocument::_generate_light(Ref<GLTFState> state, Node *scene_parent,
// Doubling the range will double the effective brightness, so we need double attenuation (half brightness).
// We want to have double intensity give double brightness, so we need half the attenuation.
const float attenuation = range / intensity;
- if (l->type == "point") {
+ if (l->light_type == "point") {
OmniLight3D *light = memnew(OmniLight3D);
light->set_param(OmniLight3D::PARAM_ATTENUATION, attenuation);
light->set_param(OmniLight3D::PARAM_RANGE, range);
light->set_color(l->color);
return light;
}
- if (l->type == "spot") {
+ if (l->light_type == "spot") {
SpotLight3D *light = memnew(SpotLight3D);
light->set_param(SpotLight3D::PARAM_ATTENUATION, attenuation);
light->set_param(SpotLight3D::PARAM_RANGE, range);
@@ -4995,9 +5109,9 @@ Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> state, Node *scene_paren
Ref<GLTFCamera> c = state->cameras[gltf_node->camera];
if (c->get_perspective()) {
- camera->set_perspective(c->get_fov_size(), c->get_znear(), c->get_zfar());
+ camera->set_perspective(c->get_fov_size(), c->get_depth_near(), c->get_depth_far());
} else {
- camera->set_orthogonal(c->get_fov_size(), c->get_znear(), c->get_zfar());
+ camera->set_orthogonal(c->get_fov_size(), c->get_depth_near(), c->get_depth_far());
}
return camera;
@@ -5011,14 +5125,10 @@ GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> state, Camera3D *p_
if (p_camera->get_projection() == Camera3D::Projection::PROJECTION_PERSPECTIVE) {
c->set_perspective(true);
- c->set_fov_size(p_camera->get_fov());
- c->set_zfar(p_camera->get_far());
- c->set_znear(p_camera->get_near());
- } else {
- c->set_fov_size(p_camera->get_fov());
- c->set_zfar(p_camera->get_far());
- c->set_znear(p_camera->get_near());
}
+ c->set_fov_size(p_camera->get_fov());
+ c->set_depth_far(p_camera->get_far());
+ c->set_depth_near(p_camera->get_near());
GLTFCameraIndex camera_index = state->cameras.size();
state->cameras.push_back(c);
return camera_index;
@@ -5031,18 +5141,18 @@ GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> state, Light3D *p_lig
l.instantiate();
l->color = p_light->get_color();
if (cast_to<DirectionalLight3D>(p_light)) {
- l->type = "directional";
+ l->light_type = "directional";
DirectionalLight3D *light = cast_to<DirectionalLight3D>(p_light);
l->intensity = light->get_param(DirectionalLight3D::PARAM_ENERGY);
l->range = FLT_MAX; // Range for directional lights is infinite in Godot.
} else if (cast_to<OmniLight3D>(p_light)) {
- l->type = "point";
+ l->light_type = "point";
OmniLight3D *light = cast_to<OmniLight3D>(p_light);
l->range = light->get_param(OmniLight3D::PARAM_RANGE);
float attenuation = p_light->get_param(OmniLight3D::PARAM_ATTENUATION);
l->intensity = l->range / attenuation;
} else if (cast_to<SpotLight3D>(p_light)) {
- l->type = "spot";
+ l->light_type = "spot";
SpotLight3D *light = cast_to<SpotLight3D>(p_light);
l->range = light->get_param(SpotLight3D::PARAM_RANGE);
float attenuation = light->get_param(SpotLight3D::PARAM_ATTENUATION);
@@ -5075,7 +5185,7 @@ void GLTFDocument::_convert_spatial(Ref<GLTFState> state, Node3D *p_spatial, Ref
Transform3D xform = p_spatial->get_transform();
p_node->scale = xform.basis.get_scale();
p_node->rotation = xform.basis.get_rotation_quaternion();
- p_node->translation = xform.origin;
+ p_node->position = xform.origin;
}
Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) {
@@ -5658,8 +5768,8 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap,
for (int i = 0; i < track.rotation_track.times.size(); i++) {
length = MAX(length, track.rotation_track.times[i]);
}
- for (int i = 0; i < track.translation_track.times.size(); i++) {
- length = MAX(length, track.translation_track.times[i]);
+ for (int i = 0; i < track.position_track.times.size(); i++) {
+ length = MAX(length, track.position_track.times[i]);
}
for (int i = 0; i < track.scale_track.times.size(); i++) {
length = MAX(length, track.scale_track.times[i]);
@@ -5673,7 +5783,7 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap,
// Animated TRS properties will not affect a skinned mesh.
const bool transform_affects_skinned_mesh_instance = gltf_node->skeleton < 0 && gltf_node->skin >= 0;
- if ((track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) && !transform_affects_skinned_mesh_instance) {
+ if ((track.rotation_track.values.size() || track.position_track.values.size() || track.scale_track.values.size()) && !transform_affects_skinned_mesh_instance) {
//make transform track
int track_idx = animation->get_track_count();
animation->add_track(Animation::TYPE_TRANSFORM3D);
@@ -5691,8 +5801,8 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap,
base_rot = state->nodes[track_i->key()]->rotation.normalized();
}
- if (!track.translation_track.values.size()) {
- base_pos = state->nodes[track_i->key()]->translation;
+ if (!track.position_track.values.size()) {
+ base_pos = state->nodes[track_i->key()]->position;
}
if (!track.scale_track.values.size()) {
@@ -5705,8 +5815,8 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap,
Quaternion rot = base_rot;
Vector3 scale = base_scale;
- if (track.translation_track.times.size()) {
- pos = _interpolate_track<Vector3>(track.translation_track.times, track.translation_track.values, time, track.translation_track.interpolation);
+ if (track.position_track.times.size()) {
+ pos = _interpolate_track<Vector3>(track.position_track.times, track.position_track.values, time, track.position_track.interpolation);
}
if (track.rotation_track.times.size()) {
@@ -5814,7 +5924,7 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) {
Transform3D mi_xform = mi->get_transform();
node->scale = mi_xform.basis.get_scale();
node->rotation = mi_xform.basis.get_rotation_quaternion();
- node->translation = mi_xform.origin;
+ node->position = mi_xform.origin;
Dictionary json_skin;
Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(mi->get_node(mi->get_skeleton_path()));
@@ -5878,7 +5988,7 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) {
Transform3D bone_rest_xform = skeleton->get_bone_rest(bone_index);
joint_node->scale = bone_rest_xform.basis.get_scale();
joint_node->rotation = bone_rest_xform.basis.get_rotation_quaternion();
- joint_node->translation = bone_rest_xform.origin;
+ joint_node->position = bone_rest_xform.origin;
joint_node->joint = true;
int32_t joint_node_i = state->nodes.size();
@@ -6024,8 +6134,8 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state
}
const float BAKE_FPS = 30.0f;
if (track_type == Animation::TYPE_TRANSFORM3D) {
- p_track.translation_track.times = times;
- p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.position_track.times = times;
+ p_track.position_track.interpolation = gltf_interpolation;
p_track.rotation_track.times = times;
p_track.rotation_track.interpolation = gltf_interpolation;
p_track.scale_track.times = times;
@@ -6033,27 +6143,27 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state
p_track.scale_track.values.resize(key_count);
p_track.scale_track.interpolation = gltf_interpolation;
- p_track.translation_track.values.resize(key_count);
- p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.position_track.values.resize(key_count);
+ p_track.position_track.interpolation = gltf_interpolation;
p_track.rotation_track.values.resize(key_count);
p_track.rotation_track.interpolation = gltf_interpolation;
for (int32_t key_i = 0; key_i < key_count; key_i++) {
- Vector3 translation;
+ Vector3 position;
Quaternion rotation;
Vector3 scale;
- Error err = p_animation->transform_track_get_key(p_track_i, key_i, &translation, &rotation, &scale);
+ Error err = p_animation->transform_track_get_key(p_track_i, key_i, &position, &rotation, &scale);
ERR_CONTINUE(err != OK);
Transform3D xform;
xform.basis.set_quaternion_scale(rotation, scale);
- xform.origin = translation;
+ xform.origin = position;
xform = p_bone_rest * xform;
- p_track.translation_track.values.write[key_i] = xform.get_origin();
+ p_track.position_track.values.write[key_i] = xform.get_origin();
p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quaternion();
p_track.scale_track.values.write[key_i] = xform.basis.get_scale();
}
} else if (path.find(":transform") != -1) {
- p_track.translation_track.times = times;
- p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.position_track.times = times;
+ p_track.position_track.interpolation = gltf_interpolation;
p_track.rotation_track.times = times;
p_track.rotation_track.interpolation = gltf_interpolation;
p_track.scale_track.times = times;
@@ -6061,13 +6171,13 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state
p_track.scale_track.values.resize(key_count);
p_track.scale_track.interpolation = gltf_interpolation;
- p_track.translation_track.values.resize(key_count);
- p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.position_track.values.resize(key_count);
+ p_track.position_track.interpolation = gltf_interpolation;
p_track.rotation_track.values.resize(key_count);
p_track.rotation_track.interpolation = gltf_interpolation;
for (int32_t key_i = 0; key_i < key_count; key_i++) {
Transform3D xform = p_animation->track_get_key_value(p_track_i, key_i);
- p_track.translation_track.values.write[key_i] = xform.get_origin();
+ p_track.position_track.values.write[key_i] = xform.get_origin();
p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quaternion();
p_track.scale_track.values.write[key_i] = xform.basis.get_scale();
}
@@ -6083,16 +6193,16 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state
Quaternion rotation_track = p_animation->track_get_key_value(p_track_i, key_i);
p_track.rotation_track.values.write[key_i] = rotation_track;
}
- } else if (path.find(":translation") != -1) {
- p_track.translation_track.times = times;
- p_track.translation_track.interpolation = gltf_interpolation;
+ } else if (path.find(":position") != -1) {
+ p_track.position_track.times = times;
+ p_track.position_track.interpolation = gltf_interpolation;
- p_track.translation_track.values.resize(key_count);
- p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.position_track.values.resize(key_count);
+ p_track.position_track.interpolation = gltf_interpolation;
for (int32_t key_i = 0; key_i < key_count; key_i++) {
- Vector3 translation = p_animation->track_get_key_value(p_track_i, key_i);
- p_track.translation_track.values.write[key_i] = translation;
+ Vector3 position = p_animation->track_get_key_value(p_track_i, key_i);
+ p_track.position_track.values.write[key_i] = position;
}
} else if (path.find(":rotation") != -1) {
p_track.rotation_track.times = times;
@@ -6151,34 +6261,34 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state
}
p_track.scale_track.values.write[key_i] = bezier_track;
}
- } else if (path.find("/translation") != -1) {
+ } else if (path.find("/position") != -1) {
const int32_t keys = p_animation->track_get_key_time(p_track_i, key_count - 1) * BAKE_FPS;
- if (!p_track.translation_track.times.size()) {
+ if (!p_track.position_track.times.size()) {
Vector<float> new_times;
new_times.resize(keys);
for (int32_t key_i = 0; key_i < keys; key_i++) {
new_times.write[key_i] = key_i / BAKE_FPS;
}
- p_track.translation_track.times = new_times;
- p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.position_track.times = new_times;
+ p_track.position_track.interpolation = gltf_interpolation;
- p_track.translation_track.values.resize(keys);
- p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.position_track.values.resize(keys);
+ p_track.position_track.interpolation = gltf_interpolation;
}
for (int32_t key_i = 0; key_i < keys; key_i++) {
- Vector3 bezier_track = p_track.translation_track.values[key_i];
- if (path.find("/translation:x") != -1) {
+ Vector3 bezier_track = p_track.position_track.values[key_i];
+ if (path.find("/position:x") != -1) {
bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
bezier_track.x = p_bone_rest.affine_inverse().origin.x * bezier_track.x;
- } else if (path.find("/translation:y") != -1) {
+ } else if (path.find("/position:y") != -1) {
bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
bezier_track.y = p_bone_rest.affine_inverse().origin.y * bezier_track.y;
- } else if (path.find("/translation:z") != -1) {
+ } else if (path.find("/position:z") != -1) {
bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
bezier_track.z = p_bone_rest.affine_inverse().origin.z * bezier_track.z;
}
- p_track.translation_track.values.write[key_i] = bezier_track;
+ p_track.position_track.values.write[key_i] = bezier_track;
}
}
}
@@ -6197,17 +6307,17 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap,
continue;
}
String orig_track_path = animation->track_get_path(track_i);
- if (String(orig_track_path).find(":translation") != -1) {
- const Vector<String> node_suffix = String(orig_track_path).split(":translation");
+ if (String(orig_track_path).find(":position") != -1) {
+ const Vector<String> node_suffix = String(orig_track_path).split(":position");
const NodePath path = node_suffix[0];
const Node *node = ap->get_parent()->get_node_or_null(path);
- for (Map<GLTFNodeIndex, Node *>::Element *translation_scene_node_i = state->scene_nodes.front(); translation_scene_node_i; translation_scene_node_i = translation_scene_node_i->next()) {
- if (translation_scene_node_i->get() == node) {
- GLTFNodeIndex node_index = translation_scene_node_i->key();
- Map<int, GLTFAnimation::Track>::Element *translation_track_i = gltf_animation->get_tracks().find(node_index);
+ for (Map<GLTFNodeIndex, Node *>::Element *position_scene_node_i = state->scene_nodes.front(); position_scene_node_i; position_scene_node_i = position_scene_node_i->next()) {
+ if (position_scene_node_i->get() == node) {
+ GLTFNodeIndex node_index = position_scene_node_i->key();
+ Map<int, GLTFAnimation::Track>::Element *position_track_i = gltf_animation->get_tracks().find(node_index);
GLTFAnimation::Track track;
- if (translation_track_i) {
- track = translation_track_i->get();
+ if (position_track_i) {
+ track = position_track_i->get();
}
track = _convert_animation_track(state, track, animation, Transform3D(), track_i, node_index);
gltf_animation->get_tracks().insert(node_index, track);
@@ -6630,3 +6740,78 @@ Error GLTFDocument::_serialize_file(Ref<GLTFState> state, const String p_path) {
}
return err;
}
+
+Error GLTFDocument::save_scene(Node *p_node, const String &p_path,
+ const String &p_src_path, uint32_t p_flags,
+ float p_bake_fps, Ref<GLTFState> r_state) {
+ Ref<GLTFDocument> gltf_document;
+ gltf_document.instantiate();
+ if (r_state == Ref<GLTFState>()) {
+ r_state.instantiate();
+ }
+ return gltf_document->serialize(r_state, p_node, p_path);
+}
+
+Node *GLTFDocument::import_scene_gltf(const String &p_path, uint32_t p_flags, int32_t p_bake_fps, Ref<GLTFState> r_state, List<String> *r_missing_deps, Error *r_err) {
+ // TODO Add missing texture and missing .bin file paths to r_missing_deps 2021-09-10 fire
+ if (r_state == Ref<GLTFState>()) {
+ r_state.instantiate();
+ }
+ r_state->use_named_skin_binds =
+ p_flags & EditorSceneImporter::IMPORT_USE_NAMED_SKIN_BINDS;
+
+ Ref<GLTFDocument> gltf_document;
+ gltf_document.instantiate();
+ Error err = gltf_document->parse(r_state, p_path);
+ if (r_err) {
+ *r_err = err;
+ }
+ ERR_FAIL_COND_V(err != Error::OK, nullptr);
+
+ Node3D *root = memnew(Node3D);
+ for (int32_t root_i = 0; root_i < r_state->root_nodes.size(); root_i++) {
+ gltf_document->_generate_scene_node(r_state, root, root, r_state->root_nodes[root_i]);
+ }
+ gltf_document->_process_mesh_instances(r_state, root);
+ if (r_state->animations.size()) {
+ AnimationPlayer *ap = memnew(AnimationPlayer);
+ root->add_child(ap);
+ ap->set_owner(root);
+ for (int i = 0; i < r_state->animations.size(); i++) {
+ gltf_document->_import_animation(r_state, ap, i, p_bake_fps);
+ }
+ }
+
+ return root;
+}
+
+void GLTFDocument::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("save_scene", "node", "path", "src_path", "flags", "bake_fps", "state"),
+ &GLTFDocument::save_scene, DEFVAL(0), DEFVAL(30), DEFVAL(Ref<GLTFState>()));
+ ClassDB::bind_method(D_METHOD("import_scene", "path", "flags", "bake_fps", "state"),
+ &GLTFDocument::import_scene, DEFVAL(0), DEFVAL(30), DEFVAL(Ref<GLTFState>()));
+}
+
+void GLTFDocument::_build_parent_hierachy(Ref<GLTFState> state) {
+ // build the hierarchy
+ for (GLTFNodeIndex node_i = 0; node_i < state->nodes.size(); node_i++) {
+ for (int j = 0; j < state->nodes[node_i]->children.size(); j++) {
+ GLTFNodeIndex child_i = state->nodes[node_i]->children[j];
+ ERR_FAIL_INDEX(child_i, state->nodes.size());
+ if (state->nodes.write[child_i]->parent != -1) {
+ continue;
+ }
+ state->nodes.write[child_i]->parent = node_i;
+ }
+ }
+}
+
+Node *GLTFDocument::import_scene(const String &p_path, uint32_t p_flags, int32_t p_bake_fps, Ref<GLTFState> r_state) {
+ Error err = FAILED;
+ List<String> deps;
+ Node *node = import_scene_gltf(p_path, p_flags, p_bake_fps, r_state, &deps, &err);
+ if (err != OK) {
+ return nullptr;
+ }
+ return node;
+}
diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h
index 7a826897a9..fb798a055a 100644
--- a/modules/gltf/gltf_document.h
+++ b/modules/gltf/gltf_document.h
@@ -44,6 +44,7 @@
#include "scene/resources/texture.h"
#include "modules/modules_enabled.gen.h"
+#include <cstdint>
class GLTFState;
class GLTFSkin;
@@ -102,6 +103,16 @@ public:
COMPONENT_TYPE_FLOAT = 5126,
};
+protected:
+ static void _bind_methods();
+
+public:
+ Node *import_scene(const String &p_path, uint32_t p_flags, int32_t p_bake_fps, Ref<GLTFState> r_state);
+ Node *import_scene_gltf(const String &p_path, uint32_t p_flags, int32_t p_bake_fps, Ref<GLTFState> r_state, List<String> *r_missing_deps, Error *r_err = nullptr);
+ Error save_scene(Node *p_node, const String &p_path,
+ const String &p_src_path, uint32_t p_flags,
+ float p_bake_fps, Ref<GLTFState> r_state);
+
private:
template <class T>
static Array to_array(const Vector<T> &p_inp) {
@@ -155,6 +166,7 @@ private:
r_out[keys[i]] = p_inp[keys[i]];
}
}
+ void _build_parent_hierachy(Ref<GLTFState> state);
double _filter_number(double p_float);
String _get_component_type_name(const uint32_t p_component);
int _get_component_type_size(const int component_type);
diff --git a/modules/gltf/gltf_light.cpp b/modules/gltf/gltf_light.cpp
index 95cca9cf71..c5aa8d5724 100644
--- a/modules/gltf/gltf_light.cpp
+++ b/modules/gltf/gltf_light.cpp
@@ -35,8 +35,8 @@ void GLTFLight::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_color", "color"), &GLTFLight::set_color);
ClassDB::bind_method(D_METHOD("get_intensity"), &GLTFLight::get_intensity);
ClassDB::bind_method(D_METHOD("set_intensity", "intensity"), &GLTFLight::set_intensity);
- ClassDB::bind_method(D_METHOD("get_type"), &GLTFLight::get_type);
- ClassDB::bind_method(D_METHOD("set_type", "type"), &GLTFLight::set_type);
+ ClassDB::bind_method(D_METHOD("get_light_type"), &GLTFLight::get_light_type);
+ ClassDB::bind_method(D_METHOD("set_light_type", "light_type"), &GLTFLight::set_light_type);
ClassDB::bind_method(D_METHOD("get_range"), &GLTFLight::get_range);
ClassDB::bind_method(D_METHOD("set_range", "range"), &GLTFLight::set_range);
ClassDB::bind_method(D_METHOD("get_inner_cone_angle"), &GLTFLight::get_inner_cone_angle);
@@ -46,7 +46,7 @@ void GLTFLight::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); // Color
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "intensity"), "set_intensity", "get_intensity"); // float
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "type"), "set_type", "get_type"); // String
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "light_type"), "set_light_type", "get_light_type"); // String
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "range"), "set_range", "get_range"); // float
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "inner_cone_angle"), "set_inner_cone_angle", "get_inner_cone_angle"); // float
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "outer_cone_angle"), "set_outer_cone_angle", "get_outer_cone_angle"); // float
@@ -68,12 +68,12 @@ void GLTFLight::set_intensity(float p_intensity) {
intensity = p_intensity;
}
-String GLTFLight::get_type() {
- return type;
+String GLTFLight::get_light_type() {
+ return light_type;
}
-void GLTFLight::set_type(String p_type) {
- type = p_type;
+void GLTFLight::set_light_type(String p_light_type) {
+ light_type = p_light_type;
}
float GLTFLight::get_range() {
diff --git a/modules/gltf/gltf_light.h b/modules/gltf/gltf_light.h
index a859ca1833..079fb18151 100644
--- a/modules/gltf/gltf_light.h
+++ b/modules/gltf/gltf_light.h
@@ -44,7 +44,7 @@ protected:
private:
Color color;
float intensity = 0.0f;
- String type;
+ String light_type;
float range = 0.0f;
float inner_cone_angle = 0.0f;
float outer_cone_angle = 0.0f;
@@ -56,8 +56,8 @@ public:
float get_intensity();
void set_intensity(float p_intensity);
- String get_type();
- void set_type(String p_type);
+ String get_light_type();
+ void set_light_type(String p_light_type);
float get_range();
void set_range(float p_range);
diff --git a/modules/gltf/gltf_node.cpp b/modules/gltf/gltf_node.cpp
index 5db7ad66c3..9f925c7bbc 100644
--- a/modules/gltf/gltf_node.cpp
+++ b/modules/gltf/gltf_node.cpp
@@ -47,8 +47,8 @@ void GLTFNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_skeleton", "skeleton"), &GLTFNode::set_skeleton);
ClassDB::bind_method(D_METHOD("get_joint"), &GLTFNode::get_joint);
ClassDB::bind_method(D_METHOD("set_joint", "joint"), &GLTFNode::set_joint);
- ClassDB::bind_method(D_METHOD("get_translation"), &GLTFNode::get_translation);
- ClassDB::bind_method(D_METHOD("set_translation", "translation"), &GLTFNode::set_translation);
+ ClassDB::bind_method(D_METHOD("get_position"), &GLTFNode::get_position);
+ ClassDB::bind_method(D_METHOD("set_position", "position"), &GLTFNode::set_position);
ClassDB::bind_method(D_METHOD("get_rotation"), &GLTFNode::get_rotation);
ClassDB::bind_method(D_METHOD("set_rotation", "rotation"), &GLTFNode::set_rotation);
ClassDB::bind_method(D_METHOD("get_scale"), &GLTFNode::get_scale);
@@ -66,7 +66,7 @@ void GLTFNode::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "skin"), "set_skin", "get_skin"); // GLTFSkinIndex
ADD_PROPERTY(PropertyInfo(Variant::INT, "skeleton"), "set_skeleton", "get_skeleton"); // GLTFSkeletonIndex
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "joint"), "set_joint", "get_joint"); // bool
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "translation"), "set_translation", "get_translation"); // Vector3
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "position"), "set_position", "get_position"); // Vector3
ADD_PROPERTY(PropertyInfo(Variant::QUATERNION, "rotation"), "set_rotation", "get_rotation"); // Quaternion
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale"), "set_scale", "get_scale"); // Vector3
ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "children"), "set_children", "get_children"); // Vector<int>
@@ -137,12 +137,12 @@ void GLTFNode::set_joint(bool p_joint) {
joint = p_joint;
}
-Vector3 GLTFNode::get_translation() {
- return translation;
+Vector3 GLTFNode::get_position() {
+ return position;
}
-void GLTFNode::set_translation(Vector3 p_translation) {
- translation = p_translation;
+void GLTFNode::set_position(Vector3 p_position) {
+ position = p_position;
}
Quaternion GLTFNode::get_rotation() {
diff --git a/modules/gltf/gltf_node.h b/modules/gltf/gltf_node.h
index 378b6da8bf..3b6e061449 100644
--- a/modules/gltf/gltf_node.h
+++ b/modules/gltf/gltf_node.h
@@ -37,7 +37,6 @@
class GLTFNode : public Resource {
GDCLASS(GLTFNode, Resource);
friend class GLTFDocument;
- friend class PackedSceneGLTF;
private:
// matrices need to be transformed to this
@@ -49,7 +48,7 @@ private:
GLTFSkinIndex skin = -1;
GLTFSkeletonIndex skeleton = -1;
bool joint = false;
- Vector3 translation;
+ Vector3 position;
Quaternion rotation;
Vector3 scale = Vector3(1, 1, 1);
Vector<int> children;
@@ -83,8 +82,8 @@ public:
bool get_joint();
void set_joint(bool p_joint);
- Vector3 get_translation();
- void set_translation(Vector3 p_translation);
+ Vector3 get_position();
+ void set_position(Vector3 p_position);
Quaternion get_rotation();
void set_rotation(Quaternion p_rotation);
diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h
index d8209523c5..896ea5fc56 100644
--- a/modules/gltf/gltf_state.h
+++ b/modules/gltf/gltf_state.h
@@ -51,7 +51,6 @@
class GLTFState : public Resource {
GDCLASS(GLTFState, Resource);
friend class GLTFDocument;
- friend class PackedSceneGLTF;
String filename;
Dictionary json;
diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp
index 85921490d2..d6020f50f0 100644
--- a/modules/gltf/register_types.cpp
+++ b/modules/gltf/register_types.cpp
@@ -80,7 +80,6 @@ void register_gltf_types() {
GDREGISTER_CLASS(GLTFLight);
GDREGISTER_CLASS(GLTFState);
GDREGISTER_CLASS(GLTFDocument);
- GDREGISTER_CLASS(PackedSceneGLTF);
#endif
}
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index 8e8b6f14ad..487e6deac0 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -475,7 +475,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
}
Pair<Transform3D, IndexKey> p;
- p.first = xform;
+ p.first = xform * mesh_library->get_item_mesh_transform(c.item);
p.second = E->get();
multimesh_items[c.item].push_back(p);
}
diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp
index 2331a12d0f..c170bb107e 100644
--- a/modules/gridmap/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/grid_map_editor_plugin.cpp
@@ -255,6 +255,12 @@ void GridMapEditor::_update_cursor_transform() {
cursor_transform.basis *= node->get_cell_scale();
cursor_transform = node->get_global_transform() * cursor_transform;
+ if (selected_palette >= 0) {
+ if (node && !node->get_mesh_library().is_null()) {
+ cursor_transform *= node->get_mesh_library()->get_item_mesh_transform(selected_palette);
+ }
+ }
+
if (cursor_instance.is_valid()) {
RenderingServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform);
RenderingServer::get_singleton()->instance_set_visible(cursor_instance, cursor_visible);
diff --git a/modules/lightmapper_rd/SCsub b/modules/lightmapper_rd/SCsub
index 2f04f1833e..5cc9d8ee8b 100644
--- a/modules/lightmapper_rd/SCsub
+++ b/modules/lightmapper_rd/SCsub
@@ -7,6 +7,9 @@ env_lightmapper_rd = env_modules.Clone()
env_lightmapper_rd.GLSL_HEADER("lm_raster.glsl")
env_lightmapper_rd.GLSL_HEADER("lm_compute.glsl")
env_lightmapper_rd.GLSL_HEADER("lm_blendseams.glsl")
+env_lightmapper_rd.Depends("lm_raster.glsl.gen.h", "lm_common_inc.glsl")
+env_lightmapper_rd.Depends("lm_compute.glsl.gen.h", "lm_common_inc.glsl")
+env_lightmapper_rd.Depends("lm_blendseams.glsl.gen.h", "lm_common_inc.glsl")
# Godot source files
env_lightmapper_rd.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/lightmapper_rd/lightmapper_rd.cpp b/modules/lightmapper_rd/lightmapper_rd.cpp
index fe941e25e7..ba4ef3be8d 100644
--- a/modules/lightmapper_rd/lightmapper_rd.cpp
+++ b/modules/lightmapper_rd/lightmapper_rd.cpp
@@ -274,13 +274,12 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_
return BAKE_OK;
}
-void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &box_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
+void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
HashMap<Vertex, uint32_t, VertexHash> vertex_map;
//fill triangles array and vertex array
LocalVector<Triangle> triangles;
LocalVector<Vertex> vertex_array;
- LocalVector<Box> box_array;
LocalVector<Seam> seams;
slice_triangle_count.resize(atlas_slices);
@@ -387,16 +386,13 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i
}
}
- Box box;
- box.min_bounds[0] = taabb.position.x;
- box.min_bounds[1] = taabb.position.y;
- box.min_bounds[2] = taabb.position.z;
- box.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
- box.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
- box.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
- box.pad0 = box.pad1 = 0; //make valgrind not complain
- box_array.push_back(box);
-
+ t.min_bounds[0] = taabb.position.x;
+ t.min_bounds[1] = taabb.position.y;
+ t.min_bounds[2] = taabb.position.z;
+ t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
+ t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
+ t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
+ t.pad0 = t.pad1 = 0; //make valgrind not complain
triangles.push_back(t);
slice_triangle_count.write[t.slice]++;
}
@@ -505,9 +501,6 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i
Vector<uint8_t> tb = triangles.to_byte_array();
triangle_buffer = rd->storage_buffer_create(tb.size(), tb);
- Vector<uint8_t> bb = box_array.to_byte_array();
- box_buffer = rd->storage_buffer_create(bb.size(), bb);
-
Vector<uint8_t> tib = triangle_indices.to_byte_array();
triangle_cell_indices_buffer = rd->storage_buffer_create(tib.size(), tib);
@@ -755,7 +748,6 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
Vector<int> slice_triangle_count;
RID vertex_buffer;
RID triangle_buffer;
- RID box_buffer;
RID lights_buffer;
RID triangle_cell_indices_buffer;
RID grid_texture;
@@ -767,14 +759,13 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
#define FREE_BUFFERS \
rd->free(vertex_buffer); \
rd->free(triangle_buffer); \
- rd->free(box_buffer); \
rd->free(lights_buffer); \
rd->free(triangle_cell_indices_buffer); \
rd->free(grid_texture); \
rd->free(seams_buffer); \
rd->free(probe_positions_buffer);
- _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, box_buffer, lights_buffer, triangle_cell_indices_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);
+ _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_cell_indices_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);
if (p_step_function) {
p_step_function(0.47, TTR("Preparing shaders"), p_bake_userdata, true);
@@ -828,62 +819,55 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
u.binding = 3;
- u.ids.push_back(box_buffer);
- base_uniforms.push_back(u);
- }
- {
- RD::Uniform u;
- u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
- u.binding = 4;
u.ids.push_back(triangle_cell_indices_buffer);
base_uniforms.push_back(u);
}
{
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
- u.binding = 5;
+ u.binding = 4;
u.ids.push_back(lights_buffer);
base_uniforms.push_back(u);
}
{
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
- u.binding = 6;
+ u.binding = 5;
u.ids.push_back(seams_buffer);
base_uniforms.push_back(u);
}
{
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
- u.binding = 7;
+ u.binding = 6;
u.ids.push_back(probe_positions_buffer);
base_uniforms.push_back(u);
}
{
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
- u.binding = 8;
+ u.binding = 7;
u.ids.push_back(grid_texture);
base_uniforms.push_back(u);
}
{
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
- u.binding = 9;
+ u.binding = 8;
u.ids.push_back(albedo_array_tex);
base_uniforms.push_back(u);
}
{
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
- u.binding = 10;
+ u.binding = 9;
u.ids.push_back(emission_array_tex);
base_uniforms.push_back(u);
}
{
RD::Uniform u;
u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
- u.binding = 11;
+ u.binding = 10;
u.ids.push_back(sampler);
base_uniforms.push_back(u);
}
diff --git a/modules/lightmapper_rd/lightmapper_rd.h b/modules/lightmapper_rd/lightmapper_rd.h
index 7ab7f34464..a6a3740051 100644
--- a/modules/lightmapper_rd/lightmapper_rd.h
+++ b/modules/lightmapper_rd/lightmapper_rd.h
@@ -157,16 +157,13 @@ class LightmapperRD : public Lightmapper {
}
};
- struct Box {
+ struct Triangle {
+ uint32_t indices[3] = {};
+ uint32_t slice = 0;
float min_bounds[3] = {};
float pad0 = 0.0;
float max_bounds[3] = {};
float pad1 = 0.0;
- };
-
- struct Triangle {
- uint32_t indices[3] = {};
- uint32_t slice = 0;
bool operator<(const Triangle &p_triangle) const {
return slice < p_triangle.slice;
}
@@ -231,7 +228,7 @@ class LightmapperRD : public Lightmapper {
Vector<Color> probe_values;
BakeError _blit_meshes_into_atlas(int p_max_texture_size, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, BakeStepFunc p_step_function, void *p_bake_userdata);
- void _create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &box_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata);
+ void _create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata);
void _raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform);
public:
diff --git a/modules/lightmapper_rd/lm_common_inc.glsl b/modules/lightmapper_rd/lm_common_inc.glsl
index 1581639036..22172d50e4 100644
--- a/modules/lightmapper_rd/lm_common_inc.glsl
+++ b/modules/lightmapper_rd/lm_common_inc.glsl
@@ -16,26 +16,18 @@ vertices;
struct Triangle {
uvec3 indices;
uint slice;
-};
-
-layout(set = 0, binding = 2, std430) restrict readonly buffer Triangles {
- Triangle data[];
-}
-triangles;
-
-struct Box {
vec3 min_bounds;
uint pad0;
vec3 max_bounds;
uint pad1;
};
-layout(set = 0, binding = 3, std430) restrict readonly buffer Boxes {
- Box data[];
+layout(set = 0, binding = 2, std430) restrict readonly buffer Triangles {
+ Triangle data[];
}
-boxes;
+triangles;
-layout(set = 0, binding = 4, std430) restrict readonly buffer GridIndices {
+layout(set = 0, binding = 3, std430) restrict readonly buffer GridIndices {
uint data[];
}
grid_indices;
@@ -63,7 +55,7 @@ struct Light {
uint pad[3];
};
-layout(set = 0, binding = 5, std430) restrict readonly buffer Lights {
+layout(set = 0, binding = 4, std430) restrict readonly buffer Lights {
Light data[];
}
lights;
@@ -73,19 +65,19 @@ struct Seam {
uvec2 b;
};
-layout(set = 0, binding = 6, std430) restrict readonly buffer Seams {
+layout(set = 0, binding = 5, std430) restrict readonly buffer Seams {
Seam data[];
}
seams;
-layout(set = 0, binding = 7, std430) restrict readonly buffer Probes {
+layout(set = 0, binding = 6, std430) restrict readonly buffer Probes {
vec4 data[];
}
probe_positions;
-layout(set = 0, binding = 8) uniform utexture3D grid;
+layout(set = 0, binding = 7) uniform utexture3D grid;
-layout(set = 0, binding = 9) uniform texture2DArray albedo_tex;
-layout(set = 0, binding = 10) uniform texture2DArray emission_tex;
+layout(set = 0, binding = 8) uniform texture2DArray albedo_tex;
+layout(set = 0, binding = 9) uniform texture2DArray emission_tex;
-layout(set = 0, binding = 11) uniform sampler linear_sampler;
+layout(set = 0, binding = 10) uniform sampler linear_sampler;
diff --git a/modules/lightmapper_rd/lm_compute.glsl b/modules/lightmapper_rd/lm_compute.glsl
index 9ca40535f9..a71652d5c4 100644
--- a/modules/lightmapper_rd/lm_compute.glsl
+++ b/modules/lightmapper_rd/lm_compute.glsl
@@ -160,18 +160,19 @@ bool trace_ray(vec3 p_from, vec3 p_to
uint tidx = grid_indices.data[cell_data.y + i];
//Ray-Box test
- vec3 t0 = (boxes.data[tidx].min_bounds - p_from) * inv_dir;
- vec3 t1 = (boxes.data[tidx].max_bounds - p_from) * inv_dir;
+ Triangle triangle = triangles.data[tidx];
+ vec3 t0 = (triangle.min_bounds - p_from) * inv_dir;
+ vec3 t1 = (triangle.max_bounds - p_from) * inv_dir;
vec3 tmin = min(t0, t1), tmax = max(t0, t1);
- if (max(tmin.x, max(tmin.y, tmin.z)) <= min(tmax.x, min(tmax.y, tmax.z))) {
+ if (max(tmin.x, max(tmin.y, tmin.z)) > min(tmax.x, min(tmax.y, tmax.z))) {
continue; //ray box failed
}
//prepare triangle vertices
- vec3 vtx0 = vertices.data[triangles.data[tidx].indices.x].position;
- vec3 vtx1 = vertices.data[triangles.data[tidx].indices.y].position;
- vec3 vtx2 = vertices.data[triangles.data[tidx].indices.z].position;
+ vec3 vtx0 = vertices.data[triangle.indices.x].position;
+ vec3 vtx1 = vertices.data[triangle.indices.y].position;
+ vec3 vtx2 = vertices.data[triangle.indices.z].position;
#if defined(MODE_UNOCCLUDE)
vec3 normal = -normalize(cross((vtx0 - vtx1), (vtx0 - vtx2)));
diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp
index 3437dbd194..17846eb281 100644
--- a/modules/mono/csharp_script.cpp
+++ b/modules/mono/csharp_script.cpp
@@ -43,8 +43,10 @@
#include "core/os/thread.h"
#ifdef TOOLS_ENABLED
+#include "core/os/keyboard.h"
#include "editor/bindings_generator.h"
#include "editor/editor_node.h"
+#include "editor/editor_settings.h"
#include "editor/node_dock.h"
#endif
@@ -1353,6 +1355,7 @@ void CSharpLanguage::_editor_init_callback() {
// Enable it as a plugin
EditorNode::add_editor_plugin(godotsharp_editor);
+ ED_SHORTCUT("mono/build_solution", TTR("Build Solution"), KEY_MASK_ALT | KEY_B);
godotsharp_editor->enable_plugin();
get_singleton()->godotsharp_editor = godotsharp_editor;
@@ -1861,6 +1864,28 @@ Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *
return Variant::NIL;
}
+void CSharpInstance::get_method_list(List<MethodInfo> *p_list) const {
+ if (!script->is_valid() || !script->script_class)
+ return;
+
+ GD_MONO_SCOPE_THREAD_ATTACH;
+
+ // TODO: We're filtering out constructors but there may be other methods unsuitable for explicit calls.
+ GDMonoClass *top = script->script_class;
+
+ while (top && top != script->native) {
+ const Vector<GDMonoMethod *> &methods = top->get_all_methods();
+ for (int i = 0; i < methods.size(); ++i) {
+ MethodInfo minfo = methods[i]->get_method_info();
+ if (minfo.name != CACHED_STRING_NAME(dotctor)) {
+ p_list->push_back(minfo);
+ }
+ }
+
+ top = top->get_parent_class();
+ }
+}
+
bool CSharpInstance::has_method(const StringName &p_method) const {
if (!script.is_valid()) {
return false;
@@ -3280,10 +3305,19 @@ void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
GD_MONO_SCOPE_THREAD_ATTACH;
- // TODO: Filter out things unsuitable for explicit calls, like constructors.
- const Vector<GDMonoMethod *> &methods = script_class->get_all_methods();
- for (int i = 0; i < methods.size(); ++i) {
- p_list->push_back(methods[i]->get_method_info());
+ // TODO: We're filtering out constructors but there may be other methods unsuitable for explicit calls.
+ GDMonoClass *top = script_class;
+
+ while (top && top != native) {
+ const Vector<GDMonoMethod *> &methods = top->get_all_methods();
+ for (int i = 0; i < methods.size(); ++i) {
+ MethodInfo minfo = methods[i]->get_method_info();
+ if (minfo.name != CACHED_STRING_NAME(dotctor)) {
+ p_list->push_back(methods[i]->get_method_info());
+ }
+ }
+
+ top = top->get_parent_class();
}
}
diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h
index e3bbb20dec..afc17f694a 100644
--- a/modules/mono/csharp_script.h
+++ b/modules/mono/csharp_script.h
@@ -293,7 +293,7 @@ public:
void get_property_list(List<PropertyInfo> *p_properties) const override;
Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override;
- /* TODO */ void get_method_list(List<MethodInfo> *p_list) const override {}
+ void get_method_list(List<MethodInfo> *p_list) const override;
bool has_method(const StringName &p_method) const override;
Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
index 73cabf8561..98c6881166 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
@@ -418,11 +418,15 @@ namespace GodotTools
AddToolSubmenuItem("C#", _menuPopup);
+ var buildSolutionShortcut = (Shortcut)EditorShortcut("mono/build_solution");
+
_toolBarBuildButton = new Button
{
Text = "Build",
- HintTooltip = "Build solution",
- FocusMode = Control.FocusModeEnum.None
+ HintTooltip = "Build Solution".TTR(),
+ FocusMode = Control.FocusModeEnum.None,
+ Shortcut = buildSolutionShortcut,
+ ShortcutInTooltip = true
};
_toolBarBuildButton.PressedSignal += BuildSolutionPressed;
AddControlToContainer(CustomControlContainer.Toolbar, _toolBarBuildButton);
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
index 793f84fd77..5c5ced8c29 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
@@ -13,6 +13,9 @@ namespace GodotTools.Internals
public static object EditorDef(string setting, object defaultValue, bool restartIfChanged = false) =>
internal_EditorDef(setting, defaultValue, restartIfChanged);
+ public static object EditorShortcut(string setting) =>
+ internal_EditorShortcut(setting);
+
[SuppressMessage("ReSharper", "InconsistentNaming")]
public static string TTR(this string text) => internal_TTR(text);
@@ -28,6 +31,9 @@ namespace GodotTools.Internals
private static extern object internal_EditorDef(string setting, object defaultValue, bool restartIfChanged);
[MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern object internal_EditorShortcut(string setting);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
private static extern string internal_TTR(string text);
}
}
diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp
index 67bcb34b1c..e03c5fd248 100644
--- a/modules/mono/editor/bindings_generator.cpp
+++ b/modules/mono/editor/bindings_generator.cpp
@@ -2610,7 +2610,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
Map<StringName, StringName> accessor_methods;
for (const PropertyInfo &property : property_list) {
- if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY) {
+ if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY || (property.type == Variant::NIL && property.usage & PROPERTY_USAGE_ARRAY)) {
continue;
}
diff --git a/modules/mono/editor/code_completion.cpp b/modules/mono/editor/code_completion.cpp
index d911f6461c..7433c865f5 100644
--- a/modules/mono/editor/code_completion.cpp
+++ b/modules/mono/editor/code_completion.cpp
@@ -123,8 +123,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr
// AutoLoads
OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
- for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
- const ProjectSettings::AutoloadInfo &info = E.value;
+ for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
+ const ProjectSettings::AutoloadInfo &info = E.value();
suggestions.push_back(quoted("/root/" + String(info.name)));
}
}
diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp
index 6692a6efec..9a61b63c12 100644
--- a/modules/mono/editor/editor_internal_calls.cpp
+++ b/modules/mono/editor/editor_internal_calls.cpp
@@ -306,6 +306,12 @@ MonoObject *godot_icall_Globals_EditorDef(MonoString *p_setting, MonoObject *p_d
return GDMonoMarshal::variant_to_mono_object(result);
}
+MonoObject *godot_icall_Globals_EditorShortcut(MonoString *p_setting) {
+ String setting = GDMonoMarshal::mono_string_to_godot(p_setting);
+ Ref<Shortcut> result = ED_GET_SHORTCUT(setting);
+ return GDMonoMarshal::variant_to_mono_object(result);
+}
+
MonoString *godot_icall_Globals_TTR(MonoString *p_text) {
String text = GDMonoMarshal::mono_string_to_godot(p_text);
return GDMonoMarshal::mono_string_from_godot(TTR(text));
@@ -380,6 +386,7 @@ void register_editor_internal_calls() {
GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorScale", godot_icall_Globals_EditorScale);
GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_GlobalDef", godot_icall_Globals_GlobalDef);
GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorDef", godot_icall_Globals_EditorDef);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorShortcut", godot_icall_Globals_EditorShortcut);
GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_TTR", godot_icall_Globals_TTR);
// Utils.OS
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
index 53c02feaa2..ef42374041 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
@@ -376,7 +376,7 @@ namespace Godot
/// <example>
/// <code>
/// GD.Print(GD.RandRange(0, 1)); // Prints 0 or 1
- /// GD.Print(GD.RangeRange(-10, 1000)); // Prints any number from -10 to 1000
+ /// GD.Print(GD.RandRange(-10, 1000)); // Prints any number from -10 to 1000
/// </code>
/// </example>
/// <returns>A random <see langword="int"/> number inside the given range.</returns>
diff --git a/modules/ogg/config.py b/modules/ogg/config.py
index d22f9454ed..5a417ba8dd 100644
--- a/modules/ogg/config.py
+++ b/modules/ogg/config.py
@@ -4,3 +4,14 @@ def can_build(env, platform):
def configure(env):
pass
+
+
+def get_doc_classes():
+ return [
+ "OGGPacketSequence",
+ "OGGPacketSequencePlayback",
+ ]
+
+
+def get_doc_path():
+ return "doc_classes"
diff --git a/modules/ogg/doc_classes/OGGPacketSequence.xml b/modules/ogg/doc_classes/OGGPacketSequence.xml
new file mode 100644
index 0000000000..9d3789cb07
--- /dev/null
+++ b/modules/ogg/doc_classes/OGGPacketSequence.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="OGGPacketSequence" inherits="Resource" version="4.0">
+ <brief_description>
+ A sequence of OGG packets.
+ </brief_description>
+ <description>
+ A sequence of OGG packets.
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="get_length" qualifiers="const">
+ <return type="float" />
+ <description>
+ The length of this stream, in seconds.
+ </description>
+ </method>
+ </methods>
+ <members>
+ <member name="granule_positions" type="Array" setter="set_packet_granule_positions" getter="get_packet_granule_positions" default="[]">
+ Contains the granule positions for each page in this packet sequence.
+ </member>
+ <member name="packet_data" type="Array" setter="set_packet_data" getter="get_packet_data" default="[]">
+ Contains the raw packets that make up this OGGPacketSequence.
+ </member>
+ <member name="sampling_rate" type="float" setter="set_sampling_rate" getter="get_sampling_rate" default="0.0">
+ Holds sample rate information about this sequence. Must be set by another class that actually understands the codec.
+ </member>
+ </members>
+ <constants>
+ </constants>
+</class>
diff --git a/modules/ogg/doc_classes/OGGPacketSequencePlayback.xml b/modules/ogg/doc_classes/OGGPacketSequencePlayback.xml
new file mode 100644
index 0000000000..49e32f0d6e
--- /dev/null
+++ b/modules/ogg/doc_classes/OGGPacketSequencePlayback.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="OGGPacketSequencePlayback" inherits="RefCounted" version="4.0">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/modules/ogg/ogg_packet_sequence.cpp b/modules/ogg/ogg_packet_sequence.cpp
new file mode 100644
index 0000000000..b7a3ad2876
--- /dev/null
+++ b/modules/ogg/ogg_packet_sequence.cpp
@@ -0,0 +1,220 @@
+/*************************************************************************/
+/* ogg_packet_sequence.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "ogg_packet_sequence.h"
+#include "core/variant/typed_array.h"
+
+void OGGPacketSequence::push_page(int64_t p_granule_pos, const Vector<PackedByteArray> &p_data) {
+ Vector<PackedByteArray> data_stored;
+ for (int i = 0; i < p_data.size(); i++) {
+ data_stored.push_back(p_data[i]);
+ }
+ page_granule_positions.push_back(p_granule_pos);
+ page_data.push_back(data_stored);
+ data_version++;
+}
+
+void OGGPacketSequence::set_packet_data(const Array &p_data) {
+ data_version++; // Update the data version so old playbacks know that they can't rely on us anymore.
+ page_data.clear();
+ for (int page_idx = 0; page_idx < p_data.size(); page_idx++) {
+ // Push a new page. We cleared the vector so this will be at index `page_idx`.
+ page_data.push_back(Vector<PackedByteArray>());
+ TypedArray<PackedByteArray> this_page_data = p_data[page_idx];
+ for (int packet = 0; packet < this_page_data.size(); packet++) {
+ page_data.write[page_idx].push_back(this_page_data[packet]);
+ }
+ }
+}
+
+Array OGGPacketSequence::get_packet_data() const {
+ Array ret;
+ for (const Vector<PackedByteArray> &page : page_data) {
+ Array page_variant;
+ for (const PackedByteArray &packet : page) {
+ page_variant.push_back(packet);
+ }
+ ret.push_back(page_variant);
+ }
+ return ret;
+}
+
+void OGGPacketSequence::set_packet_granule_positions(const Array &p_granule_positions) {
+ data_version++; // Update the data version so old playbacks know that they can't rely on us anymore.
+ page_granule_positions.clear();
+ for (int page_idx = 0; page_idx < p_granule_positions.size(); page_idx++) {
+ int64_t granule_pos = p_granule_positions[page_idx];
+ page_granule_positions.push_back(granule_pos);
+ }
+}
+
+Array OGGPacketSequence::get_packet_granule_positions() const {
+ Array ret;
+ for (int64_t granule_pos : page_granule_positions) {
+ ret.push_back(granule_pos);
+ }
+ return ret;
+}
+
+void OGGPacketSequence::set_sampling_rate(float p_sampling_rate) {
+ sampling_rate = p_sampling_rate;
+}
+
+float OGGPacketSequence::get_sampling_rate() const {
+ return sampling_rate;
+}
+
+int64_t OGGPacketSequence::get_final_granule_pos() const {
+ if (!page_granule_positions.is_empty()) {
+ return page_granule_positions[page_granule_positions.size() - 1];
+ }
+ return -1;
+}
+
+float OGGPacketSequence::get_length() const {
+ int64_t granule_pos = get_final_granule_pos();
+ if (granule_pos < 0) {
+ return 0;
+ }
+ return granule_pos / sampling_rate;
+}
+
+Ref<OGGPacketSequencePlayback> OGGPacketSequence::instance_playback() {
+ Ref<OGGPacketSequencePlayback> playback;
+ playback.instantiate();
+ playback->ogg_packet_sequence = Ref<OGGPacketSequence>(this);
+ playback->data_version = data_version;
+
+ return playback;
+}
+
+void OGGPacketSequence::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_packet_data", "packet_data"), &OGGPacketSequence::set_packet_data);
+ ClassDB::bind_method(D_METHOD("get_packet_data"), &OGGPacketSequence::get_packet_data);
+
+ ClassDB::bind_method(D_METHOD("set_packet_granule_positions", "granule_positions"), &OGGPacketSequence::set_packet_granule_positions);
+ ClassDB::bind_method(D_METHOD("get_packet_granule_positions"), &OGGPacketSequence::get_packet_granule_positions);
+
+ ClassDB::bind_method(D_METHOD("set_sampling_rate", "sampling_rate"), &OGGPacketSequence::set_sampling_rate);
+ ClassDB::bind_method(D_METHOD("get_sampling_rate"), &OGGPacketSequence::get_sampling_rate);
+
+ ClassDB::bind_method(D_METHOD("get_length"), &OGGPacketSequence::get_length);
+
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "packet_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_packet_data", "get_packet_data");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "granule_positions", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_packet_granule_positions", "get_packet_granule_positions");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "sampling_rate", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_sampling_rate", "get_sampling_rate");
+}
+
+bool OGGPacketSequencePlayback::next_ogg_packet(ogg_packet **p_packet) const {
+ ERR_FAIL_COND_V(data_version != ogg_packet_sequence->data_version, false);
+ ERR_FAIL_COND_V(ogg_packet_sequence->page_data.is_empty(), false);
+ ERR_FAIL_COND_V(ogg_packet_sequence->page_granule_positions.is_empty(), false);
+ // Move on to the next page if need be. This happens first to help simplify seek logic.
+ while (packet_cursor >= ogg_packet_sequence->page_data[page_cursor].size()) {
+ packet_cursor = 0;
+ page_cursor++;
+ if (page_cursor >= ogg_packet_sequence->page_data.size()) {
+ return false;
+ }
+ }
+
+ ERR_FAIL_COND_V(page_cursor >= ogg_packet_sequence->page_data.size(), false);
+
+ packet->b_o_s = page_cursor == 0 && packet_cursor == 0;
+ packet->e_o_s = page_cursor == ogg_packet_sequence->page_data.size() - 1 && packet_cursor == ogg_packet_sequence->page_data[page_cursor].size() - 1;
+ packet->granulepos = packet_cursor == ogg_packet_sequence->page_data[page_cursor].size() - 1 ? ogg_packet_sequence->page_granule_positions[page_cursor] : -1;
+ packet->packetno = packetno++;
+ packet->bytes = ogg_packet_sequence->page_data[page_cursor][packet_cursor].size();
+ packet->packet = (unsigned char *)(ogg_packet_sequence->page_data[page_cursor][packet_cursor].ptr());
+
+ *p_packet = packet;
+
+ packet_cursor++;
+
+ return true;
+}
+
+uint32_t OGGPacketSequencePlayback::seek_page_internal(int64_t granule, uint32_t after_page_inclusive, uint32_t before_page_inclusive) {
+ if (before_page_inclusive == after_page_inclusive) {
+ return before_page_inclusive;
+ }
+ uint32_t actual_middle_page = after_page_inclusive + (before_page_inclusive - after_page_inclusive) / 2;
+ // Complicating the bisection search algorithm, the middle page might not have a packet that ends on it,
+ // which means it might not have a correct granule position. Find a nearby page that does have a packet ending on it.
+ uint32_t bisection_page = -1;
+ for (uint32_t test_page = actual_middle_page; test_page <= before_page_inclusive; test_page++) {
+ if (ogg_packet_sequence->page_data[test_page].size() > 0) {
+ bisection_page = test_page;
+ break;
+ }
+ }
+ // Check if we have to go backwards.
+ if (bisection_page == (unsigned int)-1) {
+ for (uint32_t test_page = actual_middle_page; test_page >= after_page_inclusive; test_page--) {
+ if (ogg_packet_sequence->page_data[test_page].size() > 0) {
+ bisection_page = test_page;
+ break;
+ }
+ }
+ }
+ if (bisection_page == (unsigned int)-1) {
+ return -1;
+ }
+
+ int64_t bisection_granule_pos = ogg_packet_sequence->page_granule_positions[bisection_page];
+ if (granule > bisection_granule_pos) {
+ return seek_page_internal(granule, bisection_page + 1, before_page_inclusive);
+ } else {
+ return seek_page_internal(granule, after_page_inclusive, bisection_page);
+ }
+}
+
+bool OGGPacketSequencePlayback::seek_page(int64_t p_granule_pos) {
+ int correct_page = seek_page_internal(p_granule_pos, 0, ogg_packet_sequence->page_data.size() - 1);
+ if (correct_page == -1) {
+ return false;
+ }
+
+ packet_cursor = 0;
+ page_cursor = correct_page;
+
+ // Don't pretend subsequent packets are contiguous with previous ones.
+ packetno = 0;
+
+ return true;
+}
+
+OGGPacketSequencePlayback::OGGPacketSequencePlayback() {
+ packet = new ogg_packet();
+}
+
+OGGPacketSequencePlayback::~OGGPacketSequencePlayback() {
+ delete packet;
+}
diff --git a/modules/ogg/ogg_packet_sequence.h b/modules/ogg/ogg_packet_sequence.h
new file mode 100644
index 0000000000..b00ada06c1
--- /dev/null
+++ b/modules/ogg/ogg_packet_sequence.h
@@ -0,0 +1,128 @@
+/*************************************************************************/
+/* ogg_packet_sequence.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef OGG_PACKET_SEQUENCE_H
+#define OGG_PACKET_SEQUENCE_H
+
+#include "core/io/resource.h"
+#include "core/object/gdvirtual.gen.inc"
+#include "core/variant/native_ptr.h"
+#include "core/variant/typed_array.h"
+#include "core/variant/variant.h"
+#include "thirdparty/libogg/ogg/ogg.h"
+
+class OGGPacketSequencePlayback;
+
+class OGGPacketSequence : public Resource {
+ GDCLASS(OGGPacketSequence, Resource);
+
+ friend class OGGPacketSequencePlayback;
+
+ // List of pages, each of which is a list of packets on that page. The innermost PackedByteArrays contain complete ogg packets.
+ Vector<Vector<PackedByteArray>> page_data;
+
+ // List of the granule position for each page.
+ Vector<uint64_t> page_granule_positions;
+
+ // The page after the current last page. Similar semantics to an end() iterator.
+ int64_t end_page = 0;
+
+ uint64_t data_version = 0;
+
+ float sampling_rate = 0;
+ float length = 0;
+
+protected:
+ static void _bind_methods();
+
+public:
+ // Pushes information about all the pages that ended on this page.
+ // This should be called for each page, even for pages that no packets ended on.
+ void push_page(int64_t p_granule_pos, const Vector<PackedByteArray> &p_data);
+
+ void set_packet_data(const Array &p_data);
+ Array get_packet_data() const;
+
+ void set_packet_granule_positions(const Array &p_granule_positions);
+ Array get_packet_granule_positions() const;
+
+ // Sets a sampling rate associated with this object. OGGPacketSequence doesn't understand codecs,
+ // so this value is naively stored as a convenience.
+ void set_sampling_rate(float p_sampling_rate);
+
+ // Returns a sampling rate previously set by set_sampling_rate().
+ float get_sampling_rate() const;
+
+ // Returns a length previously set by set_length().
+ float get_length() const;
+
+ // Returns the granule position of the last page in this sequence.
+ int64_t get_final_granule_pos() const;
+
+ Ref<OGGPacketSequencePlayback> instance_playback();
+
+ OGGPacketSequence() {}
+ virtual ~OGGPacketSequence() {}
+};
+
+class OGGPacketSequencePlayback : public RefCounted {
+ GDCLASS(OGGPacketSequencePlayback, RefCounted);
+
+ friend class OGGPacketSequence;
+
+ Ref<OGGPacketSequence> ogg_packet_sequence;
+
+ mutable int64_t page_cursor = 0;
+ mutable int32_t packet_cursor = 0;
+
+ mutable ogg_packet *packet;
+
+ uint64_t data_version;
+
+ mutable int64_t packetno = 0;
+
+ // Recursive bisection search for the correct page.
+ uint32_t seek_page_internal(int64_t granule, uint32_t after_page_inclusive, uint32_t before_page_inclusive);
+
+public:
+ // Calling functions must not modify this packet.
+ // Returns true on success, false on error or if there is no next packet.
+ bool next_ogg_packet(ogg_packet **p_packet) const;
+
+ // Seeks to the page such that the previous page has a granule position less than or equal to this value,
+ // and the current page has a granule position greater than this value.
+ // Returns true on success, false on failure.
+ bool seek_page(int64_t p_granule_pos);
+
+ OGGPacketSequencePlayback();
+ virtual ~OGGPacketSequencePlayback();
+};
+
+#endif // OGG_PACKET_SEQUENCE_H
diff --git a/modules/ogg/register_types.cpp b/modules/ogg/register_types.cpp
index b23ea65378..3448e7063a 100644
--- a/modules/ogg/register_types.cpp
+++ b/modules/ogg/register_types.cpp
@@ -30,8 +30,11 @@
#include "register_types.h"
-// Dummy module as libogg is needed by other modules (vorbis, theora, opus, ...)
+#include "ogg_packet_sequence.h"
-void register_ogg_types() {}
+void register_ogg_types() {
+ GDREGISTER_CLASS(OGGPacketSequence);
+ GDREGISTER_CLASS(OGGPacketSequencePlayback);
+}
void unregister_ogg_types() {}
diff --git a/modules/raycast/SCsub b/modules/raycast/SCsub
index 6e7b3e7b8d..1fdc8fe1b3 100644
--- a/modules/raycast/SCsub
+++ b/modules/raycast/SCsub
@@ -55,6 +55,9 @@ if env["builtin_embree"]:
"kernels/bvh/bvh_builder_sah_mb.cpp",
"kernels/bvh/bvh_builder_twolevel.cpp",
"kernels/bvh/bvh_intersector1_bvh4.cpp",
+ "kernels/bvh/bvh_intersector_hybrid4_bvh4.cpp",
+ "kernels/bvh/bvh_intersector_stream_bvh4.cpp",
+ "kernels/bvh/bvh_intersector_stream_filters.cpp",
]
thirdparty_sources = [thirdparty_dir + file for file in embree_src]
diff --git a/modules/raycast/godot_update_embree.py b/modules/raycast/godot_update_embree.py
index 31a25a318f..e31d88b741 100644
--- a/modules/raycast/godot_update_embree.py
+++ b/modules/raycast/godot_update_embree.py
@@ -61,6 +61,11 @@ cpp_files = [
"kernels/bvh/bvh_builder_twolevel.cpp",
"kernels/bvh/bvh_intersector1.cpp",
"kernels/bvh/bvh_intersector1_bvh4.cpp",
+ "kernels/bvh/bvh_intersector_hybrid4_bvh4.cpp",
+ "kernels/bvh/bvh_intersector_stream_bvh4.cpp",
+ "kernels/bvh/bvh_intersector_stream_filters.cpp",
+ "kernels/bvh/bvh_intersector_hybrid.cpp",
+ "kernels/bvh/bvh_intersector_stream.cpp",
]
os.chdir("../../thirdparty")
@@ -117,7 +122,7 @@ with open(os.path.join(dest_dir, "kernels/config.h"), "w") as config_file:
/* #undef EMBREE_GEOMETRY_INSTANCE */
/* #undef EMBREE_GEOMETRY_GRID */
/* #undef EMBREE_GEOMETRY_POINT */
-/* #undef EMBREE_RAY_PACKETS */
+#define EMBREE_RAY_PACKETS
/* #undef EMBREE_COMPACT_POLYS */
#define EMBREE_CURVE_SELF_INTERSECTION_AVOIDANCE_FACTOR 2.0
@@ -249,3 +254,8 @@ with open(os.path.join(dest_dir, "include/embree3/rtcore_config.h"), "w") as con
os.chdir("..")
shutil.rmtree("embree-tmp")
+
+subprocess.run(["git", "restore", "embree/patches"])
+
+for patch in os.listdir("embree/patches"):
+ subprocess.run(["git", "apply", "embree/patches/" + patch])
diff --git a/modules/stb_vorbis/SCsub b/modules/stb_vorbis/SCsub
deleted file mode 100644
index 8fddb23dc8..0000000000
--- a/modules/stb_vorbis/SCsub
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/usr/bin/env python
-
-Import("env")
-Import("env_modules")
-
-env_stb_vorbis = env_modules.Clone()
-
-# Thirdparty source files
-
-thirdparty_obj = []
-
-thirdparty_sources = ["#thirdparty/misc/stb_vorbis.c"]
-
-env_thirdparty = env_stb_vorbis.Clone()
-env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
-env.modules_sources += thirdparty_obj
-
-# Godot source files
-
-module_obj = []
-
-env_stb_vorbis.add_source_files(module_obj, "*.cpp")
-env.modules_sources += module_obj
-
-# Needed to force rebuilding the module files when the thirdparty library is updated.
-env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
deleted file mode 100644
index 6554c6e274..0000000000
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
+++ /dev/null
@@ -1,278 +0,0 @@
-/*************************************************************************/
-/* audio_stream_ogg_vorbis.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "audio_stream_ogg_vorbis.h"
-
-#include "core/io/file_access.h"
-
-int AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) {
- ERR_FAIL_COND_V(!active, 0);
-
- int todo = p_frames;
-
- int start_buffer = 0;
-
- int frames_mixed_this_step = p_frames;
-
- while (todo && active) {
- float *buffer = (float *)p_buffer;
- if (start_buffer > 0) {
- buffer = (buffer + start_buffer * 2);
- }
- int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, buffer, todo * 2);
- if (vorbis_stream->channels == 1 && mixed > 0) {
- //mix mono to stereo
- for (int i = start_buffer; i < start_buffer + mixed; i++) {
- p_buffer[i].r = p_buffer[i].l;
- }
- }
- todo -= mixed;
- frames_mixed += mixed;
-
- if (todo) {
- //end of file!
- bool is_not_empty = mixed > 0 || stb_vorbis_stream_length_in_samples(ogg_stream) > 0;
- if (vorbis_stream->loop && is_not_empty) {
- //loop
- seek(vorbis_stream->loop_offset);
- loops++;
- // we still have buffer to fill, start from this element in the next iteration.
- start_buffer = p_frames - todo;
- } else {
- frames_mixed_this_step = p_frames - todo;
- for (int i = p_frames - todo; i < p_frames; i++) {
- p_buffer[i] = AudioFrame(0, 0);
- }
- active = false;
- todo = 0;
- }
- }
- }
- return frames_mixed_this_step;
-}
-
-float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() {
- return vorbis_stream->sample_rate;
-}
-
-void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) {
- active = true;
- seek(p_from_pos);
- loops = 0;
- _begin_resample();
-}
-
-void AudioStreamPlaybackOGGVorbis::stop() {
- active = false;
-}
-
-bool AudioStreamPlaybackOGGVorbis::is_playing() const {
- return active;
-}
-
-int AudioStreamPlaybackOGGVorbis::get_loop_count() const {
- return loops;
-}
-
-float AudioStreamPlaybackOGGVorbis::get_playback_position() const {
- return float(frames_mixed) / vorbis_stream->sample_rate;
-}
-
-void AudioStreamPlaybackOGGVorbis::seek(float p_time) {
- if (!active) {
- return;
- }
-
- if (p_time >= vorbis_stream->get_length()) {
- p_time = 0;
- }
- frames_mixed = uint32_t(vorbis_stream->sample_rate * p_time);
-
- stb_vorbis_seek(ogg_stream, frames_mixed);
-}
-
-AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() {
- if (ogg_alloc.alloc_buffer) {
- stb_vorbis_close(ogg_stream);
- memfree(ogg_alloc.alloc_buffer);
- }
-}
-
-Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() {
- Ref<AudioStreamPlaybackOGGVorbis> ovs;
-
- ERR_FAIL_COND_V_MSG(data == nullptr, ovs,
- "This AudioStreamOGGVorbis does not have an audio file assigned "
- "to it. AudioStreamOGGVorbis should not be created from the "
- "inspector or with `.new()`. Instead, load an audio file.");
-
- ovs.instantiate();
- ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this);
- ovs->ogg_alloc.alloc_buffer = (char *)memalloc(decode_mem_size);
- ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size;
- ovs->frames_mixed = 0;
- ovs->active = false;
- ovs->loops = 0;
- int error;
- ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc);
- if (!ovs->ogg_stream) {
- memfree(ovs->ogg_alloc.alloc_buffer);
- ovs->ogg_alloc.alloc_buffer = nullptr;
- ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>());
- }
-
- return ovs;
-}
-
-String AudioStreamOGGVorbis::get_stream_name() const {
- return ""; //return stream_name;
-}
-
-void AudioStreamOGGVorbis::clear_data() {
- if (data) {
- memfree(data);
- data = nullptr;
- data_len = 0;
- }
-}
-
-void AudioStreamOGGVorbis::set_data(const Vector<uint8_t> &p_data) {
- int src_data_len = p_data.size();
- uint32_t alloc_try = 1024;
- Vector<char> alloc_mem;
- char *w;
- stb_vorbis *ogg_stream = nullptr;
- stb_vorbis_alloc ogg_alloc;
-
- // Vorbis comments may be up to UINT32_MAX, but that's arguably pretty rare.
- // Let's go with 2^30 so we don't risk going out of bounds.
- const uint32_t MAX_TEST_MEM = 1 << 30;
-
- while (alloc_try < MAX_TEST_MEM) {
- alloc_mem.resize(alloc_try);
- w = alloc_mem.ptrw();
-
- ogg_alloc.alloc_buffer = w;
- ogg_alloc.alloc_buffer_length_in_bytes = alloc_try;
-
- const uint8_t *src_datar = p_data.ptr();
-
- int error;
- ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar, src_data_len, &error, &ogg_alloc);
-
- if (!ogg_stream && error == VORBIS_outofmem) {
- alloc_try *= 2;
- } else {
- ERR_FAIL_COND(alloc_try == MAX_TEST_MEM);
- ERR_FAIL_COND(ogg_stream == nullptr);
-
- stb_vorbis_info info = stb_vorbis_get_info(ogg_stream);
-
- channels = info.channels;
- sample_rate = info.sample_rate;
- decode_mem_size = alloc_try;
- //does this work? (it's less mem..)
- //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size;
-
- length = stb_vorbis_stream_length_in_seconds(ogg_stream);
- stb_vorbis_close(ogg_stream);
-
- // free any existing data
- clear_data();
-
- data = memalloc(src_data_len);
- memcpy(data, src_datar, src_data_len);
- data_len = src_data_len;
-
- break;
- }
- }
-
- ERR_FAIL_COND_MSG(alloc_try == MAX_TEST_MEM, vformat("Couldn't set vorbis data even with an alloc buffer of %d bytes, report bug.", MAX_TEST_MEM));
-}
-
-Vector<uint8_t> AudioStreamOGGVorbis::get_data() const {
- Vector<uint8_t> vdata;
-
- if (data_len && data) {
- vdata.resize(data_len);
- {
- uint8_t *w = vdata.ptrw();
- memcpy(w, data, data_len);
- }
- }
-
- return vdata;
-}
-
-void AudioStreamOGGVorbis::set_loop(bool p_enable) {
- loop = p_enable;
-}
-
-bool AudioStreamOGGVorbis::has_loop() const {
- return loop;
-}
-
-void AudioStreamOGGVorbis::set_loop_offset(float p_seconds) {
- loop_offset = p_seconds;
-}
-
-float AudioStreamOGGVorbis::get_loop_offset() const {
- return loop_offset;
-}
-
-float AudioStreamOGGVorbis::get_length() const {
- return length;
-}
-
-bool AudioStreamOGGVorbis::is_monophonic() const {
- return false;
-}
-
-void AudioStreamOGGVorbis::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data);
- ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data);
-
- ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop);
- ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop);
-
- ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOGGVorbis::set_loop_offset);
- ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOGGVorbis::get_loop_offset);
-
- ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "loop_offset"), "set_loop_offset", "get_loop_offset");
-}
-
-AudioStreamOGGVorbis::AudioStreamOGGVorbis() {}
-
-AudioStreamOGGVorbis::~AudioStreamOGGVorbis() {
- clear_data();
-}
diff --git a/modules/stb_vorbis/config.py b/modules/stb_vorbis/config.py
deleted file mode 100644
index 1eb0a8cf33..0000000000
--- a/modules/stb_vorbis/config.py
+++ /dev/null
@@ -1,16 +0,0 @@
-def can_build(env, platform):
- return True
-
-
-def configure(env):
- pass
-
-
-def get_doc_classes():
- return [
- "AudioStreamOGGVorbis",
- ]
-
-
-def get_doc_path():
- return "doc_classes"
diff --git a/modules/text_server_adv/script_iterator.cpp b/modules/text_server_adv/script_iterator.cpp
index f9bbd25a5f..d1e849def8 100644
--- a/modules/text_server_adv/script_iterator.cpp
+++ b/modules/text_server_adv/script_iterator.cpp
@@ -30,6 +30,8 @@
#include "script_iterator.h"
+// This implementation is derived from ICU: icu4c/source/extra/scrptrun/scrptrun.cpp
+
bool ScriptIterator::same_script(int32_t p_script_one, int32_t p_script_two) {
return p_script_one <= USCRIPT_INHERITED || p_script_two <= USCRIPT_INHERITED || p_script_one == p_script_two;
}
@@ -48,7 +50,8 @@ ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length
p_start = 0;
}
- ParenStackEntry paren_stack[128];
+ int paren_size = PAREN_STACK_DEPTH;
+ ParenStackEntry *paren_stack = (ParenStackEntry *)memalloc(paren_size * sizeof(ParenStackEntry));
int script_start;
int script_end = p_start;
@@ -64,13 +67,22 @@ ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length
UChar32 ch = str[script_end];
UScriptCode sc = uscript_getScript(ch, &err);
if (U_FAILURE(err)) {
+ memfree(paren_stack);
ERR_FAIL_MSG(u_errorName(err));
}
if (u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) != U_BPT_NONE) {
if (u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_OPEN) {
- paren_stack[++paren_sp].pair_index = ch;
+ // If it's an open character, push it onto the stack.
+ paren_sp++;
+ if (unlikely(paren_sp >= paren_size)) {
+ // If the stack is full, allocate more space to handle deeply nested parentheses. This is unlikely to happen with any real text.
+ paren_size += PAREN_STACK_DEPTH;
+ paren_stack = (ParenStackEntry *)memrealloc(paren_stack, paren_size * sizeof(ParenStackEntry));
+ }
+ paren_stack[paren_sp].pair_index = ch;
paren_stack[paren_sp].script_code = script_code;
} else if (paren_sp >= 0) {
+ // If it's a close character, find the matching open on the stack, and use that script code. Any non-matching open characters above it on the stack will be poped.
UChar32 paired_ch = u_getBidiPairedBracket(ch);
while (paren_sp >= 0 && paren_stack[paren_sp].pair_index != paired_ch) {
paren_sp -= 1;
@@ -87,11 +99,13 @@ ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length
if (same_script(script_code, sc)) {
if (script_code <= USCRIPT_INHERITED && sc > USCRIPT_INHERITED) {
script_code = sc;
+ // Now that we have a final script code, fix any open characters we pushed before we knew the script code.
while (start_sp < paren_sp) {
paren_stack[++start_sp].script_code = script_code;
}
}
if ((u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE) && paren_sp >= 0) {
+ // If this character is a close paired character pop the matching open character from the stack.
paren_sp -= 1;
if (start_sp >= 0) {
start_sp -= 1;
@@ -109,4 +123,6 @@ ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length
script_ranges.push_back(rng);
} while (script_end < p_length);
+
+ memfree(paren_stack);
}
diff --git a/modules/text_server_adv/script_iterator.h b/modules/text_server_adv/script_iterator.h
index 896a0e5c15..5efd40f7c4 100644
--- a/modules/text_server_adv/script_iterator.h
+++ b/modules/text_server_adv/script_iterator.h
@@ -43,6 +43,8 @@
#include <hb.h>
class ScriptIterator {
+ static const int PAREN_STACK_DEPTH = 128;
+
public:
struct ScriptRange {
int start = 0;
diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp
index 19e94adf68..22706f9b6a 100644
--- a/modules/text_server_adv/text_server_adv.cpp
+++ b/modules/text_server_adv/text_server_adv.cpp
@@ -30,6 +30,7 @@
#include "text_server_adv.h"
+#include "core/error/error_macros.h"
#include "core/string/print_string.h"
#include "core/string/translation.h"
@@ -1225,7 +1226,7 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontDataAdvanced
int error = 0;
if (!library) {
error = FT_Init_FreeType(&library);
- ERR_FAIL_COND_V_MSG(error != 0, false, TTR("FreeType: Error initializing library:") + " '" + String(FT_Error_String(error)) + "'.");
+ ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
}
memset(&fd->stream, 0, sizeof(FT_StreamRec));
@@ -1243,13 +1244,7 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontDataAdvanced
if (error) {
FT_Done_Face(fd->face);
fd->face = nullptr;
- ERR_FAIL_V_MSG(false, TTR("FreeType: Error loading font:") + " '" + String(FT_Error_String(error)) + "'.");
- }
- fd->hb_handle = hb_ft_font_create(fd->face, nullptr);
- if (fd->hb_handle == nullptr) {
- FT_Done_Face(fd->face);
- fd->face = nullptr;
- ERR_FAIL_V_MSG(false, TTR("HarfBuzz: Error creating FreeType font object."));
+ ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'.");
}
if (p_font_data->msdf) {
@@ -1278,6 +1273,8 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontDataAdvanced
FT_Set_Pixel_Sizes(fd->face, 0, fd->size.x * fd->oversampling);
}
+ fd->hb_handle = hb_ft_font_create(fd->face, nullptr);
+
fd->ascent = (fd->face->size->metrics.ascender / 64.0) / fd->oversampling * fd->scale;
fd->descent = (-fd->face->size->metrics.descender / 64.0) / fd->oversampling * fd->scale;
fd->underline_position = (-FT_MulFix(fd->face->underline_position, fd->face->size->metrics.y_scale) / 64.0) / fd->oversampling * fd->scale;
@@ -1592,14 +1589,11 @@ _FORCE_INLINE_ bool TextServerAdvanced::_ensure_cache_for_size(FontDataAdvanced
FT_Done_MM_Var(library, amaster);
}
#else
- ERR_FAIL_V_MSG(false, TTR("FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
+ ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
#endif
} else {
// Init bitmap font.
fd->hb_handle = hb_bmp_font_create(fd, nullptr);
- if (!fd->hb_handle) {
- ERR_FAIL_V_MSG(false, TTR("HarfBuzz: Error creating bitmap font object."));
- }
}
p_font_data->cache[p_size] = fd;
return true;
diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp
index e4e6797f92..8a1bd93c65 100644
--- a/modules/text_server_fb/text_server_fb.cpp
+++ b/modules/text_server_fb/text_server_fb.cpp
@@ -30,6 +30,7 @@
#include "text_server_fb.h"
+#include "core/error/error_macros.h"
#include "core/string/print_string.h"
#ifdef MODULE_MSDFGEN_ENABLED
@@ -686,7 +687,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontDataFallback
int error = 0;
if (!library) {
error = FT_Init_FreeType(&library);
- ERR_FAIL_COND_V_MSG(error != 0, false, TTR("FreeType: Error initializing library:") + " '" + String(FT_Error_String(error)) + "'.");
+ ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
}
memset(&fd->stream, 0, sizeof(FT_StreamRec));
@@ -704,7 +705,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontDataFallback
if (error) {
FT_Done_Face(fd->face);
fd->face = nullptr;
- ERR_FAIL_V_MSG(false, TTR("FreeType: Error loading font:") + " '" + String(FT_Error_String(error)) + "'.");
+ ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "'.");
}
if (p_font_data->msdf) {
@@ -784,7 +785,7 @@ _FORCE_INLINE_ bool TextServerFallback::_ensure_cache_for_size(FontDataFallback
FT_Done_MM_Var(library, amaster);
}
#else
- ERR_FAIL_V_MSG(false, TTR("FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
+ ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
#endif
}
p_font_data->cache[p_size] = fd;
diff --git a/modules/vhacd/register_types.cpp b/modules/vhacd/register_types.cpp
index 2b48e94604..54240e66fc 100644
--- a/modules/vhacd/register_types.cpp
+++ b/modules/vhacd/register_types.cpp
@@ -32,48 +32,55 @@
#include "scene/resources/mesh.h"
#include "thirdparty/vhacd/public/VHACD.h"
-static Vector<Vector<Face3>> convex_decompose(const Vector<Face3> &p_faces, int p_max_convex_hulls = -1) {
- Vector<real_t> vertices;
- vertices.resize(p_faces.size() * 9);
- Vector<uint32_t> indices;
- indices.resize(p_faces.size() * 3);
-
- for (int i = 0; i < p_faces.size(); i++) {
- for (int j = 0; j < 3; j++) {
- vertices.write[i * 9 + j * 3 + 0] = p_faces[i].vertex[j].x;
- vertices.write[i * 9 + j * 3 + 1] = p_faces[i].vertex[j].y;
- vertices.write[i * 9 + j * 3 + 2] = p_faces[i].vertex[j].z;
- indices.write[i * 3 + j] = i * 3 + j;
- }
- }
-
+static Vector<Vector<Vector3>> convex_decompose(const real_t *p_vertices, int p_vertex_count, const uint32_t *p_triangles, int p_triangle_count, const Mesh::ConvexDecompositionSettings &p_settings, Vector<Vector<uint32_t>> *r_convex_indices) {
VHACD::IVHACD::Parameters params;
- if (p_max_convex_hulls > 0) {
- params.m_maxConvexHulls = p_max_convex_hulls;
- }
+ params.m_concavity = p_settings.max_concavity;
+ params.m_alpha = p_settings.symmetry_planes_clipping_bias;
+ params.m_beta = p_settings.revolution_axes_clipping_bias;
+ params.m_minVolumePerCH = p_settings.min_volume_per_convex_hull;
+ params.m_resolution = p_settings.resolution;
+ params.m_maxNumVerticesPerCH = p_settings.max_num_vertices_per_convex_hull;
+ params.m_planeDownsampling = p_settings.plane_downsampling;
+ params.m_convexhullDownsampling = p_settings.convexhull_downsampling;
+ params.m_pca = p_settings.normalize_mesh;
+ params.m_mode = p_settings.mode;
+ params.m_convexhullApproximation = p_settings.convexhull_approximation;
+ params.m_oclAcceleration = true;
+ params.m_maxConvexHulls = p_settings.max_convex_hulls;
+ params.m_projectHullVertices = p_settings.project_hull_vertices;
VHACD::IVHACD *decomposer = VHACD::CreateVHACD();
- decomposer->Compute(vertices.ptr(), vertices.size() / 3, indices.ptr(), indices.size() / 3, params);
+ decomposer->Compute(p_vertices, p_vertex_count, p_triangles, p_triangle_count, params);
int hull_count = decomposer->GetNConvexHulls();
- Vector<Vector<Face3>> ret;
+ Vector<Vector<Vector3>> ret;
+ ret.resize(hull_count);
+
+ if (r_convex_indices) {
+ r_convex_indices->resize(hull_count);
+ }
for (int i = 0; i < hull_count; i++) {
- Vector<Face3> triangles;
VHACD::IVHACD::ConvexHull hull;
decomposer->GetConvexHull(i, hull);
- triangles.resize(hull.m_nTriangles);
- for (uint32_t j = 0; j < hull.m_nTriangles; j++) {
- Face3 f;
+
+ Vector<Vector3> &points = ret.write[i];
+ points.resize(hull.m_nPoints);
+
+ Vector3 *w = points.ptrw();
+ for (uint32_t j = 0; j < hull.m_nPoints; ++j) {
for (int k = 0; k < 3; k++) {
- for (int l = 0; l < 3; l++) {
- f.vertex[k][l] = hull.m_points[hull.m_triangles[j * 3 + k] * 3 + l];
- }
+ w[j][k] = hull.m_points[j * 3 + k];
}
- triangles.write[j] = f;
}
- ret.push_back(triangles);
+
+ if (r_convex_indices) {
+ Vector<uint32_t> &indices = r_convex_indices->write[i];
+ indices.resize(hull.m_nTriangles * 3);
+
+ memcpy(indices.ptrw(), hull.m_triangles, hull.m_nTriangles * 3 * sizeof(uint32_t));
+ }
}
decomposer->Clean();
@@ -83,9 +90,9 @@ static Vector<Vector<Face3>> convex_decompose(const Vector<Face3> &p_faces, int
}
void register_vhacd_types() {
- Mesh::convex_composition_function = convex_decompose;
+ Mesh::convex_decomposition_function = convex_decompose;
}
void unregister_vhacd_types() {
- Mesh::convex_composition_function = nullptr;
+ Mesh::convex_decomposition_function = nullptr;
}
diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
index b574576856..2c6313c80a 100644
--- a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
+++ b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
@@ -131,7 +131,7 @@
The [code]inputs[/code] array contains the values of the input ports.
[code]outputs[/code] is an array whose indices should be set to the respective outputs.
The [code]start_mode[/code] is usually [constant START_MODE_BEGIN_SEQUENCE], unless you have used the [code]STEP_*[/code] constants.
- [code]working_mem[/code] is an array which can be used to persist information between runs of the custom node.
+ [code]working_mem[/code] is an array which can be used to persist information between runs of the custom node. The size needs to be predefined using [method _get_working_memory_size].
When returning, you can mask the returned value with one of the [code]STEP_*[/code] constants.
</description>
</method>
diff --git a/modules/visual_script/register_types.cpp b/modules/visual_script/register_types.cpp
index 7fb9707fce..890861cf82 100644
--- a/modules/visual_script/register_types.cpp
+++ b/modules/visual_script/register_types.cpp
@@ -117,7 +117,7 @@ void register_visual_script_types() {
GDREGISTER_CLASS(VisualScriptCustomNodes);
ClassDB::set_current_api(ClassDB::API_CORE);
vs_custom_nodes_singleton = memnew(VisualScriptCustomNodes);
- Engine::get_singleton()->add_singleton(Engine::Singleton("VisualScriptEditor", VisualScriptCustomNodes::get_singleton()));
+ Engine::get_singleton()->add_singleton(Engine::Singleton("VisualScriptCustomNodes", VisualScriptCustomNodes::get_singleton()));
VisualScriptEditor::register_editor();
#endif
diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp
index 6ba5ad4fd6..205918a5f0 100644
--- a/modules/visual_script/visual_script_func_nodes.cpp
+++ b/modules/visual_script/visual_script_func_nodes.cpp
@@ -1010,7 +1010,7 @@ PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const
if (index != StringName()) {
detail_prop_name += "." + String(index);
}
- PropertyInfo pinfo = PropertyInfo(E.type, detail_prop_name, PROPERTY_HINT_TYPE_STRING, E.hint_string);
+ PropertyInfo pinfo = PropertyInfo(E.type, detail_prop_name, E.hint, E.hint_string);
_adjust_input_index(pinfo);
return pinfo;
}
diff --git a/modules/vorbis/SCsub b/modules/vorbis/SCsub
index bc31fff066..322314487f 100644
--- a/modules/vorbis/SCsub
+++ b/modules/vorbis/SCsub
@@ -3,9 +3,6 @@
Import("env")
Import("env_modules")
-# Only kept to build the thirdparty library used by the theora and webm
-# modules. We now use stb_vorbis for AudioStreamOGGVorbis.
-
env_vorbis = env_modules.Clone()
# Thirdparty source files
diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp
new file mode 100644
index 0000000000..e4a80c339f
--- /dev/null
+++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp
@@ -0,0 +1,435 @@
+/*************************************************************************/
+/* audio_stream_ogg_vorbis.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "audio_stream_ogg_vorbis.h"
+
+#include "core/io/file_access.h"
+#include "core/variant/typed_array.h"
+#include "thirdparty/libogg/ogg/ogg.h"
+
+int AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) {
+ ERR_FAIL_COND_V(!ready, 0);
+ ERR_FAIL_COND_V(!active, 0);
+
+ int todo = p_frames;
+
+ int start_buffer = 0;
+
+ int frames_mixed_this_step = p_frames;
+
+ while (todo && active) {
+ AudioFrame *buffer = p_buffer;
+ if (start_buffer > 0) {
+ buffer = buffer + start_buffer;
+ }
+ int mixed = _mix_frames_vorbis(buffer, todo);
+ if (mixed < 0) {
+ return 0;
+ }
+ todo -= mixed;
+ frames_mixed += mixed;
+ start_buffer += mixed;
+ if (!have_packets_left) {
+ //end of file!
+ bool is_not_empty = mixed > 0 || vorbis_stream->get_length() > 0;
+ if (vorbis_stream->loop && is_not_empty) {
+ //loop
+
+ seek(vorbis_stream->loop_offset);
+ loops++;
+ // we still have buffer to fill, start from this element in the next iteration.
+ start_buffer = p_frames - todo;
+ } else {
+ frames_mixed_this_step = p_frames - todo;
+ for (int i = p_frames - todo; i < p_frames; i++) {
+ p_buffer[i] = AudioFrame(0, 0);
+ }
+ active = false;
+ todo = 0;
+ }
+ }
+ }
+ return frames_mixed_this_step;
+}
+
+int AudioStreamPlaybackOGGVorbis::_mix_frames_vorbis(AudioFrame *p_buffer, int p_frames) {
+ ERR_FAIL_COND_V(!ready, 0);
+ if (!have_samples_left) {
+ ogg_packet *packet = nullptr;
+ int err;
+
+ if (!vorbis_data_playback->next_ogg_packet(&packet)) {
+ have_packets_left = false;
+ WARN_PRINT("ran out of packets in stream");
+ return -1;
+ }
+
+ ERR_FAIL_COND_V_MSG((err = vorbis_synthesis(&block, packet)), 0, "Error during vorbis synthesis " + itos(err));
+ ERR_FAIL_COND_V_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), 0, "Error during vorbis block processing " + itos(err));
+
+ have_packets_left = !packet->e_o_s;
+ }
+
+ float **pcm; // Accessed with pcm[channel_idx][sample_idx].
+
+ int frames = vorbis_synthesis_pcmout(&dsp_state, &pcm);
+ if (frames > p_frames) {
+ frames = p_frames;
+ have_samples_left = true;
+ } else {
+ have_samples_left = false;
+ }
+
+ if (info.channels > 1) {
+ for (int frame = 0; frame < frames; frame++) {
+ p_buffer[frame].l = pcm[0][frame];
+ p_buffer[frame].r = pcm[0][frame];
+ }
+ } else {
+ for (int frame = 0; frame < frames; frame++) {
+ p_buffer[frame].l = pcm[0][frame];
+ p_buffer[frame].r = pcm[0][frame];
+ }
+ }
+ vorbis_synthesis_read(&dsp_state, frames);
+ return frames;
+}
+
+float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() {
+ return vorbis_data->get_sampling_rate();
+}
+
+bool AudioStreamPlaybackOGGVorbis::_alloc_vorbis() {
+ vorbis_info_init(&info);
+ info_is_allocated = true;
+ vorbis_comment_init(&comment);
+ comment_is_allocated = true;
+
+ ERR_FAIL_COND_V(vorbis_data.is_null(), false);
+ vorbis_data_playback = vorbis_data->instance_playback();
+
+ ogg_packet *packet;
+ int err;
+
+ for (int i = 0; i < 3; i++) {
+ if (!vorbis_data_playback->next_ogg_packet(&packet)) {
+ WARN_PRINT("Not enough packets to parse header");
+ return false;
+ }
+
+ err = vorbis_synthesis_headerin(&info, &comment, packet);
+ ERR_FAIL_COND_V_MSG(err != 0, false, "Error parsing header");
+ }
+
+ err = vorbis_synthesis_init(&dsp_state, &info);
+ ERR_FAIL_COND_V_MSG(err != 0, false, "Error initializing dsp state");
+ dsp_state_is_allocated = true;
+
+ err = vorbis_block_init(&dsp_state, &block);
+ ERR_FAIL_COND_V_MSG(err != 0, false, "Error initializing block");
+ block_is_allocated = true;
+
+ ready = true;
+
+ return true;
+}
+
+void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) {
+ ERR_FAIL_COND(!ready);
+ active = true;
+ seek(p_from_pos);
+ loops = 0;
+ _begin_resample();
+}
+
+void AudioStreamPlaybackOGGVorbis::stop() {
+ active = false;
+}
+
+bool AudioStreamPlaybackOGGVorbis::is_playing() const {
+ return active;
+}
+
+int AudioStreamPlaybackOGGVorbis::get_loop_count() const {
+ return loops;
+}
+
+float AudioStreamPlaybackOGGVorbis::get_playback_position() const {
+ return float(frames_mixed) / vorbis_data->get_sampling_rate();
+}
+
+void AudioStreamPlaybackOGGVorbis::seek(float p_time) {
+ ERR_FAIL_COND(!ready);
+ ERR_FAIL_COND(vorbis_stream.is_null());
+ if (!active) {
+ return;
+ }
+
+ vorbis_synthesis_restart(&dsp_state);
+
+ if (p_time >= vorbis_stream->get_length()) {
+ p_time = 0;
+ }
+ frames_mixed = uint32_t(vorbis_data->get_sampling_rate() * p_time);
+
+ const int64_t desired_sample = p_time * get_stream_sampling_rate();
+
+ if (!vorbis_data_playback->seek_page(desired_sample)) {
+ WARN_PRINT("seek failed");
+ return;
+ }
+
+ ogg_packet *packet;
+ if (!vorbis_data_playback->next_ogg_packet(&packet)) {
+ WARN_PRINT_ONCE("seeking beyond limits");
+ return;
+ }
+
+ // The granule position of the page we're seeking through.
+ int64_t granule_pos = 0;
+
+ int headers_remaining = 0;
+ int samples_in_page = 0;
+ int err;
+ while (true) {
+ if (vorbis_synthesis_idheader(packet)) {
+ headers_remaining = 3;
+ }
+ if (!headers_remaining) {
+ ERR_FAIL_COND_MSG((err = vorbis_synthesis(&block, packet)), "Error during vorbis synthesis " + itos(err));
+ ERR_FAIL_COND_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), "Error during vorbis block processing " + itos(err));
+
+ int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr);
+ ERR_FAIL_COND_MSG((err = vorbis_synthesis_read(&dsp_state, samples_out)), "Error during vorbis read updating " + itos(err));
+
+ samples_in_page += samples_out;
+
+ } else {
+ headers_remaining--;
+ }
+ if (packet->granulepos != -1 && headers_remaining == 0) {
+ // This indicates the end of the page.
+ granule_pos = packet->granulepos;
+ break;
+ }
+ if (packet->e_o_s) {
+ break;
+ }
+ if (!vorbis_data_playback->next_ogg_packet(&packet)) {
+ // We should get an e_o_s flag before this happens.
+ WARN_PRINT("Vorbis file ended without warning.");
+ break;
+ }
+ }
+
+ int64_t samples_to_burn = samples_in_page - (granule_pos - desired_sample);
+
+ if (samples_to_burn > samples_in_page) {
+ WARN_PRINT("Burning more samples than we have in this page. Check seek algorithm.");
+ } else if (samples_to_burn < 0) {
+ WARN_PRINT("Burning negative samples doesn't make sense. Check seek algorithm.");
+ }
+
+ // Seek again, this time we'll burn a specific number of samples instead of all of them.
+ if (!vorbis_data_playback->seek_page(desired_sample)) {
+ WARN_PRINT("seek failed");
+ return;
+ }
+
+ if (!vorbis_data_playback->next_ogg_packet(&packet)) {
+ WARN_PRINT_ONCE("seeking beyond limits");
+ return;
+ }
+ vorbis_synthesis_restart(&dsp_state);
+
+ while (true) {
+ if (vorbis_synthesis_idheader(packet)) {
+ headers_remaining = 3;
+ }
+ if (!headers_remaining) {
+ ERR_FAIL_COND_MSG((err = vorbis_synthesis(&block, packet)), "Error during vorbis synthesis " + itos(err));
+ ERR_FAIL_COND_MSG((err = vorbis_synthesis_blockin(&dsp_state, &block)), "Error during vorbis block processing " + itos(err));
+
+ int samples_out = vorbis_synthesis_pcmout(&dsp_state, nullptr);
+ int read_samples = samples_to_burn > samples_out ? samples_out : samples_to_burn;
+ ERR_FAIL_COND_MSG((err = vorbis_synthesis_read(&dsp_state, samples_out)), "Error during vorbis read updating " + itos(err));
+ samples_to_burn -= read_samples;
+
+ if (samples_to_burn <= 0) {
+ break;
+ }
+ } else {
+ headers_remaining--;
+ }
+ if (packet->granulepos != -1 && headers_remaining == 0) {
+ // This indicates the end of the page.
+ break;
+ }
+ if (packet->e_o_s) {
+ break;
+ }
+ if (!vorbis_data_playback->next_ogg_packet(&packet)) {
+ // We should get an e_o_s flag before this happens.
+ WARN_PRINT("Vorbis file ended without warning.");
+ break;
+ }
+ }
+}
+
+AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() {
+ if (block_is_allocated) {
+ vorbis_block_clear(&block);
+ }
+ if (dsp_state_is_allocated) {
+ vorbis_dsp_clear(&dsp_state);
+ }
+ if (comment_is_allocated) {
+ vorbis_comment_clear(&comment);
+ }
+ if (info_is_allocated) {
+ vorbis_info_clear(&info);
+ }
+}
+
+Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() {
+ Ref<AudioStreamPlaybackOGGVorbis> ovs;
+
+ ERR_FAIL_COND_V(packet_sequence.is_null(), nullptr);
+
+ ovs.instantiate();
+ ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this);
+ ovs->vorbis_data = packet_sequence;
+ ovs->frames_mixed = 0;
+ ovs->active = false;
+ ovs->loops = 0;
+ if (ovs->_alloc_vorbis()) {
+ return ovs;
+ }
+ // Failed to allocate data structures.
+ return nullptr;
+}
+
+String AudioStreamOGGVorbis::get_stream_name() const {
+ return ""; //return stream_name;
+}
+
+void AudioStreamOGGVorbis::maybe_update_info() {
+ ERR_FAIL_COND(packet_sequence.is_null());
+
+ vorbis_info info;
+ vorbis_comment comment;
+ int err;
+
+ vorbis_info_init(&info);
+ vorbis_comment_init(&comment);
+
+ int packet_count = 0;
+ Ref<OGGPacketSequencePlayback> packet_sequence_playback = packet_sequence->instance_playback();
+
+ for (int i = 0; i < 3; i++) {
+ ogg_packet *packet;
+ if (!packet_sequence_playback->next_ogg_packet(&packet)) {
+ WARN_PRINT("Failed to get header packet");
+ break;
+ }
+ if (i == 0) {
+ packet->b_o_s = 1;
+ }
+
+ if (i == 0) {
+ ERR_FAIL_COND(!vorbis_synthesis_idheader(packet));
+ }
+
+ err = vorbis_synthesis_headerin(&info, &comment, packet);
+ ERR_FAIL_COND_MSG(err != 0, "Error parsing header packet " + itos(i) + ": " + itos(err));
+
+ packet_count++;
+ }
+
+ packet_sequence->set_sampling_rate(info.rate);
+
+ vorbis_comment_clear(&comment);
+ vorbis_info_clear(&info);
+}
+
+void AudioStreamOGGVorbis::set_packet_sequence(Ref<OGGPacketSequence> p_packet_sequence) {
+ packet_sequence = p_packet_sequence;
+ if (packet_sequence.is_valid()) {
+ maybe_update_info();
+ }
+}
+
+Ref<OGGPacketSequence> AudioStreamOGGVorbis::get_packet_sequence() const {
+ return packet_sequence;
+}
+
+void AudioStreamOGGVorbis::set_loop(bool p_enable) {
+ loop = p_enable;
+}
+
+bool AudioStreamOGGVorbis::has_loop() const {
+ return loop;
+}
+
+void AudioStreamOGGVorbis::set_loop_offset(float p_seconds) {
+ loop_offset = p_seconds;
+}
+
+float AudioStreamOGGVorbis::get_loop_offset() const {
+ return loop_offset;
+}
+
+float AudioStreamOGGVorbis::get_length() const {
+ ERR_FAIL_COND_V(packet_sequence.is_null(), 0);
+ return packet_sequence->get_length();
+}
+
+bool AudioStreamOGGVorbis::is_monophonic() const {
+ return false;
+}
+
+void AudioStreamOGGVorbis::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_packet_sequence", "packet_sequence"), &AudioStreamOGGVorbis::set_packet_sequence);
+ ClassDB::bind_method(D_METHOD("get_packet_sequence"), &AudioStreamOGGVorbis::get_packet_sequence);
+
+ ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop);
+ ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop);
+
+ ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamOGGVorbis::set_loop_offset);
+ ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamOGGVorbis::get_loop_offset);
+
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "packet_sequence", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_packet_sequence", "get_packet_sequence");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "loop_offset"), "set_loop_offset", "get_loop_offset");
+}
+
+AudioStreamOGGVorbis::AudioStreamOGGVorbis() {}
+
+AudioStreamOGGVorbis::~AudioStreamOGGVorbis() {}
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h
index 1311c4ce7a..59a1318a6b 100644
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.h
+++ b/modules/vorbis/audio_stream_ogg_vorbis.h
@@ -28,29 +28,49 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef AUDIO_STREAM_STB_VORBIS_H
-#define AUDIO_STREAM_STB_VORBIS_H
+#ifndef AUDIO_STREAM_LIBVORBIS_H
+#define AUDIO_STREAM_LIBVORBIS_H
-#include "core/io/resource_loader.h"
+#include "core/variant/variant.h"
+#include "modules/ogg/ogg_packet_sequence.h"
#include "servers/audio/audio_stream.h"
-
-#include "thirdparty/misc/stb_vorbis.h"
+#include "thirdparty/libvorbis/vorbis/codec.h"
class AudioStreamOGGVorbis;
class AudioStreamPlaybackOGGVorbis : public AudioStreamPlaybackResampled {
GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled);
- stb_vorbis *ogg_stream = nullptr;
- stb_vorbis_alloc ogg_alloc;
uint32_t frames_mixed = 0;
bool active = false;
int loops = 0;
+ vorbis_info info;
+ vorbis_comment comment;
+ vorbis_dsp_state dsp_state;
+ vorbis_block block;
+
+ bool info_is_allocated = false;
+ bool comment_is_allocated = false;
+ bool dsp_state_is_allocated = false;
+ bool block_is_allocated = false;
+
+ bool ready = false;
+
+ bool have_samples_left = false;
+ bool have_packets_left = false;
+
friend class AudioStreamOGGVorbis;
+ Ref<OGGPacketSequence> vorbis_data;
+ Ref<OGGPacketSequencePlayback> vorbis_data_playback;
Ref<AudioStreamOGGVorbis> vorbis_stream;
+ int _mix_frames_vorbis(AudioFrame *p_buffer, int p_frames);
+
+ // Allocates vorbis data structures. Returns true upon success, false on failure.
+ bool _alloc_vorbis();
+
protected:
virtual int _mix_internal(AudioFrame *p_buffer, int p_frames) override;
virtual float get_stream_sampling_rate() override;
@@ -72,20 +92,20 @@ public:
class AudioStreamOGGVorbis : public AudioStream {
GDCLASS(AudioStreamOGGVorbis, AudioStream);
OBJ_SAVE_TYPE(AudioStream); // Saves derived classes with common type so they can be interchanged.
- RES_BASE_EXTENSION("oggstr");
+ RES_BASE_EXTENSION("oggvorbisstr");
friend class AudioStreamPlaybackOGGVorbis;
- void *data = nullptr;
- uint32_t data_len = 0;
-
- int decode_mem_size = 0;
- float sample_rate = 1.0;
int channels = 1;
float length = 0.0;
bool loop = false;
float loop_offset = 0.0;
- void clear_data();
+
+ // Performs a seek to the beginning of the stream, should not be called during playback!
+ // Also causes allocation and deallocation.
+ void maybe_update_info();
+
+ Ref<OGGPacketSequence> packet_sequence;
protected:
static void _bind_methods();
@@ -100,8 +120,8 @@ public:
virtual Ref<AudioStreamPlayback> instance_playback() override;
virtual String get_stream_name() const override;
- void set_data(const Vector<uint8_t> &p_data);
- Vector<uint8_t> get_data() const;
+ void set_packet_sequence(Ref<OGGPacketSequence> p_packet_sequence);
+ Ref<OGGPacketSequence> get_packet_sequence() const;
virtual float get_length() const override; //if supported, otherwise return 0
@@ -111,4 +131,4 @@ public:
virtual ~AudioStreamOGGVorbis();
};
-#endif
+#endif // AUDIO_STREAM_LIBVORBIS_H
diff --git a/modules/vorbis/config.py b/modules/vorbis/config.py
index 8a384e3066..978eccb29f 100644
--- a/modules/vorbis/config.py
+++ b/modules/vorbis/config.py
@@ -4,3 +4,14 @@ def can_build(env, platform):
def configure(env):
pass
+
+
+def get_doc_classes():
+ return [
+ "AudioStreamOGGVorbis",
+ "AudioStreamPlaybackOGGVorbis",
+ ]
+
+
+def get_doc_path():
+ return "doc_classes"
diff --git a/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml b/modules/vorbis/doc_classes/AudioStreamOGGVorbis.xml
index 94fdff5d43..a680a2f999 100644
--- a/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml
+++ b/modules/vorbis/doc_classes/AudioStreamOGGVorbis.xml
@@ -1,25 +1,23 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="AudioStreamOGGVorbis" inherits="AudioStream" version="4.0">
<brief_description>
- OGG Vorbis audio stream driver.
</brief_description>
<description>
- OGG Vorbis audio stream driver.
</description>
<tutorials>
</tutorials>
<methods>
</methods>
<members>
- <member name="data" type="PackedByteArray" setter="set_data" getter="get_data" default="PackedByteArray()">
- Contains the audio data in bytes.
- </member>
<member name="loop" type="bool" setter="set_loop" getter="has_loop" default="false">
If [code]true[/code], the stream will automatically loop when it reaches the end.
</member>
<member name="loop_offset" type="float" setter="set_loop_offset" getter="get_loop_offset" default="0.0">
Time in seconds at which the stream starts after being looped.
</member>
+ <member name="packet_sequence" type="OGGPacketSequence" setter="set_packet_sequence" getter="get_packet_sequence">
+ Contains the raw OGG data for this stream.
+ </member>
</members>
<constants>
</constants>
diff --git a/modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml b/modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml
new file mode 100644
index 0000000000..3120f2a9e6
--- /dev/null
+++ b/modules/vorbis/doc_classes/AudioStreamPlaybackOGGVorbis.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioStreamPlaybackOGGVorbis" inherits="AudioStreamPlaybackResampled" version="4.0">
+ <brief_description>
+ </brief_description>
+ <description>
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/modules/vorbis/register_types.cpp b/modules/vorbis/register_types.cpp
index d3e77ea629..de3f41afdd 100644
--- a/modules/vorbis/register_types.cpp
+++ b/modules/vorbis/register_types.cpp
@@ -30,8 +30,19 @@
#include "register_types.h"
-// Dummy module as libvorbis is needed by other modules (theora ...)
+#include "audio_stream_ogg_vorbis.h"
+#include "resource_importer_ogg_vorbis.h"
-void register_vorbis_types() {}
+void register_vorbis_types() {
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ Ref<ResourceImporterOGGVorbis> ogg_vorbis_importer;
+ ogg_vorbis_importer.instantiate();
+ ResourceFormatImporter::get_singleton()->add_importer(ogg_vorbis_importer);
+ }
+#endif
+ GDREGISTER_CLASS(AudioStreamOGGVorbis);
+ GDREGISTER_CLASS(AudioStreamPlaybackOGGVorbis);
+}
void unregister_vorbis_types() {}
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp b/modules/vorbis/resource_importer_ogg_vorbis.cpp
index 85de698efd..33ee6cf359 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
+++ b/modules/vorbis/resource_importer_ogg_vorbis.cpp
@@ -30,16 +30,19 @@
#include "resource_importer_ogg_vorbis.h"
+#include "audio_stream_ogg_vorbis.h"
#include "core/io/file_access.h"
#include "core/io/resource_saver.h"
#include "scene/resources/texture.h"
+#include "thirdparty/libogg/ogg/ogg.h"
+#include "thirdparty/libvorbis/vorbis/codec.h"
String ResourceImporterOGGVorbis::get_importer_name() const {
- return "ogg_vorbis";
+ return "oggvorbisstr";
}
String ResourceImporterOGGVorbis::get_visible_name() const {
- return "OGGVorbis";
+ return "oggvorbisstr";
}
void ResourceImporterOGGVorbis::get_recognized_extensions(List<String> *p_extensions) const {
@@ -47,7 +50,7 @@ void ResourceImporterOGGVorbis::get_recognized_extensions(List<String> *p_extens
}
String ResourceImporterOGGVorbis::get_save_extension() const {
- return "oggstr";
+ return "oggvorbisstr";
}
String ResourceImporterOGGVorbis::get_resource_type() const {
@@ -81,23 +84,106 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin
uint64_t len = f->get_length();
- Vector<uint8_t> data;
- data.resize(len);
- uint8_t *w = data.ptrw();
+ Vector<uint8_t> file_data;
+ file_data.resize(len);
+ uint8_t *w = file_data.ptrw();
f->get_buffer(w, len);
memdelete(f);
- Ref<AudioStreamOGGVorbis> ogg_stream;
- ogg_stream.instantiate();
-
- ogg_stream->set_data(data);
- ERR_FAIL_COND_V(!ogg_stream->get_data().size(), ERR_FILE_CORRUPT);
- ogg_stream->set_loop(loop);
- ogg_stream->set_loop_offset(loop_offset);
-
- return ResourceSaver::save(p_save_path + ".oggstr", ogg_stream);
+ Ref<AudioStreamOGGVorbis> ogg_vorbis_stream;
+ ogg_vorbis_stream.instantiate();
+
+ Ref<OGGPacketSequence> ogg_packet_sequence;
+ ogg_packet_sequence.instantiate();
+
+ ogg_stream_state stream_state;
+ ogg_sync_state sync_state;
+ ogg_page page;
+ ogg_packet packet;
+ bool initialized_stream = false;
+
+ ogg_sync_init(&sync_state);
+ int err;
+ size_t cursor = 0;
+ size_t packet_count = 0;
+ bool done = false;
+ while (!done) {
+ ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Error::ERR_INVALID_DATA, "Ogg sync error " + itos(err));
+ while (ogg_sync_pageout(&sync_state, &page) != 1) {
+ if (cursor >= len) {
+ done = true;
+ break;
+ }
+ ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Error::ERR_INVALID_DATA, "Ogg sync error " + itos(err));
+ char *sync_buf = ogg_sync_buffer(&sync_state, OGG_SYNC_BUFFER_SIZE);
+ ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Error::ERR_INVALID_DATA, "Ogg sync error " + itos(err));
+ ERR_FAIL_COND_V(cursor > len, Error::ERR_INVALID_DATA);
+ size_t copy_size = len - cursor;
+ if (copy_size > OGG_SYNC_BUFFER_SIZE) {
+ copy_size = OGG_SYNC_BUFFER_SIZE;
+ }
+ memcpy(sync_buf, &file_data[cursor], copy_size);
+ ogg_sync_wrote(&sync_state, copy_size);
+ cursor += copy_size;
+ ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Error::ERR_INVALID_DATA, "Ogg sync error " + itos(err));
+ }
+ if (done) {
+ break;
+ }
+ ERR_FAIL_COND_V_MSG((err = ogg_sync_check(&sync_state)), Error::ERR_INVALID_DATA, "Ogg sync error " + itos(err));
+
+ // Have a page now.
+ if (!initialized_stream) {
+ ogg_stream_init(&stream_state, ogg_page_serialno(&page));
+ ERR_FAIL_COND_V_MSG((err = ogg_stream_check(&stream_state)), Error::ERR_INVALID_DATA, "Ogg stream error " + itos(err));
+ initialized_stream = true;
+ }
+ ERR_FAIL_COND_V_MSG((err = ogg_stream_check(&stream_state)), Error::ERR_INVALID_DATA, "Ogg stream error " + itos(err));
+ ogg_stream_pagein(&stream_state, &page);
+ ERR_FAIL_COND_V_MSG((err = ogg_stream_check(&stream_state)), Error::ERR_INVALID_DATA, "Ogg stream error " + itos(err));
+ int desync_iters = 0;
+
+ Vector<Vector<uint8_t>> packet_data;
+ int64_t granule_pos = 0;
+
+ while (true) {
+ err = ogg_stream_packetout(&stream_state, &packet);
+ if (err == -1) {
+ // According to the docs this is usually recoverable, but don't sit here spinning forever.
+ desync_iters++;
+ ERR_FAIL_COND_V_MSG(desync_iters > 100, Error::ERR_INVALID_DATA, "Packet sync issue during ogg import");
+ continue;
+ } else if (err == 0) {
+ // Not enough data to fully reconstruct a packet. Go on to the next page.
+ break;
+ }
+ if (packet_count == 0 && vorbis_synthesis_idheader(&packet) == 0) {
+ WARN_PRINT("Found a non-vorbis-header packet in a header position");
+ // Clearly this logical stream is not a vorbis stream, so destroy it and try again with the next page.
+ ogg_stream_destroy(&stream_state);
+ initialized_stream = false;
+ break;
+ }
+ granule_pos = packet.granulepos;
+
+ PackedByteArray data;
+ data.resize(packet.bytes);
+ memcpy(data.ptrw(), packet.packet, packet.bytes);
+ packet_data.push_back(data);
+ packet_count++;
+ }
+ if (initialized_stream) {
+ ogg_packet_sequence->push_page(granule_pos, packet_data);
+ }
+ }
+
+ ogg_vorbis_stream->set_packet_sequence(ogg_packet_sequence);
+ ogg_vorbis_stream->set_loop(loop);
+ ogg_vorbis_stream->set_loop_offset(loop_offset);
+
+ return ResourceSaver::save(p_save_path + ".oggvorbisstr", ogg_vorbis_stream);
}
ResourceImporterOGGVorbis::ResourceImporterOGGVorbis() {
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.h b/modules/vorbis/resource_importer_ogg_vorbis.h
index 60fe3381fb..acdc1a3d38 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.h
+++ b/modules/vorbis/resource_importer_ogg_vorbis.h
@@ -28,25 +28,29 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef RESOURCEIMPORTEROGGVORBIS_H
-#define RESOURCEIMPORTEROGGVORBIS_H
+#ifndef RESOURCE_IMPORTER_OGG_VORBIS_H
+#define RESOURCE_IMPORTER_OGG_VORBIS_H
-#include "audio_stream_ogg_vorbis.h"
#include "core/io/resource_importer.h"
class ResourceImporterOGGVorbis : public ResourceImporter {
GDCLASS(ResourceImporterOGGVorbis, ResourceImporter);
+ enum {
+ OGG_SYNC_BUFFER_SIZE = 8192,
+ };
+
+private:
+ // virtual int get_samples_in_packet(Vector<uint8_t> p_packet) = 0;
+
public:
- virtual String get_importer_name() const override;
- virtual String get_visible_name() const override;
virtual void get_recognized_extensions(List<String> *p_extensions) const override;
virtual String get_save_extension() const override;
virtual String get_resource_type() const override;
-
+ virtual String get_importer_name() const override;
+ virtual String get_visible_name() const override;
virtual int get_preset_count() const override;
virtual String get_preset_name(int p_idx) const override;
-
virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const override;
virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const override;
@@ -55,4 +59,4 @@ public:
ResourceImporterOGGVorbis();
};
-#endif // RESOURCEIMPORTEROGGVORBIS_H
+#endif // RESOURCE_IMPORTER_OGG_VORBIS_H
diff --git a/modules/websocket/editor_debugger_server_websocket.cpp b/modules/websocket/editor_debugger_server_websocket.cpp
index 2e61cbfc08..d248433d82 100644
--- a/modules/websocket/editor_debugger_server_websocket.cpp
+++ b/modules/websocket/editor_debugger_server_websocket.cpp
@@ -48,11 +48,19 @@ void EditorDebuggerServerWebSocket::poll() {
server->poll();
}
-Error EditorDebuggerServerWebSocket::start() {
- int remote_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
+Error EditorDebuggerServerWebSocket::start(const String &p_uri) {
+ int bind_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
+ String bind_host = EditorSettings::get_singleton()->get("network/debug/remote_host");
+ if (!p_uri.is_empty() && p_uri != "ws://") {
+ String scheme, path;
+ Error err = p_uri.parse_url(scheme, bind_host, bind_port, path);
+ ERR_FAIL_COND_V(err != OK, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!bind_host.is_valid_ip_address() && bind_host != "*", ERR_INVALID_PARAMETER);
+ }
+ server->set_bind_ip(bind_host);
Vector<String> compatible_protocols;
compatible_protocols.push_back("binary"); // compatibility with EMSCRIPTEN TCP-to-WebSocket layer.
- return server->listen(remote_port, compatible_protocols);
+ return server->listen(bind_port, compatible_protocols);
}
void EditorDebuggerServerWebSocket::stop() {
diff --git a/modules/websocket/editor_debugger_server_websocket.h b/modules/websocket/editor_debugger_server_websocket.h
index d9543bb647..14ab0109b2 100644
--- a/modules/websocket/editor_debugger_server_websocket.h
+++ b/modules/websocket/editor_debugger_server_websocket.h
@@ -48,7 +48,7 @@ public:
void _peer_disconnected(int p_peer, bool p_was_clean);
void poll() override;
- Error start() override;
+ Error start(const String &p_uri) override;
void stop() override;
bool is_active() const override;
bool is_connection_available() const override;
diff --git a/platform/android/README.md b/platform/android/README.md
new file mode 100644
index 0000000000..343e588553
--- /dev/null
+++ b/platform/android/README.md
@@ -0,0 +1,14 @@
+# Android platform port
+
+This folder contains the Java and C++ (JNI) code for the Android platform port,
+using [Gradle](https://gradle.org/) as a build system.
+
+## Artwork license
+
+[`logo.png`](logo.png) and [`run_icon.png`](run_icon.png) are licensed under
+[Creative Commons Attribution 3.0 Unported](https://developer.android.com/distribute/marketing-tools/brand-guidelines#android_robot)
+per the Android logo usage guidelines:
+
+> The Android robot is reproduced or modified from work created and shared by
+> Google and used according to terms described in the Creative Commons 3.0
+> Attribution License.
diff --git a/platform/android/export/export_plugin.cpp b/platform/android/export/export_plugin.cpp
index e5422a28af..60ba1c558a 100644
--- a/platform/android/export/export_plugin.cpp
+++ b/platform/android/export/export_plugin.cpp
@@ -221,6 +221,9 @@ static const LauncherIcon launcher_adaptive_icon_backgrounds[icon_densities_coun
static const int EXPORT_FORMAT_APK = 0;
static const int EXPORT_FORMAT_AAB = 1;
+static const char *APK_ASSETS_DIRECTORY = "res://android/build/assets";
+static const char *AAB_ASSETS_DIRECTORY = "res://android/build/assetPacks/installTime/src/main/assets";
+
void EditorExportPlatformAndroid::_check_for_changes_poll_thread(void *ud) {
EditorExportPlatformAndroid *ea = (EditorExportPlatformAndroid *)ud;
@@ -426,6 +429,11 @@ String EditorExportPlatformAndroid::get_package_name(const String &p_package) co
return pname;
}
+String EditorExportPlatformAndroid::get_assets_directory(const Ref<EditorExportPreset> &p_preset) const {
+ int export_format = int(p_preset->get("custom_template/export_format"));
+ return export_format == EXPORT_FORMAT_AAB ? AAB_ASSETS_DIRECTORY : APK_ASSETS_DIRECTORY;
+}
+
bool EditorExportPlatformAndroid::is_package_name_valid(const String &p_package, String *r_error) const {
String pname = p_package;
@@ -2335,11 +2343,21 @@ Error EditorExportPlatformAndroid::sign_apk(const Ref<EditorExportPreset> &p_pre
void EditorExportPlatformAndroid::_clear_assets_directory() {
DirAccessRef da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- if (da_res->dir_exists("res://android/build/assets")) {
- print_verbose("Clearing assets directory..");
- DirAccessRef da_assets = DirAccess::open("res://android/build/assets");
+
+ // Clear the APK assets directory
+ if (da_res->dir_exists(APK_ASSETS_DIRECTORY)) {
+ print_verbose("Clearing APK assets directory..");
+ DirAccessRef da_assets = DirAccess::open(APK_ASSETS_DIRECTORY);
+ da_assets->erase_contents_recursive();
+ da_res->remove(APK_ASSETS_DIRECTORY);
+ }
+
+ // Clear the AAB assets directory
+ if (da_res->dir_exists(AAB_ASSETS_DIRECTORY)) {
+ print_verbose("Clearing AAB assets directory..");
+ DirAccessRef da_assets = DirAccess::open(AAB_ASSETS_DIRECTORY);
da_assets->erase_contents_recursive();
- da_res->remove("res://android/build/assets");
+ da_res->remove(AAB_ASSETS_DIRECTORY);
}
}
@@ -2459,6 +2477,7 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP
return ERR_UNCONFIGURED;
}
}
+ const String assets_directory = get_assets_directory(p_preset);
String sdk_path = EDITOR_GET("export/android/android_sdk_path");
ERR_FAIL_COND_V_MSG(sdk_path.is_empty(), ERR_UNCONFIGURED, "Android SDK path must be configured in Editor Settings at 'export/android/android_sdk_path'.");
print_verbose("Android sdk path: " + sdk_path);
@@ -2480,6 +2499,7 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP
if (!apk_expansion) {
print_verbose("Exporting project files..");
CustomExportData user_data;
+ user_data.assets_directory = assets_directory;
user_data.debug = p_debug;
err = export_project_files(p_preset, rename_and_store_file_in_gradle_project, &user_data, copy_gradle_so);
if (err != OK) {
@@ -2501,7 +2521,7 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP
}
}
print_verbose("Storing command line flags..");
- store_file_at_path("res://android/build/assets/_cl_", command_line_flags);
+ store_file_at_path(assets_directory + "/_cl_", command_line_flags);
print_verbose("Updating ANDROID_HOME environment to " + sdk_path);
OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required
diff --git a/platform/android/export/export_plugin.h b/platform/android/export/export_plugin.h
index b061ee4e04..d33f616f11 100644
--- a/platform/android/export/export_plugin.h
+++ b/platform/android/export/export_plugin.h
@@ -87,11 +87,6 @@ class EditorExportPlatformAndroid : public EditorExportPlatform {
EditorProgress *ep = nullptr;
};
- struct CustomExportData {
- bool debug;
- Vector<String> libs;
- };
-
Vector<PluginConfigAndroid> plugins;
String last_plugin_names;
uint64_t last_custom_build_time = 0;
@@ -109,6 +104,8 @@ class EditorExportPlatformAndroid : public EditorExportPlatform {
String get_package_name(const String &p_package) const;
+ String get_assets_directory(const Ref<EditorExportPreset> &p_preset) const;
+
bool is_package_name_valid(const String &p_package, String *r_error = nullptr) const;
static bool _should_compress_asset(const String &p_path, const Vector<uint8_t> &p_data);
diff --git a/platform/android/export/gradle_export_util.cpp b/platform/android/export/gradle_export_util.cpp
index 6fbdf73cd0..851bd0ac52 100644
--- a/platform/android/export/gradle_export_util.cpp
+++ b/platform/android/export/gradle_export_util.cpp
@@ -121,7 +121,8 @@ Error store_string_at_path(const String &p_path, const String &p_data) {
// It's functionality mirrors that of the method save_apk_file.
// This method will be called ONLY when custom build is enabled.
Error rename_and_store_file_in_gradle_project(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key) {
- String dst_path = p_path.replace_first("res://", "res://android/build/assets/");
+ CustomExportData *export_data = (CustomExportData *)p_userdata;
+ String dst_path = p_path.replace_first("res://", export_data->assets_directory + "/");
print_verbose("Saving project files from " + p_path + " into " + dst_path);
Error err = store_file_at_path(dst_path, p_data);
return err;
diff --git a/platform/android/export/gradle_export_util.h b/platform/android/export/gradle_export_util.h
index 8a93c25d79..744022f1f9 100644
--- a/platform/android/export/gradle_export_util.h
+++ b/platform/android/export/gradle_export_util.h
@@ -44,6 +44,12 @@ const String godot_project_name_xml_string = R"(<?xml version="1.0" encoding="ut
</resources>
)";
+struct CustomExportData {
+ String assets_directory;
+ bool debug;
+ Vector<String> libs;
+};
+
int _get_android_orientation_value(DisplayServer::ScreenOrientation screen_orientation);
String _get_android_orientation_label(DisplayServer::ScreenOrientation screen_orientation);
diff --git a/platform/android/java/app/assetPacks/installTime/build.gradle b/platform/android/java/app/assetPacks/installTime/build.gradle
new file mode 100644
index 0000000000..b06faac374
--- /dev/null
+++ b/platform/android/java/app/assetPacks/installTime/build.gradle
@@ -0,0 +1,8 @@
+apply plugin: 'com.android.asset-pack'
+
+assetPack {
+ packName = "installTime" // Directory name for the asset pack
+ dynamicDelivery {
+ deliveryType = "install-time" // Delivery mode
+ }
+}
diff --git a/platform/android/java/app/build.gradle b/platform/android/java/app/build.gradle
index 9640887399..a391a3ca9a 100644
--- a/platform/android/java/app/build.gradle
+++ b/platform/android/java/app/build.gradle
@@ -72,6 +72,8 @@ android {
targetCompatibility versions.javaVersion
}
+ assetPacks = [":assetPacks:installTime"]
+
defaultConfig {
// The default ignore pattern for the 'assets' directory includes hidden files and directories which are used by Godot projects.
aaptOptions {
diff --git a/platform/android/java/app/settings.gradle b/platform/android/java/app/settings.gradle
index 33b863c7bf..e38d7b2ba6 100644
--- a/platform/android/java/app/settings.gradle
+++ b/platform/android/java/app/settings.gradle
@@ -1,2 +1,2 @@
-// Empty settings.gradle file to denote this directory as being the root project
-// of the Godot custom build.
+// This is the root directory of the Godot custom build.
+include ':assetPacks:installTime'
diff --git a/platform/android/java/settings.gradle b/platform/android/java/settings.gradle
index 524031d93f..584b626900 100644
--- a/platform/android/java/settings.gradle
+++ b/platform/android/java/settings.gradle
@@ -4,3 +4,6 @@ rootProject.name = "Godot"
include ':app'
include ':lib'
include ':nativeSrcsConfigs'
+
+include ':assetPacks:installTime'
+project(':assetPacks:installTime').projectDir = file("app/assetPacks/installTime")
diff --git a/platform/android/logo.png b/platform/android/logo.png
index f44d360a25..9c8be93646 100644
--- a/platform/android/logo.png
+++ b/platform/android/logo.png
Binary files differ
diff --git a/platform/javascript/README.md b/platform/javascript/README.md
new file mode 100644
index 0000000000..f181bea9e0
--- /dev/null
+++ b/platform/javascript/README.md
@@ -0,0 +1,15 @@
+# HTML5 platform port
+
+This folder contains the C++ and JavaScript code for the HTML5/WebAssembly platform port,
+compiled using [Emscripten](https://emscripten.org/).
+
+It also contains a ESLint linting setup (see [`package.json`](package.json)).
+
+See also [`misc/dist/html`](/misc/dist/html) folder for files used by this platform
+such as the HTML5 shell.
+
+## Artwork license
+
+[`logo.png`](logo.png) and [`run_icon.png`](run_icon.png) are licensed under
+[Creative Commons Attribution 3.0 Unported](https://www.w3.org/html/logo/faq.html#how-licenced)
+per the HTML5 logo usage guidelines.
diff --git a/platform/javascript/api/javascript_tools_editor_plugin.cpp b/platform/javascript/api/javascript_tools_editor_plugin.cpp
index c50195639c..45a2cd595a 100644
--- a/platform/javascript/api/javascript_tools_editor_plugin.cpp
+++ b/platform/javascript/api/javascript_tools_editor_plugin.cpp
@@ -71,8 +71,8 @@ void JavaScriptToolsEditorPlugin::_download_zip(Variant p_v) {
// Replace characters not allowed (or risky) in Windows file names with safe characters.
// In the project name, all invalid characters become an empty string so that a name
// like "Platformer 2: Godette's Revenge" becomes "platformer_2-_godette-s_revenge".
- const String project_name_safe =
- GLOBAL_GET("application/config/name").to_lower().replace(" ", "_");
+ const String project_name = GLOBAL_GET("application/config/name");
+ const String project_name_safe = project_name.to_lower().replace(" ", "_");
const String datetime_safe =
Time::get_singleton()->get_datetime_string_from_system(false, true).replace(" ", "_");
const String output_name = OS::get_singleton()->get_safe_dir_name(vformat("%s_%s.zip"));
diff --git a/platform/javascript/audio_driver_javascript.cpp b/platform/javascript/audio_driver_javascript.cpp
index 478e848675..420cb2f2f7 100644
--- a/platform/javascript/audio_driver_javascript.cpp
+++ b/platform/javascript/audio_driver_javascript.cpp
@@ -108,7 +108,7 @@ Error AudioDriverJavaScript::init() {
mix_rate = GLOBAL_GET("audio/driver/mix_rate");
int latency = GLOBAL_GET("audio/driver/output_latency");
- channel_count = godot_audio_init(mix_rate, latency, &_state_change_callback, &_latency_update_callback);
+ channel_count = godot_audio_init(&mix_rate, latency, &_state_change_callback, &_latency_update_callback);
buffer_length = closest_power_of_2((latency * mix_rate / 1000));
#ifndef NO_THREADS
node = memnew(WorkletNode);
diff --git a/platform/javascript/display_server_javascript.cpp b/platform/javascript/display_server_javascript.cpp
index fda18a5c19..b43614eb99 100644
--- a/platform/javascript/display_server_javascript.cpp
+++ b/platform/javascript/display_server_javascript.cpp
@@ -158,6 +158,10 @@ EM_BOOL DisplayServerJavaScript::keydown_callback(int p_event_type, const Emscri
return false;
}
Input::get_singleton()->parse_input_event(ev);
+
+ // Make sure to flush all events so we can call restricted APIs inside the event.
+ Input::get_singleton()->flush_buffered_events();
+
return true;
}
@@ -165,6 +169,10 @@ EM_BOOL DisplayServerJavaScript::keypress_callback(int p_event_type, const Emscr
DisplayServerJavaScript *display = get_singleton();
display->deferred_key_event->set_unicode(p_event->charCode);
Input::get_singleton()->parse_input_event(display->deferred_key_event);
+
+ // Make sure to flush all events so we can call restricted APIs inside the event.
+ Input::get_singleton()->flush_buffered_events();
+
return true;
}
@@ -172,6 +180,10 @@ EM_BOOL DisplayServerJavaScript::keyup_callback(int p_event_type, const Emscript
Ref<InputEventKey> ev = setup_key_event(p_event);
ev->set_pressed(false);
Input::get_singleton()->parse_input_event(ev);
+
+ // Make sure to flush all events so we can call restricted APIs inside the event.
+ Input::get_singleton()->flush_buffered_events();
+
return ev->get_keycode() != KEY_UNKNOWN && ev->get_keycode() != (Key)0;
}
@@ -245,6 +257,10 @@ EM_BOOL DisplayServerJavaScript::mouse_button_callback(int p_event_type, const E
ev->set_button_mask(mask);
input->parse_input_event(ev);
+
+ // Make sure to flush all events so we can call restricted APIs inside the event.
+ Input::get_singleton()->flush_buffered_events();
+
// Prevent multi-click text selection and wheel-click scrolling anchor.
// Context menu is prevented through contextmenu event.
return true;
@@ -507,6 +523,10 @@ EM_BOOL DisplayServerJavaScript::touch_press_callback(int p_event_type, const Em
Input::get_singleton()->parse_input_event(ev);
}
+
+ // Make sure to flush all events so we can call restricted APIs inside the event.
+ Input::get_singleton()->flush_buffered_events();
+
// Resume audio context after input in case autoplay was denied.
return true;
}
@@ -1019,6 +1039,7 @@ bool DisplayServerJavaScript::can_any_window_draw() const {
}
void DisplayServerJavaScript::process_events() {
+ Input::get_singleton()->flush_buffered_events();
if (godot_js_display_gamepad_sample() == OK) {
process_joypads();
}
diff --git a/platform/javascript/godot_audio.h b/platform/javascript/godot_audio.h
index 54fc8fa3b5..de8f046bbd 100644
--- a/platform/javascript/godot_audio.h
+++ b/platform/javascript/godot_audio.h
@@ -38,7 +38,7 @@ extern "C" {
#include "stddef.h"
extern int godot_audio_is_available();
-extern int godot_audio_init(int p_mix_rate, int p_latency, void (*_state_cb)(int), void (*_latency_cb)(float));
+extern int godot_audio_init(int *p_mix_rate, int p_latency, void (*_state_cb)(int), void (*_latency_cb)(float));
extern void godot_audio_resume();
extern int godot_audio_capture_start();
diff --git a/platform/javascript/js/libs/audio.worklet.js b/platform/javascript/js/libs/audio.worklet.js
index 866f845139..df475ba52d 100644
--- a/platform/javascript/js/libs/audio.worklet.js
+++ b/platform/javascript/js/libs/audio.worklet.js
@@ -66,17 +66,17 @@ class RingBuffer {
const mw = this.buffer.length - this.wpos;
if (mw >= to_write) {
this.buffer.set(p_buffer, this.wpos);
+ this.wpos += to_write;
+ if (mw === to_write) {
+ this.wpos = 0;
+ }
} else {
- const high = p_buffer.subarray(0, to_write - mw);
- const low = p_buffer.subarray(to_write - mw);
+ const high = p_buffer.subarray(0, mw);
+ const low = p_buffer.subarray(mw);
this.buffer.set(high, this.wpos);
this.buffer.set(low);
+ this.wpos = low.length;
}
- let diff = to_write;
- if (this.wpos + diff >= this.buffer.length) {
- diff -= this.buffer.length;
- }
- this.wpos += diff;
Atomics.add(this.avail, 0, to_write);
Atomics.notify(this.avail, 0);
}
diff --git a/platform/javascript/js/libs/library_godot_audio.js b/platform/javascript/js/libs/library_godot_audio.js
index 45c3a3fe2e..c9dae1a7af 100644
--- a/platform/javascript/js/libs/library_godot_audio.js
+++ b/platform/javascript/js/libs/library_godot_audio.js
@@ -37,10 +37,14 @@ const GodotAudio = {
interval: 0,
init: function (mix_rate, latency, onstatechange, onlatencyupdate) {
- const ctx = new (window.AudioContext || window.webkitAudioContext)({
- sampleRate: mix_rate,
- // latencyHint: latency / 1000 // Do not specify, leave 'interactive' for good performance.
- });
+ const opts = {};
+ // If mix_rate is 0, let the browser choose.
+ if (mix_rate) {
+ opts['sampleRate'] = mix_rate;
+ }
+ // Do not specify, leave 'interactive' for good performance.
+ // opts['latencyHint'] = latency / 1000;
+ const ctx = new (window.AudioContext || window.webkitAudioContext)(opts);
GodotAudio.ctx = ctx;
ctx.onstatechange = function () {
let state = 0;
@@ -159,7 +163,10 @@ const GodotAudio = {
godot_audio_init: function (p_mix_rate, p_latency, p_state_change, p_latency_update) {
const statechange = GodotRuntime.get_func(p_state_change);
const latencyupdate = GodotRuntime.get_func(p_latency_update);
- return GodotAudio.init(p_mix_rate, p_latency, statechange, latencyupdate);
+ const mix_rate = GodotRuntime.getHeapValue(p_mix_rate, 'i32');
+ const channels = GodotAudio.init(mix_rate, p_latency, statechange, latencyupdate);
+ GodotRuntime.setHeapValue(p_mix_rate, GodotAudio.ctx.sampleRate, 'i32');
+ return channels;
},
godot_audio_resume__sig: 'v',
diff --git a/platform/linuxbsd/README.md b/platform/linuxbsd/README.md
new file mode 100644
index 0000000000..0d3fb37be5
--- /dev/null
+++ b/platform/linuxbsd/README.md
@@ -0,0 +1,11 @@
+# Linux/*BSD platform port
+
+This folder contains the C++ code for the Linux/*BSD platform port.
+
+## Artwork license
+
+[`logo.png`](logo.png) is derived from the [Linux logo](https://isc.tamu.edu/~lewing/linux/):
+
+> Permission to use and/or modify this image is granted provided you acknowledge me
+ <lewing@isc.tamu.edu> and [The GIMP](https://isc.tamu.edu/~lewing/gimp/)
+ if someone asks.
diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py
index 3e3ed469ed..8eb22c1c72 100644
--- a/platform/linuxbsd/detect.py
+++ b/platform/linuxbsd/detect.py
@@ -18,40 +18,42 @@ def can_build():
# Check the minimal dependencies
x11_error = os.system("pkg-config --version > /dev/null")
if x11_error:
+ print("Error: pkg-config not found. Aborting.")
return False
- x11_error = os.system("pkg-config x11 --modversion > /dev/null ")
+ x11_error = os.system("pkg-config x11 --modversion > /dev/null")
if x11_error:
+ print("Error: X11 libraries not found. Aborting.")
return False
- x11_error = os.system("pkg-config xcursor --modversion > /dev/null ")
+ x11_error = os.system("pkg-config xcursor --modversion > /dev/null")
if x11_error:
- print("xcursor not found.. x11 disabled.")
+ print("Error: Xcursor library not found. Aborting.")
return False
- x11_error = os.system("pkg-config xinerama --modversion > /dev/null ")
+ x11_error = os.system("pkg-config xinerama --modversion > /dev/null")
if x11_error:
- print("xinerama not found.. x11 disabled.")
+ print("Error: Xinerama library not found. Aborting.")
return False
- x11_error = os.system("pkg-config xext --modversion > /dev/null ")
+ x11_error = os.system("pkg-config xext --modversion > /dev/null")
if x11_error:
- print("xext not found.. x11 disabled.")
+ print("Error: Xext library not found. Aborting.")
return False
- x11_error = os.system("pkg-config xrandr --modversion > /dev/null ")
+ x11_error = os.system("pkg-config xrandr --modversion > /dev/null")
if x11_error:
- print("xrandr not found.. x11 disabled.")
+ print("Error: XrandR library not found. Aborting.")
return False
- x11_error = os.system("pkg-config xrender --modversion > /dev/null ")
+ x11_error = os.system("pkg-config xrender --modversion > /dev/null")
if x11_error:
- print("xrender not found.. x11 disabled.")
+ print("Error: XRender library not found. Aborting.")
return False
- x11_error = os.system("pkg-config xi --modversion > /dev/null ")
+ x11_error = os.system("pkg-config xi --modversion > /dev/null")
if x11_error:
- print("xi not found.. Aborting.")
+ print("Error: Xi library not found. Aborting.")
return False
return True
@@ -138,7 +140,7 @@ def configure(env):
# A convenience so you don't need to write use_lto too when using SCons
env["use_lto"] = True
else:
- print("Using LLD with GCC is not supported yet, try compiling with 'use_llvm=yes'.")
+ print("Using LLD with GCC is not supported yet. Try compiling with 'use_llvm=yes'.")
sys.exit(255)
if env["use_coverage"]:
@@ -201,11 +203,6 @@ def configure(env):
env.Append(CCFLAGS=["-pipe"])
env.Append(LINKFLAGS=["-pipe"])
- # -fpie and -no-pie is supported on GCC 6+ and Clang 4+, both below our
- # minimal requirements.
- env.Append(CCFLAGS=["-fpie"])
- env.Append(LINKFLAGS=["-no-pie"])
-
## Dependencies
env.ParseConfig("pkg-config x11 --cflags --libs")
@@ -334,36 +331,32 @@ def configure(env):
## Flags
if os.system("pkg-config --exists alsa") == 0: # 0 means found
- print("Enabling ALSA")
env["alsa"] = True
env.Append(CPPDEFINES=["ALSA_ENABLED", "ALSAMIDI_ENABLED"])
else:
- print("ALSA libraries not found, disabling driver")
+ print("Warning: ALSA libraries not found. Disabling the ALSA audio driver.")
if env["pulseaudio"]:
if os.system("pkg-config --exists libpulse") == 0: # 0 means found
- print("Enabling PulseAudio")
env.Append(CPPDEFINES=["PULSEAUDIO_ENABLED"])
env.ParseConfig("pkg-config --cflags libpulse")
else:
- print("PulseAudio development libraries not found, disabling driver")
+ print("Warning: PulseAudio development libraries not found. Disabling the PulseAudio audio driver.")
if env["dbus"]:
if os.system("pkg-config --exists dbus-1") == 0: # 0 means found
- print("Enabling D-Bus")
env.Append(CPPDEFINES=["DBUS_ENABLED"])
env.ParseConfig("pkg-config --cflags --libs dbus-1")
else:
- print("D-Bus development libraries not found, disabling dependent features")
+ print("Warning: D-Bus development libraries not found. Disabling screensaver prevention.")
if platform.system() == "Linux":
env.Append(CPPDEFINES=["JOYDEV_ENABLED"])
if env["udev"]:
if os.system("pkg-config --exists libudev") == 0: # 0 means found
- print("Enabling udev support")
env.Append(CPPDEFINES=["UDEV_ENABLED"])
else:
- print("libudev development libraries not found, disabling udev support")
+ print("Warning: libudev development libraries not found. Disabling controller hotplugging support.")
else:
env["udev"] = False # Linux specific
@@ -412,7 +405,7 @@ def configure(env):
gnu_ld_version = re.search("^GNU ld [^$]*(\d+\.\d+)$", linker_version_str, re.MULTILINE)
if not gnu_ld_version:
print(
- "Warning: Creating template binaries enabled for PCK embedding is currently only supported with GNU ld"
+ "Warning: Creating template binaries enabled for PCK embedding is currently only supported with GNU ld, not gold or LLD."
)
else:
if float(gnu_ld_version.group(1)) >= 2.30:
diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp
index cf51caa6d5..1723026849 100644
--- a/platform/windows/display_server_windows.cpp
+++ b/platform/windows/display_server_windows.cpp
@@ -80,7 +80,7 @@ String DisplayServerWindows::get_name() const {
}
void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) {
- if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN) {
+ if (windows.has(MAIN_WINDOW_ID) && (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN)) {
// Mouse is grabbed (captured or confined).
WindowData &wd = windows[MAIN_WINDOW_ID];
@@ -118,8 +118,10 @@ void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) {
void DisplayServerWindows::mouse_set_mode(MouseMode p_mode) {
_THREAD_SAFE_METHOD_
- if (mouse_mode == p_mode)
+ if (mouse_mode == p_mode) {
+ // Already in the same mode; do nothing.
return;
+ }
mouse_mode = p_mode;
@@ -134,7 +136,7 @@ void DisplayServerWindows::mouse_warp_to_position(const Point2i &p_to) {
_THREAD_SAFE_METHOD_
if (!windows.has(last_focused_window)) {
- return; //no window focused?
+ return; // No focused window?
}
if (mouse_mode == MOUSE_MODE_CAPTURED) {
@@ -154,7 +156,6 @@ Point2i DisplayServerWindows::mouse_get_position() const {
POINT p;
GetCursorPos(&p);
return Point2i(p.x, p.y);
- //return Point2(old_x, old_y);
}
MouseButton DisplayServerWindows::mouse_get_button_state() const {
@@ -165,12 +166,12 @@ void DisplayServerWindows::clipboard_set(const String &p_text) {
_THREAD_SAFE_METHOD_
if (!windows.has(last_focused_window)) {
- return; //no window focused?
+ return; // No focused window?
}
- // Convert LF line endings to CRLF in clipboard content
- // Otherwise, line endings won't be visible when pasted in other software
- String text = p_text.replace("\r\n", "\n").replace("\n", "\r\n"); // avoid \r\r\n
+ // Convert LF line endings to CRLF in clipboard content.
+ // Otherwise, line endings won't be visible when pasted in other software.
+ String text = p_text.replace("\r\n", "\n").replace("\n", "\r\n"); // Avoid \r\r\n.
if (!OpenClipboard(windows[last_focused_window].hWnd)) {
ERR_FAIL_MSG("Unable to open clipboard.");
@@ -187,7 +188,7 @@ void DisplayServerWindows::clipboard_set(const String &p_text) {
SetClipboardData(CF_UNICODETEXT, mem);
- // set the CF_TEXT version (not needed?)
+ // Set the CF_TEXT version (not needed?).
CharString utf8 = text.utf8();
mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
ERR_FAIL_COND_MSG(mem == nullptr, "Unable to allocate memory for clipboard contents.");
@@ -206,7 +207,7 @@ String DisplayServerWindows::clipboard_get() const {
_THREAD_SAFE_METHOD_
if (!windows.has(last_focused_window)) {
- return String(); //no window focused?
+ return String(); // No focused window?
}
String ret;
@@ -498,16 +499,18 @@ DisplayServer::WindowID DisplayServerWindows::create_sub_window(WindowMode p_mod
}
void DisplayServerWindows::show_window(WindowID p_id) {
+ ERR_FAIL_COND(!windows.has(p_id));
+
WindowData &wd = windows[p_id];
if (p_id != MAIN_WINDOW_ID) {
_update_window_style(p_id);
}
- ShowWindow(wd.hWnd, wd.no_focus ? SW_SHOWNOACTIVATE : SW_SHOW); // Show The Window
+ ShowWindow(wd.hWnd, wd.no_focus ? SW_SHOWNOACTIVATE : SW_SHOW); // Show the window.
if (!wd.no_focus) {
- SetForegroundWindow(wd.hWnd); // Slightly Higher Priority
- SetFocus(wd.hWnd); // Sets Keyboard Focus To
+ SetForegroundWindow(wd.hWnd); // Slightly higher priority.
+ SetFocus(wd.hWnd); // Set keyboard focus.
}
}
@@ -606,6 +609,8 @@ void DisplayServerWindows::window_set_mouse_passthrough(const Vector<Vector2> &p
}
void DisplayServerWindows::_update_window_mouse_passthrough(WindowID p_window) {
+ ERR_FAIL_COND(!windows.has(p_window));
+
if (windows[p_window].mpath.size() == 0) {
SetWindowRgn(windows[p_window].hWnd, nullptr, TRUE);
} else {
@@ -664,16 +669,11 @@ Point2i DisplayServerWindows::window_get_position(WindowID p_window) const {
ClientToScreen(wd.hWnd, &point);
return Point2i(point.x, point.y);
-
-#if 0
- //do not use this method, as it includes windows decorations
- RECT r;
- GetWindowRect(wd.hWnd, &r);
- return Point2(r.left, r.top);
-#endif
}
void DisplayServerWindows::_update_real_mouse_position(WindowID p_window) {
+ ERR_FAIL_COND(!windows.has(p_window));
+
POINT mouse_pos;
if (GetCursorPos(&mouse_pos) && ScreenToClient(windows[p_window].hWnd, &mouse_pos)) {
if (mouse_pos.x > 0 && mouse_pos.y > 0 && mouse_pos.x <= windows[p_window].width && mouse_pos.y <= windows[p_window].height) {
@@ -691,14 +691,9 @@ void DisplayServerWindows::window_set_position(const Point2i &p_position, Window
ERR_FAIL_COND(!windows.has(p_window));
WindowData &wd = windows[p_window];
- if (wd.fullscreen)
+ if (wd.fullscreen) {
return;
-#if 0
- //wrong needs to account properly for decorations
- RECT r;
- GetWindowRect(wd.hWnd, &r);
- MoveWindow(wd.hWnd, p_position.x, p_position.y, r.right - r.left, r.bottom - r.top, TRUE);
-#else
+ }
RECT rc;
rc.left = p_position.x;
@@ -711,8 +706,8 @@ void DisplayServerWindows::window_set_position(const Point2i &p_position, Window
AdjustWindowRectEx(&rc, style, false, exStyle);
MoveWindow(wd.hWnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, TRUE);
-#endif
- // Don't let the mouse leave the window when moved
+
+ // Don't let the mouse leave the window when moved.
if (mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
RECT rect;
GetClientRect(wd.hWnd, &rect);
@@ -729,16 +724,15 @@ void DisplayServerWindows::window_set_transient(WindowID p_window, WindowID p_pa
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(p_window == p_parent);
-
ERR_FAIL_COND(!windows.has(p_window));
+
WindowData &wd_window = windows[p_window];
ERR_FAIL_COND(wd_window.transient_parent == p_parent);
-
ERR_FAIL_COND_MSG(wd_window.always_on_top, "Windows with the 'on top' can't become transient.");
if (p_parent == INVALID_WINDOW_ID) {
- //remove transient
+ // Remove transient.
ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
@@ -838,7 +832,7 @@ void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_windo
MoveWindow(wd.hWnd, rect.left, rect.top, w, h, TRUE);
- // Don't let the mouse leave the window when resizing to a smaller resolution
+ // Don't let the mouse leave the window when resizing to a smaller resolution.
if (mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
RECT crect;
GetClientRect(wd.hWnd, &crect);
@@ -860,7 +854,7 @@ Size2i DisplayServerWindows::window_get_size(WindowID p_window) const {
}
RECT r;
- if (GetClientRect(wd.hWnd, &r)) { // Retrieves area inside of window border.
+ if (GetClientRect(wd.hWnd, &r)) { // Retrieves area inside of window border, including decoration.
return Size2(r.right - r.left, r.bottom - r.top);
}
return Size2();
@@ -873,13 +867,17 @@ Size2i DisplayServerWindows::window_get_real_size(WindowID p_window) const {
const WindowData &wd = windows[p_window];
RECT r;
- if (GetWindowRect(wd.hWnd, &r)) { // Includes area of the window border
+ if (GetWindowRect(wd.hWnd, &r)) { // Retrieves area inside of window border, including decoration.
return Size2(r.right - r.left, r.bottom - r.top);
}
return Size2();
}
void DisplayServerWindows::_get_window_style(bool p_main_window, bool p_fullscreen, bool p_borderless, bool p_resizable, bool p_maximized, bool p_no_activate_focus, DWORD &r_style, DWORD &r_style_ex) {
+ // Windows docs for window styles:
+ // https://docs.microsoft.com/en-us/windows/win32/winmsg/window-styles
+ // https://docs.microsoft.com/en-us/windows/win32/winmsg/extended-window-styles
+
r_style = 0;
r_style_ex = WS_EX_WINDOWEDGE;
if (p_main_window) {
@@ -887,10 +885,7 @@ void DisplayServerWindows::_get_window_style(bool p_main_window, bool p_fullscre
}
if (p_fullscreen || p_borderless) {
- r_style |= WS_POPUP;
- //if (p_borderless) {
- // r_style_ex |= WS_EX_TOOLWINDOW;
- //}
+ r_style |= WS_POPUP; // p_borderless was WS_EX_TOOLWINDOW in the past.
} else {
if (p_resizable) {
if (p_maximized) {
@@ -1026,7 +1021,7 @@ bool DisplayServerWindows::window_is_maximize_allowed(WindowID p_window) const {
// FIXME: Implement this, or confirm that it should always be true.
- return true; //no idea
+ return true;
}
void DisplayServerWindows::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
@@ -1171,8 +1166,9 @@ void DisplayServerWindows::window_set_ime_position(const Point2i &p_pos, WindowI
void DisplayServerWindows::console_set_visible(bool p_enabled) {
_THREAD_SAFE_METHOD_
- if (console_visible == p_enabled)
+ if (console_visible == p_enabled) {
return;
+ }
ShowWindow(GetConsoleWindow(), p_enabled ? SW_SHOW : SW_HIDE);
console_visible = p_enabled;
}
@@ -1186,8 +1182,9 @@ void DisplayServerWindows::cursor_set_shape(CursorShape p_shape) {
ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
- if (cursor_shape == p_shape)
+ if (cursor_shape == p_shape) {
return;
+ }
if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
cursor_shape = p_shape;
@@ -1197,7 +1194,7 @@ void DisplayServerWindows::cursor_set_shape(CursorShape p_shape) {
static const LPCTSTR win_cursors[CURSOR_MAX] = {
IDC_ARROW,
IDC_IBEAM,
- IDC_HAND, //finger
+ IDC_HAND, // Finger.
IDC_CROSS,
IDC_WAIT,
IDC_APPSTARTING,
@@ -1228,49 +1225,49 @@ DisplayServer::CursorShape DisplayServerWindows::cursor_get_shape() const {
}
void DisplayServerWindows::GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap) {
- // Get the system display DC
+ // Get the system display DC.
HDC hDC = GetDC(nullptr);
- // Create helper DC
+ // Create helper DC.
HDC hMainDC = CreateCompatibleDC(hDC);
HDC hAndMaskDC = CreateCompatibleDC(hDC);
HDC hXorMaskDC = CreateCompatibleDC(hDC);
- // Get the dimensions of the source bitmap
+ // Get the dimensions of the source bitmap.
BITMAP bm;
GetObject(hSourceBitmap, sizeof(BITMAP), &bm);
- // Create the mask bitmaps
- hAndMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
- hXorMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
+ // Create the mask bitmaps.
+ hAndMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // Color.
+ hXorMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // Color.
- // Release the system display DC
+ // Release the system display DC.
ReleaseDC(nullptr, hDC);
- // Select the bitmaps to helper DC
+ // Select the bitmaps to helper DC.
HBITMAP hOldMainBitmap = (HBITMAP)SelectObject(hMainDC, hSourceBitmap);
HBITMAP hOldAndMaskBitmap = (HBITMAP)SelectObject(hAndMaskDC, hAndMaskBitmap);
HBITMAP hOldXorMaskBitmap = (HBITMAP)SelectObject(hXorMaskDC, hXorMaskBitmap);
// Assign the monochrome AND mask bitmap pixels so that the pixels of the source bitmap
- // with 'clrTransparent' will be white pixels of the monochrome bitmap
+ // with 'clrTransparent' will be white pixels of the monochrome bitmap.
SetBkColor(hMainDC, clrTransparent);
BitBlt(hAndMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCCOPY);
// Assign the color XOR mask bitmap pixels so that the pixels of the source bitmap
// with 'clrTransparent' will be black and rest the pixels same as corresponding
- // pixels of the source bitmap
+ // pixels of the source bitmap.
SetBkColor(hXorMaskDC, RGB(0, 0, 0));
SetTextColor(hXorMaskDC, RGB(255, 255, 255));
BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hAndMaskDC, 0, 0, SRCCOPY);
BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCAND);
- // Deselect bitmaps from the helper DC
+ // Deselect bitmaps from the helper DC.
SelectObject(hMainDC, hOldMainBitmap);
SelectObject(hAndMaskDC, hOldAndMaskBitmap);
SelectObject(hXorMaskDC, hOldXorMaskBitmap);
- // Delete the helper DC
+ // Delete the helper DC.
DeleteDC(hXorMaskDC);
DeleteDC(hAndMaskDC);
DeleteDC(hMainDC);
@@ -1327,7 +1324,7 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh
UINT image_size = texture_size.width * texture_size.height;
- // Create the BITMAP with alpha channel
+ // Create the BITMAP with alpha channel.
COLORREF *buffer = (COLORREF *)memalloc(sizeof(COLORREF) * image_size);
for (UINT index = 0; index < image_size; index++) {
@@ -1342,11 +1339,11 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh
*(buffer + index) = image->get_pixel(column_index, row_index).to_argb32();
}
- // Using 4 channels, so 4 * 8 bits
+ // Using 4 channels, so 4 * 8 bits.
HBITMAP bitmap = CreateBitmap(texture_size.width, texture_size.height, 1, 4 * 8, buffer);
COLORREF clrTransparent = -1;
- // Create the AND and XOR masks for the bitmap
+ // Create the AND and XOR masks for the bitmap.
HBITMAP hAndMask = nullptr;
HBITMAP hXorMask = nullptr;
@@ -1358,7 +1355,7 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh
return;
}
- // Finally, create the icon
+ // Finally, create the icon.
ICONINFO iconinfo;
iconinfo.fIcon = FALSE;
iconinfo.xHotspot = p_hotspot.x;
@@ -1366,8 +1363,9 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh
iconinfo.hbmMask = hAndMask;
iconinfo.hbmColor = hXorMask;
- if (cursors[p_shape])
+ if (cursors[p_shape]) {
DestroyIcon(cursors[p_shape]);
+ }
cursors[p_shape] = CreateIconIndirect(&iconinfo);
@@ -1393,7 +1391,7 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh
memfree(buffer);
DeleteObject(bitmap);
} else {
- // Reset to default system cursor
+ // Reset to default system cursor.
if (cursors[p_shape]) {
DestroyIcon(cursors[p_shape]);
cursors[p_shape] = nullptr;
@@ -1575,9 +1573,9 @@ void DisplayServerWindows::set_native_icon(const String &p_filename) {
icon_dir = (ICONDIR *)memrealloc(icon_dir, 3 * sizeof(WORD) + icon_dir->idCount * sizeof(ICONDIRENTRY));
f->get_buffer((uint8_t *)&icon_dir->idEntries[0], icon_dir->idCount * sizeof(ICONDIRENTRY));
- int small_icon_index = -1; // Select 16x16 with largest color count
+ int small_icon_index = -1; // Select 16x16 with largest color count.
int small_icon_cc = 0;
- int big_icon_index = -1; // Select largest
+ int big_icon_index = -1; // Select largest.
int big_icon_width = 16;
int big_icon_cc = 0;
@@ -1607,7 +1605,7 @@ void DisplayServerWindows::set_native_icon(const String &p_filename) {
small_icon_cc = big_icon_cc;
}
- // Read the big icon
+ // Read the big icon.
DWORD bytecount_big = icon_dir->idEntries[big_icon_index].dwBytesInRes;
Vector<uint8_t> data_big;
data_big.resize(bytecount_big);
@@ -1617,7 +1615,7 @@ void DisplayServerWindows::set_native_icon(const String &p_filename) {
HICON icon_big = CreateIconFromResource((PBYTE)&data_big.write[0], bytecount_big, TRUE, 0x00030000);
ERR_FAIL_COND_MSG(!icon_big, "Could not create " + itos(big_icon_width) + "x" + itos(big_icon_width) + " @" + itos(big_icon_cc) + " icon, error: " + format_error_message(GetLastError()) + ".");
- // Read the small icon
+ // Read the small icon.
DWORD bytecount_small = icon_dir->idEntries[small_icon_index].dwBytesInRes;
Vector<uint8_t> data_small;
data_small.resize(bytecount_small);
@@ -1627,7 +1625,7 @@ void DisplayServerWindows::set_native_icon(const String &p_filename) {
HICON icon_small = CreateIconFromResource((PBYTE)&data_small.write[0], bytecount_small, TRUE, 0x00030000);
ERR_FAIL_COND_MSG(!icon_small, "Could not create 16x16 @" + itos(small_icon_cc) + " icon, error: " + format_error_message(GetLastError()) + ".");
- // Online tradition says to be sure last error is cleared and set the small icon first
+ // Online tradition says to be sure last error is cleared and set the small icon first.
int err = 0;
SetLastError(err);
@@ -1648,12 +1646,13 @@ void DisplayServerWindows::set_icon(const Ref<Image> &p_icon) {
ERR_FAIL_COND(!p_icon.is_valid());
Ref<Image> icon = p_icon->duplicate();
- if (icon->get_format() != Image::FORMAT_RGBA8)
+ if (icon->get_format() != Image::FORMAT_RGBA8) {
icon->convert(Image::FORMAT_RGBA8);
+ }
int w = icon->get_width();
int h = icon->get_height();
- /* Create temporary bitmap buffer */
+ // Create temporary bitmap buffer.
int icon_len = 40 + h * w * 4;
Vector<BYTE> v;
v.resize(icon_len);
@@ -1687,10 +1686,10 @@ void DisplayServerWindows::set_icon(const Ref<Image> &p_icon) {
HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
- /* Set the icon for the window */
+ // Set the icon for the window.
SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
- /* Set the icon in the task manager (should we do this?) */
+ // Set the icon in the task manager (should we do this?).
SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
}
@@ -1718,13 +1717,13 @@ void DisplayServerWindows::set_context(Context p_context) {
// Keeping the name suggested by Microsoft, but this macro really answers:
// Is this mouse event emulated from touch or pen input?
#define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
-// This one tells whether the event comes from touchscreen (and not from pen)
+// This one tells whether the event comes from touchscreen (and not from pen).
#define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw)&0x80))
void DisplayServerWindows::_touch_event(WindowID p_window, bool p_pressed, float p_x, float p_y, int idx) {
- // Defensive
- if (touch_state.has(idx) == p_pressed)
+ if (touch_state.has(idx) == p_pressed) {
return;
+ }
if (p_pressed) {
touch_state.insert(idx, Vector2(p_x, p_y));
@@ -1744,12 +1743,13 @@ void DisplayServerWindows::_touch_event(WindowID p_window, bool p_pressed, float
void DisplayServerWindows::_drag_event(WindowID p_window, float p_x, float p_y, int idx) {
Map<int, Vector2>::Element *curr = touch_state.find(idx);
- // Defensive
- if (!curr)
+ if (!curr) {
return;
+ }
- if (curr->get() == Vector2(p_x, p_y))
+ if (curr->get() == Vector2(p_x, p_y)) {
return;
+ }
Ref<InputEventScreenDrag> event;
event.instantiate();
@@ -1791,7 +1791,7 @@ void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event)
Ref<InputEventFromWindow> event_from_window = p_event;
if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
- //send to a window
+ // Send to a single window.
if (!windows.has(event_from_window->get_window_id())) {
in_dispatch_input_event = false;
ERR_FAIL_MSG("DisplayServerWindows: Invalid window id in input event.");
@@ -1803,7 +1803,7 @@ void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event)
}
callable.call((const Variant **)&evp, 1, ret, ce);
} else {
- //send to all windows
+ // Send to all windows.
for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
Callable callable = E->get().input_event_callback;
if (callable.is_null()) {
@@ -1816,6 +1816,9 @@ void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event)
in_dispatch_input_event = false;
}
+// Our default window procedure to handle processing of window-related system messages/events.
+// Also known as DefProc or DefWindowProc.
+// See: https://docs.microsoft.com/en-us/windows/win32/winmsg/window-procedures
LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
if (drop_events) {
if (user_proc) {
@@ -1828,6 +1831,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
WindowID window_id = INVALID_WINDOW_ID;
bool window_created = false;
+ // Check whether window exists.
for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
if (E->get().hWnd == hWnd) {
window_id = E->key();
@@ -1836,19 +1840,19 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
}
+ // Window doesn't exist or creation in progress, don't handle messages yet.
if (!window_created) {
- // Window creation in progress.
window_id = window_id_counter;
ERR_FAIL_COND_V(!windows.has(window_id), 0);
}
- switch (uMsg) // Check For Windows Messages
- {
+ // Process window messages.
+ switch (uMsg) {
case WM_SETFOCUS: {
windows[window_id].window_has_focus = true;
last_focused_window = window_id;
- // Restore mouse mode
+ // Restore mouse mode.
_set_mouse_mode_impl(mouse_mode);
if (!app_focused) {
@@ -1857,16 +1861,15 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
app_focused = true;
}
- break;
- }
+ } break;
case WM_KILLFOCUS: {
windows[window_id].window_has_focus = false;
last_focused_window = window_id;
- // Release capture unconditionally because it can be set due to dragging, in addition to captured mode
+ // Release capture unconditionally because it can be set due to dragging, in addition to captured mode.
ReleaseCapture();
- // Release every touch to avoid sticky points
+ // Release every touch to avoid sticky points.
for (Map<int, Vector2>::Element *E = touch_state.front(); E; E = E->next()) {
_touch_event(window_id, false, E->get().x, E->get().y, E->key());
}
@@ -1884,10 +1887,8 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
app_focused = false;
}
-
- break;
- }
- case WM_ACTIVATE: { // Watch For Window Activate Message
+ } break;
+ case WM_ACTIVATE: { // Watch for window activate message.
if (!windows[window_id].window_focused) {
_process_activate_event(window_id, wParam, lParam);
} else {
@@ -1897,8 +1898,8 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
// Run a timer to prevent event catching warning if the focused window is closing.
windows[window_id].focus_timer_id = SetTimer(windows[window_id].hWnd, 2, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
}
- return 0; // Return To The Message Loop
- }
+ return 0; // Return to the message loop.
+ } break;
case WM_GETMINMAXINFO: {
if (windows[window_id].resizable && !windows[window_id].fullscreen) {
// Size of window decorations.
@@ -1914,37 +1915,31 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
min_max_info->ptMaxTrackSize.y = windows[window_id].max_size.y + decor.y;
}
return 0;
- } else {
- break;
}
- }
- case WM_PAINT:
-
+ } break;
+ case WM_PAINT: {
Main::force_redraw();
- break;
-
- case WM_SYSCOMMAND: // Intercept System Commands
+ } break;
+ case WM_SYSCOMMAND: // Intercept system commands.
{
- switch (wParam) // Check System Calls
+ switch (wParam) // Check system calls.
{
- case SC_SCREENSAVE: // Screensaver Trying To Start?
- case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
- return 0; // Prevent From Happening
+ case SC_SCREENSAVE: // Screensaver trying to start?
+ case SC_MONITORPOWER: // Monitor trying to enter powersave?
+ return 0; // Prevent from happening.
case SC_KEYMENU:
if ((lParam >> 16) <= 0)
return 0;
}
- break; // Exit
- }
-
- case WM_CLOSE: // Did We Receive A Close Message?
+ } break;
+ case WM_CLOSE: // Did we receive a close message?
{
if (windows[window_id].focus_timer_id != 0U) {
KillTimer(windows[window_id].hWnd, windows[window_id].focus_timer_id);
}
_send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
- return 0; // Jump Back
+ return 0; // Jump back.
}
case WM_MOUSELEAVE: {
old_invalid = true;
@@ -1986,7 +1981,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
- // centering just so it works as before
+ // Centering just so it works as before.
POINT pos = { (int)c.x, (int)c.y };
ClientToScreen(windows[window_id].hWnd, &pos);
SetCursorPos(pos.x, pos.y);
@@ -2009,7 +2004,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
(double(raw->data.mouse.lLastX) - 65536.0 / (nScreenWidth)) * nScreenWidth / 65536.0 + nScreenLeft,
(double(raw->data.mouse.lLastY) - 65536.0 / (nScreenHeight)) * nScreenHeight / 65536.0 + nScreenTop);
- POINT coords; //client coords
+ POINT coords; // Client coords.
coords.x = abs_pos.x;
coords.y = abs_pos.y;
@@ -2018,14 +2013,11 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
mm->set_relative(Vector2(coords.x - old_x, coords.y - old_y));
old_x = coords.x;
old_y = coords.y;
-
- /*Input.mi.dx = (int)((((double)(pos.x)-nScreenLeft) * 65536) / nScreenWidth + 65536 / (nScreenWidth));
- Input.mi.dy = (int)((((double)(pos.y)-nScreenTop) * 65536) / nScreenHeight + 65536 / (nScreenHeight));
- */
}
- if (windows[window_id].window_has_focus && mm->get_relative() != Vector2())
+ if (windows[window_id].window_has_focus && mm->get_relative() != Vector2()) {
Input::get_singleton()->parse_input_event(mm);
+ }
}
delete[] lpb;
} break;
@@ -2170,7 +2162,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
- // Universal translation enabled; ignore OS translation
+ // Universal translation enabled; ignore OS translation.
LPARAM extra = GetMessageExtraInfo();
if (IsTouchEvent(extra)) {
break;
@@ -2178,7 +2170,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
if (outside) {
- //mouse enter
+ // Mouse enter.
if (mouse_mode != MOUSE_MODE_CAPTURED) {
_send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
@@ -2189,7 +2181,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
cursor_set_shape(c);
outside = false;
- //Once-Off notification, must call again....
+ // Once-off notification, must call again.
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
@@ -2222,7 +2214,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
mm->set_button_mask(last_button_state);
- POINT coords; //client coords
+ POINT coords; // Client coords.
coords.x = GET_X_LPARAM(lParam);
coords.y = GET_Y_LPARAM(lParam);
@@ -2264,7 +2256,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
Input::get_singleton()->parse_input_event(mm);
}
- return 0; //Pointer event handled return 0 to avoid duplicate WM_MOUSEMOVE event
+ return 0; // Pointer event handled return 0 to avoid duplicate WM_MOUSEMOVE event.
} break;
case WM_MOUSEMOVE: {
if (windows[window_id].block_mm) {
@@ -2276,7 +2268,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
- // Universal translation enabled; ignore OS translation
+ // Universal translation enabled; ignore OS translation.
LPARAM extra = GetMessageExtraInfo();
if (IsTouchEvent(extra)) {
break;
@@ -2284,7 +2276,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
if (outside) {
- //mouse enter
+ // Mouse enter.
if (mouse_mode != MOUSE_MODE_CAPTURED) {
_send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
@@ -2295,7 +2287,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
cursor_set_shape(c);
outside = false;
- //Once-Off notification, must call again....
+ // Once-off notification, must call again.
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
@@ -2373,7 +2365,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
- // Universal translation enabled; ignore OS translations for left button
+ // Universal translation enabled; ignore OS translations for left button.
LPARAM extra = GetMessageExtraInfo();
if (IsTouchEvent(extra)) {
break;
@@ -2497,7 +2489,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
mb->set_ctrl_pressed((wParam & MK_CONTROL) != 0);
mb->set_shift_pressed((wParam & MK_SHIFT) != 0);
mb->set_alt_pressed(alt_mem);
- //mb->is_alt_pressed()=(wParam&MK_MENU)!=0;
+ // mb->is_alt_pressed()=(wParam&MK_MENU)!=0;
if (mb->is_pressed()) {
last_button_state |= MouseButton(1 << (mb->get_button_index() - 1));
} else {
@@ -2524,7 +2516,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
}
} else {
- // for reasons unknown to mankind, wheel comes in screen coordinates
+ // For reasons unknown to mankind, wheel comes in screen coordinates.
POINT coords;
coords.x = mb->get_position().x;
coords.y = mb->get_position().y;
@@ -2538,7 +2530,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
Input::get_singleton()->parse_input_event(mb);
if (mb->is_pressed() && mb->get_button_index() > 3 && mb->get_button_index() < 8) {
- //send release for mouse wheel
+ // Send release for mouse wheel.
Ref<InputEventMouseButton> mbd = mb->duplicate();
mbd->set_window_id(window_id);
last_button_state &= (MouseButton) ~(1 << (mbd->get_button_index() - 1));
@@ -2548,7 +2540,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
} break;
-
case WM_MOVE: {
if (!IsIconic(windows[window_id].hWnd)) {
int x = int16_t(LOWORD(lParam));
@@ -2564,7 +2555,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
}
} break;
-
case WM_SIZE: {
// Ignore window size change when a SIZE_MINIMIZED event is triggered.
if (wParam != SIZE_MINIMIZED) {
@@ -2642,7 +2632,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
#endif
} break;
-
case WM_ENTERSIZEMOVE: {
Input::get_singleton()->release_pressed_events();
windows[window_id].move_timer_id = SetTimer(windows[window_id].hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
@@ -2662,7 +2651,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
windows[window_id].focus_timer_id = 0U;
}
} break;
-
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_KEYUP:
@@ -2714,7 +2702,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
case WM_INPUTLANGCHANGEREQUEST: {
// FIXME: Do something?
} break;
-
case WM_TOUCH: {
BOOL bHandled = FALSE;
UINT cInputs = LOWORD(wParam);
@@ -2728,7 +2715,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
TOUCH_COORD_TO_PIXEL(ti.y),
};
ScreenToClient(hWnd, &touch_pos);
- //do something with each touch input entry
+ // Do something with each touch input entry.
if (ti.dwFlags & TOUCHEVENTF_MOVE) {
_drag_event(window_id, touch_pos.x, touch_pos.y, ti.dwID);
} else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
@@ -2737,11 +2724,11 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
bHandled = TRUE;
} else {
- /* handle the error here */
+ // TODO: Handle the error here.
}
memdelete_arr(pInputs);
} else {
- /* handle the error here, probably out of memory */
+ // TODO: Handle the error here, probably out of memory.
}
if (bHandled) {
CloseTouchInputHandle((HTOUCHINPUT)lParam);
@@ -2749,14 +2736,13 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
};
} break;
-
case WM_DEVICECHANGE: {
joypad->probe_joypads();
} break;
case WM_SETCURSOR: {
if (LOWORD(lParam) == HTCLIENT) {
if (windows[window_id].window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN)) {
- //Hide the cursor
+ // Hide the cursor.
if (hCursor == nullptr) {
hCursor = SetCursor(nullptr);
} else {
@@ -2771,7 +2757,6 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
}
}
}
-
} break;
case WM_DROPFILES: {
HDROP hDropInfo = (HDROP)wParam;
@@ -2795,9 +2780,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
Callable::CallError ce;
windows[window_id].drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
}
-
} break;
-
default: {
if (user_proc) {
return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
@@ -2823,7 +2806,7 @@ void DisplayServerWindows::_process_activate_event(WindowID p_window_id, WPARAM
alt_mem = false;
control_mem = false;
shift_mem = false;
- } else { // WM_INACTIVE
+ } else { // WM_INACTIVE.
Input::get_singleton()->release_pressed_events();
_send_window_event(windows[p_window_id], WINDOW_EVENT_FOCUS_OUT);
windows[p_window_id].window_focused = false;
@@ -2840,7 +2823,7 @@ void DisplayServerWindows::_process_key_events() {
KeyEvent &ke = key_event_buffer[i];
switch (ke.uMsg) {
case WM_CHAR: {
- // extended keys should only be processed as WM_KEYDOWN message.
+ // Extended keys should only be processed as WM_KEYDOWN message.
if (!KeyMappingWindows::is_extended_key(ke.wParam) && ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR))) {
static char32_t prev_wc = 0;
char32_t unicode = ke.wParam;
@@ -2881,9 +2864,9 @@ void DisplayServerWindows::_process_key_events() {
k->set_unicode(0);
Input::get_singleton()->parse_input_event(k);
+ } else {
+ // Do nothing.
}
-
- //do nothing
} break;
case WM_KEYUP:
case WM_KEYDOWN: {
@@ -2899,7 +2882,7 @@ void DisplayServerWindows::_process_key_events() {
k->set_pressed(ke.uMsg == WM_KEYDOWN);
if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
- // Special case for Numpad Enter key
+ // Special case for Numpad Enter key.
k->set_keycode(KEY_KP_ENTER);
} else {
k->set_keycode((Key)KeyMappingWindows::get_keysym(ke.wParam));
@@ -3045,8 +3028,8 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode,
if (p_mode != WINDOW_MODE_FULLSCREEN) {
wd.pre_fs_valid = true;
}
-#ifdef VULKAN_ENABLED
+#ifdef VULKAN_ENABLED
if (rendering_driver == "vulkan") {
if (context_vulkan->window_create(id, p_vsync_mode, wd.hWnd, hInstance, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top) == -1) {
memdelete(context_vulkan);
@@ -3101,7 +3084,7 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode,
wd.last_pressure_update = 0;
wd.last_tilt = Vector2();
- // IME
+ // IME.
wd.im_himc = ImmGetContext(wd.hWnd);
ImmReleaseContext(wd.hWnd, wd.im_himc);
@@ -3116,7 +3099,7 @@ DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode,
return id;
}
-// WinTab API
+// WinTab API.
bool DisplayServerWindows::wintab_available = false;
WTOpenPtr DisplayServerWindows::wintab_WTOpen = nullptr;
WTClosePtr DisplayServerWindows::wintab_WTClose = nullptr;
@@ -3124,7 +3107,7 @@ WTInfoPtr DisplayServerWindows::wintab_WTInfo = nullptr;
WTPacketPtr DisplayServerWindows::wintab_WTPacket = nullptr;
WTEnablePtr DisplayServerWindows::wintab_WTEnable = nullptr;
-// Windows Ink API
+// Windows Ink API.
bool DisplayServerWindows::winink_available = false;
GetPointerTypePtr DisplayServerWindows::win8p_GetPointerType = nullptr;
GetPointerPenInfoPtr DisplayServerWindows::win8p_GetPointerPenInfo = nullptr;
@@ -3187,7 +3170,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
outside = true;
- //Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
+ // Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
HMODULE wintab_lib = LoadLibraryW(L"wintab32.dll");
if (wintab_lib) {
wintab_WTOpen = (WTOpenPtr)GetProcAddress(wintab_lib, "WTOpenW");
@@ -3203,7 +3186,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
tablet_drivers.push_back("wintab");
}
- //Note: Windows Ink API for pen input, available on Windows 8+ only.
+ // Note: Windows Ink API for pen input, available on Windows 8+ only.
HMODULE user32_lib = LoadLibraryW(L"user32.dll");
if (user32_lib) {
win8p_GetPointerType = (GetPointerTypePtr)GetProcAddress(user32_lib, "GetPointerType");
@@ -3236,7 +3219,6 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
wc.lpfnWndProc = (WNDPROC)::WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
- //wc.hInstance = hInstance;
wc.hInstance = hInstance ? hInstance : GetModuleHandle(nullptr);
wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
wc.hCursor = nullptr; //LoadCursor(nullptr, IDC_ARROW);
@@ -3260,7 +3242,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
Rid[0].hwndTarget = 0;
if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) {
- //registration failed.
+ // Registration failed.
use_raw_input = false;
}
@@ -3277,6 +3259,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
}
}
#endif
+
#if defined(OPENGL_ENABLED)
if (rendering_driver_index == VIDEO_DRIVER_GLES2) {
context_gles2 = memnew(ContextGL_Windows(hWnd, false));
@@ -3299,6 +3282,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
}
}
#endif
+
Point2i window_position(
(screen_get_size(0).width - p_resolution.width) / 2,
(screen_get_size(0).height - p_resolution.height) / 2);
@@ -3327,7 +3311,6 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
//set_ime_active(false);
if (!OS::get_singleton()->is_in_low_processor_usage_mode()) {
- //SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
DWORD index = 0;
HANDLE handle = AvSetMmThreadCharacteristics("Games", &index);
@@ -3335,7 +3318,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win
AvSetMmThreadPriority(handle, AVRT_PRIORITY_CRITICAL);
// This is needed to make sure that background work does not starve the main thread.
- // This is only setting priority of this thread, not the whole process.
+ // This is only setting the priority of this thread, not the whole process.
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
}
diff --git a/scene/2d/audio_stream_player_2d.cpp b/scene/2d/audio_stream_player_2d.cpp
index 9280e35c3f..8401909384 100644
--- a/scene/2d/audio_stream_player_2d.cpp
+++ b/scene/2d/audio_stream_player_2d.cpp
@@ -31,6 +31,7 @@
#include "audio_stream_player_2d.h"
#include "scene/2d/area_2d.h"
+#include "scene/2d/listener_2d.h"
#include "scene/main/window.h"
void AudioStreamPlayer2D::_notification(int p_what) {
@@ -150,13 +151,22 @@ void AudioStreamPlayer2D::_update_panning() {
continue;
}
//compute matrix to convert to screen
- Transform2D to_screen = vp->get_global_canvas_transform() * vp->get_canvas_transform();
Vector2 screen_size = vp->get_visible_rect().size;
+ Vector2 listener_in_global;
+ Vector2 relative_to_listener;
//screen in global is used for attenuation
- Vector2 screen_in_global = to_screen.affine_inverse().xform(screen_size * 0.5);
+ Listener2D *listener = vp->get_listener_2d();
+ if (listener) {
+ listener_in_global = listener->get_global_position();
+ relative_to_listener = global_pos - listener_in_global;
+ } else {
+ Transform2D to_listener = vp->get_global_canvas_transform() * vp->get_canvas_transform();
+ listener_in_global = to_listener.affine_inverse().xform(screen_size * 0.5);
+ relative_to_listener = to_listener.xform(global_pos) - screen_size * 0.5;
+ }
- float dist = global_pos.distance_to(screen_in_global); //distance to screen center
+ float dist = global_pos.distance_to(listener_in_global); // Distance to listener, or screen if none.
if (dist > max_distance) {
continue; //can't hear this sound in this viewport
@@ -165,10 +175,7 @@ void AudioStreamPlayer2D::_update_panning() {
float multiplier = Math::pow(1.0f - dist / max_distance, attenuation);
multiplier *= Math::db2linear(volume_db); //also apply player volume!
- //point in screen is used for panning
- Vector2 point_in_screen = to_screen.xform(global_pos);
-
- float pan = CLAMP(point_in_screen.x / screen_size.width, 0.0, 1.0);
+ float pan = CLAMP((relative_to_listener.x + screen_size.x * 0.5) / screen_size.x, 0.0, 1.0);
float l = 1.0 - pan;
float r = pan;
diff --git a/scene/2d/listener_2d.cpp b/scene/2d/listener_2d.cpp
new file mode 100644
index 0000000000..444f05f2b1
--- /dev/null
+++ b/scene/2d/listener_2d.cpp
@@ -0,0 +1,112 @@
+/*************************************************************************/
+/* listener_2d.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "listener_2d.h"
+
+bool Listener2D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "current") {
+ if (p_value.operator bool()) {
+ make_current();
+ } else {
+ clear_current();
+ }
+ } else {
+ return false;
+ }
+ return true;
+}
+
+bool Listener2D::_get(const StringName &p_name, Variant &r_ret) const {
+ if (p_name == "current") {
+ if (is_inside_tree() && get_tree()->is_node_being_edited(this)) {
+ r_ret = current;
+ } else {
+ r_ret = is_current();
+ }
+ } else {
+ return false;
+ }
+ return true;
+}
+
+void Listener2D::_get_property_list(List<PropertyInfo> *p_list) const {
+ p_list->push_back(PropertyInfo(Variant::BOOL, "current"));
+}
+
+void Listener2D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ if (!get_tree()->is_node_being_edited(this) && current) {
+ make_current();
+ }
+ } break;
+ case NOTIFICATION_EXIT_TREE: {
+ if (!get_tree()->is_node_being_edited(this)) {
+ if (is_current()) {
+ clear_current();
+ current = true; // Keep it true.
+ } else {
+ current = false;
+ }
+ }
+ } break;
+ }
+}
+
+void Listener2D::make_current() {
+ current = true;
+ if (!is_inside_tree()) {
+ return;
+ }
+ get_viewport()->_listener_2d_set(this);
+}
+
+void Listener2D::clear_current() {
+ current = false;
+ if (!is_inside_tree()) {
+ return;
+ }
+ get_viewport()->_listener_2d_remove(this);
+}
+
+bool Listener2D::is_current() const {
+ if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) {
+ return get_viewport()->get_listener_2d() == this;
+ } else {
+ return current;
+ }
+ return false;
+}
+
+void Listener2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("make_current"), &Listener2D::make_current);
+ ClassDB::bind_method(D_METHOD("clear_current"), &Listener2D::clear_current);
+ ClassDB::bind_method(D_METHOD("is_current"), &Listener2D::is_current);
+}
diff --git a/modules/stb_vorbis/register_types.cpp b/scene/2d/listener_2d.h
index bdb1cf69cf..0289a8087d 100644
--- a/modules/stb_vorbis/register_types.cpp
+++ b/scene/2d/listener_2d.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* register_types.cpp */
+/* listener_2d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,25 +28,34 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "register_types.h"
+#ifndef LISTENER_2D_H
+#define LISTENER_2D_H
-#include "audio_stream_ogg_vorbis.h"
+#include "scene/2d/node_2d.h"
+#include "scene/main/window.h"
-#ifdef TOOLS_ENABLED
-#include "core/config/engine.h"
-#include "resource_importer_ogg_vorbis.h"
-#endif
+class Listener2D : public Node2D {
+ GDCLASS(Listener2D, Node2D);
-void register_stb_vorbis_types() {
-#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
- Ref<ResourceImporterOGGVorbis> ogg_import;
- ogg_import.instantiate();
- ResourceFormatImporter::get_singleton()->add_importer(ogg_import);
- }
-#endif
- GDREGISTER_CLASS(AudioStreamOGGVorbis);
-}
+private:
+ bool current = false;
+
+ friend class Viewport;
+
+protected:
+ void _update_listener();
-void unregister_stb_vorbis_types() {
-}
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
+ void _notification(int p_what);
+
+ static void _bind_methods();
+
+public:
+ void make_current();
+ void clear_current();
+ bool is_current() const;
+};
+
+#endif
diff --git a/scene/2d/parallax_layer.cpp b/scene/2d/parallax_layer.cpp
index 1fe6a4a4b8..67e35cc7a3 100644
--- a/scene/2d/parallax_layer.cpp
+++ b/scene/2d/parallax_layer.cpp
@@ -100,6 +100,10 @@ void ParallaxLayer::_notification(int p_what) {
_update_mirroring();
} break;
case NOTIFICATION_EXIT_TREE: {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ break;
+ }
+
set_position(orig_offset);
set_scale(orig_scale);
} break;
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index e1552b3b60..a139a92ab4 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -236,6 +236,8 @@ Vector2i TileMap::transform_coords_layout(Vector2i p_coords, TileSet::TileOffset
}
int TileMap::get_effective_quadrant_size(int p_layer) const {
+ ERR_FAIL_INDEX_V(p_layer, (int)layers.size(), 1);
+
// When using YSort, the quadrant size is reduced to 1 to have one CanvasItem per quadrant
if (is_y_sort_enabled() && layers[p_layer].y_sort_enabled) {
return 1;
@@ -259,6 +261,7 @@ void TileMap::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
pending_update = true;
+ _clear_internals();
_recreate_internals();
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -296,6 +299,7 @@ void TileMap::set_tileset(const Ref<TileSet> &p_tileset) {
if (tile_set.is_valid()) {
tile_set->connect("changed", callable_mp(this, &TileMap::_tile_set_changed));
+ _clear_internals();
_recreate_internals();
}
@@ -306,6 +310,7 @@ void TileMap::set_quadrant_size(int p_size) {
ERR_FAIL_COND_MSG(p_size < 1, "TileMapQuadrant size cannot be smaller than 1.");
quadrant_size = p_size;
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
}
@@ -325,6 +330,9 @@ void TileMap::add_layer(int p_to_pos) {
ERR_FAIL_INDEX(p_to_pos, (int)layers.size() + 1);
+ // Must clear before adding the layer.
+ _clear_internals();
+
layers.insert(p_to_pos, TileMapLayer());
_recreate_internals();
notify_property_list_changed();
@@ -338,6 +346,9 @@ void TileMap::move_layer(int p_layer, int p_to_pos) {
ERR_FAIL_INDEX(p_layer, (int)layers.size());
ERR_FAIL_INDEX(p_to_pos, (int)layers.size() + 1);
+ // Clear before shuffling layers.
+ _clear_internals();
+
TileMapLayer tl = layers[p_layer];
layers.insert(p_to_pos, tl);
layers.remove(p_to_pos < p_layer ? p_layer + 1 : p_layer);
@@ -356,6 +367,9 @@ void TileMap::move_layer(int p_layer, int p_to_pos) {
void TileMap::remove_layer(int p_layer) {
ERR_FAIL_INDEX(p_layer, (int)layers.size());
+ // Clear before removing the layer.
+ _clear_internals();
+
layers.remove(p_layer);
_recreate_internals();
notify_property_list_changed();
@@ -383,6 +397,7 @@ String TileMap::get_layer_name(int p_layer) const {
void TileMap::set_layer_enabled(int p_layer, bool p_enabled) {
ERR_FAIL_INDEX(p_layer, (int)layers.size());
layers[p_layer].enabled = p_enabled;
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
@@ -397,6 +412,7 @@ bool TileMap::is_layer_enabled(int p_layer) const {
void TileMap::set_layer_y_sort_enabled(int p_layer, bool p_y_sort_enabled) {
ERR_FAIL_INDEX(p_layer, (int)layers.size());
layers[p_layer].y_sort_enabled = p_y_sort_enabled;
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
@@ -411,6 +427,7 @@ bool TileMap::is_layer_y_sort_enabled(int p_layer) const {
void TileMap::set_layer_y_sort_origin(int p_layer, int p_y_sort_origin) {
ERR_FAIL_INDEX(p_layer, (int)layers.size());
layers[p_layer].y_sort_origin = p_y_sort_origin;
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
}
@@ -423,6 +440,7 @@ int TileMap::get_layer_y_sort_origin(int p_layer) const {
void TileMap::set_layer_z_index(int p_layer, int p_z_index) {
ERR_FAIL_INDEX(p_layer, (int)layers.size());
layers[p_layer].z_index = p_z_index;
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
@@ -436,6 +454,7 @@ int TileMap::get_layer_z_index(int p_layer) const {
void TileMap::set_collision_visibility_mode(TileMap::VisibilityMode p_show_collision) {
collision_visibility_mode = p_show_collision;
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
}
@@ -446,6 +465,7 @@ TileMap::VisibilityMode TileMap::get_collision_visibility_mode() {
void TileMap::set_navigation_visibility_mode(TileMap::VisibilityMode p_show_navigation) {
navigation_visibility_mode = p_show_navigation;
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
}
@@ -456,6 +476,7 @@ TileMap::VisibilityMode TileMap::get_navigation_visibility_mode() {
void TileMap::set_y_sort_enabled(bool p_enable) {
Node2D::set_y_sort_enabled(p_enable);
+ _clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
}
@@ -576,10 +597,10 @@ void TileMap::_update_dirty_quadrants() {
}
void TileMap::_recreate_internals() {
- // Clear all internals.
- _clear_internals();
-
for (unsigned int layer = 0; layer < layers.size(); layer++) {
+ // Make sure that _clear_internals() was called prior.
+ ERR_FAIL_COND_MSG(layers[layer].quadrant_map.size() > 0, "TileMap layer " + itos(layer) + " had a non-empty quadrant map.");
+
if (!layers[layer].enabled) {
continue;
}
@@ -815,7 +836,7 @@ void TileMap::_rendering_update_dirty_quadrants(SelfList<TileMapQuadrant>::List
if (atlas_source) {
// Get the tile data.
TileData *tile_data = Object::cast_to<TileData>(atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile));
- Ref<ShaderMaterial> mat = tile_data->tile_get_material();
+ Ref<ShaderMaterial> mat = tile_data->get_material();
int z_index = tile_data->get_z_index();
// Quandrant pos.
@@ -2855,50 +2876,57 @@ void TileMap::draw_cells_outline(Control *p_control, Set<Vector2i> p_cells, Colo
// Create a set.
Vector2i tile_size = tile_set->get_tile_size();
- Vector<Vector2> uvs;
+ Vector<Vector2> polygon = tile_set->get_tile_shape_polygon();
+ TileSet::TileShape shape = tile_set->get_tile_shape();
- if (tile_set->get_tile_shape() == TileSet::TILE_SHAPE_SQUARE) {
- uvs.append(Vector2(1.0, 0.0));
- uvs.append(Vector2(1.0, 1.0));
- uvs.append(Vector2(0.0, 1.0));
- uvs.append(Vector2(0.0, 0.0));
- } else {
- float overlap = 0.0;
- switch (tile_set->get_tile_shape()) {
- case TileSet::TILE_SHAPE_ISOMETRIC:
- overlap = 0.5;
- break;
- case TileSet::TILE_SHAPE_HEXAGON:
- overlap = 0.25;
- break;
- case TileSet::TILE_SHAPE_HALF_OFFSET_SQUARE:
- overlap = 0.0;
- break;
- default:
- break;
- }
- uvs.append(Vector2(1.0, overlap));
- uvs.append(Vector2(1.0, 1.0 - overlap));
- uvs.append(Vector2(0.5, 1.0));
- uvs.append(Vector2(0.0, 1.0 - overlap));
- uvs.append(Vector2(0.0, overlap));
- uvs.append(Vector2(0.5, 0.0));
- if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL) {
- for (int i = 0; i < uvs.size(); i++) {
- uvs.write[i] = Vector2(uvs[i].y, uvs[i].x);
- }
- }
+ for (Set<Vector2i>::Element *E = p_cells.front(); E; E = E->next()) {
+ Vector2 center = map_to_world(E->get());
+
+#define DRAW_SIDE_IF_NEEDED(side, polygon_index_from, polygon_index_to) \
+ if (!p_cells.has(get_neighbor_cell(E->get(), side))) { \
+ Vector2 from = p_transform.xform(center + polygon[polygon_index_from] * tile_size); \
+ Vector2 to = p_transform.xform(center + polygon[polygon_index_to] * tile_size); \
+ p_control->draw_line(from, to, p_color); \
}
- for (Set<Vector2i>::Element *E = p_cells.front(); E; E = E->next()) {
- Vector2 top_left = map_to_world(E->get()) - tile_size / 2;
- TypedArray<Vector2i> surrounding_tiles = get_surrounding_tiles(E->get());
- for (int i = 0; i < surrounding_tiles.size(); i++) {
- if (!p_cells.has(surrounding_tiles[i])) {
- p_control->draw_line(p_transform.xform(top_left + uvs[i] * tile_size), p_transform.xform(top_left + uvs[(i + 1) % uvs.size()] * tile_size), p_color);
+ if (shape == TileSet::TILE_SHAPE_SQUARE) {
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_RIGHT_SIDE, 1, 2);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_SIDE, 2, 3);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_LEFT_SIDE, 3, 0);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_SIDE, 0, 1);
+ } else {
+ if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
+ if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 2, 3);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 5, 0);
+ } else {
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 2, 3);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_LEFT_SIDE, 1, 2);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 5, 0);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_RIGHT_SIDE, 4, 5);
+ }
+ } else {
+ if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 5, 0);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 2, 3);
+ } else {
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_SIDE, 4, 5);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 5, 0);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_SIDE, 1, 2);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 2, 3);
+ }
}
}
}
+#undef DRAW_SIDE_IF_NEEDED
}
TypedArray<String> TileMap::get_configuration_warnings() const {
@@ -2931,9 +2959,9 @@ void TileMap::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_quadrant_size"), &TileMap::get_quadrant_size);
ClassDB::bind_method(D_METHOD("get_layers_count"), &TileMap::get_layers_count);
- ClassDB::bind_method(D_METHOD("add_layer"), &TileMap::add_layer);
- ClassDB::bind_method(D_METHOD("move_layer"), &TileMap::move_layer);
- ClassDB::bind_method(D_METHOD("remove_layer"), &TileMap::remove_layer);
+ ClassDB::bind_method(D_METHOD("add_layer", "to_position"), &TileMap::add_layer);
+ ClassDB::bind_method(D_METHOD("move_layer", "layer", "to_position"), &TileMap::move_layer);
+ ClassDB::bind_method(D_METHOD("remove_layer", "layer"), &TileMap::remove_layer);
ClassDB::bind_method(D_METHOD("set_layer_name", "layer", "name"), &TileMap::set_layer_name);
ClassDB::bind_method(D_METHOD("get_layer_name", "layer"), &TileMap::get_layer_name);
ClassDB::bind_method(D_METHOD("set_layer_enabled", "layer", "enabled"), &TileMap::set_layer_enabled);
@@ -2943,7 +2971,7 @@ void TileMap::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_layer_y_sort_origin", "layer", "y_sort_origin"), &TileMap::set_layer_y_sort_origin);
ClassDB::bind_method(D_METHOD("get_layer_y_sort_origin", "layer"), &TileMap::get_layer_y_sort_origin);
ClassDB::bind_method(D_METHOD("set_layer_z_index", "layer", "z_index"), &TileMap::set_layer_z_index);
- ClassDB::bind_method(D_METHOD("get_layer_z_indexd", "layer"), &TileMap::get_layer_z_index);
+ ClassDB::bind_method(D_METHOD("get_layer_z_index", "layer"), &TileMap::get_layer_z_index);
ClassDB::bind_method(D_METHOD("set_collision_visibility_mode", "collision_visibility_mode"), &TileMap::set_collision_visibility_mode);
ClassDB::bind_method(D_METHOD("get_collision_visibility_mode"), &TileMap::get_collision_visibility_mode);
@@ -2991,6 +3019,7 @@ void TileMap::_bind_methods() {
void TileMap::_tile_set_changed() {
emit_signal(SNAME("changed"));
+ _clear_internals();
_recreate_internals();
}
diff --git a/scene/3d/mesh_instance_3d.cpp b/scene/3d/mesh_instance_3d.cpp
index de6925244a..7e7db57af3 100644
--- a/scene/3d/mesh_instance_3d.cpp
+++ b/scene/3d/mesh_instance_3d.cpp
@@ -274,7 +274,8 @@ Node *MeshInstance3D::create_multiple_convex_collisions_node() {
return nullptr;
}
- Vector<Ref<Shape3D>> shapes = mesh->convex_decompose();
+ Mesh::ConvexDecompositionSettings settings;
+ Vector<Ref<Shape3D>> shapes = mesh->convex_decompose(settings);
if (!shapes.size()) {
return nullptr;
}
diff --git a/scene/3d/skeleton_ik_3d.cpp b/scene/3d/skeleton_ik_3d.cpp
index a891566633..466f67afb8 100644
--- a/scene/3d/skeleton_ik_3d.cpp
+++ b/scene/3d/skeleton_ik_3d.cpp
@@ -542,7 +542,7 @@ Transform3D SkeletonIK3D::_get_target_transform() {
target_node_override = Object::cast_to<Node3D>(get_node(target_node_path_override));
}
- if (target_node_override) {
+ if (target_node_override && target_node_override->is_inside_tree()) {
return target_node_override->get_global_transform();
} else {
return target;
diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp
index f6091f224c..5825a35030 100644
--- a/scene/animation/animation_player.cpp
+++ b/scene/animation/animation_player.cpp
@@ -737,7 +737,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (anim->has_loop()) {
at_anim_pos = Math::fposmod(p_time - pos, (double)anim->get_length()); //seek to loop
} else {
- at_anim_pos = MAX((double)anim->get_length(), p_time - pos); //seek to end
+ at_anim_pos = MIN((double)anim->get_length(), p_time - pos); //seek to end
}
if (player->is_playing() || p_seeked) {
@@ -765,6 +765,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
}
} else {
player->play(anim_name);
+ player->seek(0.0, true);
nc->animation_playing = true;
playing_caches.insert(nc);
}
diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp
index 542011618d..3018fd3ae6 100644
--- a/scene/animation/tween.cpp
+++ b/scene/animation/tween.cpp
@@ -36,6 +36,10 @@ void Tweener::set_tween(Ref<Tween> p_tween) {
tween = p_tween;
}
+void Tweener::clear_tween() {
+ tween.unref();
+}
+
void Tweener::_bind_methods() {
ADD_SIGNAL(MethodInfo("finished"));
}
@@ -53,7 +57,7 @@ void Tween::start_tweeners() {
Ref<PropertyTweener> Tween::tween_property(Object *p_target, NodePath p_property, Variant p_to, float p_duration) {
ERR_FAIL_NULL_V(p_target, nullptr);
- ERR_FAIL_COND_V_MSG(invalid, nullptr, "Tween was created outside the scene tree, can't use Tweeners.");
+ ERR_FAIL_COND_V_MSG(!valid, nullptr, "Tween invalid. Either finished or created outside scene tree.");
ERR_FAIL_COND_V_MSG(started, nullptr, "Can't append to a Tween that has started. Use stop() first.");
Ref<PropertyTweener> tweener = memnew(PropertyTweener(p_target, p_property, p_to, p_duration));
@@ -62,7 +66,7 @@ Ref<PropertyTweener> Tween::tween_property(Object *p_target, NodePath p_property
}
Ref<IntervalTweener> Tween::tween_interval(float p_time) {
- ERR_FAIL_COND_V_MSG(invalid, nullptr, "Tween was created outside the scene tree, can't use Tweeners.");
+ ERR_FAIL_COND_V_MSG(!valid, nullptr, "Tween invalid. Either finished or created outside scene tree.");
ERR_FAIL_COND_V_MSG(started, nullptr, "Can't append to a Tween that has started. Use stop() first.");
Ref<IntervalTweener> tweener = memnew(IntervalTweener(p_time));
@@ -71,7 +75,7 @@ Ref<IntervalTweener> Tween::tween_interval(float p_time) {
}
Ref<CallbackTweener> Tween::tween_callback(Callable p_callback) {
- ERR_FAIL_COND_V_MSG(invalid, nullptr, "Tween was created outside the scene tree, can't use Tweeners.");
+ ERR_FAIL_COND_V_MSG(!valid, nullptr, "Tween invalid. Either finished or created outside scene tree.");
ERR_FAIL_COND_V_MSG(started, nullptr, "Can't append to a Tween that has started. Use stop() first.");
Ref<CallbackTweener> tweener = memnew(CallbackTweener(p_callback));
@@ -80,7 +84,7 @@ Ref<CallbackTweener> Tween::tween_callback(Callable p_callback) {
}
Ref<MethodTweener> Tween::tween_method(Callable p_callback, float p_from, float p_to, float p_duration) {
- ERR_FAIL_COND_V_MSG(invalid, nullptr, "Tween was created outside the scene tree, can't use Tweeners.");
+ ERR_FAIL_COND_V_MSG(!valid, nullptr, "Tween invalid. Either finished or created outside scene tree.");
ERR_FAIL_COND_V_MSG(started, nullptr, "Can't append to a Tween that has started. Use stop() first.");
Ref<MethodTweener> tweener = memnew(MethodTweener(p_callback, p_from, p_to, p_duration));
@@ -88,9 +92,7 @@ Ref<MethodTweener> Tween::tween_method(Callable p_callback, float p_from, float
return tweener;
}
-Ref<Tween> Tween::append(Ref<Tweener> p_tweener) {
- ERR_FAIL_COND_V_MSG(invalid, nullptr, "Tween was created outside the scene tree, can't use Tweeners.");
- ERR_FAIL_COND_V_MSG(started, nullptr, "Can't append to a Tween that has started. Use stop() first.");
+void Tween::append(Ref<Tweener> p_tweener) {
p_tweener->set_tween(this);
if (parallel_enabled) {
@@ -102,8 +104,6 @@ Ref<Tween> Tween::append(Ref<Tweener> p_tweener) {
tweeners.resize(current_step + 1);
tweeners.write[current_step].push_back(p_tweener);
-
- return this;
}
void Tween::stop() {
@@ -117,7 +117,7 @@ void Tween::pause() {
}
void Tween::play() {
- ERR_FAIL_COND_MSG(invalid, "Tween invalid, can't play.");
+ ERR_FAIL_COND_MSG(!valid, "Tween invalid. Either finished or created outside scene tree.");
ERR_FAIL_COND_MSG(dead, "Can't play finished Tween, use stop() first to reset its state.");
running = true;
}
@@ -132,11 +132,22 @@ bool Tween::is_running() {
}
void Tween::set_valid(bool p_valid) {
- invalid = !p_valid;
+ valid = p_valid;
}
bool Tween::is_valid() {
- return invalid;
+ return valid;
+}
+
+void Tween::clear() {
+ valid = false;
+
+ for (List<Ref<Tweener>> &step : tweeners) {
+ for (Ref<Tweener> &tweener : step) {
+ tweener->clear_tween();
+ }
+ }
+ tweeners.clear();
}
Ref<Tween> Tween::bind_node(Node *p_node) {
diff --git a/scene/animation/tween.h b/scene/animation/tween.h
index 947cdb7c2d..953d573539 100644
--- a/scene/animation/tween.h
+++ b/scene/animation/tween.h
@@ -43,6 +43,7 @@ public:
virtual void set_tween(Ref<Tween> p_tween);
virtual void start() = 0;
virtual bool step(float &r_delta) = 0;
+ void clear_tween();
protected:
static void _bind_methods();
@@ -111,7 +112,7 @@ private:
bool started = false;
bool running = true;
bool dead = false;
- bool invalid = true;
+ bool valid = false;
bool default_parallel = false;
bool parallel_enabled = false;
@@ -128,7 +129,7 @@ public:
Ref<IntervalTweener> tween_interval(float p_time);
Ref<CallbackTweener> tween_callback(Callable p_callback);
Ref<MethodTweener> tween_method(Callable p_callback, float p_from, float p_to, float p_duration);
- Ref<Tween> append(Ref<Tweener> p_tweener);
+ void append(Ref<Tweener> p_tweener);
bool custom_step(float p_delta);
void stop();
@@ -139,6 +140,7 @@ public:
bool is_running();
void set_valid(bool p_valid);
bool is_valid();
+ void clear();
Ref<Tween> bind_node(Node *p_node);
Ref<Tween> set_process_mode(TweenProcessMode p_mode);
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index d05762b6c0..e7769f9372 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -654,7 +654,7 @@ void CodeEdit::_backspace_internal() {
// For space indentation we need to do a simple unindent if there are no chars to the left, acting in the
// same way as tabs.
if (indent_using_spaces && cc != 0) {
- if (get_first_non_whitespace_column(cl) > cc) {
+ if (get_first_non_whitespace_column(cl) >= cc) {
prev_column = cc - _calculate_spaces_till_next_left_indent(cc);
prev_line = cl;
}
@@ -987,10 +987,10 @@ void CodeEdit::_new_line(bool p_split_current_line, bool p_above) {
/* No need to move the brace below if we are not taking the text with us. */
if (p_split_current_line) {
brace_indent = true;
- ins += "\n" + ins.substr(1, ins.length() - 2);
+ ins += "\n" + ins.substr(indent_text.size(), ins.length() - 2);
} else {
brace_indent = false;
- ins = "\n" + ins.substr(1, ins.length() - 2);
+ ins = "\n" + ins.substr(indent_text.size(), ins.length() - 2);
}
}
}
@@ -1407,9 +1407,14 @@ void CodeEdit::fold_line(int p_line) {
int in_string = (in_comment == -1) ? is_in_string(p_line) : -1;
if (in_string != -1 || in_comment != -1) {
end_line = get_delimiter_end_position(p_line, get_line(p_line).size() - 1).y;
- /* End line is the same therefore we have a block. */
+ /* End line is the same therefore we have a block of single line delimiters. */
if (end_line == p_line) {
for (int i = p_line + 1; i <= line_count; i++) {
+ if (i == line_count) {
+ end_line = line_count;
+ break;
+ }
+
if ((in_string != -1 && is_in_string(i) == -1) || (in_comment != -1 && is_in_comment(i) == -1)) {
end_line = i - 1;
break;
@@ -1617,7 +1622,8 @@ Point2 CodeEdit::get_delimiter_start_position(int p_line, int p_column) const {
}
/* Region was found on this line and is not a multiline continuation. */
- if (start_position.x != -1 && start_position.x != get_line(p_line).length() + 1) {
+ int line_length = get_line(p_line).length();
+ if (start_position.x != -1 && line_length > 0 && start_position.x != line_length + 1) {
start_position.y = p_line;
return start_position;
}
@@ -1636,7 +1642,8 @@ Point2 CodeEdit::get_delimiter_start_position(int p_line, int p_column) const {
start_position.x = delimiter_cache[i].back()->key();
/* Make sure it's not a multiline continuation. */
- if (start_position.x != get_line(i).length() + 1) {
+ line_length = get_line(i).length();
+ if (line_length > 0 && start_position.x != line_length + 1) {
break;
}
}
@@ -2027,7 +2034,9 @@ String CodeEdit::get_text_for_symbol_lookup() {
void CodeEdit::set_symbol_lookup_word_as_valid(bool p_valid) {
symbol_lookup_word = p_valid ? symbol_lookup_new_word : "";
symbol_lookup_new_word = "";
- _set_symbol_lookup_word(symbol_lookup_word);
+ if (lookup_symbol_word != symbol_lookup_word) {
+ _set_symbol_lookup_word(symbol_lookup_word);
+ }
}
void CodeEdit::_bind_methods() {
@@ -2562,7 +2571,10 @@ int CodeEdit::_is_in_delimiter(int p_line, int p_column, DelimiterType p_type) c
}
void CodeEdit::_add_delimiter(const String &p_start_key, const String &p_end_key, bool p_line_only, DelimiterType p_type) {
- if (p_start_key.length() > 0) {
+ // If we are the editor allow "null" as a valid start key, otherwise users cannot add delimiters via the inspector.
+ if (!(Engine::get_singleton()->is_editor_hint() && p_start_key == "null")) {
+ ERR_FAIL_COND_MSG(p_start_key.is_empty(), "delimiter start key cannot be empty");
+
for (int i = 0; i < p_start_key.length(); i++) {
ERR_FAIL_COND_MSG(!is_symbol(p_start_key[i]), "delimiter must start with a symbol");
}
@@ -2627,7 +2639,11 @@ void CodeEdit::_set_delimiters(const TypedArray<String> &p_delimiters, Delimiter
_clear_delimiters(p_type);
for (int i = 0; i < p_delimiters.size(); i++) {
- String key = p_delimiters[i].is_null() ? "" : p_delimiters[i];
+ String key = p_delimiters[i];
+
+ if (key.is_empty()) {
+ continue;
+ }
const String start_key = key.get_slice(" ", 0);
const String end_key = key.get_slice_count(" ") > 1 ? key.get_slice(" ", 1) : String();
diff --git a/scene/gui/code_edit.h b/scene/gui/code_edit.h
index 4fbb5194e6..740548d559 100644
--- a/scene/gui/code_edit.h
+++ b/scene/gui/code_edit.h
@@ -248,7 +248,6 @@ private:
void _text_changed();
protected:
- void gui_input(const Ref<InputEvent> &p_gui_input) override;
void _notification(int p_what);
static void _bind_methods();
@@ -265,6 +264,7 @@ protected:
public:
/* General overrides */
+ virtual void gui_input(const Ref<InputEvent> &p_gui_input) override;
virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const override;
/* Indent management */
diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp
index cabae9feb2..b9b02b1427 100644
--- a/scene/gui/graph_edit.cpp
+++ b/scene/gui/graph_edit.cpp
@@ -356,16 +356,6 @@ void GraphEdit::_graph_node_raised(Node *p_gn) {
} else {
gn->raise();
}
- int first_not_comment = 0;
- for (int i = 0; i < get_child_count(); i++) {
- GraphNode *gn2 = Object::cast_to<GraphNode>(get_child(i));
- if (gn2 && !gn2->is_comment()) {
- first_not_comment = i;
- break;
- }
- }
-
- move_child(connections_layer, first_not_comment);
emit_signal(SNAME("node_selected"), p_gn);
}
diff --git a/scene/gui/label.cpp b/scene/gui/label.cpp
index 3f87003423..5600816b2d 100644
--- a/scene/gui/label.cpp
+++ b/scene/gui/label.cpp
@@ -227,7 +227,15 @@ void Label::_update_visible() {
}
}
-inline void draw_glyph(const TextServer::Glyph &p_gl, const RID &p_canvas, const Color &p_font_color, const Color &p_font_shadow_color, const Color &p_font_outline_color, const int &p_shadow_outline_size, const int &p_outline_size, const Vector2 &p_ofs, const Vector2 &shadow_ofs) {
+inline void draw_glyph(const TextServer::Glyph &p_gl, const RID &p_canvas, const Color &p_font_color, const Vector2 &p_ofs) {
+ if (p_gl.font_rid != RID()) {
+ TS->font_draw_glyph(p_gl.font_rid, p_canvas, p_gl.font_size, p_ofs + Vector2(p_gl.x_off, p_gl.y_off), p_gl.index, p_font_color);
+ } else {
+ TS->draw_hex_code_box(p_canvas, p_gl.font_size, p_ofs + Vector2(p_gl.x_off, p_gl.y_off), p_gl.index, p_font_color);
+ }
+}
+
+inline void draw_glyph_outline(const TextServer::Glyph &p_gl, const RID &p_canvas, const Color &p_font_color, const Color &p_font_shadow_color, const Color &p_font_outline_color, const int &p_shadow_outline_size, const int &p_outline_size, const Vector2 &p_ofs, const Vector2 &shadow_ofs) {
if (p_gl.font_rid != RID()) {
if (p_font_shadow_color.a > 0) {
TS->font_draw_glyph(p_gl.font_rid, p_canvas, p_gl.font_size, p_ofs + Vector2(p_gl.x_off, p_gl.y_off) + shadow_ofs, p_gl.index, p_font_shadow_color);
@@ -240,9 +248,6 @@ inline void draw_glyph(const TextServer::Glyph &p_gl, const RID &p_canvas, const
if (p_font_outline_color.a != 0.0 && p_outline_size > 0) {
TS->font_draw_glyph_outline(p_gl.font_rid, p_canvas, p_gl.font_size, p_outline_size, p_ofs + Vector2(p_gl.x_off, p_gl.y_off), p_gl.index, p_font_outline_color);
}
- TS->font_draw_glyph(p_gl.font_rid, p_canvas, p_gl.font_size, p_ofs + Vector2(p_gl.x_off, p_gl.y_off), p_gl.index, p_font_color);
- } else {
- TS->draw_hex_code_box(p_canvas, p_gl.font_size, p_ofs + Vector2(p_gl.x_off, p_gl.y_off), p_gl.index, p_font_color);
}
}
@@ -385,12 +390,70 @@ void Label::_notification(int p_what) {
int gl_size = visual.size();
TextServer::TrimData trim_data = TS->shaped_text_get_trim_data(lines_rid[i]);
+ // Draw outline. Note: Do not merge this into the single loop with the main text, to prevent overlaps.
+ if (font_shadow_color.a > 0 || (font_outline_color.a != 0.0 && outline_size > 0)) {
+ Vector2 offset = ofs;
+ // Draw RTL ellipsis string when necessary.
+ if (rtl && trim_data.ellipsis_pos >= 0) {
+ for (int gl_idx = trim_data.ellipsis_glyph_buf.size() - 1; gl_idx >= 0; gl_idx--) {
+ for (int j = 0; j < trim_data.ellipsis_glyph_buf[gl_idx].repeat; j++) {
+ //Draw glyph outlines and shadow.
+ draw_glyph_outline(trim_data.ellipsis_glyph_buf[gl_idx], ci, font_color, font_shadow_color, font_outline_color, shadow_outline_size, outline_size, offset, shadow_ofs);
+ offset.x += trim_data.ellipsis_glyph_buf[gl_idx].advance;
+ }
+ }
+ }
+
+ // Draw main text.
+ for (int j = 0; j < gl_size; j++) {
+ for (int k = 0; k < glyphs[j].repeat; k++) {
+ if (visible_glyphs != -1) {
+ if ((glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) != TextServer::GRAPHEME_IS_VIRTUAL) {
+ if (glyhps_drawn >= visible_glyphs) {
+ return;
+ }
+ }
+ }
+
+ // Trim when necessary.
+ if (trim_data.trim_pos >= 0) {
+ if (rtl) {
+ if (j < trim_data.trim_pos && (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) != TextServer::GRAPHEME_IS_VIRTUAL) {
+ continue;
+ }
+ } else {
+ if (j >= trim_data.trim_pos && (glyphs[j].flags & TextServer::GRAPHEME_IS_VIRTUAL) != TextServer::GRAPHEME_IS_VIRTUAL) {
+ break;
+ }
+ }
+ }
+
+ // Draw glyph outlines and shadow.
+ draw_glyph_outline(glyphs[j], ci, font_color, font_shadow_color, font_outline_color, shadow_outline_size, outline_size, offset, shadow_ofs);
+ offset.x += glyphs[j].advance;
+ glyhps_drawn++;
+ }
+ }
+ // Draw LTR ellipsis string when necessary.
+ if (!rtl && trim_data.ellipsis_pos >= 0) {
+ for (int gl_idx = 0; gl_idx < trim_data.ellipsis_glyph_buf.size(); gl_idx++) {
+ for (int j = 0; j < trim_data.ellipsis_glyph_buf[gl_idx].repeat; j++) {
+ //Draw glyph outlines and shadow.
+ draw_glyph_outline(trim_data.ellipsis_glyph_buf[gl_idx], ci, font_color, font_shadow_color, font_outline_color, shadow_outline_size, outline_size, offset, shadow_ofs);
+ offset.x += trim_data.ellipsis_glyph_buf[gl_idx].advance;
+ }
+ }
+ }
+ }
+
+ // Draw main text. Note: Do not merge this into the single loop with the outline, to prevent overlaps.
+
// Draw RTL ellipsis string when necessary.
if (rtl && trim_data.ellipsis_pos >= 0) {
for (int gl_idx = trim_data.ellipsis_glyph_buf.size() - 1; gl_idx >= 0; gl_idx--) {
for (int j = 0; j < trim_data.ellipsis_glyph_buf[gl_idx].repeat; j++) {
//Draw glyph outlines and shadow.
- draw_glyph(trim_data.ellipsis_glyph_buf[gl_idx], ci, font_color, font_shadow_color, font_outline_color, shadow_outline_size, outline_size, ofs, shadow_ofs);
+ draw_glyph(trim_data.ellipsis_glyph_buf[gl_idx], ci, font_color, ofs);
ofs.x += trim_data.ellipsis_glyph_buf[gl_idx].advance;
}
}
@@ -421,7 +484,7 @@ void Label::_notification(int p_what) {
}
// Draw glyph outlines and shadow.
- draw_glyph(glyphs[j], ci, font_color, font_shadow_color, font_outline_color, shadow_outline_size, outline_size, ofs, shadow_ofs);
+ draw_glyph(glyphs[j], ci, font_color, ofs);
ofs.x += glyphs[j].advance;
glyhps_drawn++;
}
@@ -431,7 +494,7 @@ void Label::_notification(int p_what) {
for (int gl_idx = 0; gl_idx < trim_data.ellipsis_glyph_buf.size(); gl_idx++) {
for (int j = 0; j < trim_data.ellipsis_glyph_buf[gl_idx].repeat; j++) {
//Draw glyph outlines and shadow.
- draw_glyph(trim_data.ellipsis_glyph_buf[gl_idx], ci, font_color, font_shadow_color, font_outline_color, shadow_outline_size, outline_size, ofs, shadow_ofs);
+ draw_glyph(trim_data.ellipsis_glyph_buf[gl_idx], ci, font_color, ofs);
ofs.x += trim_data.ellipsis_glyph_buf[gl_idx].advance;
}
}
diff --git a/scene/gui/option_button.h b/scene/gui/option_button.h
index d846e395ad..953337ecce 100644
--- a/scene/gui/option_button.h
+++ b/scene/gui/option_button.h
@@ -56,6 +56,10 @@ protected:
static void _bind_methods();
public:
+ // ATTENTION: This is used by the POT generator's scene parser. If the number of properties returned by `_get_items()` ever changes,
+ // this value should be updated to reflect the new size.
+ static const int ITEM_PROPERTY_SIZE = 5;
+
void add_icon_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id = -1);
void add_item(const String &p_label, int p_id = -1);
diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h
index 5c427e43bc..428076c6da 100644
--- a/scene/gui/popup_menu.h
+++ b/scene/gui/popup_menu.h
@@ -144,6 +144,10 @@ protected:
static void _bind_methods();
public:
+ // ATTENTION: This is used by the POT generator's scene parser. If the number of properties returned by `_get_items()` ever changes,
+ // this value should be updated to reflect the new size.
+ static const int ITEM_PROPERTY_SIZE = 10;
+
void add_item(const String &p_label, int p_id = -1, uint32_t p_accel = 0);
void add_icon_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id = -1, uint32_t p_accel = 0);
void add_check_item(const String &p_label, int p_id = -1, uint32_t p_accel = 0);
diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp
index aeadfd78ee..562bac60c2 100644
--- a/scene/gui/rich_text_label.cpp
+++ b/scene/gui/rich_text_label.cpp
@@ -366,7 +366,7 @@ void RichTextLabel::_resize_line(ItemFrame *p_frame, int p_line, const Ref<Font>
}
if (p_line > 0) {
- l.offset.y = p_frame->lines[p_line - 1].offset.y + p_frame->lines[p_line - 1].text_buf->get_size().y;
+ l.offset.y = p_frame->lines[p_line - 1].offset.y + p_frame->lines[p_line - 1].text_buf->get_size().y + get_theme_constant(SNAME("line_separation"));
} else {
l.offset.y = 0;
}
@@ -614,7 +614,7 @@ void RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font>
*r_char_offset = l.char_offset + l.char_count;
if (p_line > 0) {
- l.offset.y = p_frame->lines[p_line - 1].offset.y + p_frame->lines[p_line - 1].text_buf->get_size().y;
+ l.offset.y = p_frame->lines[p_line - 1].offset.y + p_frame->lines[p_line - 1].text_buf->get_size().y + get_theme_constant(SNAME("line_separation"));
} else {
l.offset.y = 0;
}
diff --git a/scene/gui/scroll_bar.cpp b/scene/gui/scroll_bar.cpp
index 08bcb0bdda..4edf373fbf 100644
--- a/scene/gui/scroll_bar.cpp
+++ b/scene/gui/scroll_bar.cpp
@@ -80,12 +80,16 @@ void ScrollBar::gui_input(const Ref<InputEvent> &p_event) {
double total = orientation == VERTICAL ? get_size().height : get_size().width;
if (ofs < decr_size) {
+ decr_active = true;
set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
+ update();
return;
}
if (ofs > total - incr_size) {
+ incr_active = true;
set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
+ update();
return;
}
@@ -130,6 +134,8 @@ void ScrollBar::gui_input(const Ref<InputEvent> &p_event) {
}
} else {
+ incr_active = false;
+ decr_active = false;
drag.active = false;
update();
}
@@ -215,8 +221,24 @@ void ScrollBar::_notification(int p_what) {
if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- Ref<Texture2D> decr = highlight == HIGHLIGHT_DECR ? get_theme_icon(SNAME("decrement_highlight")) : get_theme_icon(SNAME("decrement"));
- Ref<Texture2D> incr = highlight == HIGHLIGHT_INCR ? get_theme_icon(SNAME("increment_highlight")) : get_theme_icon(SNAME("increment"));
+ Ref<Texture2D> decr, incr;
+
+ if (decr_active) {
+ decr = get_theme_icon(SNAME("decrement_pressed"));
+ } else if (highlight == HIGHLIGHT_DECR) {
+ decr = get_theme_icon(SNAME("decrement_highlight"));
+ } else {
+ decr = get_theme_icon(SNAME("decrement"));
+ }
+
+ if (incr_active) {
+ incr = get_theme_icon(SNAME("increment_pressed"));
+ } else if (highlight == HIGHLIGHT_INCR) {
+ incr = get_theme_icon(SNAME("increment_highlight"));
+ } else {
+ incr = get_theme_icon(SNAME("increment"));
+ }
+
Ref<StyleBox> bg = has_focus() ? get_theme_stylebox(SNAME("scroll_focus")) : get_theme_stylebox(SNAME("scroll"));
Ref<StyleBox> grabber;
diff --git a/scene/gui/scroll_bar.h b/scene/gui/scroll_bar.h
index fbc035397f..574d17ee20 100644
--- a/scene/gui/scroll_bar.h
+++ b/scene/gui/scroll_bar.h
@@ -51,6 +51,9 @@ class ScrollBar : public Range {
HighlightStatus highlight = HIGHLIGHT_NONE;
+ bool incr_active = false;
+ bool decr_active = false;
+
struct Drag {
bool active = false;
float pos_at_click = 0.0;
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index f64c07df76..06dfc31621 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -2610,10 +2610,10 @@ void TextEdit::set_text(const String &p_text) {
set_caret_column(0);
begin_complex_operation();
+ deselect();
_remove_text(0, 0, MAX(0, get_line_count() - 1), MAX(get_line(MAX(get_line_count() - 1, 0)).size() - 1, 0));
insert_text_at_caret(p_text);
end_complex_operation();
- selection.active = false;
}
set_caret_line(0);
@@ -2731,6 +2731,8 @@ void TextEdit::insert_line_at(int p_at, const String &p_text) {
}
void TextEdit::insert_text_at_caret(const String &p_text) {
+ begin_complex_operation();
+
delete_selection();
int new_column, new_line;
@@ -2740,6 +2742,8 @@ void TextEdit::insert_text_at_caret(const String &p_text) {
set_caret_line(new_line, false);
set_caret_column(new_column);
update();
+
+ end_complex_operation();
}
void TextEdit::remove_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) {
@@ -3024,13 +3028,20 @@ void TextEdit::menu_option(int p_option) {
/* Versioning */
void TextEdit::begin_complex_operation() {
_push_current_op();
- next_operation_is_complex = true;
+ if (complex_operation_count == 0) {
+ next_operation_is_complex = true;
+ }
+ complex_operation_count++;
}
void TextEdit::end_complex_operation() {
_push_current_op();
ERR_FAIL_COND(undo_stack.size() == 0);
+ complex_operation_count = MAX(complex_operation_count - 1, 0);
+ if (complex_operation_count > 0) {
+ return;
+ }
if (undo_stack.back()->get().chain_forward) {
undo_stack.back()->get().chain_forward = false;
return;
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index e996bba983..b1226f2aff 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -304,6 +304,7 @@ private:
bool undo_enabled = true;
int undo_stack_max_size = 50;
+ int complex_operation_count = 0;
bool next_operation_is_complex = false;
TextOperation current_op;
@@ -545,7 +546,6 @@ private:
protected:
void _notification(int p_what);
- virtual void gui_input(const Ref<InputEvent> &p_gui_input) override;
static void _bind_methods();
@@ -594,6 +594,7 @@ protected:
public:
/* General overrides. */
+ virtual void gui_input(const Ref<InputEvent> &p_gui_input) override;
virtual Size2 get_minimum_size() const override;
virtual bool is_text_field() const override;
virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const override;
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index cb990892ed..f62c09925d 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -156,6 +156,7 @@ void TreeItem::set_cell_mode(int p_column, TreeCellMode p_mode) {
c.dirty = true;
c.icon_max_w = 0;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
TreeItem::TreeCellMode TreeItem::get_cell_mode(int p_column) const {
@@ -169,6 +170,7 @@ void TreeItem::set_checked(int p_column, bool p_checked) {
cells.write[p_column].checked = p_checked;
cells.write[p_column].indeterminate = false;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
void TreeItem::set_indeterminate(int p_column, bool p_indeterminate) {
@@ -180,6 +182,7 @@ void TreeItem::set_indeterminate(int p_column, bool p_indeterminate) {
cells.write[p_column].indeterminate = p_indeterminate;
cells.write[p_column].checked = false;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
bool TreeItem::is_checked(int p_column) const {
@@ -212,6 +215,7 @@ void TreeItem::set_text(int p_column, String p_text) {
cells.write[p_column].step = 0;
}
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
String TreeItem::get_text(int p_column) const {
@@ -227,6 +231,7 @@ void TreeItem::set_text_direction(int p_column, Control::TextDirection p_text_di
cells.write[p_column].dirty = true;
_changed_notify(p_column);
}
+ cached_minimum_size_dirty = true;
}
Control::TextDirection TreeItem::get_text_direction(int p_column) const {
@@ -239,6 +244,7 @@ void TreeItem::clear_opentype_features(int p_column) {
cells.write[p_column].opentype_features.clear();
cells.write[p_column].dirty = true;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
void TreeItem::set_opentype_feature(int p_column, const String &p_name, int p_value) {
@@ -248,6 +254,7 @@ void TreeItem::set_opentype_feature(int p_column, const String &p_name, int p_va
cells.write[p_column].opentype_features[tag] = p_value;
cells.write[p_column].dirty = true;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
}
@@ -266,6 +273,7 @@ void TreeItem::set_structured_text_bidi_override(int p_column, Control::Structur
cells.write[p_column].st_parser = p_parser;
cells.write[p_column].dirty = true;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
}
@@ -279,6 +287,7 @@ void TreeItem::set_structured_text_bidi_override_options(int p_column, Array p_a
cells.write[p_column].st_args = p_args;
cells.write[p_column].dirty = true;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
Array TreeItem::get_structured_text_bidi_override_options(int p_column) const {
@@ -292,6 +301,7 @@ void TreeItem::set_language(int p_column, const String &p_language) {
cells.write[p_column].language = p_language;
cells.write[p_column].dirty = true;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
}
@@ -305,6 +315,7 @@ void TreeItem::set_suffix(int p_column, String p_suffix) {
cells.write[p_column].suffix = p_suffix;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
String TreeItem::get_suffix(int p_column) const {
@@ -316,6 +327,7 @@ void TreeItem::set_icon(int p_column, const Ref<Texture2D> &p_icon) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].icon = p_icon;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
Ref<Texture2D> TreeItem::get_icon(int p_column) const {
@@ -327,6 +339,7 @@ void TreeItem::set_icon_region(int p_column, const Rect2 &p_icon_region) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].icon_region = p_icon_region;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
Rect2 TreeItem::get_icon_region(int p_column) const {
@@ -349,6 +362,7 @@ void TreeItem::set_icon_max_width(int p_column, int p_max) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].icon_max_w = p_max;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
int TreeItem::get_icon_max_width(int p_column) const {
@@ -461,6 +475,7 @@ void TreeItem::uncollapse_tree() {
void TreeItem::set_custom_minimum_height(int p_height) {
custom_min_height = p_height;
_changed_notify();
+ cached_minimum_size_dirty = true;
}
int TreeItem::get_custom_minimum_height() const {
@@ -785,6 +800,7 @@ void TreeItem::add_button(int p_column, const Ref<Texture2D> &p_button, int p_id
button.tooltip = p_tooltip;
cells.write[p_column].buttons.push_back(button);
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
int TreeItem::get_button_count(int p_column) const {
@@ -828,6 +844,7 @@ void TreeItem::set_button(int p_column, int p_idx, const Ref<Texture2D> &p_butto
ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
cells.write[p_column].buttons.write[p_idx].texture = p_button;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
void TreeItem::set_button_color(int p_column, int p_idx, const Color &p_color) {
@@ -843,6 +860,7 @@ void TreeItem::set_button_disabled(int p_column, int p_idx, bool p_disabled) {
cells.write[p_column].buttons.write[p_idx].disabled = p_disabled;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
bool TreeItem::is_button_disabled(int p_column, int p_idx) const {
@@ -856,6 +874,7 @@ void TreeItem::set_editable(int p_column, bool p_editable) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].editable = p_editable;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
bool TreeItem::is_editable(int p_column) {
@@ -888,6 +907,7 @@ void TreeItem::clear_custom_color(int p_column) {
void TreeItem::set_custom_font(int p_column, const Ref<Font> &p_font) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].custom_font = p_font;
+ cached_minimum_size_dirty = true;
}
Ref<Font> TreeItem::get_custom_font(int p_column) const {
@@ -898,6 +918,7 @@ Ref<Font> TreeItem::get_custom_font(int p_column) const {
void TreeItem::set_custom_font_size(int p_column, int p_font_size) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].custom_font_size = p_font_size;
+ cached_minimum_size_dirty = true;
}
int TreeItem::get_custom_font_size(int p_column) const {
@@ -941,6 +962,7 @@ Color TreeItem::get_custom_bg_color(int p_column) const {
void TreeItem::set_custom_as_button(int p_column, bool p_button) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].custom_button = p_button;
+ cached_minimum_size_dirty = true;
}
bool TreeItem::is_custom_set_as_button(int p_column) const {
@@ -952,6 +974,7 @@ void TreeItem::set_text_align(int p_column, TextAlign p_align) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].text_align = p_align;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
TreeItem::TextAlign TreeItem::get_text_align(int p_column) const {
@@ -963,6 +986,7 @@ void TreeItem::set_expand_right(int p_column, bool p_enable) {
ERR_FAIL_INDEX(p_column, cells.size());
cells.write[p_column].expand_right = p_enable;
_changed_notify(p_column);
+ cached_minimum_size_dirty = true;
}
bool TreeItem::get_expand_right(int p_column) const {
@@ -973,6 +997,7 @@ bool TreeItem::get_expand_right(int p_column) const {
void TreeItem::set_disable_folding(bool p_disable) {
disable_folding = p_disable;
_changed_notify(0);
+ cached_minimum_size_dirty = true;
}
bool TreeItem::is_folding_disabled() const {
@@ -984,49 +1009,54 @@ Size2 TreeItem::get_minimum_size(int p_column) {
Tree *tree = get_tree();
ERR_FAIL_COND_V(!tree, Size2());
- Size2 size;
+ if (cached_minimum_size_dirty) {
+ Size2 size;
- // Default offset?
- //size.width += (disable_folding || tree->hide_folding) ? tree->cache.hseparation : tree->cache.item_margin;
+ // Default offset?
+ //size.width += (disable_folding || tree->hide_folding) ? tree->cache.hseparation : tree->cache.item_margin;
- // Text.
- const TreeItem::Cell &cell = cells[p_column];
- if (!cell.text.is_empty()) {
- if (cell.dirty) {
- tree->update_item_cell(this, p_column);
+ // Text.
+ const TreeItem::Cell &cell = cells[p_column];
+ if (!cell.text.is_empty()) {
+ if (cell.dirty) {
+ tree->update_item_cell(this, p_column);
+ }
+ Size2 text_size = cell.text_buf->get_size();
+ size.width += text_size.width;
+ size.height = MAX(size.height, text_size.height);
}
- Size2 text_size = cell.text_buf->get_size();
- size.width += text_size.width;
- size.height = MAX(size.height, text_size.height);
- }
- // Icon.
- if (cell.mode == CELL_MODE_CHECK) {
- size.width += tree->cache.checked->get_width() + tree->cache.hseparation;
- }
- if (cell.icon.is_valid()) {
- Size2i icon_size = cell.get_icon_size();
- if (cell.icon_max_w > 0 && icon_size.width > cell.icon_max_w) {
- icon_size.width = cell.icon_max_w;
+ // Icon.
+ if (cell.mode == CELL_MODE_CHECK) {
+ size.width += tree->cache.checked->get_width() + tree->cache.hseparation;
+ }
+ if (cell.icon.is_valid()) {
+ Size2i icon_size = cell.get_icon_size();
+ if (cell.icon_max_w > 0 && icon_size.width > cell.icon_max_w) {
+ icon_size.width = cell.icon_max_w;
+ }
+ size.width += icon_size.width + tree->cache.hseparation;
+ size.height = MAX(size.height, icon_size.height);
}
- size.width += icon_size.width + tree->cache.hseparation;
- size.height = MAX(size.height, icon_size.height);
- }
- // Buttons.
- for (int i = 0; i < cell.buttons.size(); i++) {
- Ref<Texture2D> texture = cell.buttons[i].texture;
- if (texture.is_valid()) {
- Size2 button_size = texture->get_size() + tree->cache.button_pressed->get_minimum_size();
- size.width += button_size.width;
- size.height = MAX(size.height, button_size.height);
+ // Buttons.
+ for (int i = 0; i < cell.buttons.size(); i++) {
+ Ref<Texture2D> texture = cell.buttons[i].texture;
+ if (texture.is_valid()) {
+ Size2 button_size = texture->get_size() + tree->cache.button_pressed->get_minimum_size();
+ size.width += button_size.width;
+ size.height = MAX(size.height, button_size.height);
+ }
}
- }
- if (cell.buttons.size() >= 2) {
- size.width += (cell.buttons.size() - 1) * tree->cache.button_margin;
+ if (cell.buttons.size() >= 2) {
+ size.width += (cell.buttons.size() - 1) * tree->cache.button_margin;
+ }
+
+ cached_minimum_size = size;
+ cached_minimum_size_dirty = false;
}
- return size;
+ return cached_minimum_size;
}
Variant TreeItem::_call_recursive_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
@@ -1307,6 +1337,10 @@ void Tree::update_cache() {
cache.title_button_color = get_theme_color(SNAME("title_button_color"));
v_scroll->set_custom_step(cache.font->get_height(cache.font_size));
+
+ for (TreeItem *item = get_root(); item; item = item->get_next()) {
+ item->cached_minimum_size_dirty = true;
+ }
}
int Tree::compute_item_height(TreeItem *p_item) const {
@@ -2339,13 +2373,22 @@ int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, int
cache.click_type = Cache::CLICK_NONE;
return -1;
}
+
+ // Make sure the click is correct.
+ Point2 click_pos = get_global_mouse_position() - get_global_position();
+ if (!get_item_at_position(click_pos)) {
+ pressed_button = -1;
+ cache.click_type = Cache::CLICK_NONE;
+ return -1;
+ }
+
pressed_button = j;
cache.click_type = Cache::CLICK_BUTTON;
cache.click_index = j;
cache.click_id = c.buttons[j].id;
cache.click_item = p_item;
cache.click_column = col;
- cache.click_pos = get_global_mouse_position() - get_global_position();
+ cache.click_pos = click_pos;
update();
//emit_signal(SNAME("button_pressed"));
return -1;
diff --git a/scene/gui/tree.h b/scene/gui/tree.h
index 8b7ddc3faf..85fed941dc 100644
--- a/scene/gui/tree.h
+++ b/scene/gui/tree.h
@@ -130,6 +130,9 @@ private:
bool disable_folding = false;
int custom_min_height = 0;
+ Size2i cached_minimum_size;
+ bool cached_minimum_size_dirty = true;
+
TreeItem *parent = nullptr; // parent item
TreeItem *prev = nullptr; // previous in list
TreeItem *next = nullptr; // next in list
diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp
index 8260d0dff5..e1b1b356a9 100644
--- a/scene/main/scene_tree.cpp
+++ b/scene/main/scene_tree.cpp
@@ -544,7 +544,7 @@ void SceneTree::process_tweens(float p_delta, bool p_physics) {
}
if (!E->get()->step(p_delta)) {
- E->get()->set_valid(false);
+ E->get()->clear();
tweens.erase(E);
}
if (E == L) {
@@ -858,15 +858,6 @@ void SceneTree::_notify_group_pause(const StringName &p_group, int p_notificatio
}
}
-/*
-void SceneMainLoop::_update_listener_2d() {
- if (listener_2d.is_valid()) {
- SpatialSound2DServer::get_singleton()->listener_set_space( listener_2d, world_2d->get_sound_space() );
- }
-}
-
-*/
-
void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_call_type, const Ref<InputEvent> &p_input, Viewport *p_viewport) {
Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E) {
@@ -1346,7 +1337,7 @@ SceneTree::SceneTree() {
current_scene = nullptr;
const int msaa_mode = GLOBAL_DEF("rendering/anti_aliasing/quality/msaa", 0);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/quality/msaa", PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Fast),4× (Average),8× (Slow),16× (Slower)")));
+ ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/quality/msaa", PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")));
root->set_msaa(Viewport::MSAA(msaa_mode));
const int ssaa_mode = GLOBAL_DEF("rendering/anti_aliasing/quality/screen_space_aa", 0);
diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp
index 8ec8c193fb..fb86d37280 100644
--- a/scene/main/viewport.cpp
+++ b/scene/main/viewport.cpp
@@ -37,6 +37,7 @@
#include "core/templates/pair.h"
#include "scene/2d/camera_2d.h"
#include "scene/2d/collision_object_2d.h"
+#include "scene/2d/listener_2d.h"
#ifndef _3D_DISABLED
#include "scene/3d/camera_3d.h"
#include "scene/3d/collision_object_3d.h"
@@ -80,7 +81,7 @@ void ViewportTexture::setup_local_to_scene() {
RS::get_singleton()->texture_proxy_update(proxy, vp->texture_rid);
RS::get_singleton()->free(proxy_ph);
} else {
- ERR_FAIL_COND(proxy.is_valid()); //should be invalid
+ ERR_FAIL_COND(proxy.is_valid()); // Should be invalid.
proxy = RS::get_singleton()->texture_proxy_create(vp->texture_rid);
}
}
@@ -117,7 +118,6 @@ Size2 ViewportTexture::get_size() const {
}
RID ViewportTexture::get_rid() const {
- //ERR_FAIL_COND_V_MSG(!vp, RID(), "Viewport Texture must be set to use it.");
if (proxy.is_null()) {
proxy_ph = RS::get_singleton()->texture_2d_placeholder_create();
proxy = RS::get_singleton()->texture_proxy_create(proxy_ph);
@@ -262,7 +262,7 @@ void Viewport::_sub_window_update(Window *p_window) {
void Viewport::_sub_window_grab_focus(Window *p_window) {
if (p_window == nullptr) {
- //release current focus
+ // Release current focus.
if (gui.subwindow_focused) {
gui.subwindow_focused->_event_callback(DisplayServer::WINDOW_EVENT_FOCUS_OUT);
gui.subwindow_focused = nullptr;
@@ -288,18 +288,18 @@ void Viewport::_sub_window_grab_focus(Window *p_window) {
ERR_FAIL_COND(index == -1);
if (p_window->get_flag(Window::FLAG_NO_FOCUS)) {
- //can only move to foreground, but no focus granted
+ // Can only move to foreground, but no focus granted.
SubWindow sw = gui.sub_windows[index];
gui.sub_windows.remove(index);
gui.sub_windows.push_back(sw);
index = gui.sub_windows.size() - 1;
_sub_window_update_order();
- return; //i guess not...
+ return;
}
if (gui.subwindow_focused) {
if (gui.subwindow_focused == p_window) {
- return; //nothing to do
+ return; // Nothing to do.
}
gui.subwindow_focused->_event_callback(DisplayServer::WINDOW_EVENT_FOCUS_OUT);
gui.subwindow_drag = SUB_WINDOW_DRAG_DISABLED;
@@ -316,7 +316,7 @@ void Viewport::_sub_window_grab_focus(Window *p_window) {
gui.subwindow_focused->_event_callback(DisplayServer::WINDOW_EVENT_FOCUS_IN);
- { //move to foreground
+ { // Move to foreground.
SubWindow sw = gui.sub_windows[index];
gui.sub_windows.remove(index);
gui.sub_windows.push_back(sw);
@@ -422,7 +422,7 @@ void Viewport::_notification(int p_what) {
}
if (camera_3d_set.size() && !camera_3d) {
- //there are cameras but no current camera, pick first in tree and make it current
+ // There are cameras but no current camera, pick first in tree and make it current.
Camera3D *first = nullptr;
for (Set<Camera3D *>::Element *E = camera_3d_set.front(); E; E = E->next()) {
if (first == nullptr || first->is_greater_than(E->get())) {
@@ -521,8 +521,9 @@ void Viewport::_process_picking() {
PhysicsDirectSpaceState2D *ss2d = PhysicsServer2D::get_singleton()->space_get_direct_state(find_world_2d()->get_space());
if (physics_has_last_mousepos) {
- // if no mouse event exists, create a motion one. This is necessary because objects or camera may have moved.
- // while this extra event is sent, it is checked if both camera and last object and last ID did not move. If nothing changed, the event is discarded to avoid flooding with unnecessary motion events every frame
+ // If no mouse event exists, create a motion one. This is necessary because objects or camera may have moved.
+ // While this extra event is sent, it is checked if both camera and last object and last ID did not move.
+ // If nothing changed, the event is discarded to avoid flooding with unnecessary motion events every frame.
bool has_mouse_event = false;
for (const Ref<InputEvent> &m : physics_picking_events) {
if (m.is_valid()) {
@@ -596,7 +597,7 @@ void Viewport::_process_picking() {
Ref<InputEventKey> k = ev;
if (k.is_valid()) {
- //only for mask
+ // Only for mask.
physics_last_mouse_state.alt = k->is_alt_pressed();
physics_last_mouse_state.shift = k->is_shift_pressed();
physics_last_mouse_state.control = k->is_ctrl_pressed();
@@ -617,7 +618,7 @@ void Viewport::_process_picking() {
}
if (ss2d) {
- //send to 2D
+ // Send to 2D.
uint64_t frame = get_tree()->get_frame();
@@ -626,11 +627,11 @@ void Viewport::_process_picking() {
Transform2D canvas_transform;
ObjectID canvas_layer_id;
if (E->get()) {
- // A descendant CanvasLayer
+ // A descendant CanvasLayer.
canvas_transform = E->get()->get_transform();
canvas_layer_id = E->get()->get_instance_id();
} else {
- // This Viewport's builtin canvas
+ // This Viewport's builtin canvas.
canvas_transform = get_canvas_transform();
canvas_layer_id = ObjectID();
}
@@ -650,7 +651,7 @@ void Viewport::_process_picking() {
co->_mouse_enter();
} else {
F->get() = frame;
- // It was already hovered, so don't send the event if it's faked
+ // It was already hovered, so don't send the event if it's faked.
if (mm.is_valid() && mm->get_device() == InputEvent::DEVICE_ID_INTERNAL) {
send_event = false;
}
@@ -699,11 +700,11 @@ void Viewport::_process_picking() {
}
if (captured) {
- //none
+ // None.
} else if (pos == last_pos) {
if (last_id.is_valid()) {
if (ObjectDB::get_instance(last_id) && last_object) {
- //good, exists
+ // Good, exists.
_collision_object_3d_input_event(last_object, camera_3d, ev, result.position, result.normal, result.shape);
if (last_object->get_capture_input_on_drag() && mb.is_valid() && mb->get_button_index() == 1 && mb->is_pressed()) {
physics_object_capture = last_id;
@@ -822,7 +823,9 @@ Rect2 Viewport::get_visible_rect() const {
}
void Viewport::_update_listener_2d() {
- AudioServer::get_singleton()->notify_listener_changed();
+ if (AudioServer::get_singleton()) {
+ AudioServer::get_singleton()->notify_listener_changed();
+ }
}
void Viewport::set_as_audio_listener_2d(bool p_enable) {
@@ -831,7 +834,6 @@ void Viewport::set_as_audio_listener_2d(bool p_enable) {
}
audio_listener_2d = p_enable;
-
_update_listener_2d();
}
@@ -839,6 +841,10 @@ bool Viewport::is_audio_listener_2d() const {
return audio_listener_2d;
}
+Listener2D *Viewport::get_listener_2d() const {
+ return listener_2d;
+}
+
void Viewport::enable_canvas_transform_override(bool p_enable) {
if (override_canvas_transform == p_enable) {
return;
@@ -903,6 +909,21 @@ void Viewport::_camera_2d_set(Camera2D *p_camera_2d) {
camera_2d = p_camera_2d;
}
+void Viewport::_listener_2d_set(Listener2D *p_listener) {
+ if (listener_2d == p_listener) {
+ return;
+ } else if (listener_2d) {
+ listener_2d->clear_current();
+ }
+ listener_2d = p_listener;
+}
+
+void Viewport::_listener_2d_remove(Listener2D *p_listener) {
+ if (listener_2d == p_listener) {
+ listener_2d = nullptr;
+ }
+}
+
void Viewport::_canvas_layer_add(CanvasLayer *p_canvas_layer) {
canvas_layers.insert(p_canvas_layer);
}
@@ -1102,7 +1123,7 @@ String Viewport::_gui_get_tooltip(Control *p_control, const Vector2 &p_pos, Cont
while (p_control) {
tooltip = p_control->get_tooltip(pos);
- //Temporary solution for PopupMenus
+ // Temporary solution for PopupMenus.
PopupMenu *menu = Object::cast_to<PopupMenu>(this);
if (menu) {
tooltip = menu->get_tooltip(pos);
@@ -1216,11 +1237,9 @@ void Viewport::_gui_show_tooltip() {
}
void Viewport::_gui_call_input(Control *p_control, const Ref<InputEvent> &p_input) {
- //_block();
-
Ref<InputEvent> ev = p_input;
- //mouse wheel events can't be stopped
+ // Mouse wheel events can't be stopped.
Ref<InputEventMouseButton> mb = p_input;
bool cant_stop_me_now = (mb.is_valid() &&
@@ -1256,11 +1275,9 @@ void Viewport::_gui_call_input(Control *p_control, const Ref<InputEvent> &p_inpu
break;
}
- ev = ev->xformed_by(ci->get_transform()); //transform event upwards
+ ev = ev->xformed_by(ci->get_transform()); // Transform event upwards.
ci = ci->get_parent_item();
}
-
- //_unblock();
}
void Viewport::_gui_call_notification(Control *p_control, int p_what) {
@@ -1290,12 +1307,10 @@ void Viewport::_gui_call_notification(Control *p_control, int p_what) {
ci = ci->get_parent_item();
}
-
- //_unblock();
}
Control *Viewport::gui_find_control(const Point2 &p_global) {
- //aca va subwindows
+ // Handle subwindows.
_gui_sort_roots();
for (List<Control *>::Element *E = gui.roots.back(); E; E = E->prev()) {
@@ -1327,8 +1342,7 @@ Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_
}
if (!p_node->is_visible()) {
- //return _find_next_visible_control_at_pos(p_node,p_global,r_inv_xform);
- return nullptr; //canvas item hidden, discard
+ return nullptr; // Canvas item hidden, discard.
}
Transform2D matrix = p_xform * p_node->get_transform();
@@ -1372,32 +1386,31 @@ Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_
}
bool Viewport::_gui_drop(Control *p_at_control, Point2 p_at_pos, bool p_just_check) {
- { //attempt grab, try parent controls too
- CanvasItem *ci = p_at_control;
- while (ci) {
- Control *control = Object::cast_to<Control>(ci);
- if (control) {
- if (control->can_drop_data(p_at_pos, gui.drag_data)) {
- if (!p_just_check) {
- control->drop_data(p_at_pos, gui.drag_data);
- }
-
- return true;
+ // Attempt grab, try parent controls too.
+ CanvasItem *ci = p_at_control;
+ while (ci) {
+ Control *control = Object::cast_to<Control>(ci);
+ if (control) {
+ if (control->can_drop_data(p_at_pos, gui.drag_data)) {
+ if (!p_just_check) {
+ control->drop_data(p_at_pos, gui.drag_data);
}
- if (control->data.mouse_filter == Control::MOUSE_FILTER_STOP) {
- break;
- }
+ return true;
}
- p_at_pos = ci->get_transform().xform(p_at_pos);
-
- if (ci->is_set_as_top_level()) {
+ if (control->data.mouse_filter == Control::MOUSE_FILTER_STOP) {
break;
}
+ }
+
+ p_at_pos = ci->get_transform().xform(p_at_pos);
- ci = ci->get_parent_item();
+ if (ci->is_set_as_top_level()) {
+ break;
}
+
+ ci = ci->get_parent_item();
}
return false;
@@ -1417,23 +1430,9 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
if (mb->is_pressed()) {
Size2 pos = mpos;
if (gui.mouse_focus_mask) {
- //do not steal mouse focus and stuff while a focus mask exists
- gui.mouse_focus_mask |= 1 << (mb->get_button_index() - 1); //add the button to the mask
+ // Do not steal mouse focus and stuff while a focus mask exists.
+ gui.mouse_focus_mask |= 1 << (mb->get_button_index() - 1); // Add the button to the mask.
} else {
- bool is_handled = false;
-
- if (is_handled) {
- set_input_as_handled();
- return;
- }
-
- //Matrix32 parent_xform;
-
- /*
- if (data.parent_canvas_item)
- parent_xform=data.parent_canvas_item->get_global_transform();
- */
-
gui.mouse_focus = gui_find_control(pos);
gui.last_mouse_focus = gui.mouse_focus;
@@ -1450,7 +1449,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
}
- mb = mb->xformed_by(Transform2D()); // make a copy of the event
+ mb = mb->xformed_by(Transform2D()); // Make a copy of the event.
mb->set_global_position(pos);
@@ -1467,7 +1466,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
#endif
- if (mb->get_button_index() == MOUSE_BUTTON_LEFT) { //assign focus
+ if (mb->get_button_index() == MOUSE_BUTTON_LEFT) { // Assign focus.
CanvasItem *ci = gui.mouse_focus;
while (ci) {
Control *control = Object::cast_to<Control>(ci);
@@ -1499,7 +1498,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
set_input_as_handled();
if (gui.drag_data.get_type() != Variant::NIL && mb->get_button_index() == MOUSE_BUTTON_LEFT) {
- //alternate drop use (when using force_drag(), as proposed by #5342
+ // Alternate drop use (when using force_drag(), as proposed by #5342).
if (gui.mouse_focus) {
_gui_drop(gui.mouse_focus, pos, false);
}
@@ -1513,7 +1512,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
gui.drag_preview_id = ObjectID();
}
_propagate_viewport_notification(this, NOTIFICATION_DRAG_END);
- //change mouse accordingly
+ // Change mouse accordingly.
}
_gui_cancel_tooltip();
@@ -1533,26 +1532,28 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
gui.dragging = false;
gui.drag_mouse_over = nullptr;
_propagate_viewport_notification(this, NOTIFICATION_DRAG_END);
- //change mouse accordingly
+ // Change mouse accordingly.
}
- gui.mouse_focus_mask &= ~(1 << (mb->get_button_index() - 1)); //remove from mask
+ gui.mouse_focus_mask &= ~(1 << (mb->get_button_index() - 1)); // Remove from mask.
if (!gui.mouse_focus) {
- //release event is only sent if a mouse focus (previously pressed button) exists
+ // Release event is only sent if a mouse focus (previously pressed button) exists.
return;
}
Size2 pos = mpos;
- mb = mb->xformed_by(Transform2D()); //make a copy
+ mb = mb->xformed_by(Transform2D()); // Make a copy.
mb->set_global_position(pos);
pos = gui.focus_inv_xform.xform(pos);
mb->set_position(pos);
Control *mouse_focus = gui.mouse_focus;
- //disable mouse focus if needed before calling input, this makes popups on mouse press event work better, as the release will never be received otherwise
+ // Disable mouse focus if needed before calling input,
+ // this makes popups on mouse press event work better,
+ // as the release will never be received otherwise.
if (gui.mouse_focus_mask == 0) {
gui.mouse_focus = nullptr;
gui.forced_mouse_focus = false;
@@ -1562,11 +1563,6 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
_gui_call_input(mouse_focus, mb);
}
- /*if (gui.drag_data.get_type()!=Variant::NIL && mb->get_button_index()==MOUSE_BUTTON_LEFT) {
- _propagate_viewport_notification(this,NOTIFICATION_DRAG_END);
- gui.drag_data=Variant(); //always clear
- }*/
-
// In case the mouse was released after for example dragging a scrollbar,
// check whether the current control is different from the stored one. If
// it is different, rather than wait for it to be updated the next time the
@@ -1605,12 +1601,12 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Control *over = nullptr;
- // D&D
+ // Drag & drop.
if (!gui.drag_attempted && gui.mouse_focus && mm->get_button_mask() & MOUSE_BUTTON_MASK_LEFT) {
gui.drag_accum += mm->get_relative();
float len = gui.drag_accum.length();
if (len > 10) {
- { //attempt grab, try parent controls too
+ { // Attempt grab, try parent controls too.
CanvasItem *ci = gui.mouse_focus;
while (ci) {
Control *control = Object::cast_to<Control>(ci);
@@ -1683,14 +1679,14 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Vector2 speed = localizer.basis_xform(mm->get_speed());
Vector2 rel = localizer.basis_xform(mm->get_relative());
- mm = mm->xformed_by(Transform2D()); //make a copy
+ mm = mm->xformed_by(Transform2D()); // Make a copy.
mm->set_global_position(mpos);
mm->set_speed(speed);
mm->set_relative(rel);
if (mm->get_button_mask() == 0) {
- //nothing pressed
+ // Nothing pressed.
bool can_tooltip = true;
@@ -1714,7 +1710,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
is_tooltip_shown = true;
}
} else {
- is_tooltip_shown = true; //well, nothing to compare against, likely using custom control, so if it changes there is nothing we can do
+ is_tooltip_shown = true; // Nothing to compare against, likely using custom control, so if it changes there is nothing we can do.
}
}
} else {
@@ -1771,7 +1767,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
if (gui.drag_data.get_type() != Variant::NIL) {
- //handle dragandrop
+ // Handle drag & drop.
Control *drag_preview = _gui_get_drag_preview();
if (drag_preview) {
@@ -1781,9 +1777,8 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
gui.drag_mouse_over = over;
gui.drag_mouse_over_pos = Vector2();
- //find the window this is above of
-
- //see if there is an embedder
+ // Find the window this is above of.
+ // See if there is an embedder.
Viewport *embedder = nullptr;
Vector2 viewport_pos;
@@ -1791,7 +1786,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
embedder = this;
viewport_pos = mpos;
} else {
- //not an embedder, but may be a subwindow of an embedder
+ // Not an embedder, but may be a subwindow of an embedder.
Window *w = Object::cast_to<Window>(this);
if (w) {
if (w->is_embedded()) {
@@ -1799,7 +1794,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Transform2D ai = (get_final_transform().affine_inverse() * _get_input_pre_xform()).affine_inverse();
- viewport_pos = ai.xform(mpos) + w->get_position(); //to parent coords
+ viewport_pos = ai.xform(mpos) + w->get_position(); // To parent coords.
}
}
}
@@ -1807,7 +1802,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Viewport *viewport_under = nullptr;
if (embedder) {
- //use embedder logic
+ // Use embedder logic.
for (int i = embedder->gui.sub_windows.size() - 1; i >= 0; i--) {
Window *sw = embedder->gui.sub_windows[i].window;
@@ -1825,11 +1820,11 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
if (!viewport_under) {
- //not in a subwindow, likely in embedder
+ // Not in a subwindow, likely in embedder.
viewport_under = embedder;
}
} else {
- //use displayserver logic
+ // Use DisplayServer logic.
Vector2i screen_mouse_pos = DisplayServer::get_singleton()->mouse_get_position();
DisplayServer::WindowID window_id = DisplayServer::get_singleton()->get_window_at_screen_position(screen_mouse_pos);
@@ -1837,7 +1832,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
if (window_id != DisplayServer::INVALID_WINDOW_ID) {
ObjectID object_under = DisplayServer::get_singleton()->window_get_attached_instance_id(window_id);
- if (object_under != ObjectID()) { //fetch window
+ if (object_under != ObjectID()) { // Fetch window.
Window *w = Object::cast_to<Window>(ObjectDB::get_instance(object_under));
if (w) {
viewport_under = w;
@@ -1850,7 +1845,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
if (viewport_under) {
Transform2D ai = (viewport_under->get_final_transform().affine_inverse() * viewport_under->_get_input_pre_xform());
viewport_pos = ai.xform(viewport_pos);
- //find control under at pos
+ // Find control under at position.
gui.drag_mouse_over = viewport_under->gui_find_control(viewport_pos);
if (gui.drag_mouse_over) {
Transform2D localizer = gui.drag_mouse_over->get_global_transform_with_canvas().affine_inverse();
@@ -1882,7 +1877,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Control *over = gui_find_control(pos);
if (over) {
if (over->can_process()) {
- touch_event = touch_event->xformed_by(Transform2D()); //make a copy
+ touch_event = touch_event->xformed_by(Transform2D()); // Make a copy.
if (over == gui.mouse_focus) {
pos = gui.focus_inv_xform.xform(pos);
} else {
@@ -1896,7 +1891,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
} else if (touch_event->get_index() == 0 && gui.last_mouse_focus) {
if (gui.last_mouse_focus->can_process()) {
- touch_event = touch_event->xformed_by(Transform2D()); //make a copy
+ touch_event = touch_event->xformed_by(Transform2D()); // Make a copy.
touch_event->set_position(gui.focus_inv_xform.xform(pos));
_gui_call_input(gui.last_mouse_focus, touch_event);
@@ -1917,7 +1912,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Control *over = gui_find_control(pos);
if (over) {
if (over->can_process()) {
- gesture_event = gesture_event->xformed_by(Transform2D()); //make a copy
+ gesture_event = gesture_event->xformed_by(Transform2D()); // Make a copy.
if (over == gui.mouse_focus) {
pos = gui.focus_inv_xform.xform(pos);
} else {
@@ -1944,7 +1939,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Vector2 speed = localizer.basis_xform(drag_event->get_speed());
Vector2 rel = localizer.basis_xform(drag_event->get_relative());
- drag_event = drag_event->xformed_by(Transform2D()); //make a copy
+ drag_event = drag_event->xformed_by(Transform2D()); // Make a copy.
drag_event->set_speed(speed);
drag_event->set_relative(rel);
@@ -1975,12 +1970,11 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
}
- Control *from = gui.key_focus ? gui.key_focus : nullptr; //hmm
+ Control *from = gui.key_focus ? gui.key_focus : nullptr;
- //keyboard focus
- //if (from && p_event->is_pressed() && !p_event->is_alt_pressed() && !p_event->is_meta_pressed() && !p_event->key->is_command_pressed()) {
+ // Keyboard focus.
Ref<InputEventKey> k = p_event;
- //need to check for mods, otherwise any combination of alt/ctrl/shift+<up/down/left/right/etc> is handled here when it shouldn't be.
+ // Need to check for mods, otherwise any combination of alt/ctrl/shift+<up/down/left/right/etc> is handled here when it shouldn't be.
bool mods = k.is_valid() && (k->is_ctrl_pressed() || k->is_alt_pressed() || k->is_shift_pressed() || k->is_meta_pressed());
if (from && p_event->is_pressed()) {
@@ -2051,7 +2045,7 @@ void Viewport::_gui_set_drag_preview(Control *p_base, Control *p_control) {
}
p_control->set_as_top_level(true);
p_control->set_position(gui.last_mouse_pos);
- p_base->get_root_parent_control()->add_child(p_control); //add as child of viewport
+ p_base->get_root_parent_control()->add_child(p_control); // Add as child of viewport.
p_control->raise();
gui.drag_preview_id = p_control->get_instance_id();
@@ -2153,8 +2147,8 @@ bool Viewport::_gui_control_has_focus(const Control *p_control) {
}
void Viewport::_gui_control_grab_focus(Control *p_control) {
- //no need for change
if (gui.key_focus && gui.key_focus == p_control) {
+ // No need for change.
return;
}
get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, "_viewports", "_gui_remove_focus_for_window", (Node *)get_base_window());
@@ -2236,7 +2230,7 @@ void Viewport::_cleanup_mouseover_colliders(bool p_clean_all_frames, bool p_paus
to_erase.pop_front();
}
- // Per-shape
+ // Per-shape.
List<Map<Pair<ObjectID, int>, uint64_t, PairSort<ObjectID, int>>::Element *> shapes_to_erase;
for (Map<Pair<ObjectID, int>, uint64_t, PairSort<ObjectID, int>>::Element *E = physics_2d_shape_mouseover.front(); E; E = E->next()) {
@@ -2275,7 +2269,7 @@ void Viewport::_gui_grab_click_focus(Control *p_control) {
void Viewport::_post_gui_grab_click_focus() {
Control *focus_grabber = gui.mouse_click_grabber;
if (!focus_grabber) {
- // Redundant grab requests were made
+ // Redundant grab requests were made.
return;
}
gui.mouse_click_grabber = nullptr;
@@ -2293,7 +2287,7 @@ void Viewport::_post_gui_grab_click_focus() {
Ref<InputEventMouseButton> mb;
mb.instantiate();
- //send unclick
+ // Send unclick.
mb->set_position(click);
mb->set_button_index(MouseButton(i + 1));
@@ -2311,7 +2305,7 @@ void Viewport::_post_gui_grab_click_focus() {
Ref<InputEventMouseButton> mb;
mb.instantiate();
- //send click
+ // Send click.
mb->set_position(click);
mb->set_button_index(MouseButton(i + 1));
@@ -2348,7 +2342,7 @@ Viewport::SubWindowResize Viewport::_sub_window_get_resize_margin(Window *p_subw
r.size.y += title_height;
if (r.has_point(p_point)) {
- return SUB_WINDOW_RESIZE_DISABLED; //it's inside, so no resize
+ return SUB_WINDOW_RESIZE_DISABLED; // It's inside, so no resize.
}
int dist_x = p_point.x < r.position.x ? (p_point.x - r.position.x) : (p_point.x > (r.position.x + r.size.x) ? (p_point.x - (r.position.x + r.size.x)) : 0);
@@ -2407,12 +2401,12 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MOUSE_BUTTON_LEFT) {
if (gui.subwindow_drag == SUB_WINDOW_DRAG_CLOSE) {
if (gui.subwindow_drag_close_rect.has_point(mb->get_position())) {
- //close window
+ // Close window.
gui.subwindow_focused->_event_callback(DisplayServer::WINDOW_EVENT_CLOSE_REQUEST);
}
}
gui.subwindow_drag = SUB_WINDOW_DRAG_DISABLED;
- if (gui.subwindow_focused != nullptr) { //may have been erased
+ if (gui.subwindow_focused != nullptr) { // May have been erased.
_sub_window_update(gui.subwindow_focused);
}
}
@@ -2519,27 +2513,27 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
gui.subwindow_focused->_rect_changed_callback(r);
}
- if (gui.subwindow_focused) { //may have been erased
+ if (gui.subwindow_focused) { // May have been erased.
_sub_window_update(gui.subwindow_focused);
}
}
- return true; //handled
+ return true; // Handled.
}
Ref<InputEventMouseButton> mb = p_event;
- //if the event is a mouse button, we need to check whether another window was clicked
+ // If the event is a mouse button, we need to check whether another window was clicked.
if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == MOUSE_BUTTON_LEFT) {
bool click_on_window = false;
for (int i = gui.sub_windows.size() - 1; i >= 0; i--) {
SubWindow &sw = gui.sub_windows.write[i];
- //clicked inside window?
+ // Clicked inside window?
Rect2i r = Rect2i(sw.window->get_position(), sw.window->get_size());
if (!sw.window->get_flag(Window::FLAG_BORDERLESS)) {
- //check top bar
+ // Check top bar.
int title_height = sw.window->get_theme_constant(SNAME("title_height"));
Rect2i title_bar = r;
title_bar.position.y -= title_height;
@@ -2557,13 +2551,13 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
close_rect.size = close_icon->get_size();
if (gui.subwindow_focused != sw.window) {
- //refocus
+ // Refocus.
_sub_window_grab_focus(sw.window);
}
if (close_rect.has_point(mb->get_position())) {
gui.subwindow_drag = SUB_WINDOW_DRAG_CLOSE;
- gui.subwindow_drag_close_inside = true; //starts inside
+ gui.subwindow_drag_close_inside = true; // Starts inside.
gui.subwindow_drag_close_rect = close_rect;
} else {
gui.subwindow_drag = SUB_WINDOW_DRAG_MOVE;
@@ -2584,9 +2578,9 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
}
}
if (!click_on_window && r.has_point(mb->get_position())) {
- //clicked, see if it needs to fetch focus
+ // Clicked, see if it needs to fetch focus.
if (gui.subwindow_focused != sw.window) {
- //refocus
+ // Refocus.
_sub_window_grab_focus(sw.window);
}
@@ -2599,7 +2593,7 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
}
if (!click_on_window && gui.subwindow_focused) {
- //no window found and clicked, remove focus
+ // No window found and clicked, remove focus.
_sub_window_grab_focus(nullptr);
}
}
@@ -2623,13 +2617,13 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
DisplayServer::get_singleton()->cursor_set_shape(shapes[resize]);
- return true; //reserved for showing the resize cursor
+ return true; // Reserved for showing the resize cursor.
}
}
}
if (gui.subwindow_drag != SUB_WINDOW_DRAG_DISABLED) {
- return true; // dragging, don't pass the event
+ return true; // Dragging, don't pass the event.
}
if (!gui.subwindow_focused) {
@@ -2706,10 +2700,10 @@ void Viewport::push_unhandled_input(const Ref<InputEvent> &p_event, bool p_local
ev = p_event;
}
- // Unhandled Input
+ // Unhandled Input.
get_tree()->_call_input_pause(unhandled_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_INPUT, ev, this);
- // Unhandled key Input - used for performance reasons - This is called a lot less than _unhandled_input since it ignores MouseMotion, etc
+ // Unhandled key Input - used for performance reasons - This is called a lot less than _unhandled_input since it ignores MouseMotion, etc.
if (!is_input_handled() && (Object::cast_to<InputEventKey>(*ev) != nullptr || Object::cast_to<InputEventShortcut>(*ev) != nullptr)) {
get_tree()->_call_input_pause(unhandled_key_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_KEY_INPUT, ev, this);
}
@@ -2720,7 +2714,7 @@ void Viewport::push_unhandled_input(const Ref<InputEvent> &p_event, bool p_local
Object::cast_to<InputEventMouseMotion>(*ev) ||
Object::cast_to<InputEventScreenDrag>(*ev) ||
Object::cast_to<InputEventScreenTouch>(*ev) ||
- Object::cast_to<InputEventKey>(*ev) //to remember state
+ Object::cast_to<InputEventKey>(*ev) // To remember state.
)) {
physics_picking_events.push_back(ev);
@@ -2766,10 +2760,6 @@ Variant Viewport::gui_get_drag_data() const {
}
TypedArray<String> Viewport::get_configuration_warnings() const {
- /*if (get_parent() && !Object::cast_to<Control>(get_parent()) && !render_target) {
- return TTR("This viewport is not set as render target. If you intend for it to display its contents directly to the screen, make it a child of a Control so it can obtain a size. Otherwise, make it a RenderTarget and assign its internal texture to some node for display.");
- }*/
-
TypedArray<String> warnings = Node::get_configuration_warnings();
if (size.x == 0 || size.y == 0) {
@@ -3075,7 +3065,9 @@ bool Viewport::is_audio_listener_3d() const {
}
void Viewport::_update_listener_3d() {
- AudioServer::get_singleton()->notify_listener_changed();
+ if (AudioServer::get_singleton()) {
+ AudioServer::get_singleton()->notify_listener_changed();
+ }
}
void Viewport::_listener_transform_3d_changed_notify() {
@@ -3120,7 +3112,7 @@ void Viewport::_listener_3d_make_next_current(Listener3D *p_exclude) {
E->get()->make_current();
}
} else {
- // Attempt to reset listener to the camera position
+ // Attempt to reset listener to the camera position.
if (camera_3d != nullptr) {
_update_listener_3d();
_camera_3d_transform_changed_notify();
@@ -3133,11 +3125,11 @@ void Viewport::_collision_object_3d_input_event(CollisionObject3D *p_object, Cam
Transform3D camera_transform = p_camera->get_global_transform();
ObjectID id = p_object->get_instance_id();
- //avoid sending the fake event unnecessarily if nothing really changed in the context
+ // Avoid sending the fake event unnecessarily if nothing really changed in the context.
if (object_transform == physics_last_object_transform && camera_transform == physics_last_camera_transform && physics_last_id == id) {
Ref<InputEventMouseMotion> mm = p_input_event;
if (mm.is_valid() && mm->get_device() == InputEvent::DEVICE_ID_INTERNAL) {
- return; //discarded
+ return; // Discarded.
}
}
p_object->_input_event_call(camera_3d, p_input_event, p_pos, p_normal, p_shape);
@@ -3606,7 +3598,7 @@ void Viewport::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "snap_2d_transforms_to_pixel"), "set_snap_2d_transforms_to_pixel", "is_snap_2d_transforms_to_pixel_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "snap_2d_vertices_to_pixel"), "set_snap_2d_vertices_to_pixel", "is_snap_2d_vertices_to_pixel_enabled");
ADD_GROUP("Rendering", "");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "msaa", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Fast),4× (Average),8× (Slow),16× (Slower)")), "set_msaa", "get_msaa");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "msaa", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")), "set_msaa", "get_msaa");
ADD_PROPERTY(PropertyInfo(Variant::INT, "screen_space_aa", PROPERTY_HINT_ENUM, "Disabled (Fastest),FXAA (Fast)"), "set_screen_space_aa", "get_screen_space_aa");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_debanding"), "set_use_debanding", "is_using_debanding");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_occlusion_culling"), "set_use_occlusion_culling", "is_using_occlusion_culling");
@@ -3658,7 +3650,6 @@ void Viewport::_bind_methods() {
BIND_ENUM_CONSTANT(MSAA_2X);
BIND_ENUM_CONSTANT(MSAA_4X);
BIND_ENUM_CONSTANT(MSAA_8X);
- BIND_ENUM_CONSTANT(MSAA_16X);
BIND_ENUM_CONSTANT(MSAA_MAX);
BIND_ENUM_CONSTANT(SCREEN_SPACE_AA_DISABLED);
@@ -3733,10 +3724,8 @@ Viewport::Viewport() {
viewport_textures.insert(default_texture.ptr());
default_texture->proxy = RS::get_singleton()->texture_proxy_create(texture_rid);
- //internal_listener_2d = SpatialSound2DServer::get_singleton()->listener_create();
- canvas_layers.insert(nullptr); // This eases picking code (interpreted as the canvas of the Viewport)
+ canvas_layers.insert(nullptr); // This eases picking code (interpreted as the canvas of the Viewport).
- //clear=true;
set_shadow_atlas_size(shadow_atlas_size);
for (int i = 0; i < 4; i++) {
@@ -3764,11 +3753,11 @@ Viewport::Viewport() {
set_scale_3d((Scale3D)scale);
#endif // _3D_DISABLED
- set_sdf_oversize(sdf_oversize); //set to server
+ set_sdf_oversize(sdf_oversize); // Set to server.
}
Viewport::~Viewport() {
- //erase itself from viewport textures
+ // Erase itself from viewport textures.
for (Set<ViewportTexture *>::Element *E = viewport_textures.front(); E; E = E->next()) {
E->get()->vp = nullptr;
}
diff --git a/scene/main/viewport.h b/scene/main/viewport.h
index d9b21ce6a8..bfb52c4b98 100644
--- a/scene/main/viewport.h
+++ b/scene/main/viewport.h
@@ -41,6 +41,7 @@ class Listener3D;
class World3D;
#endif // _3D_DISABLED
+class Listener2D;
class Camera2D;
class CanvasItem;
class CanvasLayer;
@@ -112,7 +113,7 @@ public:
MSAA_2X,
MSAA_4X,
MSAA_8X,
- MSAA_16X,
+ // 16x MSAA is not supported due to its high cost and driver bugs.
MSAA_MAX
};
@@ -201,6 +202,7 @@ private:
Viewport *parent = nullptr;
+ Listener2D *listener_2d = nullptr;
Camera2D *camera_2d = nullptr;
Set<CanvasLayer *> canvas_layers;
@@ -416,6 +418,10 @@ private:
bool _gui_drop(Control *p_at_control, Point2 p_at_pos, bool p_just_check);
+ friend class Listener2D;
+ void _listener_2d_set(Listener2D *p_listener);
+ void _listener_2d_remove(Listener2D *p_listener);
+
friend class Camera2D;
void _camera_2d_set(Camera2D *p_camera_2d);
@@ -457,6 +463,7 @@ protected:
public:
uint64_t get_processed_events_count() const { return event_count; }
+ Listener2D *get_listener_2d() const;
Camera2D *get_camera_2d() const;
void set_as_audio_listener_2d(bool p_enable);
bool is_audio_listener_2d() const;
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index 102f7db74f..69f20ac990 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -49,6 +49,7 @@
#include "scene/2d/light_2d.h"
#include "scene/2d/light_occluder_2d.h"
#include "scene/2d/line_2d.h"
+#include "scene/2d/listener_2d.h"
#include "scene/2d/mesh_instance_2d.h"
#include "scene/2d/multimesh_instance_2d.h"
#include "scene/2d/navigation_agent_2d.h"
@@ -671,6 +672,7 @@ void register_scene_types() {
OS::get_singleton()->yield(); //may take time to init
GDREGISTER_CLASS(Camera2D);
+ GDREGISTER_CLASS(Listener2D);
GDREGISTER_VIRTUAL_CLASS(Joint2D);
GDREGISTER_CLASS(PinJoint2D);
GDREGISTER_CLASS(GrooveJoint2D);
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index 4845c556c6..fa3824e6eb 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -502,8 +502,10 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
theme->set_icon("increment", "HScrollBar", empty_icon);
theme->set_icon("increment_highlight", "HScrollBar", empty_icon);
+ theme->set_icon("increment_pressed", "HScrollBar", empty_icon);
theme->set_icon("decrement", "HScrollBar", empty_icon);
theme->set_icon("decrement_highlight", "HScrollBar", empty_icon);
+ theme->set_icon("decrement_pressed", "HScrollBar", empty_icon);
// VScrollBar
@@ -515,8 +517,10 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
theme->set_icon("increment", "VScrollBar", empty_icon);
theme->set_icon("increment_highlight", "VScrollBar", empty_icon);
+ theme->set_icon("increment_pressed", "VScrollBar", empty_icon);
theme->set_icon("decrement", "VScrollBar", empty_icon);
theme->set_icon("decrement_highlight", "VScrollBar", empty_icon);
+ theme->set_icon("decrement_pressed", "VScrollBar", empty_icon);
// HSlider
diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp
index 1d2a2ef26c..77a68151c4 100644
--- a/scene/resources/material.cpp
+++ b/scene/resources/material.cpp
@@ -963,7 +963,9 @@ void BaseMaterial3D::_update_shader() {
} else {
code += " float depth = 1.0 - texture(texture_heightmap, base_uv).r;\n";
}
- code += " vec2 ofs = base_uv - view_dir.xy / view_dir.z * (depth * heightmap_scale);\n";
+ // Use offset limiting to improve the appearance of non-deep parallax.
+ // This reduces the impression of depth, but avoids visible warping in the distance.
+ code += " vec2 ofs = base_uv - view_dir.xy * depth * heightmap_scale;\n";
}
code += " base_uv=ofs;\n";
diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp
index ad589a605e..8f3f25f104 100644
--- a/scene/resources/mesh.cpp
+++ b/scene/resources/mesh.cpp
@@ -38,7 +38,7 @@
#include <stdlib.h>
-Mesh::ConvexDecompositionFunc Mesh::convex_composition_function = nullptr;
+Mesh::ConvexDecompositionFunc Mesh::convex_decomposition_function = nullptr;
Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
if (triangle_mesh.is_valid()) {
@@ -167,64 +167,13 @@ Vector<Face3> Mesh::get_faces() const {
return tm->get_faces();
}
return Vector<Face3>();
- /*
- for (int i=0;i<surfaces.size();i++) {
- if (RenderingServer::get_singleton()->mesh_surface_get_primitive_type( mesh, i ) != RenderingServer::PRIMITIVE_TRIANGLES )
- continue;
-
- Vector<int> indices;
- Vector<Vector3> vertices;
-
- vertices=RenderingServer::get_singleton()->mesh_surface_get_array(mesh, i,RenderingServer::ARRAY_VERTEX);
-
- int len=RenderingServer::get_singleton()->mesh_surface_get_array_index_len(mesh, i);
- bool has_indices;
-
- if (len>0) {
- indices=RenderingServer::get_singleton()->mesh_surface_get_array(mesh, i,RenderingServer::ARRAY_INDEX);
- has_indices=true;
-
- } else {
- len=vertices.size();
- has_indices=false;
- }
-
- if (len<=0)
- continue;
-
- const int* indicesr = indices.ptr();
- const int *indicesptr = indicesr.ptr();
-
- const Vector3* verticesr = vertices.ptr();
- const Vector3 *verticesptr = verticesr.ptr();
-
- int old_faces=faces.size();
- int new_faces=old_faces+(len/3);
-
- faces.resize(new_faces);
-
- Face3* facesw = faces.ptrw();
- Face3 *facesptr=facesw.ptr();
-
-
- for (int i=0;i<len/3;i++) {
- Face3 face;
-
- for (int j=0;j<3;j++) {
- int idx=i*3+j;
- face.vertex[j] = has_indices ? verticesptr[ indicesptr[ idx ] ] : verticesptr[idx];
- }
-
- facesptr[i+old_faces]=face;
- }
-
- }
-*/
}
Ref<Shape3D> Mesh::create_convex_shape(bool p_clean, bool p_simplify) const {
if (p_simplify) {
- Vector<Ref<Shape3D>> decomposed = convex_decompose(1);
+ ConvexDecompositionSettings settings;
+ settings.max_convex_hulls = 1;
+ Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);
if (decomposed.size() == 1) {
return decomposed[0];
} else {
@@ -543,6 +492,7 @@ void Mesh::_bind_methods() {
BIND_ENUM_CONSTANT(ARRAY_FORMAT_BLEND_SHAPE_MASK);
BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_BASE);
+ BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_BITS);
BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM0_SHIFT);
BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM1_SHIFT);
BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM2_SHIFT);
@@ -564,36 +514,37 @@ void Mesh::clear_cache() const {
debug_lines.clear();
}
-Vector<Ref<Shape3D>> Mesh::convex_decompose(int p_max_convex_hulls) const {
- ERR_FAIL_COND_V(!convex_composition_function, Vector<Ref<Shape3D>>());
-
- const Vector<Face3> faces = get_faces();
+Vector<Ref<Shape3D>> Mesh::convex_decompose(const ConvexDecompositionSettings &p_settings) const {
+ ERR_FAIL_COND_V(!convex_decomposition_function, Vector<Ref<Shape3D>>());
- Vector<Vector<Face3>> decomposed = convex_composition_function(faces, p_max_convex_hulls);
-
- Vector<Ref<Shape3D>> ret;
+ Ref<TriangleMesh> tm = generate_triangle_mesh();
+ ERR_FAIL_COND_V(!tm.is_valid(), Vector<Ref<Shape3D>>());
- for (int i = 0; i < decomposed.size(); i++) {
- Set<Vector3> points;
- for (int j = 0; j < decomposed[i].size(); j++) {
- points.insert(decomposed[i][j].vertex[0]);
- points.insert(decomposed[i][j].vertex[1]);
- points.insert(decomposed[i][j].vertex[2]);
- }
+ const Vector<TriangleMesh::Triangle> &triangles = tm->get_triangles();
+ int triangle_count = triangles.size();
- Vector<Vector3> convex_points;
- convex_points.resize(points.size());
- {
- Vector3 *w = convex_points.ptrw();
- int idx = 0;
- for (Set<Vector3>::Element *E = points.front(); E; E = E->next()) {
- w[idx++] = E->get();
+ Vector<uint32_t> indices;
+ {
+ indices.resize(triangle_count * 3);
+ uint32_t *w = indices.ptrw();
+ for (int i = 0; i < triangle_count; i++) {
+ for (int j = 0; j < 3; j++) {
+ w[i * 3 + j] = triangles[i].indices[j];
}
}
+ }
+
+ const Vector<Vector3> &vertices = tm->get_vertices();
+ int vertex_count = vertices.size();
+ Vector<Vector<Vector3>> decomposed = convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), triangle_count, p_settings, nullptr);
+
+ Vector<Ref<Shape3D>> ret;
+
+ for (int i = 0; i < decomposed.size(); i++) {
Ref<ConvexPolygonShape3D> shape;
shape.instantiate();
- shape->set_points(convex_points);
+ shape->set_points(decomposed[i]);
ret.push_back(shape);
}
diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h
index 27b0eb098b..0776585a11 100644
--- a/scene/resources/mesh.h
+++ b/scene/resources/mesh.h
@@ -105,6 +105,7 @@ public:
ARRAY_FORMAT_BLEND_SHAPE_MASK = RS::ARRAY_FORMAT_BLEND_SHAPE_MASK,
ARRAY_FORMAT_CUSTOM_BASE = RS::ARRAY_FORMAT_CUSTOM_BASE,
+ ARRAY_FORMAT_CUSTOM_BITS = RS::ARRAY_FORMAT_CUSTOM_BITS,
ARRAY_FORMAT_CUSTOM0_SHIFT = RS::ARRAY_FORMAT_CUSTOM0_SHIFT,
ARRAY_FORMAT_CUSTOM1_SHIFT = RS::ARRAY_FORMAT_CUSTOM1_SHIFT,
ARRAY_FORMAT_CUSTOM2_SHIFT = RS::ARRAY_FORMAT_CUSTOM2_SHIFT,
@@ -159,11 +160,42 @@ public:
Size2i get_lightmap_size_hint() const;
void clear_cache() const;
- typedef Vector<Vector<Face3>> (*ConvexDecompositionFunc)(const Vector<Face3> &p_faces, int p_max_convex_hulls);
+ struct ConvexDecompositionSettings {
+ enum Mode : int {
+ CONVEX_DECOMPOSITION_MODE_VOXEL = 0,
+ CONVEX_DECOMPOSITION_MODE_TETRAHEDRON
+ };
+
+ /// Maximum concavity. [Range: 0.0 -> 1.0]
+ real_t max_concavity = 1.0;
+ /// Controls the bias toward clipping along symmetry planes. [Range: 0.0 -> 1.0]
+ real_t symmetry_planes_clipping_bias = 0.05;
+ /// Controls the bias toward clipping along revolution axes. [Range: 0.0 -> 1.0]
+ real_t revolution_axes_clipping_bias = 0.05;
+ real_t min_volume_per_convex_hull = 0.0001;
+ /// Maximum number of voxels generated during the voxelization stage.
+ uint32_t resolution = 10'000;
+ uint32_t max_num_vertices_per_convex_hull = 32;
+ /// Controls the granularity of the search for the "best" clipping plane.
+ /// [Range: 1 -> 16]
+ uint32_t plane_downsampling = 4;
+ /// Controls the precision of the convex-hull generation process during the
+ /// clipping plane selection stage.
+ /// [Range: 1 -> 16]
+ uint32_t convexhull_downsampling = 4;
+ /// enable/disable normalizing the mesh before applying the convex decomposition.
+ bool normalize_mesh = false;
+ Mode mode = CONVEX_DECOMPOSITION_MODE_VOXEL;
+ bool convexhull_approximation = true;
+ /// This is the maximum number of convex hulls to produce from the merge operation.
+ uint32_t max_convex_hulls = 1;
+ bool project_hull_vertices = true;
+ };
+ typedef Vector<Vector<Vector3>> (*ConvexDecompositionFunc)(const real_t *p_vertices, int p_vertex_count, const uint32_t *p_triangles, int p_triangle_count, const ConvexDecompositionSettings &p_settings, Vector<Vector<uint32_t>> *r_convex_indices);
- static ConvexDecompositionFunc convex_composition_function;
+ static ConvexDecompositionFunc convex_decomposition_function;
- Vector<Ref<Shape3D>> convex_decompose(int p_max_convex_hulls = -1) const;
+ Vector<Ref<Shape3D>> convex_decompose(const ConvexDecompositionSettings &p_settings) const;
virtual int get_builtin_bind_pose_count() const;
virtual Transform3D get_builtin_bind_pose(int p_index) const;
diff --git a/scene/resources/mesh_library.cpp b/scene/resources/mesh_library.cpp
index 33c9ca6d1e..cfb7c3e037 100644
--- a/scene/resources/mesh_library.cpp
+++ b/scene/resources/mesh_library.cpp
@@ -43,6 +43,8 @@ bool MeshLibrary::_set(const StringName &p_name, const Variant &p_value) {
set_item_name(idx, p_value);
} else if (what == "mesh") {
set_item_mesh(idx, p_value);
+ } else if (what == "mesh_transform") {
+ set_item_mesh_transform(idx, p_value);
} else if (what == "shape") {
Vector<ShapeData> shapes;
ShapeData sd;
@@ -77,6 +79,8 @@ bool MeshLibrary::_get(const StringName &p_name, Variant &r_ret) const {
r_ret = get_item_name(idx);
} else if (what == "mesh") {
r_ret = get_item_mesh(idx);
+ } else if (what == "mesh_transform") {
+ r_ret = get_item_mesh_transform(idx);
} else if (what == "shapes") {
r_ret = _get_item_shapes(idx);
} else if (what == "navmesh") {
@@ -127,6 +131,14 @@ void MeshLibrary::set_item_mesh(int p_item, const Ref<Mesh> &p_mesh) {
notify_property_list_changed();
}
+void MeshLibrary::set_item_mesh_transform(int p_item, const Transform3D &p_transform) {
+ ERR_FAIL_COND_MSG(!item_map.has(p_item), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
+ item_map[p_item].mesh_transform = p_transform;
+ notify_change_to_owners();
+ emit_changed();
+ notify_property_list_changed();
+}
+
void MeshLibrary::set_item_shapes(int p_item, const Vector<ShapeData> &p_shapes) {
ERR_FAIL_COND_MSG(!item_map.has(p_item), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
item_map[p_item].shapes = p_shapes;
@@ -170,6 +182,11 @@ Ref<Mesh> MeshLibrary::get_item_mesh(int p_item) const {
return item_map[p_item].mesh;
}
+Transform3D MeshLibrary::get_item_mesh_transform(int p_item) const {
+ ERR_FAIL_COND_V_MSG(!item_map.has(p_item), Transform3D(), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
+ return item_map[p_item].mesh_transform;
+}
+
Vector<MeshLibrary::ShapeData> MeshLibrary::get_item_shapes(int p_item) const {
ERR_FAIL_COND_V_MSG(!item_map.has(p_item), Vector<ShapeData>(), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
return item_map[p_item].shapes;
@@ -271,12 +288,14 @@ void MeshLibrary::_bind_methods() {
ClassDB::bind_method(D_METHOD("create_item", "id"), &MeshLibrary::create_item);
ClassDB::bind_method(D_METHOD("set_item_name", "id", "name"), &MeshLibrary::set_item_name);
ClassDB::bind_method(D_METHOD("set_item_mesh", "id", "mesh"), &MeshLibrary::set_item_mesh);
+ ClassDB::bind_method(D_METHOD("set_item_mesh_transform", "id", "mesh_transform"), &MeshLibrary::set_item_mesh_transform);
ClassDB::bind_method(D_METHOD("set_item_navmesh", "id", "navmesh"), &MeshLibrary::set_item_navmesh);
ClassDB::bind_method(D_METHOD("set_item_navmesh_transform", "id", "navmesh"), &MeshLibrary::set_item_navmesh_transform);
ClassDB::bind_method(D_METHOD("set_item_shapes", "id", "shapes"), &MeshLibrary::_set_item_shapes);
ClassDB::bind_method(D_METHOD("set_item_preview", "id", "texture"), &MeshLibrary::set_item_preview);
ClassDB::bind_method(D_METHOD("get_item_name", "id"), &MeshLibrary::get_item_name);
ClassDB::bind_method(D_METHOD("get_item_mesh", "id"), &MeshLibrary::get_item_mesh);
+ ClassDB::bind_method(D_METHOD("get_item_mesh_transform", "id"), &MeshLibrary::get_item_mesh_transform);
ClassDB::bind_method(D_METHOD("get_item_navmesh", "id"), &MeshLibrary::get_item_navmesh);
ClassDB::bind_method(D_METHOD("get_item_navmesh_transform", "id"), &MeshLibrary::get_item_navmesh_transform);
ClassDB::bind_method(D_METHOD("get_item_shapes", "id"), &MeshLibrary::_get_item_shapes);
diff --git a/scene/resources/mesh_library.h b/scene/resources/mesh_library.h
index 1e8a6bf3ff..c25df757e9 100644
--- a/scene/resources/mesh_library.h
+++ b/scene/resources/mesh_library.h
@@ -52,6 +52,7 @@ public:
Vector<ShapeData> shapes;
Ref<Texture2D> preview;
Transform3D navmesh_transform;
+ Transform3D mesh_transform;
Ref<NavigationMesh> navmesh;
};
@@ -72,12 +73,14 @@ public:
void create_item(int p_item);
void set_item_name(int p_item, const String &p_name);
void set_item_mesh(int p_item, const Ref<Mesh> &p_mesh);
+ void set_item_mesh_transform(int p_item, const Transform3D &p_transform);
void set_item_navmesh(int p_item, const Ref<NavigationMesh> &p_navmesh);
void set_item_navmesh_transform(int p_item, const Transform3D &p_transform);
void set_item_shapes(int p_item, const Vector<ShapeData> &p_shapes);
void set_item_preview(int p_item, const Ref<Texture2D> &p_preview);
String get_item_name(int p_item) const;
Ref<Mesh> get_item_mesh(int p_item) const;
+ Transform3D get_item_mesh_transform(int p_item) const;
Ref<NavigationMesh> get_item_navmesh(int p_item) const;
Transform3D get_item_navmesh_transform(int p_item) const;
Vector<ShapeData> get_item_shapes(int p_item) const;
diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp
index b863a309c0..341ce22185 100644
--- a/scene/resources/resource_format_text.cpp
+++ b/scene/resources/resource_format_text.cpp
@@ -1849,10 +1849,16 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_r
}
if (groups.size()) {
+ // Write all groups on the same line as they're part of a section header.
+ // This improves readability while not impacting VCS friendliness too much,
+ // since it's rare to have more than 5 groups assigned to a single node.
groups.sort_custom<StringName::AlphCompare>();
- String sgroups = " groups=[\n";
+ String sgroups = " groups=[";
for (int j = 0; j < groups.size(); j++) {
- sgroups += "\"" + String(groups[j]).c_escape() + "\",\n";
+ sgroups += "\"" + String(groups[j]).c_escape() + "\"";
+ if (j < groups.size() - 1) {
+ sgroups += ", ";
+ }
}
sgroups += "]";
header += sgroups;
diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp
index 875aa30824..d5e370568d 100644
--- a/scene/resources/surface_tool.cpp
+++ b/scene/resources/surface_tool.cpp
@@ -409,7 +409,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx * 4 + 0] = CLAMP(int32_t(c.r * 255.0), 0, 255);
w[idx * 4 + 1] = CLAMP(int32_t(c.g * 255.0), 0, 255);
w[idx * 4 + 2] = CLAMP(int32_t(c.b * 255.0), 0, 255);
@@ -426,7 +426,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx * 4 + 0] = uint8_t(int8_t(CLAMP(int32_t(c.r * 127.0), -128, 127)));
w[idx * 4 + 1] = uint8_t(int8_t(CLAMP(int32_t(c.g * 127.0), -128, 127)));
w[idx * 4 + 2] = uint8_t(int8_t(CLAMP(int32_t(c.b * 127.0), -128, 127)));
@@ -443,7 +443,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx * 2 + 0] = Math::make_half_float(c.r);
w[idx * 2 + 1] = Math::make_half_float(c.g);
}
@@ -458,7 +458,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx * 4 + 0] = Math::make_half_float(c.r);
w[idx * 4 + 1] = Math::make_half_float(c.g);
w[idx * 4 + 2] = Math::make_half_float(c.b);
@@ -475,7 +475,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx] = c.r;
}
@@ -489,7 +489,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx * 2 + 0] = c.r;
w[idx * 2 + 1] = c.g;
}
@@ -504,7 +504,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx * 3 + 0] = c.r;
w[idx * 3 + 1] = c.g;
w[idx * 3 + 2] = c.b;
@@ -520,7 +520,7 @@ Array SurfaceTool::commit_to_arrays() {
for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
const Vertex &v = vertex_array[idx];
- const Color &c = v.custom[idx];
+ const Color &c = v.custom[fmt];
w[idx * 4 + 0] = c.r;
w[idx * 4 + 1] = c.g;
w[idx * 4 + 2] = c.b;
@@ -679,6 +679,9 @@ void SurfaceTool::_create_list(const Ref<Mesh> &p_existing, int p_surface, Local
_create_list_from_arrays(arr, r_vertex, r_index, lformat);
}
+static const uint32_t custom_mask[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0, Mesh::ARRAY_FORMAT_CUSTOM1, Mesh::ARRAY_FORMAT_CUSTOM2, Mesh::ARRAY_FORMAT_CUSTOM3 };
+static const uint32_t custom_shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };
+
void SurfaceTool::create_vertex_array_from_triangle_arrays(const Array &p_arrays, LocalVector<SurfaceTool::Vertex> &ret, uint32_t *r_format) {
ret.clear();
@@ -733,8 +736,6 @@ void SurfaceTool::create_vertex_array_from_triangle_arrays(const Array &p_arrays
if (warr.size()) {
lformat |= RS::ARRAY_FORMAT_WEIGHTS;
}
- static const uint32_t custom_mask[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0, Mesh::ARRAY_FORMAT_CUSTOM1, Mesh::ARRAY_FORMAT_CUSTOM2, Mesh::ARRAY_FORMAT_CUSTOM3 };
- static const uint32_t custom_shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };
for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
ERR_CONTINUE_MSG(p_arrays[RS::ARRAY_CUSTOM0 + i].get_type() == Variant::PACKED_BYTE_ARRAY, "Extracting Byte/Half formats is not supported");
@@ -832,6 +833,12 @@ void SurfaceTool::create_from_triangle_arrays(const Array &p_arrays) {
clear();
primitive = Mesh::PRIMITIVE_TRIANGLES;
_create_list_from_arrays(p_arrays, &vertex_array, &index_array, format);
+
+ for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
+ if (format & custom_mask[j]) {
+ last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
+ }
+ }
}
void SurfaceTool::create_from(const Ref<Mesh> &p_existing, int p_surface) {
@@ -841,6 +848,12 @@ void SurfaceTool::create_from(const Ref<Mesh> &p_existing, int p_surface) {
primitive = p_existing->surface_get_primitive_type(p_surface);
_create_list(p_existing, p_surface, &vertex_array, &index_array, format);
material = p_existing->surface_get_material(p_surface);
+
+ for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
+ if (format & custom_mask[j]) {
+ last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
+ }
+ }
}
void SurfaceTool::create_from_blend_shape(const Ref<Mesh> &p_existing, int p_surface, const String &p_blend_shape_name) {
@@ -863,6 +876,12 @@ void SurfaceTool::create_from_blend_shape(const Ref<Mesh> &p_existing, int p_sur
Array mesh = arr[shape_idx];
ERR_FAIL_COND(mesh.size() != RS::ARRAY_MAX);
_create_list_from_arrays(arr[shape_idx], &vertex_array, &index_array, format);
+
+ for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
+ if (format & custom_mask[j]) {
+ last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
+ }
+ }
}
void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const Transform3D &p_xform) {
@@ -878,6 +897,16 @@ void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const
LocalVector<int> nindices;
_create_list(p_existing, p_surface, &nvertices, &nindices, nformat);
format |= nformat;
+
+ for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
+ if (format & custom_mask[j]) {
+ CustomFormat new_format = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
+ if (last_custom_format[j] != CUSTOM_MAX && last_custom_format[j] != new_format) {
+ WARN_PRINT(vformat("Custom %d format %d mismatch when appending format %d", j, last_custom_format[j], new_format));
+ }
+ last_custom_format[j] = new_format;
+ }
+ }
int vfrom = vertex_array.size();
for (uint32_t vi = 0; vi < nvertices.size(); vi++) {
diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp
index 063a13efc0..3dc32632cc 100644
--- a/scene/resources/texture.cpp
+++ b/scene/resources/texture.cpp
@@ -131,25 +131,6 @@ void ImageTexture::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::VECTOR2, "size", PROPERTY_HINT_NONE, ""));
}
-void ImageTexture::_reload_hook(const RID &p_hook) {
- String path = get_path();
- if (!path.is_resource_file()) {
- return;
- }
-
- Ref<Image> img;
- img.instantiate();
- Error err = ImageLoader::load_image(path, img);
-
- ERR_FAIL_COND_MSG(err != OK, "Cannot load image from path '" + path + "'.");
-
- RID new_texture = RenderingServer::get_singleton()->texture_2d_create(img);
- RenderingServer::get_singleton()->texture_replace(texture, new_texture);
-
- notify_property_list_changed();
- emit_changed();
-}
-
void ImageTexture::create_from_image(const Ref<Image> &p_image) {
ERR_FAIL_COND_MSG(p_image.is_null() || p_image->is_empty(), "Invalid image");
w = p_image->get_width();
@@ -192,10 +173,6 @@ void ImageTexture::update(const Ref<Image> &p_image) {
image_stored = true;
}
-void ImageTexture::_resource_path_changed() {
- String path = get_path();
-}
-
Ref<Image> ImageTexture::get_image() const {
if (image_stored) {
return RenderingServer::get_singleton()->texture_2d_get(texture);
@@ -303,7 +280,6 @@ void ImageTexture::_bind_methods() {
ClassDB::bind_method(D_METHOD("update", "image"), &ImageTexture::update);
ClassDB::bind_method(D_METHOD("set_size_override", "size"), &ImageTexture::set_size_override);
- ClassDB::bind_method(D_METHOD("_reload_hook", "rid"), &ImageTexture::_reload_hook);
}
ImageTexture::ImageTexture() {}
diff --git a/scene/resources/texture.h b/scene/resources/texture.h
index f6b991c335..93f4e2de5a 100644
--- a/scene/resources/texture.h
+++ b/scene/resources/texture.h
@@ -98,8 +98,6 @@ protected:
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
- void _reload_hook(const RID &p_hook);
- virtual void _resource_path_changed() override;
static void _bind_methods();
public:
diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp
index d383961d87..918fc3fe9c 100644
--- a/scene/resources/tile_set.cpp
+++ b/scene/resources/tile_set.cpp
@@ -257,7 +257,7 @@ int TileSet::get_occlusion_layer_light_mask(int p_layer_index) const {
return occlusion_layers[p_layer_index].light_mask;
}
-void TileSet::set_occlusion_layer_sdf_collision(int p_layer_index, int p_sdf_collision) {
+void TileSet::set_occlusion_layer_sdf_collision(int p_layer_index, bool p_sdf_collision) {
ERR_FAIL_INDEX(p_layer_index, occlusion_layers.size());
occlusion_layers.write[p_layer_index].sdf_collision = p_sdf_collision;
emit_changed();
@@ -982,10 +982,10 @@ void TileSet::clear_tile_proxies() {
Vector<Vector2> TileSet::get_tile_shape_polygon() {
Vector<Vector2> points;
if (tile_shape == TileSet::TILE_SHAPE_SQUARE) {
- points.append(Vector2(0.0, 0.0));
- points.append(Vector2(1.0, 0.0));
- points.append(Vector2(1.0, 1.0));
- points.append(Vector2(0.0, 1.0));
+ points.append(Vector2(-0.5, -0.5));
+ points.append(Vector2(0.5, -0.5));
+ points.append(Vector2(0.5, 0.5));
+ points.append(Vector2(-0.5, 0.5));
} else {
float overlap = 0.0;
switch (tile_shape) {
@@ -1002,31 +1002,24 @@ Vector<Vector2> TileSet::get_tile_shape_polygon() {
break;
}
- points.append(Vector2(0.5, 0.0));
- points.append(Vector2(0.0, overlap));
- points.append(Vector2(0.0, 1.0 - overlap));
- points.append(Vector2(0.5, 1.0));
- points.append(Vector2(1.0, 1.0 - overlap));
- points.append(Vector2(1.0, overlap));
- points.append(Vector2(0.5, 0.0));
+ points.append(Vector2(0.0, -0.5));
+ points.append(Vector2(-0.5, overlap - 0.5));
+ points.append(Vector2(-0.5, 0.5 - overlap));
+ points.append(Vector2(0.0, 0.5));
+ points.append(Vector2(0.5, 0.5 - overlap));
+ points.append(Vector2(0.5, overlap - 0.5));
if (get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL) {
for (int i = 0; i < points.size(); i++) {
points.write[i] = Vector2(points[i].y, points[i].x);
}
}
}
- for (int i = 0; i < points.size(); i++) {
- points.write[i] = points[i] * tile_size - tile_size / 2;
- }
return points;
}
-void TileSet::draw_tile_shape(CanvasItem *p_canvas_item, Rect2 p_region, Color p_color, bool p_filled, Ref<Texture2D> p_texture) {
+void TileSet::draw_tile_shape(CanvasItem *p_canvas_item, Transform2D p_transform, Color p_color, bool p_filled, Ref<Texture2D> p_texture) {
if (tile_meshes_dirty) {
Vector<Vector2> uvs = get_tile_shape_polygon();
- for (int i = 0; i < uvs.size(); i++) {
- uvs.write[i] = (uvs[i] + tile_size / 2) / tile_size;
- }
Vector<Color> colors;
colors.resize(uvs.size());
@@ -1056,13 +1049,10 @@ void TileSet::draw_tile_shape(CanvasItem *p_canvas_item, Rect2 p_region, Color p
tile_meshes_dirty = false;
}
- Transform2D xform;
- xform.scale(p_region.size);
- xform.set_origin(p_region.get_position());
if (p_filled) {
- p_canvas_item->draw_mesh(tile_filled_mesh, p_texture, xform, p_color);
+ p_canvas_item->draw_mesh(tile_filled_mesh, p_texture, p_transform, p_color);
} else {
- p_canvas_item->draw_mesh(tile_lines_mesh, Ref<Texture2D>(), xform, p_color);
+ p_canvas_item->draw_mesh(tile_lines_mesh, Ref<Texture2D>(), p_transform, p_color);
}
}
@@ -1966,7 +1956,7 @@ void TileSet::_compatibility_conversion() {
tile_data->set_flip_h(flip_h);
tile_data->set_flip_v(flip_v);
tile_data->set_transpose(transpose);
- tile_data->tile_set_material(ctd->material);
+ tile_data->set_material(ctd->material);
tile_data->set_modulate(ctd->modulate);
tile_data->set_z_index(ctd->z_index);
@@ -2058,7 +2048,7 @@ void TileSet::_compatibility_conversion() {
tile_data->set_flip_h(flip_h);
tile_data->set_flip_v(flip_v);
tile_data->set_transpose(transpose);
- tile_data->tile_set_material(ctd->material);
+ tile_data->set_material(ctd->material);
tile_data->set_modulate(ctd->modulate);
tile_data->set_z_index(ctd->z_index);
if (ctd->autotile_occluder_map.has(coords)) {
@@ -2693,13 +2683,13 @@ void TileSet::_get_property_list(List<PropertyInfo> *p_list) const {
void TileSet::_bind_methods() {
// Sources management.
ClassDB::bind_method(D_METHOD("get_next_source_id"), &TileSet::get_next_source_id);
- ClassDB::bind_method(D_METHOD("add_source", "atlas_source_id_override"), &TileSet::add_source, DEFVAL(TileSet::INVALID_SOURCE));
+ ClassDB::bind_method(D_METHOD("add_source", "source", "atlas_source_id_override"), &TileSet::add_source, DEFVAL(TileSet::INVALID_SOURCE));
ClassDB::bind_method(D_METHOD("remove_source", "source_id"), &TileSet::remove_source);
- ClassDB::bind_method(D_METHOD("set_source_id", "source_id"), &TileSet::set_source_id);
+ ClassDB::bind_method(D_METHOD("set_source_id", "source_id", "new_source_id"), &TileSet::set_source_id);
ClassDB::bind_method(D_METHOD("get_source_count"), &TileSet::get_source_count);
ClassDB::bind_method(D_METHOD("get_source_id", "index"), &TileSet::get_source_id);
- ClassDB::bind_method(D_METHOD("has_source", "index"), &TileSet::has_source);
- ClassDB::bind_method(D_METHOD("get_source", "index"), &TileSet::get_source);
+ ClassDB::bind_method(D_METHOD("has_source", "source_id"), &TileSet::has_source);
+ ClassDB::bind_method(D_METHOD("get_source", "source_id"), &TileSet::get_source);
// Shape and layout.
ClassDB::bind_method(D_METHOD("set_tile_shape", "shape"), &TileSet::set_tile_shape);
@@ -2725,9 +2715,9 @@ void TileSet::_bind_methods() {
ClassDB::bind_method(D_METHOD("move_occlusion_layer", "layer_index", "to_position"), &TileSet::move_occlusion_layer);
ClassDB::bind_method(D_METHOD("remove_occlusion_layer", "layer_index"), &TileSet::remove_occlusion_layer);
ClassDB::bind_method(D_METHOD("set_occlusion_layer_light_mask", "layer_index", "light_mask"), &TileSet::set_occlusion_layer_light_mask);
- ClassDB::bind_method(D_METHOD("get_occlusion_layer_light_mask"), &TileSet::get_occlusion_layer_light_mask);
+ ClassDB::bind_method(D_METHOD("get_occlusion_layer_light_mask", "layer_index"), &TileSet::get_occlusion_layer_light_mask);
ClassDB::bind_method(D_METHOD("set_occlusion_layer_sdf_collision", "layer_index", "sdf_collision"), &TileSet::set_occlusion_layer_sdf_collision);
- ClassDB::bind_method(D_METHOD("get_occlusion_layer_sdf_collision"), &TileSet::get_occlusion_layer_sdf_collision);
+ ClassDB::bind_method(D_METHOD("get_occlusion_layer_sdf_collision", "layer_index"), &TileSet::get_occlusion_layer_sdf_collision);
// Physics
ClassDB::bind_method(D_METHOD("get_physics_layers_count"), &TileSet::get_physics_layers_count);
@@ -2744,8 +2734,8 @@ void TileSet::_bind_methods() {
// Terrains
ClassDB::bind_method(D_METHOD("get_terrain_sets_count"), &TileSet::get_terrain_sets_count);
ClassDB::bind_method(D_METHOD("add_terrain_set", "to_position"), &TileSet::add_terrain_set, DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("move_terrain_set", "layer_index", "to_position"), &TileSet::move_terrain_set);
- ClassDB::bind_method(D_METHOD("remove_terrain_set", "layer_index"), &TileSet::remove_terrain_set);
+ ClassDB::bind_method(D_METHOD("move_terrain_set", "terrain_set", "to_position"), &TileSet::move_terrain_set);
+ ClassDB::bind_method(D_METHOD("remove_terrain_set", "terrain_set"), &TileSet::remove_terrain_set);
ClassDB::bind_method(D_METHOD("set_terrain_set_mode", "terrain_set", "mode"), &TileSet::set_terrain_set_mode);
ClassDB::bind_method(D_METHOD("get_terrain_set_mode", "terrain_set"), &TileSet::get_terrain_set_mode);
@@ -2870,6 +2860,18 @@ void TileSetSource::set_tile_set(const TileSet *p_tile_set) {
tile_set = p_tile_set;
}
+void TileSetSource::_bind_methods() {
+ // Base tiles
+ ClassDB::bind_method(D_METHOD("get_tiles_count"), &TileSetSource::get_tiles_count);
+ ClassDB::bind_method(D_METHOD("get_tile_id", "index"), &TileSetSource::get_tile_id);
+ ClassDB::bind_method(D_METHOD("has_tile", "atlas_coords"), &TileSetSource::has_tile);
+
+ // Alternative tiles
+ ClassDB::bind_method(D_METHOD("get_alternative_tiles_count", "atlas_coords"), &TileSetSource::get_alternative_tiles_count);
+ ClassDB::bind_method(D_METHOD("get_alternative_tile_id", "atlas_coords", "index"), &TileSetSource::get_alternative_tile_id);
+ ClassDB::bind_method(D_METHOD("has_alternative_tile", "atlas_coords", "alternative_tile"), &TileSetSource::has_alternative_tile);
+}
+
/////////////////////////////// TileSetAtlasSource //////////////////////////////////////
void TileSetAtlasSource::set_tile_set(const TileSet *p_tile_set) {
@@ -3559,32 +3561,24 @@ void TileSetAtlasSource::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D", PROPERTY_USAGE_NOEDITOR), "set_texture", "get_texture");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "margins", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_margins", "get_margins");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "separation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_separation", "get_separation");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "tile_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_texture_region_size", "get_texture_region_size");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "texture_region_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_texture_region_size", "get_texture_region_size");
// Base tiles
ClassDB::bind_method(D_METHOD("create_tile", "atlas_coords", "size"), &TileSetAtlasSource::create_tile, DEFVAL(Vector2i(1, 1)));
ClassDB::bind_method(D_METHOD("remove_tile", "atlas_coords"), &TileSetAtlasSource::remove_tile); // Remove a tile. If p_tile_key.alternative_tile if different from 0, remove the alternative
- ClassDB::bind_method(D_METHOD("has_tile", "atlas_coords"), &TileSetAtlasSource::has_tile);
ClassDB::bind_method(D_METHOD("can_move_tile_in_atlas", "atlas_coords", "new_atlas_coords", "new_size"), &TileSetAtlasSource::can_move_tile_in_atlas, DEFVAL(INVALID_ATLAS_COORDS), DEFVAL(Vector2i(-1, -1)));
ClassDB::bind_method(D_METHOD("move_tile_in_atlas", "atlas_coords", "new_atlas_coords", "new_size"), &TileSetAtlasSource::move_tile_in_atlas, DEFVAL(INVALID_ATLAS_COORDS), DEFVAL(Vector2i(-1, -1)));
ClassDB::bind_method(D_METHOD("get_tile_size_in_atlas", "atlas_coords"), &TileSetAtlasSource::get_tile_size_in_atlas);
- ClassDB::bind_method(D_METHOD("get_tiles_count"), &TileSetAtlasSource::get_tiles_count);
- ClassDB::bind_method(D_METHOD("get_tile_id", "index"), &TileSetAtlasSource::get_tile_id);
-
ClassDB::bind_method(D_METHOD("get_tile_at_coords", "atlas_coords"), &TileSetAtlasSource::get_tile_at_coords);
// Alternative tiles
ClassDB::bind_method(D_METHOD("create_alternative_tile", "atlas_coords", "alternative_id_override"), &TileSetAtlasSource::create_alternative_tile, DEFVAL(INVALID_TILE_ALTERNATIVE));
ClassDB::bind_method(D_METHOD("remove_alternative_tile", "atlas_coords", "alternative_tile"), &TileSetAtlasSource::remove_alternative_tile);
ClassDB::bind_method(D_METHOD("set_alternative_tile_id", "atlas_coords", "alternative_tile", "new_id"), &TileSetAtlasSource::set_alternative_tile_id);
- ClassDB::bind_method(D_METHOD("has_alternative_tile", "atlas_coords", "alternative_tile"), &TileSetAtlasSource::has_alternative_tile);
ClassDB::bind_method(D_METHOD("get_next_alternative_tile_id", "atlas_coords"), &TileSetAtlasSource::get_next_alternative_tile_id);
- ClassDB::bind_method(D_METHOD("get_alternative_tiles_count", "atlas_coords"), &TileSetAtlasSource::get_alternative_tiles_count);
- ClassDB::bind_method(D_METHOD("get_alternative_tile_id", "atlas_coords", "index"), &TileSetAtlasSource::get_alternative_tile_id);
-
- ClassDB::bind_method(D_METHOD("get_tile_data", "atlas_coords", "index"), &TileSetAtlasSource::get_tile_data);
+ ClassDB::bind_method(D_METHOD("get_tile_data", "atlas_coords", "alternative_tile"), &TileSetAtlasSource::get_tile_data);
// Helpers.
ClassDB::bind_method(D_METHOD("get_atlas_grid_size"), &TileSetAtlasSource::get_atlas_grid_size);
@@ -3797,16 +3791,6 @@ void TileSetScenesCollectionSource::_get_property_list(List<PropertyInfo> *p_lis
}
void TileSetScenesCollectionSource::_bind_methods() {
- // Base tiles
- ClassDB::bind_method(D_METHOD("get_tiles_count"), &TileSetScenesCollectionSource::get_tiles_count);
- ClassDB::bind_method(D_METHOD("get_tile_id", "index"), &TileSetScenesCollectionSource::get_tile_id);
- ClassDB::bind_method(D_METHOD("has_tile", "atlas_coords"), &TileSetScenesCollectionSource::has_tile);
-
- // Alternative tiles
- ClassDB::bind_method(D_METHOD("get_alternative_tiles_count", "atlas_coords"), &TileSetScenesCollectionSource::get_alternative_tiles_count);
- ClassDB::bind_method(D_METHOD("get_alternative_tile_id", "atlas_coords", "index"), &TileSetScenesCollectionSource::get_alternative_tile_id);
- ClassDB::bind_method(D_METHOD("has_alternative_tile", "atlas_coords", "alternative_tile"), &TileSetScenesCollectionSource::has_alternative_tile);
-
ClassDB::bind_method(D_METHOD("get_scene_tiles_count"), &TileSetScenesCollectionSource::get_scene_tiles_count);
ClassDB::bind_method(D_METHOD("get_scene_tile_id", "index"), &TileSetScenesCollectionSource::get_scene_tile_id);
ClassDB::bind_method(D_METHOD("has_scene_tile_id", "id"), &TileSetScenesCollectionSource::has_scene_tile_id);
@@ -4063,11 +4047,11 @@ Vector2i TileData::get_texture_offset() const {
return tex_offset;
}
-void TileData::tile_set_material(Ref<ShaderMaterial> p_material) {
+void TileData::set_material(Ref<ShaderMaterial> p_material) {
material = p_material;
emit_signal(SNAME("changed"));
}
-Ref<ShaderMaterial> TileData::tile_get_material() const {
+Ref<ShaderMaterial> TileData::get_material() const {
return material;
}
@@ -4583,8 +4567,8 @@ void TileData::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_flip_v"), &TileData::get_flip_v);
ClassDB::bind_method(D_METHOD("set_transpose", "transpose"), &TileData::set_transpose);
ClassDB::bind_method(D_METHOD("get_transpose"), &TileData::get_transpose);
- ClassDB::bind_method(D_METHOD("tile_set_material", "material"), &TileData::tile_set_material);
- ClassDB::bind_method(D_METHOD("tile_get_material"), &TileData::tile_get_material);
+ ClassDB::bind_method(D_METHOD("set_material", "material"), &TileData::set_material);
+ ClassDB::bind_method(D_METHOD("get_material"), &TileData::get_material);
ClassDB::bind_method(D_METHOD("set_texture_offset", "texture_offset"), &TileData::set_texture_offset);
ClassDB::bind_method(D_METHOD("get_texture_offset"), &TileData::get_texture_offset);
ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &TileData::set_modulate);
@@ -4635,6 +4619,7 @@ void TileData::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "transpose"), "set_transpose", "get_transpose");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "texture_offset"), "set_texture_offset", "get_texture_offset");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial"), "set_material", "get_material");
ADD_PROPERTY(PropertyInfo(Variant::INT, "z_index"), "set_z_index", "get_z_index");
ADD_PROPERTY(PropertyInfo(Variant::INT, "y_sort_origin"), "set_y_sort_origin", "get_y_sort_origin");
diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h
index 29a71d31d2..ba7207241a 100644
--- a/scene/resources/tile_set.h
+++ b/scene/resources/tile_set.h
@@ -304,7 +304,7 @@ public:
void remove_occlusion_layer(int p_index);
void set_occlusion_layer_light_mask(int p_layer_index, int p_light_mask);
int get_occlusion_layer_light_mask(int p_layer_index) const;
- void set_occlusion_layer_sdf_collision(int p_layer_index, int p_sdf_collision);
+ void set_occlusion_layer_sdf_collision(int p_layer_index, bool p_sdf_collision);
bool get_occlusion_layer_sdf_collision(int p_layer_index) const;
// Physics
@@ -385,7 +385,7 @@ public:
// Helpers
Vector<Vector2> get_tile_shape_polygon();
- void draw_tile_shape(CanvasItem *p_canvas_item, Rect2 p_region, Color p_color, bool p_filled = false, Ref<Texture2D> p_texture = Ref<Texture2D>());
+ void draw_tile_shape(CanvasItem *p_canvas_item, Transform2D p_transform, Color p_color, bool p_filled = false, Ref<Texture2D> p_texture = Ref<Texture2D>());
Vector<Point2> get_terrain_bit_polygon(int p_terrain_set, TileSet::CellNeighbor p_bit);
void draw_terrains(CanvasItem *p_canvas_item, Transform2D p_transform, const TileData *p_tile_data);
@@ -404,6 +404,8 @@ class TileSetSource : public Resource {
protected:
const TileSet *tile_set = nullptr;
+ static void _bind_methods();
+
public:
static const Vector2i INVALID_ATLAS_COORDS; // Vector2i(-1, -1);
static const int INVALID_TILE_ALTERNATIVE; // -1;
@@ -679,8 +681,8 @@ public:
void set_texture_offset(Vector2i p_texture_offset);
Vector2i get_texture_offset() const;
- void tile_set_material(Ref<ShaderMaterial> p_material);
- Ref<ShaderMaterial> tile_get_material() const;
+ void set_material(Ref<ShaderMaterial> p_material);
+ Ref<ShaderMaterial> get_material() const;
void set_modulate(Color p_modulate);
Color get_modulate() const;
void set_z_index(int p_z_index);
diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp
index 758ce766c3..ac1569c15d 100644
--- a/servers/audio_server.cpp
+++ b/servers/audio_server.cpp
@@ -196,6 +196,7 @@ int AudioDriverManager::get_driver_count() {
void AudioDriverManager::initialize(int p_driver) {
GLOBAL_DEF_RST("audio/driver/enable_input", false);
GLOBAL_DEF_RST("audio/driver/mix_rate", DEFAULT_MIX_RATE);
+ GLOBAL_DEF_RST("audio/driver/mix_rate.web", 0); // Safer default output_latency for web (use browser default).
GLOBAL_DEF_RST("audio/driver/output_latency", DEFAULT_OUTPUT_LATENCY);
GLOBAL_DEF_RST("audio/driver/output_latency.web", 50); // Safer default output_latency for web.
diff --git a/servers/display_server.cpp b/servers/display_server.cpp
index 3d44484033..cdf892094d 100644
--- a/servers/display_server.cpp
+++ b/servers/display_server.cpp
@@ -605,4 +605,5 @@ DisplayServer::DisplayServer() {
}
DisplayServer::~DisplayServer() {
+ singleton = nullptr;
}
diff --git a/servers/physics_3d/gjk_epa.cpp b/servers/physics_3d/gjk_epa.cpp
index f2f712193a..2df991563d 100644
--- a/servers/physics_3d/gjk_epa.cpp
+++ b/servers/physics_3d/gjk_epa.cpp
@@ -37,7 +37,7 @@
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2008 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/
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
diff --git a/servers/physics_3d/joints/generic_6dof_joint_3d_sw.cpp b/servers/physics_3d/joints/generic_6dof_joint_3d_sw.cpp
index d2b64ce6e3..56aba24b42 100644
--- a/servers/physics_3d/joints/generic_6dof_joint_3d_sw.cpp
+++ b/servers/physics_3d/joints/generic_6dof_joint_3d_sw.cpp
@@ -34,7 +34,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h b/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h
index c2a0443aff..d0f3dbbd35 100644
--- a/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h
+++ b/servers/physics_3d/joints/generic_6dof_joint_3d_sw.h
@@ -40,7 +40,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/hinge_joint_3d_sw.cpp b/servers/physics_3d/joints/hinge_joint_3d_sw.cpp
index e2bf2845fe..b928f18231 100644
--- a/servers/physics_3d/joints/hinge_joint_3d_sw.cpp
+++ b/servers/physics_3d/joints/hinge_joint_3d_sw.cpp
@@ -34,7 +34,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/hinge_joint_3d_sw.h b/servers/physics_3d/joints/hinge_joint_3d_sw.h
index 572c35266f..22eb2f4660 100644
--- a/servers/physics_3d/joints/hinge_joint_3d_sw.h
+++ b/servers/physics_3d/joints/hinge_joint_3d_sw.h
@@ -40,7 +40,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/jacobian_entry_3d_sw.h b/servers/physics_3d/joints/jacobian_entry_3d_sw.h
index 30c80db23f..6afa70c816 100644
--- a/servers/physics_3d/joints/jacobian_entry_3d_sw.h
+++ b/servers/physics_3d/joints/jacobian_entry_3d_sw.h
@@ -37,7 +37,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/pin_joint_3d_sw.cpp b/servers/physics_3d/joints/pin_joint_3d_sw.cpp
index 7a713c1161..8eb84d1c2f 100644
--- a/servers/physics_3d/joints/pin_joint_3d_sw.cpp
+++ b/servers/physics_3d/joints/pin_joint_3d_sw.cpp
@@ -34,7 +34,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/pin_joint_3d_sw.h b/servers/physics_3d/joints/pin_joint_3d_sw.h
index 09deefc5c4..3d91452850 100644
--- a/servers/physics_3d/joints/pin_joint_3d_sw.h
+++ b/servers/physics_3d/joints/pin_joint_3d_sw.h
@@ -40,7 +40,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/slider_joint_3d_sw.cpp b/servers/physics_3d/joints/slider_joint_3d_sw.cpp
index 9f01196c30..1895fe1e2e 100644
--- a/servers/physics_3d/joints/slider_joint_3d_sw.cpp
+++ b/servers/physics_3d/joints/slider_joint_3d_sw.cpp
@@ -34,7 +34,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/joints/slider_joint_3d_sw.h b/servers/physics_3d/joints/slider_joint_3d_sw.h
index f09476f570..f357bbd67a 100644
--- a/servers/physics_3d/joints/slider_joint_3d_sw.h
+++ b/servers/physics_3d/joints/slider_joint_3d_sw.h
@@ -40,7 +40,7 @@ Adapted to Godot from the Bullet library.
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/physics_3d/shape_3d_sw.cpp b/servers/physics_3d/shape_3d_sw.cpp
index 5858817e3b..c28ea92fb6 100644
--- a/servers/physics_3d/shape_3d_sw.cpp
+++ b/servers/physics_3d/shape_3d_sw.cpp
@@ -39,7 +39,7 @@
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2009 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
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.
diff --git a/servers/physics_3d/soft_body_3d_sw.cpp b/servers/physics_3d/soft_body_3d_sw.cpp
index d7e13867bf..5f6e202c73 100644
--- a/servers/physics_3d/soft_body_3d_sw.cpp
+++ b/servers/physics_3d/soft_body_3d_sw.cpp
@@ -38,7 +38,7 @@
/*
Bullet Continuous Collision Detection and Physics Library
-Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org
+Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
diff --git a/servers/rendering/rasterizer_dummy.h b/servers/rendering/rasterizer_dummy.h
index f58d124140..35bb7722e7 100644
--- a/servers/rendering/rasterizer_dummy.h
+++ b/servers/rendering/rasterizer_dummy.h
@@ -197,7 +197,7 @@ public:
TypedArray<Image> bake_render_uv2(RID p_base, const Vector<RID> &p_material_overrides, const Size2i &p_image_size) override { return TypedArray<Image>(); }
- bool free(RID p_rid) override { return true; }
+ bool free(RID p_rid) override { return false; }
void update() override {}
void sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) override {}
@@ -664,8 +664,9 @@ public:
DummyTexture *texture = texture_owner.getornull(p_rid);
texture_owner.free(p_rid);
memdelete(texture);
+ return true;
}
- return true;
+ return false;
}
virtual void update_memory_info() override {}
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 1b730567d9..9201f917db 100644
--- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp
+++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp
@@ -223,7 +223,6 @@ void RenderForwardClustered::RenderBufferDataForwardClustered::configure(RID p_c
RD::TEXTURE_SAMPLES_2,
RD::TEXTURE_SAMPLES_4,
RD::TEXTURE_SAMPLES_8,
- RD::TEXTURE_SAMPLES_16
};
texture_samples = ts[p_msaa];
@@ -1163,7 +1162,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co
render_buffer = (RenderBufferDataForwardClustered *)render_buffers_get_data(p_render_data->render_buffers);
}
RendererSceneEnvironmentRD *env = get_environment(p_render_data->environment);
- static const int texture_multisamples[RS::VIEWPORT_MSAA_MAX] = { 1, 2, 4, 8, 16 };
+ static const int texture_multisamples[RS::VIEWPORT_MSAA_MAX] = { 1, 2, 4, 8 };
//first of all, make a new render pass
//fill up ubo
diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp
index a24860996c..d0f02b44cb 100644
--- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp
+++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp
@@ -601,10 +601,10 @@ void SceneShaderForwardClustered::init(RendererStorageRD *p_storage, const Strin
actions.usage_defines["UV2"] = "#define UV2_USED\n";
actions.usage_defines["BONE_INDICES"] = "#define BONES_USED\n";
actions.usage_defines["BONE_WEIGHTS"] = "#define WEIGHTS_USED\n";
- actions.usage_defines["CUSTOM0"] = "#define CUSTOM0\n";
- actions.usage_defines["CUSTOM1"] = "#define CUSTOM1\n";
- actions.usage_defines["CUSTOM2"] = "#define CUSTOM2\n";
- actions.usage_defines["CUSTOM3"] = "#define CUSTOM3\n";
+ actions.usage_defines["CUSTOM0"] = "#define CUSTOM0_USED\n";
+ actions.usage_defines["CUSTOM1"] = "#define CUSTOM1_USED\n";
+ actions.usage_defines["CUSTOM2"] = "#define CUSTOM2_USED\n";
+ actions.usage_defines["CUSTOM3"] = "#define CUSTOM3_USED\n";
actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";
actions.usage_defines["NORMAL_MAP_DEPTH"] = "@NORMAL_MAP";
actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
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 276a44bc27..a5cc2db48f 100644
--- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp
+++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp
@@ -159,7 +159,6 @@ void RenderForwardMobile::RenderBufferDataForwardMobile::configure(RID p_color_b
RD::TEXTURE_SAMPLES_2,
RD::TEXTURE_SAMPLES_4,
RD::TEXTURE_SAMPLES_8,
- RD::TEXTURE_SAMPLES_16
};
texture_samples = ts[p_msaa];
diff --git a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp
index 14b3b6d9aa..cd314d8c56 100644
--- a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp
+++ b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp
@@ -593,10 +593,10 @@ void SceneShaderForwardMobile::init(RendererStorageRD *p_storage, const String p
actions.usage_defines["UV2"] = "#define UV2_USED\n";
actions.usage_defines["BONE_INDICES"] = "#define BONES_USED\n";
actions.usage_defines["BONE_WEIGHTS"] = "#define WEIGHTS_USED\n";
- actions.usage_defines["CUSTOM0"] = "#define CUSTOM0\n";
- actions.usage_defines["CUSTOM1"] = "#define CUSTOM1\n";
- actions.usage_defines["CUSTOM2"] = "#define CUSTOM2\n";
- actions.usage_defines["CUSTOM3"] = "#define CUSTOM3\n";
+ actions.usage_defines["CUSTOM0"] = "#define CUSTOM0_USED\n";
+ actions.usage_defines["CUSTOM1"] = "#define CUSTOM1_USED\n";
+ actions.usage_defines["CUSTOM2"] = "#define CUSTOM2_USED\n";
+ actions.usage_defines["CUSTOM3"] = "#define CUSTOM3_USED\n";
actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";
actions.usage_defines["NORMAL_MAP_DEPTH"] = "@NORMAL_MAP";
actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
index 647c348d9f..3c66fadbe9 100644
--- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp
@@ -1086,7 +1086,7 @@ void RendererCanvasRenderRD::_render_items(RID p_to_render_target, int p_item_co
}
}
- RID material = ci->material;
+ 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;
@@ -1354,8 +1354,10 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p
}
}
- if (ci->material.is_valid()) {
- MaterialData *md = (MaterialData *)storage->material_get_data(ci->material, RendererStorageRD::SHADER_TYPE_2D);
+ RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
+
+ if (material.is_valid()) {
+ MaterialData *md = (MaterialData *)storage->material_get_data(material, RendererStorageRD::SHADER_TYPE_2D);
if (md && md->shader_data->valid) {
if (md->shader_data->uses_screen_texture && canvas_group_owner == nullptr) {
if (!material_screen_texture_found) {
@@ -1375,7 +1377,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p
if (!RD::get_singleton()->uniform_set_is_valid(md->uniform_set)) {
// uniform set may be gone because a dependency was erased. In this case, it will happen
// if a texture is deleted, so just re-create it.
- storage->material_force_update_textures(ci->material, RendererStorageRD::SHADER_TYPE_2D);
+ storage->material_force_update_textures(material, RendererStorageRD::SHADER_TYPE_2D);
}
}
}
diff --git a/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp
index 098e2a5c87..36943c5e5c 100644
--- a/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp
+++ b/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp
@@ -1469,7 +1469,7 @@ void RendererSceneGIRD::SDFGI::pre_process_gi(const Transform3D &p_transform, Re
lights[idx].color[1] = color.g;
lights[idx].color[2] = color.b;
lights[idx].type = RS::LIGHT_DIRECTIONAL;
- lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
+ lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY) * storage->light_get_param(li->light, RS::LIGHT_PARAM_INDIRECT_ENERGY);
lights[idx].has_shadow = storage->light_has_shadow(li->light);
idx++;
@@ -1514,7 +1514,7 @@ void RendererSceneGIRD::SDFGI::pre_process_gi(const Transform3D &p_transform, Re
lights[idx].color[1] = color.g;
lights[idx].color[2] = color.b;
lights[idx].type = storage->light_get_type(li->light);
- lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
+ lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY) * storage->light_get_param(li->light, RS::LIGHT_PARAM_INDIRECT_ENERGY);
lights[idx].has_shadow = storage->light_has_shadow(li->light);
lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
@@ -1953,7 +1953,7 @@ void RendererSceneGIRD::SDFGI::render_static_lights(RID p_render_buffers, uint32
lights[idx].color[0] = color.r;
lights[idx].color[1] = color.g;
lights[idx].color[2] = color.b;
- lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
+ lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY) * storage->light_get_param(li->light, RS::LIGHT_PARAM_INDIRECT_ENERGY);
lights[idx].has_shadow = storage->light_has_shadow(li->light);
lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl
index edbe1031b7..8cb56fbc83 100644
--- a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl
+++ b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl
@@ -903,6 +903,7 @@ void main() {
if (scene_data.use_reflection_cubemap) {
vec3 ref_vec = reflect(-view, normal);
+ float horizon = min(1.0 + dot(ref_vec, normal), 1.0);
ref_vec = scene_data.radiance_inverse_xform * ref_vec;
#ifdef USE_RADIANCE_CUBEMAP_ARRAY
@@ -915,7 +916,6 @@ void main() {
specular_light = textureLod(samplerCube(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), ref_vec, roughness * MAX_ROUGHNESS_LOD).rgb;
#endif //USE_RADIANCE_CUBEMAP_ARRAY
- float horizon = min(1.0 + dot(ref_vec, normal), 1.0);
specular_light *= horizon * horizon;
specular_light *= scene_data.ambient_light_color_energy.a;
}
diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl
index 518b0a6c7f..c3c4139450 100644
--- a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl
+++ b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl
@@ -868,6 +868,7 @@ void main() {
if (scene_data.use_reflection_cubemap) {
vec3 ref_vec = reflect(-view, normal);
+ float horizon = min(1.0 + dot(ref_vec, normal), 1.0);
ref_vec = scene_data.radiance_inverse_xform * ref_vec;
#ifdef USE_RADIANCE_CUBEMAP_ARRAY
@@ -880,7 +881,6 @@ void main() {
specular_light = textureLod(samplerCube(radiance_cubemap, material_samplers[SAMPLER_LINEAR_WITH_MIPMAPS_CLAMP]), ref_vec, roughness * MAX_ROUGHNESS_LOD).rgb;
#endif //USE_RADIANCE_CUBEMAP_ARRAY
- float horizon = min(1.0 + dot(ref_vec, normal), 1.0);
specular_light *= horizon * horizon;
specular_light *= scene_data.ambient_light_color_energy.a;
}
diff --git a/servers/rendering/renderer_rd/shaders/tonemap.glsl b/servers/rendering/renderer_rd/shaders/tonemap.glsl
index 4411587116..1ce3e04421 100644
--- a/servers/rendering/renderer_rd/shaders/tonemap.glsl
+++ b/servers/rendering/renderer_rd/shaders/tonemap.glsl
@@ -169,16 +169,33 @@ vec3 tonemap_filmic(vec3 color, float white) {
return color_tonemapped / white_tonemapped;
}
+// Adapted from https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl
+// (MIT License).
vec3 tonemap_aces(vec3 color, float white) {
- const float exposure_bias = 0.85f;
- const float A = 2.51f * exposure_bias * exposure_bias;
- const float B = 0.03f * exposure_bias;
- const float C = 2.43f * exposure_bias * exposure_bias;
- const float D = 0.59f * exposure_bias;
- const float E = 0.14f;
-
- vec3 color_tonemapped = (color * (A * color + B)) / (color * (C * color + D) + E);
- float white_tonemapped = (white * (A * white + B)) / (white * (C * white + D) + E);
+ const float exposure_bias = 1.8f;
+ const float A = 0.0245786f;
+ const float B = 0.000090537f;
+ const float C = 0.983729f;
+ const float D = 0.432951f;
+ const float E = 0.238081f;
+
+ // Exposure bias baked into transform to save shader instructions. Equivalent to `color *= exposure_bias`
+ const mat3 rgb_to_rrt = mat3(
+ vec3(0.59719f * exposure_bias, 0.35458f * exposure_bias, 0.04823f * exposure_bias),
+ vec3(0.07600f * exposure_bias, 0.90834f * exposure_bias, 0.01566f * exposure_bias),
+ vec3(0.02840f * exposure_bias, 0.13383f * exposure_bias, 0.83777f * exposure_bias));
+
+ const mat3 odt_to_rgb = mat3(
+ vec3(1.60475f, -0.53108f, -0.07367f),
+ vec3(-0.10208f, 1.10813f, -0.00605f),
+ vec3(-0.00327f, -0.07276f, 1.07602f));
+
+ color *= rgb_to_rrt;
+ vec3 color_tonemapped = (color * (color + A) - B) / (color * (C * color + D) + E);
+ color_tonemapped *= odt_to_rgb;
+
+ white *= exposure_bias;
+ float white_tonemapped = (white * (white + A) - B) / (white * (C * white + D) + E);
return color_tonemapped / white_tonemapped;
}
@@ -200,15 +217,16 @@ vec3 linear_to_srgb(vec3 color) {
#define TONEMAPPER_ACES 3
vec3 apply_tonemapping(vec3 color, float white) { // inputs are LINEAR, always outputs clamped [0;1] color
-
+ // Ensure color values passed to tonemappers are positive.
+ // They can be negative in the case of negative lights, which leads to undesired behavior.
if (params.tonemapper == TONEMAPPER_LINEAR) {
return color;
} else if (params.tonemapper == TONEMAPPER_REINHARD) {
- return tonemap_reinhard(color, white);
+ return tonemap_reinhard(max(vec3(0.0f), color), white);
} else if (params.tonemapper == TONEMAPPER_FILMIC) {
- return tonemap_filmic(color, white);
+ return tonemap_filmic(max(vec3(0.0f), color), white);
} else { // TONEMAPPER_ACES
- return tonemap_aces(color, white);
+ return tonemap_aces(max(vec3(0.0f), color), white);
}
}
@@ -401,9 +419,7 @@ void main() {
color += screen_space_dither(gl_FragCoord.xy);
}
- // Ensure color values passed to tonemappers are positive.
- // They can be negative in the case of negative lights, which leads to undesired behavior.
- color = apply_tonemapping(max(vec3(0.0), color), params.white);
+ color = apply_tonemapping(color, params.white);
color = linear_to_srgb(color); // regular linear -> SRGB conversion
diff --git a/servers/rendering/rendering_device.cpp b/servers/rendering/rendering_device.cpp
index b302c6b793..70f676e5ac 100644
--- a/servers/rendering/rendering_device.cpp
+++ b/servers/rendering/rendering_device.cpp
@@ -478,12 +478,28 @@ void RenderingDevice::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_memory_usage"), &RenderingDevice::get_memory_usage);
+ ClassDB::bind_method(D_METHOD("get_driver_resource", "resource", "rid", "index"), &RenderingDevice::get_driver_resource);
+
BIND_CONSTANT(BARRIER_MASK_RASTER);
BIND_CONSTANT(BARRIER_MASK_COMPUTE);
BIND_CONSTANT(BARRIER_MASK_TRANSFER);
BIND_CONSTANT(BARRIER_MASK_ALL);
BIND_CONSTANT(BARRIER_MASK_NO_BARRIER);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DEVICE);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_INSTANCE);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_VIEW);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_SAMPLER);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_BUFFER);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE);
+ BIND_ENUM_CONSTANT(DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE);
+
BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4_UNORM_PACK8);
BIND_ENUM_CONSTANT(DATA_FORMAT_R4G4B4A4_UNORM_PACK16);
BIND_ENUM_CONSTANT(DATA_FORMAT_B4G4R4A4_UNORM_PACK16);
diff --git a/servers/rendering/rendering_device.h b/servers/rendering/rendering_device.h
index 2cf1f165dd..5eb8f1cead 100644
--- a/servers/rendering/rendering_device.h
+++ b/servers/rendering/rendering_device.h
@@ -60,6 +60,23 @@ public:
DEVICE_DIRECTX
};
+ enum DriverResource {
+ DRIVER_RESOURCE_VULKAN_DEVICE = 0,
+ DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE,
+ DRIVER_RESOURCE_VULKAN_INSTANCE,
+ DRIVER_RESOURCE_VULKAN_QUEUE,
+ DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX,
+ DRIVER_RESOURCE_VULKAN_IMAGE,
+ DRIVER_RESOURCE_VULKAN_IMAGE_VIEW,
+ DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT,
+ DRIVER_RESOURCE_VULKAN_SAMPLER,
+ DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET,
+ DRIVER_RESOURCE_VULKAN_BUFFER,
+ DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE,
+ DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE,
+ //next driver continue enum from 1000 to keep order
+ };
+
enum ShaderStage {
SHADER_STAGE_VERTEX,
SHADER_STAGE_FRAGMENT,
@@ -1183,6 +1200,8 @@ public:
virtual String get_device_name() const = 0;
virtual String get_device_pipeline_cache_uuid() const = 0;
+ virtual uint64_t get_driver_resource(DriverResource p_resource, RID p_rid = RID(), uint64_t p_index = 0) = 0;
+
static RenderingDevice *get_singleton();
RenderingDevice();
@@ -1217,6 +1236,7 @@ protected:
Vector<int64_t> _draw_list_switch_to_next_pass_split(uint32_t p_splits);
};
+VARIANT_ENUM_CAST(RenderingDevice::DriverResource)
VARIANT_ENUM_CAST(RenderingDevice::ShaderStage)
VARIANT_ENUM_CAST(RenderingDevice::ShaderLanguage)
VARIANT_ENUM_CAST(RenderingDevice::CompareOperator)
diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp
index 78604dfe8c..1b10e4dcbe 100644
--- a/servers/rendering_server.cpp
+++ b/servers/rendering_server.cpp
@@ -500,7 +500,7 @@ Error RenderingServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint
case RS::ARRAY_CUSTOM1:
case RS::ARRAY_CUSTOM2:
case RS::ARRAY_CUSTOM3: {
- uint32_t type = (p_format >> (ARRAY_FORMAT_CUSTOM_BASE + ARRAY_FORMAT_CUSTOM_BITS * (RS::ARRAY_CUSTOM0 - ai))) & ARRAY_FORMAT_CUSTOM_MASK;
+ uint32_t type = (p_format >> (ARRAY_FORMAT_CUSTOM_BASE + ARRAY_FORMAT_CUSTOM_BITS * (ai - RS::ARRAY_CUSTOM0))) & ARRAY_FORMAT_CUSTOM_MASK;
switch (type) {
case ARRAY_CUSTOM_RGBA8_UNORM:
case ARRAY_CUSTOM_RGBA8_SNORM:
@@ -541,14 +541,14 @@ Error RenderingServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint
ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::PACKED_FLOAT32_ARRAY, ERR_INVALID_PARAMETER);
Vector<float> array = p_arrays[ai];
- int32_t s = ARRAY_CUSTOM_R_FLOAT - ai + 1;
+ int32_t s = type - ARRAY_CUSTOM_R_FLOAT + 1;
ERR_FAIL_COND_V(array.size() != p_vertex_array_len * s, ERR_INVALID_PARAMETER);
const float *src = array.ptr();
for (int i = 0; i < p_vertex_array_len; i++) {
- memcpy(&aw[p_offsets[ai] + i * p_attrib_stride], &src[i * s], 4 * s);
+ memcpy(&aw[p_offsets[ai] + i * p_attrib_stride], &src[i * s], sizeof(float) * s);
}
} break;
default: {
@@ -938,6 +938,13 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa
}
}
+ for (uint32_t i = 0; i < RS::ARRAY_CUSTOM_COUNT; ++i) {
+ // include custom array format type.
+ if (format & (1 << (ARRAY_CUSTOM0 + i))) {
+ format |= (RS::ARRAY_FORMAT_CUSTOM_MASK << (RS::ARRAY_FORMAT_CUSTOM_BASE + i * RS::ARRAY_FORMAT_CUSTOM_BITS)) & p_compress_format;
+ }
+ }
+
uint32_t offsets[RS::ARRAY_MAX];
uint32_t vertex_element_size;
@@ -1191,7 +1198,7 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
case RS::ARRAY_CUSTOM1:
case RS::ARRAY_CUSTOM2:
case RS::ARRAY_CUSTOM3: {
- uint32_t type = (p_format >> (ARRAY_FORMAT_CUSTOM_BASE + ARRAY_FORMAT_CUSTOM_BITS * (RS::ARRAY_CUSTOM0 - i))) & ARRAY_FORMAT_CUSTOM_MASK;
+ uint32_t type = (p_format >> (ARRAY_FORMAT_CUSTOM_BASE + ARRAY_FORMAT_CUSTOM_BITS * (i - RS::ARRAY_CUSTOM0))) & ARRAY_FORMAT_CUSTOM_MASK;
switch (type) {
case ARRAY_CUSTOM_RGBA8_UNORM:
case ARRAY_CUSTOM_RGBA8_SNORM:
@@ -1219,6 +1226,8 @@ Array RenderingServer::_get_array_from_surface(uint32_t p_format, Vector<uint8_t
uint32_t s = type - ARRAY_CUSTOM_R_FLOAT + 1;
Vector<float> arr;
+ arr.resize(s * p_vertex_len);
+
float *w = arr.ptrw();
for (int j = 0; j < p_vertex_len; j++) {
@@ -1467,6 +1476,11 @@ ShaderLanguage::DataType RenderingServer::global_variable_type_get_shader_dataty
}
}
+RenderingDevice *RenderingServer::get_rendering_device() const {
+ // return the rendering device we're using globally
+ return RenderingDevice::get_singleton();
+}
+
RenderingDevice *RenderingServer::create_local_rendering_device() const {
return RenderingDevice::get_singleton()->create_local_device();
}
@@ -2211,7 +2225,6 @@ void RenderingServer::_bind_methods() {
BIND_ENUM_CONSTANT(VIEWPORT_MSAA_2X);
BIND_ENUM_CONSTANT(VIEWPORT_MSAA_4X);
BIND_ENUM_CONSTANT(VIEWPORT_MSAA_8X);
- BIND_ENUM_CONSTANT(VIEWPORT_MSAA_16X);
BIND_ENUM_CONSTANT(VIEWPORT_MSAA_MAX);
BIND_ENUM_CONSTANT(VIEWPORT_SCREEN_SPACE_AA_DISABLED);
@@ -2714,6 +2727,7 @@ void RenderingServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("force_sync"), &RenderingServer::sync);
ClassDB::bind_method(D_METHOD("force_draw", "swap_buffers", "frame_step"), &RenderingServer::draw, DEFVAL(true), DEFVAL(0.0));
+ ClassDB::bind_method(D_METHOD("get_rendering_device"), &RenderingServer::get_rendering_device);
ClassDB::bind_method(D_METHOD("create_local_rendering_device"), &RenderingServer::create_local_rendering_device);
}
diff --git a/servers/rendering_server.h b/servers/rendering_server.h
index 8fbf231d9b..1b04a6e5e2 100644
--- a/servers/rendering_server.h
+++ b/servers/rendering_server.h
@@ -836,7 +836,6 @@ public:
VIEWPORT_MSAA_2X,
VIEWPORT_MSAA_4X,
VIEWPORT_MSAA_8X,
- VIEWPORT_MSAA_16X,
VIEWPORT_MSAA_MAX,
};
@@ -1493,6 +1492,7 @@ public:
virtual void set_print_gpu_profile(bool p_enable) = 0;
+ RenderingDevice *get_rendering_device() const;
RenderingDevice *create_local_rendering_device() const;
bool is_render_loop_enabled() const;
diff --git a/servers/xr/xr_interface.cpp b/servers/xr/xr_interface.cpp
index fc1d82a964..bf54158905 100644
--- a/servers/xr/xr_interface.cpp
+++ b/servers/xr/xr_interface.cpp
@@ -29,7 +29,7 @@
/*************************************************************************/
#include "xr_interface.h"
-#include "servers/rendering/renderer_compositor.h"
+// #include "servers/rendering/renderer_compositor.h"
void XRInterface::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_name"), &XRInterface::get_name);
diff --git a/servers/xr/xr_interface_extension.cpp b/servers/xr/xr_interface_extension.cpp
index 5c90139375..6340485bde 100644
--- a/servers/xr/xr_interface_extension.cpp
+++ b/servers/xr/xr_interface_extension.cpp
@@ -29,7 +29,8 @@
/*************************************************************************/
#include "xr_interface_extension.h"
-#include "servers/rendering/renderer_compositor.h"
+#include "servers/rendering/renderer_storage.h"
+#include "servers/rendering/rendering_server_globals.h"
void XRInterfaceExtension::_bind_methods() {
GDVIRTUAL_BIND(_get_name);
@@ -41,8 +42,6 @@ void XRInterfaceExtension::_bind_methods() {
GDVIRTUAL_BIND(_get_tracking_status);
- ClassDB::bind_method(D_METHOD("add_blit", "render_target", "src_rect", "dst_rect", "use_layer", "layer", "apply_lens_distortion", "eye_center", "k1", "k2", "upscale", "aspect_ratio"), &XRInterfaceExtension::add_blit);
-
GDVIRTUAL_BIND(_get_render_target_size);
GDVIRTUAL_BIND(_get_view_count);
GDVIRTUAL_BIND(_get_camera_transform);
@@ -60,6 +59,11 @@ void XRInterfaceExtension::_bind_methods() {
GDVIRTUAL_BIND(_get_anchor_detection_is_enabled);
GDVIRTUAL_BIND(_set_anchor_detection_is_enabled, "enabled");
GDVIRTUAL_BIND(_get_camera_feed_id);
+
+ // helper methods
+ ClassDB::bind_method(D_METHOD("add_blit", "render_target", "src_rect", "dst_rect", "use_layer", "layer", "apply_lens_distortion", "eye_center", "k1", "k2", "upscale", "aspect_ratio"), &XRInterfaceExtension::add_blit);
+ ClassDB::bind_method(D_METHOD("get_render_target_texture", "render_target"), &XRInterfaceExtension::get_render_target_texture);
+ // ClassDB::bind_method(D_METHOD("get_render_target_depth", "render_target"), &XRInterfaceExtension::get_render_target_depth);
}
StringName XRInterfaceExtension::get_name() const {
@@ -240,3 +244,19 @@ void XRInterfaceExtension::process() {
void XRInterfaceExtension::notification(int p_what) {
GDVIRTUAL_CALL(_notification, p_what);
}
+
+RID XRInterfaceExtension::get_render_target_texture(RID p_render_target) {
+ RendererStorage *storage = RSG::storage;
+ ERR_FAIL_NULL_V_MSG(storage, RID(), "Renderer storage not setup");
+
+ return storage->render_target_get_texture(p_render_target);
+}
+
+/*
+RID XRInterfaceExtension::get_render_target_depth(RID p_render_target) {
+ RendererStorage *storage = RSG::storage;
+ ERR_FAIL_NULL_V_MSG(storage, RID(), "Renderer storage not setup");
+
+ return storage->render_target_get_depth(p_render_target);
+}
+*/
diff --git a/servers/xr/xr_interface_extension.h b/servers/xr/xr_interface_extension.h
index df6f5f8e35..94914a7b3f 100644
--- a/servers/xr/xr_interface_extension.h
+++ b/servers/xr/xr_interface_extension.h
@@ -100,6 +100,10 @@ public:
GDVIRTUAL0(_process);
GDVIRTUAL1(_notification, int);
+
+ /* access to some internals we need */
+ RID get_render_target_texture(RID p_render_target);
+ // RID get_render_target_depth(RID p_render_target);
};
#endif // !XR_INTERFACE_EXTENSION_H
diff --git a/tests/test_array.h b/tests/test_array.h
index 52da256860..3bd476fd27 100644
--- a/tests/test_array.h
+++ b/tests/test_array.h
@@ -39,6 +39,7 @@
#include "core/variant/container_type_validate.h"
#include "core/variant/variant.h"
#include "tests/test_macros.h"
+#include "tests/test_tools.h"
namespace TestArray {
@@ -170,6 +171,56 @@ TEST_CASE("[Array] push_front(), pop_front(), pop_back()") {
CHECK(arr.size() == 2);
}
+TEST_CASE("[Array] pop_at()") {
+ ErrorDetector ed;
+
+ Array arr;
+ arr.push_back(2);
+ arr.push_back(4);
+ arr.push_back(6);
+ arr.push_back(8);
+ arr.push_back(10);
+
+ REQUIRE(int(arr.pop_at(2)) == 6);
+ REQUIRE(arr.size() == 4);
+ CHECK(int(arr[0]) == 2);
+ CHECK(int(arr[1]) == 4);
+ CHECK(int(arr[2]) == 8);
+ CHECK(int(arr[3]) == 10);
+
+ REQUIRE(int(arr.pop_at(2)) == 8);
+ REQUIRE(arr.size() == 3);
+ CHECK(int(arr[0]) == 2);
+ CHECK(int(arr[1]) == 4);
+ CHECK(int(arr[2]) == 10);
+
+ // Negative index.
+ REQUIRE(int(arr.pop_at(-1)) == 10);
+ REQUIRE(arr.size() == 2);
+ CHECK(int(arr[0]) == 2);
+ CHECK(int(arr[1]) == 4);
+
+ // Invalid pop.
+ ed.clear();
+ ERR_PRINT_OFF;
+ const Variant ret = arr.pop_at(-15);
+ ERR_PRINT_ON;
+ REQUIRE(ret.is_null());
+ CHECK(ed.has_error);
+
+ REQUIRE(int(arr.pop_at(0)) == 2);
+ REQUIRE(arr.size() == 1);
+ CHECK(int(arr[0]) == 4);
+
+ REQUIRE(int(arr.pop_at(0)) == 4);
+ REQUIRE(arr.is_empty());
+
+ // Pop from empty array.
+ ed.clear();
+ REQUIRE(arr.pop_at(24).is_null());
+ CHECK_FALSE(ed.has_error);
+}
+
TEST_CASE("[Array] max() and min()") {
Array arr;
arr.push_back(3);
diff --git a/tests/test_code_edit.h b/tests/test_code_edit.h
new file mode 100644
index 0000000000..9579d8ebef
--- /dev/null
+++ b/tests/test_code_edit.h
@@ -0,0 +1,813 @@
+/*************************************************************************/
+/* test_code_edit.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_CODE_EDIT_H
+#define TEST_CODE_EDIT_H
+
+#include "core/input/input_map.h"
+#include "core/object/message_queue.h"
+#include "core/os/keyboard.h"
+#include "core/string/string_builder.h"
+#include "scene/gui/code_edit.h"
+#include "scene/resources/default_theme/default_theme.h"
+
+#include "tests/test_macros.h"
+
+namespace TestCodeEdit {
+
+TEST_CASE("[SceneTree][CodeEdit] line gutters") {
+ CodeEdit *code_edit = memnew(CodeEdit);
+ SceneTree::get_singleton()->get_root()->add_child(code_edit);
+
+ SUBCASE("[CodeEdit] breakpoints") {
+ SIGNAL_WATCH(code_edit, "breakpoint_toggled");
+
+ SUBCASE("[CodeEdit] draw breakpoints gutter") {
+ code_edit->set_draw_breakpoints_gutter(false);
+ CHECK_FALSE(code_edit->is_drawing_breakpoints_gutter());
+
+ code_edit->set_draw_breakpoints_gutter(true);
+ CHECK(code_edit->is_drawing_breakpoints_gutter());
+ }
+
+ SUBCASE("[CodeEdit] set line as breakpoint") {
+ /* Out of bounds. */
+ ERR_PRINT_OFF;
+
+ code_edit->set_line_as_breakpoint(-1, true);
+ CHECK_FALSE(code_edit->is_line_breakpointed(-1));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ code_edit->set_line_as_breakpoint(1, true);
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ ERR_PRINT_ON;
+
+ Array arg1;
+ arg1.push_back(0);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_line_as_breakpoint(0, true);
+ CHECK(code_edit->is_line_breakpointed(0));
+ CHECK(code_edit->get_breakpointed_lines()[0] == Variant(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ code_edit->set_line_as_breakpoint(0, false);
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] clear breakpointed lines") {
+ code_edit->clear_breakpointed_lines();
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ Array arg1;
+ arg1.push_back(0);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_line_as_breakpoint(0, true);
+ CHECK(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ code_edit->clear_breakpointed_lines();
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and set text") {
+ Array arg1;
+ arg1.push_back(0);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_breakpoint(0, true);
+ CHECK(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* breakpoint on lines that still exist are kept. */
+ code_edit->set_text("");
+ MessageQueue::get_singleton()->flush();
+ CHECK(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ /* breakpoint on lines that are removed should also be removed. */
+ code_edit->clear_breakpointed_lines();
+ SIGNAL_DISCARD("breakpoint_toggled")
+
+ ((Array)args[0])[0] = 1;
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_breakpoint(1, true);
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ code_edit->set_text("");
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ ERR_PRINT_ON;
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and clear") {
+ Array arg1;
+ arg1.push_back(0);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_breakpoint(0, true);
+ CHECK(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* breakpoint on lines that still exist are removed. */
+ code_edit->clear();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* breakpoint on lines that are removed should also be removed. */
+ code_edit->clear_breakpointed_lines();
+ SIGNAL_DISCARD("breakpoint_toggled")
+
+ ((Array)args[0])[0] = 1;
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_breakpoint(1, true);
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ code_edit->clear();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ ERR_PRINT_ON;
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and new lines no text") {
+ Array arg1;
+ arg1.push_back(0);
+ Array args;
+ args.push_back(arg1);
+
+ /* No text moves breakpoint. */
+ code_edit->set_line_as_breakpoint(0, true);
+ CHECK(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* Normal. */
+ ((Array)args[0])[0] = 0;
+ Array arg2;
+ arg2.push_back(1);
+ args.push_back(arg2);
+
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* Non-Breaking. */
+ ((Array)args[0])[0] = 1;
+ ((Array)args[1])[0] = 2;
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_blank");
+ CHECK(code_edit->get_line_count() == 3);
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ CHECK(code_edit->is_line_breakpointed(2));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* Above. */
+ ((Array)args[0])[0] = 2;
+ ((Array)args[1])[0] = 3;
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_above");
+ CHECK(code_edit->get_line_count() == 4);
+ CHECK_FALSE(code_edit->is_line_breakpointed(2));
+ CHECK(code_edit->is_line_breakpointed(3));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and new lines with text") {
+ Array arg1;
+ arg1.push_back(0);
+ Array args;
+ args.push_back(arg1);
+
+ /* Having text does not move breakpoint. */
+ code_edit->insert_text_at_caret("text");
+ code_edit->set_line_as_breakpoint(0, true);
+ CHECK(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* Normal. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK(code_edit->is_line_breakpointed(0));
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ /* Non-Breaking. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_blank");
+ CHECK(code_edit->get_line_count() == 3);
+ CHECK(code_edit->is_line_breakpointed(0));
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ /* Above does move. */
+ ((Array)args[0])[0] = 0;
+ Array arg2;
+ arg2.push_back(1);
+ args.push_back(arg2);
+
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_above");
+ CHECK(code_edit->get_line_count() == 4);
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and backspace") {
+ Array arg1;
+ arg1.push_back(1);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_breakpoint(1, true);
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ code_edit->set_caret_line(2);
+
+ /* backspace onto line does not remove breakpoint */
+ SEND_GUI_ACTION(code_edit, "ui_text_backspace");
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ /* backspace on breakpointed line removes it */
+ SEND_GUI_ACTION(code_edit, "ui_text_backspace");
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ ERR_PRINT_ON;
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and delete") {
+ Array arg1;
+ arg1.push_back(1);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_breakpoint(1, true);
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ code_edit->set_caret_line(1);
+
+ /* Delete onto breakpointed lines does not remove it. */
+ SEND_GUI_ACTION(code_edit, "ui_text_delete");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+
+ /* Delete moving breakpointed line up removes it. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_delete");
+ CHECK(code_edit->get_line_count() == 1);
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ ERR_PRINT_ON;
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and delete selection") {
+ Array arg1;
+ arg1.push_back(1);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_breakpoint(1, true);
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ code_edit->select(0, 0, 2, 0);
+ code_edit->delete_selection();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+ }
+
+ SUBCASE("[CodeEdit] breakpoints and undo") {
+ Array arg1;
+ arg1.push_back(1);
+ Array args;
+ args.push_back(arg1);
+
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_breakpoint(1, true);
+ CHECK(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ code_edit->select(0, 0, 2, 0);
+ code_edit->delete_selection();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_breakpointed(0));
+ SIGNAL_CHECK("breakpoint_toggled", args);
+
+ /* Undo does not restore breakpoint. */
+ code_edit->undo();
+ CHECK_FALSE(code_edit->is_line_breakpointed(1));
+ SIGNAL_CHECK_FALSE("breakpoint_toggled");
+ }
+
+ SIGNAL_UNWATCH(code_edit, "breakpoint_toggled");
+ }
+
+ SUBCASE("[CodeEdit] bookmarks") {
+ SUBCASE("[CodeEdit] draw bookmarks gutter") {
+ code_edit->set_draw_bookmarks_gutter(false);
+ CHECK_FALSE(code_edit->is_drawing_bookmarks_gutter());
+
+ code_edit->set_draw_bookmarks_gutter(true);
+ CHECK(code_edit->is_drawing_bookmarks_gutter());
+ }
+
+ SUBCASE("[CodeEdit] set line as bookmarks") {
+ /* Out of bounds. */
+ ERR_PRINT_OFF;
+
+ code_edit->set_line_as_bookmarked(-1, true);
+ CHECK_FALSE(code_edit->is_line_bookmarked(-1));
+
+ code_edit->set_line_as_bookmarked(1, true);
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+
+ ERR_PRINT_ON;
+
+ code_edit->set_line_as_bookmarked(0, true);
+ CHECK(code_edit->get_bookmarked_lines()[0] == Variant(0));
+ CHECK(code_edit->is_line_bookmarked(0));
+
+ code_edit->set_line_as_bookmarked(0, false);
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ }
+
+ SUBCASE("[CodeEdit] clear bookmarked lines") {
+ code_edit->clear_bookmarked_lines();
+
+ code_edit->set_line_as_bookmarked(0, true);
+ CHECK(code_edit->is_line_bookmarked(0));
+
+ code_edit->clear_bookmarked_lines();
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and set text") {
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_bookmarked(0, true);
+ CHECK(code_edit->is_line_bookmarked(0));
+
+ /* bookmarks on lines that still exist are kept. */
+ code_edit->set_text("");
+ MessageQueue::get_singleton()->flush();
+ CHECK(code_edit->is_line_bookmarked(0));
+
+ /* bookmarks on lines that are removed should also be removed. */
+ code_edit->clear_bookmarked_lines();
+
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_bookmarked(1, true);
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ code_edit->set_text("");
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and clear") {
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_bookmarked(0, true);
+ CHECK(code_edit->is_line_bookmarked(0));
+
+ /* bookmarks on lines that still exist are removed. */
+ code_edit->clear();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+
+ /* bookmarks on lines that are removed should also be removed. */
+ code_edit->clear_bookmarked_lines();
+
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_bookmarked(1, true);
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ code_edit->clear();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and new lines no text") {
+ /* No text moves bookmarks. */
+ code_edit->set_line_as_bookmarked(0, true);
+ CHECK(code_edit->is_line_bookmarked(0));
+
+ /* Normal. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ /* Non-Breaking. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_blank");
+ CHECK(code_edit->get_line_count() == 3);
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+ CHECK(code_edit->is_line_bookmarked(2));
+
+ /* Above. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_above");
+ CHECK(code_edit->get_line_count() == 4);
+ CHECK_FALSE(code_edit->is_line_bookmarked(2));
+ CHECK(code_edit->is_line_bookmarked(3));
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and new lines with text") {
+ /* Having text does not move bookmark. */
+ code_edit->insert_text_at_caret("text");
+ code_edit->set_line_as_bookmarked(0, true);
+ CHECK(code_edit->is_line_bookmarked(0));
+
+ /* Normal. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK(code_edit->is_line_bookmarked(0));
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+
+ /* Non-Breaking. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_blank");
+ CHECK(code_edit->get_line_count() == 3);
+ CHECK(code_edit->is_line_bookmarked(0));
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+
+ /* Above does move. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_above");
+ CHECK(code_edit->get_line_count() == 4);
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ CHECK(code_edit->is_line_bookmarked(1));
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and backspace") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_bookmarked(1, true);
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ code_edit->set_caret_line(2);
+
+ /* backspace onto line does not remove bookmark */
+ SEND_GUI_ACTION(code_edit, "ui_text_backspace");
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ /* backspace on bookmarked line removes it */
+ SEND_GUI_ACTION(code_edit, "ui_text_backspace");
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and delete") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_bookmarked(1, true);
+ CHECK(code_edit->is_line_bookmarked(1));
+ code_edit->set_caret_line(1);
+
+ /* Delete onto bookmarked lines does not remove it. */
+ SEND_GUI_ACTION(code_edit, "ui_text_delete");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ /* Delete moving bookmarked line up removes it. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_delete");
+ CHECK(code_edit->get_line_count() == 1);
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and delete selection") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_bookmarked(1, true);
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ code_edit->select(0, 0, 2, 0);
+ code_edit->delete_selection();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+ }
+
+ SUBCASE("[CodeEdit] bookmarks and undo") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_bookmarked(1, true);
+ CHECK(code_edit->is_line_bookmarked(1));
+
+ code_edit->select(0, 0, 2, 0);
+ code_edit->delete_selection();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_bookmarked(0));
+
+ /* Undo does not restore bookmark. */
+ code_edit->undo();
+ CHECK_FALSE(code_edit->is_line_bookmarked(1));
+ }
+ }
+
+ SUBCASE("[CodeEdit] executing lines") {
+ SUBCASE("[CodeEdit] draw executing lines gutter") {
+ code_edit->set_draw_executing_lines_gutter(false);
+ CHECK_FALSE(code_edit->is_drawing_executing_lines_gutter());
+
+ code_edit->set_draw_executing_lines_gutter(true);
+ CHECK(code_edit->is_drawing_executing_lines_gutter());
+ }
+
+ SUBCASE("[CodeEdit] set line as executing lines") {
+ /* Out of bounds. */
+ ERR_PRINT_OFF;
+
+ code_edit->set_line_as_executing(-1, true);
+ CHECK_FALSE(code_edit->is_line_executing(-1));
+
+ code_edit->set_line_as_executing(1, true);
+ CHECK_FALSE(code_edit->is_line_executing(1));
+
+ ERR_PRINT_ON;
+
+ code_edit->set_line_as_executing(0, true);
+ CHECK(code_edit->get_executing_lines()[0] == Variant(0));
+ CHECK(code_edit->is_line_executing(0));
+
+ code_edit->set_line_as_executing(0, false);
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ }
+
+ SUBCASE("[CodeEdit] clear executing lines lines") {
+ code_edit->clear_executing_lines();
+
+ code_edit->set_line_as_executing(0, true);
+ CHECK(code_edit->is_line_executing(0));
+
+ code_edit->clear_executing_lines();
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ }
+
+ SUBCASE("[CodeEdit] executing lines and set text") {
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_executing(0, true);
+ CHECK(code_edit->is_line_executing(0));
+
+ /* executing on lines that still exist are kept. */
+ code_edit->set_text("");
+ MessageQueue::get_singleton()->flush();
+ CHECK(code_edit->is_line_executing(0));
+
+ /* executing on lines that are removed should also be removed. */
+ code_edit->clear_executing_lines();
+
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_executing(1, true);
+ CHECK(code_edit->is_line_executing(1));
+
+ code_edit->set_text("");
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_executing(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] executing lines and clear") {
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_executing(0, true);
+ CHECK(code_edit->is_line_executing(0));
+
+ /* executing on lines that still exist are removed. */
+ code_edit->clear();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_executing(0));
+
+ /* executing on lines that are removed should also be removed. */
+ code_edit->clear_executing_lines();
+
+ code_edit->set_text("test\nline");
+ code_edit->set_line_as_executing(1, true);
+ CHECK(code_edit->is_line_executing(1));
+
+ code_edit->clear();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_executing(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] executing lines and new lines no text") {
+ /* No text moves executing lines. */
+ code_edit->set_line_as_executing(0, true);
+ CHECK(code_edit->is_line_executing(0));
+
+ /* Normal. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ CHECK(code_edit->is_line_executing(1));
+
+ /* Non-Breaking. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_blank");
+ CHECK(code_edit->get_line_count() == 3);
+ CHECK_FALSE(code_edit->is_line_executing(1));
+ CHECK(code_edit->is_line_executing(2));
+
+ /* Above. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_above");
+ CHECK(code_edit->get_line_count() == 4);
+ CHECK_FALSE(code_edit->is_line_executing(2));
+ CHECK(code_edit->is_line_executing(3));
+ }
+
+ SUBCASE("[CodeEdit] executing lines and new lines with text") {
+ /* Having text does not move executing lines. */
+ code_edit->insert_text_at_caret("text");
+ code_edit->set_line_as_executing(0, true);
+ CHECK(code_edit->is_line_executing(0));
+
+ /* Normal. */
+ SEND_GUI_ACTION(code_edit, "ui_text_newline");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK(code_edit->is_line_executing(0));
+ CHECK_FALSE(code_edit->is_line_executing(1));
+
+ /* Non-Breaking. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_blank");
+ CHECK(code_edit->get_line_count() == 3);
+ CHECK(code_edit->is_line_executing(0));
+ CHECK_FALSE(code_edit->is_line_executing(1));
+
+ /* Above does move. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_newline_above");
+ CHECK(code_edit->get_line_count() == 4);
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ CHECK(code_edit->is_line_executing(1));
+ }
+
+ SUBCASE("[CodeEdit] executing lines and backspace") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_executing(1, true);
+ CHECK(code_edit->is_line_executing(1));
+
+ code_edit->set_caret_line(2);
+
+ /* backspace onto line does not remove executing lines. */
+ SEND_GUI_ACTION(code_edit, "ui_text_backspace");
+ CHECK(code_edit->is_line_executing(1));
+
+ /* backspace on executing line removes it */
+ SEND_GUI_ACTION(code_edit, "ui_text_backspace");
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_executing(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] executing lines and delete") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_executing(1, true);
+ CHECK(code_edit->is_line_executing(1));
+ code_edit->set_caret_line(1);
+
+ /* Delete onto executing lines does not remove it. */
+ SEND_GUI_ACTION(code_edit, "ui_text_delete");
+ CHECK(code_edit->get_line_count() == 2);
+ CHECK(code_edit->is_line_executing(1));
+
+ /* Delete moving executing line up removes it. */
+ code_edit->set_caret_line(0);
+ SEND_GUI_ACTION(code_edit, "ui_text_delete");
+ CHECK(code_edit->get_line_count() == 1);
+ ERR_PRINT_OFF;
+ CHECK_FALSE(code_edit->is_line_executing(1));
+ ERR_PRINT_ON;
+ }
+
+ SUBCASE("[CodeEdit] executing lines and delete selection") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_executing(1, true);
+ CHECK(code_edit->is_line_executing(1));
+
+ code_edit->select(0, 0, 2, 0);
+ code_edit->delete_selection();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_executing(0));
+ }
+
+ SUBCASE("[CodeEdit] executing lines and undo") {
+ code_edit->set_text("\n\n");
+ code_edit->set_line_as_executing(1, true);
+ CHECK(code_edit->is_line_executing(1));
+
+ code_edit->select(0, 0, 2, 0);
+ code_edit->delete_selection();
+ MessageQueue::get_singleton()->flush();
+ CHECK_FALSE(code_edit->is_line_executing(0));
+
+ /* Undo does not restore executing lines. */
+ code_edit->undo();
+ CHECK_FALSE(code_edit->is_line_executing(1));
+ }
+ }
+
+ SUBCASE("[CodeEdit] line numbers") {
+ SUBCASE("[CodeEdit] draw line numbers gutter and padding") {
+ code_edit->set_draw_line_numbers(false);
+ CHECK_FALSE(code_edit->is_draw_line_numbers_enabled());
+
+ code_edit->set_draw_line_numbers(true);
+ CHECK(code_edit->is_draw_line_numbers_enabled());
+
+ code_edit->set_line_numbers_zero_padded(false);
+ CHECK_FALSE(code_edit->is_line_numbers_zero_padded());
+
+ code_edit->set_line_numbers_zero_padded(true);
+ CHECK(code_edit->is_line_numbers_zero_padded());
+
+ code_edit->set_line_numbers_zero_padded(false);
+ CHECK_FALSE(code_edit->is_line_numbers_zero_padded());
+
+ code_edit->set_draw_line_numbers(false);
+ CHECK_FALSE(code_edit->is_draw_line_numbers_enabled());
+
+ code_edit->set_line_numbers_zero_padded(true);
+ CHECK(code_edit->is_line_numbers_zero_padded());
+ }
+ }
+
+ SUBCASE("[CodeEdit] line folding") {
+ SUBCASE("[CodeEdit] draw line folding gutter") {
+ code_edit->set_draw_fold_gutter(false);
+ CHECK_FALSE(code_edit->is_drawing_fold_gutter());
+
+ code_edit->set_draw_fold_gutter(true);
+ CHECK(code_edit->is_drawing_fold_gutter());
+ }
+ }
+
+ memdelete(code_edit);
+}
+
+} // namespace TestCodeEdit
+
+#endif // TEST_CODE_EDIT_H
diff --git a/tests/test_macros.h b/tests/test_macros.h
index a1f1932db4..bf1001fa67 100644
--- a/tests/test_macros.h
+++ b/tests/test_macros.h
@@ -31,6 +31,8 @@
#ifndef TEST_MACROS_H
#define TEST_MACROS_H
+#include "core/object/callable_method_pointer.h"
+#include "core/object/class_db.h"
#include "core/templates/map.h"
#include "core/variant/variant.h"
@@ -129,4 +131,186 @@ int register_test_command(String p_command, TestFunc p_function);
register_test_command(m_command, m_function); \
DOCTEST_GLOBAL_NO_WARNINGS_END()
+// Utility macro to send an action event to a given object
+// Requires Message Queue and InputMap to be setup.
+
+#define SEND_GUI_ACTION(m_object, m_action) \
+ { \
+ const List<Ref<InputEvent>> *events = InputMap::get_singleton()->action_get_events(m_action); \
+ const List<Ref<InputEvent>>::Element *first_event = events->front(); \
+ Ref<InputEventKey> event = first_event->get(); \
+ event->set_pressed(true); \
+ m_object->gui_input(event); \
+ MessageQueue::get_singleton()->flush(); \
+ }
+
+// Utility class / macros for testing signals
+//
+// Use SIGNAL_WATCH(*object, "signal_name") to start watching
+// Makes sure to call SIGNAL_UNWATCH(*object, "signal_name") to stop watching in cleanup, this is not done automatically.
+//
+// The SignalWatcher will capture all signals and their args sent between checks.
+//
+// Use SIGNAL_CHECK("signal_name"), Vector<Vector<Variant>>), to check the arguments of all fired signals.
+// The outer vector is each fired signal, the inner vector the list of arguments for that signal. Order does matter.
+//
+// Use SIGNAL_CHECK_FALSE("signal_name") to check if a signal was not fired.
+//
+// Use SIGNAL_DISCARD("signal_name") to discard records all of the given signal, use only in placed you don't need to check.
+//
+// All signals are automaticaly discared between test/sub test cases.
+
+class SignalWatcher : public Object {
+private:
+ inline static SignalWatcher *singleton;
+
+ /* Equal to: Map<String, Vector<Vector<Variant>>> */
+ Map<String, Array> _signals;
+ void _add_signal_entry(const Array &p_args, const String &p_name) {
+ if (!_signals.has(p_name)) {
+ _signals[p_name] = Array();
+ }
+ _signals[p_name].push_back(p_args);
+ }
+
+ void _signal_callback_zero(const String &p_name) {
+ Array args;
+ _add_signal_entry(args, p_name);
+ }
+
+ void _signal_callback_one(Variant p_arg1, const String &p_name) {
+ Array args;
+ args.push_back(p_arg1);
+ _add_signal_entry(args, p_name);
+ }
+
+ void _signal_callback_two(Variant p_arg1, Variant p_arg2, const String &p_name) {
+ Array args;
+ args.push_back(p_arg1);
+ args.push_back(p_arg2);
+ _add_signal_entry(args, p_name);
+ }
+
+ void _signal_callback_three(Variant p_arg1, Variant p_arg2, Variant p_arg3, const String &p_name) {
+ Array args;
+ args.push_back(p_arg1);
+ args.push_back(p_arg2);
+ args.push_back(p_arg3);
+ _add_signal_entry(args, p_name);
+ }
+
+public:
+ static SignalWatcher *get_singleton() { return singleton; }
+
+ void watch_signal(Object *p_object, const String &p_signal) {
+ Vector<Variant> args;
+ args.push_back(p_signal);
+ MethodInfo method_info;
+ ClassDB::get_signal(p_object->get_class(), p_signal, &method_info);
+ switch (method_info.arguments.size()) {
+ case 0: {
+ p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_zero), args);
+ } break;
+ case 1: {
+ p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_one), args);
+ } break;
+ case 2: {
+ p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_two), args);
+ } break;
+ case 3: {
+ p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_three), args);
+ } break;
+ default: {
+ MESSAGE("Signal ", p_signal, " arg count not supported.");
+ } break;
+ }
+ }
+
+ void unwatch_signal(Object *p_object, const String &p_signal) {
+ MethodInfo method_info;
+ ClassDB::get_signal(p_object->get_class(), p_signal, &method_info);
+ switch (method_info.arguments.size()) {
+ case 0: {
+ p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_zero));
+ } break;
+ case 1: {
+ p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_one));
+ } break;
+ case 2: {
+ p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_two));
+ } break;
+ case 3: {
+ p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_three));
+ } break;
+ default: {
+ MESSAGE("Signal ", p_signal, " arg count not supported.");
+ } break;
+ }
+ }
+
+ bool check(const String &p_name, const Array &p_args) {
+ if (!_signals.has(p_name)) {
+ MESSAGE("Signal ", p_name, " not emitted");
+ return false;
+ }
+
+ if (p_args.size() != _signals[p_name].size()) {
+ MESSAGE("Signal has " << _signals[p_name] << " expected " << p_args);
+ discard_signal(p_name);
+ return false;
+ }
+
+ bool match = true;
+ for (int i = 0; i < p_args.size(); i++) {
+ if (((Array)p_args[i]).size() != ((Array)_signals[p_name][i]).size()) {
+ MESSAGE("Signal has " << _signals[p_name][i] << " expected " << p_args[i]);
+ match = false;
+ continue;
+ }
+
+ for (int j = 0; j < ((Array)p_args[i]).size(); j++) {
+ if (((Array)p_args[i])[j] != ((Array)_signals[p_name][i])[j]) {
+ MESSAGE("Signal has " << _signals[p_name][i] << " expected " << p_args[i]);
+ match = false;
+ break;
+ }
+ }
+ }
+
+ discard_signal(p_name);
+ return match;
+ }
+
+ bool check_false(const String &p_name) {
+ bool has = _signals.has(p_name);
+ discard_signal(p_name);
+ return !has;
+ }
+
+ void discard_signal(const String &p_name) {
+ if (_signals.has(p_name)) {
+ _signals.erase(p_name);
+ }
+ }
+
+ void _clear_signals() {
+ _signals.clear();
+ }
+
+ SignalWatcher() {
+ singleton = this;
+ }
+
+ ~SignalWatcher() {
+ singleton = nullptr;
+ }
+};
+
+#define SIGNAL_WATCH(m_object, m_signal) SignalWatcher::get_singleton()->watch_signal(m_object, m_signal);
+#define SIGNAL_UNWATCH(m_object, m_signal) SignalWatcher::get_singleton()->unwatch_signal(m_object, m_signal);
+
+#define SIGNAL_CHECK(m_signal, m_args) CHECK(SignalWatcher::get_singleton()->check(m_signal, m_args));
+#define SIGNAL_CHECK_FALSE(m_signal) CHECK(SignalWatcher::get_singleton()->check_false(m_signal));
+#define SIGNAL_DISCARD(m_signal) SignalWatcher::get_singleton()->discard_signal(m_signal);
+
#endif // TEST_MACROS_H
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index d0466d1e2d..e4aa4c38ff 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -37,6 +37,7 @@
#include "test_astar.h"
#include "test_basis.h"
#include "test_class_db.h"
+#include "test_code_edit.h"
#include "test_color.h"
#include "test_command_queue.h"
#include "test_config_file.h"
@@ -146,3 +147,153 @@ int test_main(int argc, char *argv[]) {
return test_context.run();
}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+#include "servers/navigation_server_2d.h"
+#include "servers/navigation_server_3d.h"
+#include "servers/rendering/rendering_server_default.h"
+
+struct GodotTestCaseListener : public doctest::IReporter {
+ GodotTestCaseListener(const doctest::ContextOptions &p_in) {}
+
+ SignalWatcher *signal_watcher = nullptr;
+
+ PhysicsServer3D *physics_3d_server = nullptr;
+ PhysicsServer2D *physics_2d_server = nullptr;
+ NavigationServer3D *navigation_3d_server = nullptr;
+ NavigationServer2D *navigation_2d_server = nullptr;
+
+ void test_case_start(const doctest::TestCaseData &p_in) override {
+ SignalWatcher::get_singleton()->_clear_signals();
+
+ String name = String(p_in.m_name);
+
+ if (name.find("[SceneTree]") != -1) {
+ GLOBAL_DEF("memory/limits/multithreaded_server/rid_pool_prealloc", 60);
+ memnew(MessageQueue);
+
+ GLOBAL_DEF("internationalization/rendering/force_right_to_left_layout_direction", false);
+ memnew(TextServerManager);
+ Error err = OK;
+ TextServerManager::initialize(0, err);
+
+ 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);
+ break;
+ }
+ }
+ memnew(RenderingServerDefault());
+ RenderingServerDefault::get_singleton()->init();
+ RenderingServerDefault::get_singleton()->set_render_loop_enabled(false);
+
+ physics_3d_server = PhysicsServer3DManager::new_default_server();
+ physics_3d_server->init();
+
+ physics_2d_server = PhysicsServer2DManager::new_default_server();
+ physics_2d_server->init();
+
+ navigation_3d_server = NavigationServer3DManager::new_default_server();
+ navigation_2d_server = memnew(NavigationServer2D);
+
+ memnew(InputMap);
+ InputMap::get_singleton()->load_default();
+
+ make_default_theme(false, Ref<Font>());
+
+ memnew(SceneTree);
+ SceneTree::get_singleton()->initialize();
+ return;
+ }
+ }
+
+ void test_case_end(const doctest::CurrentTestCaseStats &) override {
+ if (SceneTree::get_singleton()) {
+ SceneTree::get_singleton()->finalize();
+ }
+
+ if (MessageQueue::get_singleton()) {
+ MessageQueue::get_singleton()->flush();
+ }
+
+ if (SceneTree::get_singleton()) {
+ memdelete(SceneTree::get_singleton());
+ }
+
+ clear_default_theme();
+
+ if (TextServerManager::get_singleton()) {
+ memdelete(TextServerManager::get_singleton());
+ }
+
+ if (navigation_3d_server) {
+ memdelete(navigation_3d_server);
+ navigation_3d_server = nullptr;
+ }
+
+ if (navigation_2d_server) {
+ memdelete(navigation_2d_server);
+ navigation_2d_server = nullptr;
+ }
+
+ if (physics_3d_server) {
+ physics_3d_server->finish();
+ memdelete(physics_3d_server);
+ physics_3d_server = nullptr;
+ }
+
+ if (physics_2d_server) {
+ physics_2d_server->finish();
+ memdelete(physics_2d_server);
+ physics_2d_server = nullptr;
+ }
+
+ if (RenderingServer::get_singleton()) {
+ RenderingServer::get_singleton()->sync();
+ RenderingServer::get_singleton()->global_variables_clear();
+ RenderingServer::get_singleton()->finish();
+ memdelete(RenderingServer::get_singleton());
+ }
+
+ if (DisplayServer::get_singleton()) {
+ memdelete(DisplayServer::get_singleton());
+ }
+
+ if (InputMap::get_singleton()) {
+ memdelete(InputMap::get_singleton());
+ }
+
+ if (MessageQueue::get_singleton()) {
+ MessageQueue::get_singleton()->flush();
+ memdelete(MessageQueue::get_singleton());
+ }
+ }
+
+ void test_run_start() override {
+ signal_watcher = memnew(SignalWatcher);
+ }
+
+ void test_run_end(const doctest::TestRunStats &) override {
+ memdelete(signal_watcher);
+ }
+
+ void test_case_reenter(const doctest::TestCaseData &) override {
+ SignalWatcher::get_singleton()->_clear_signals();
+ }
+
+ void subcase_start(const doctest::SubcaseSignature &) override {
+ SignalWatcher::get_singleton()->_clear_signals();
+ }
+
+ void report_query(const doctest::QueryData &) override {}
+ void test_case_exception(const doctest::TestCaseException &) override {}
+ void subcase_end() override {}
+
+ void log_assert(const doctest::AssertData &in) override {}
+ void log_message(const doctest::MessageData &) override {}
+ void test_case_skipped(const doctest::TestCaseData &) override {}
+};
+
+REGISTER_LISTENER("GodotTestCaseListener", 1, GodotTestCaseListener);
diff --git a/tests/test_string.h b/tests/test_string.h
index 82b23d8a00..c1b7220fdb 100644
--- a/tests/test_string.h
+++ b/tests/test_string.h
@@ -355,13 +355,23 @@ TEST_CASE("[String] Number to string") {
CHECK(String::num(-0.0) == "-0"); // Includes sign even for zero.
CHECK(String::num(3.141593) == "3.141593");
CHECK(String::num(3.141593, 3) == "3.142");
- CHECK(String::num_real(3.141593) == "3.141593");
CHECK(String::num_scientific(30000000) == "3e+07");
CHECK(String::num_int64(3141593) == "3141593");
CHECK(String::num_int64(0xA141593, 16) == "a141593");
CHECK(String::num_int64(0xA141593, 16, true) == "A141593");
CHECK(String::num(42.100023, 4) == "42.1"); // No trailing zeros.
+ // String::num_real tests.
+ 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(Math_PI) == "3.14159265358979", "Prints the appropriate amount of digits for real_t = double.");
+ CHECK_MESSAGE(String::num_real(3.1415f) == "3.14149999618530", "Prints more digits of 32-bit float when real_t = double (ones that would be reliable for double).");
+#else
+ 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
+
// Checks doubles with many decimal places.
CHECK(String::num(0.0000012345432123454321, -1) == "0.00000123454321"); // -1 uses 14 as sane default.
CHECK(String::num(0.0000012345432123454321) == "0.00000123454321"); // -1 is the default value.
@@ -1142,14 +1152,14 @@ TEST_CASE("[String] dedent") {
}
TEST_CASE("[String] Path functions") {
- static const char *path[4] = { "C:\\Godot\\project\\test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot\\test.doc" };
- static const char *base_dir[4] = { "C:\\Godot\\project", "/Godot/project", "../Godot/project", "Godot" };
- static const char *base_name[4] = { "C:\\Godot\\project\\test", "/Godot/project/test", "../Godot/project/test", "Godot\\test" };
- static const char *ext[4] = { "tscn", "xscn", "scn", "doc" };
- static const char *file[4] = { "test.tscn", "test.xscn", "test.scn", "test.doc" };
- static const bool abs[4] = { true, true, false, false };
-
- for (int i = 0; i < 4; i++) {
+ 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++) {
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]);
diff --git a/modules/stb_vorbis/register_types.h b/tests/test_tools.h
index d36d87606c..3ea953cb07 100644
--- a/modules/stb_vorbis/register_types.h
+++ b/tests/test_tools.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* register_types.h */
+/* test_tools.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,10 +28,34 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef STB_VORBIS_REGISTER_TYPES_H
-#define STB_VORBIS_REGISTER_TYPES_H
+#ifndef TEST_TOOLS_H
+#define TEST_TOOLS_H
-void register_stb_vorbis_types();
-void unregister_stb_vorbis_types();
+#include "core/error/error_macros.h"
-#endif // STB_VORBIS_REGISTER_TYPES_H
+struct ErrorDetector {
+ ErrorDetector() {
+ eh.errfunc = _detect_error;
+ eh.userdata = this;
+
+ add_error_handler(&eh);
+ }
+
+ ~ErrorDetector() {
+ remove_error_handler(&eh);
+ }
+
+ void clear() {
+ has_error = false;
+ }
+
+ static void _detect_error(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, ErrorHandlerType p_type) {
+ ErrorDetector *self = (ErrorDetector *)p_self;
+ self->has_error = true;
+ }
+
+ ErrorHandlerList eh;
+ bool has_error = false;
+};
+
+#endif // TEST_TOOLS_H
diff --git a/tests/test_validate_testing.h b/tests/test_validate_testing.h
index f301047509..40b255e18a 100644
--- a/tests/test_validate_testing.h
+++ b/tests/test_validate_testing.h
@@ -34,6 +34,7 @@
#include "core/os/os.h"
#include "tests/test_macros.h"
+#include "tests/test_tools.h"
TEST_SUITE("Validate tests") {
TEST_CASE("Always pass") {
@@ -182,6 +183,17 @@ TEST_SUITE("Validate tests") {
// doctest string concatenation.
CHECK_MESSAGE(true, var, " ", vec2, " ", rect2, " ", color);
}
+ TEST_CASE("Detect error messages") {
+ ErrorDetector ed;
+
+ REQUIRE_FALSE(ed.has_error);
+
+ ERR_PRINT_OFF;
+ ERR_PRINT("Still waiting for Godot!");
+ ERR_PRINT_ON;
+
+ REQUIRE(ed.has_error);
+ }
}
#endif // TEST_VALIDATE_TESTING_H
diff --git a/thirdparty/README.md b/thirdparty/README.md
index dd2f509516..3b5ec77b73 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -472,10 +472,6 @@ Collection of single-file libraries used in Godot components.
* Upstream: https://github.com/nothings/stb
* Version: 1.00 (2bb4a0accd4003c1db4c24533981e01b1adfd656, 2019)
* License: Public Domain or Unlicense or MIT
-- `stb_vorbis.c`
- * Upstream: https://github.com/nothings/stb
- * Version: 1.20 (314d0a6f9af5af27e585336eecea333e95c5a2d8, 2020)
- * License: Public Domain or Unlicense or MIT
- `yuv2rgb.h`
* Upstream: http://wss.co.uk/pinknoise/yuv2rgb/ (to check)
* Version: ?
diff --git a/thirdparty/embree/include/embree3/rtcore_config.h b/thirdparty/embree/include/embree3/rtcore_config.h
index 3a9819c9f1..62b7b6f4dc 100644
--- a/thirdparty/embree/include/embree3/rtcore_config.h
+++ b/thirdparty/embree/include/embree3/rtcore_config.h
@@ -6,9 +6,9 @@
#define RTC_VERSION_MAJOR 3
#define RTC_VERSION_MINOR 13
-#define RTC_VERSION_PATCH 0
-#define RTC_VERSION 31300
-#define RTC_VERSION_STRING "3.13.0"
+#define RTC_VERSION_PATCH 1
+#define RTC_VERSION 31301
+#define RTC_VERSION_STRING "3.13.1"
#define RTC_MAX_INSTANCE_LEVEL_COUNT 1
diff --git a/thirdparty/embree/kernels/bvh/bvh_intersector_hybrid.cpp b/thirdparty/embree/kernels/bvh/bvh_intersector_hybrid.cpp
new file mode 100644
index 0000000000..6e9a5a538e
--- /dev/null
+++ b/thirdparty/embree/kernels/bvh/bvh_intersector_hybrid.cpp
@@ -0,0 +1,917 @@
+// Copyright 2009-2021 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "bvh_intersector_hybrid.h"
+#include "bvh_traverser1.h"
+#include "node_intersector1.h"
+#include "node_intersector_packet.h"
+
+#include "../geometry/intersector_iterators.h"
+#include "../geometry/triangle_intersector.h"
+#include "../geometry/trianglev_intersector.h"
+#include "../geometry/trianglev_mb_intersector.h"
+#include "../geometry/trianglei_intersector.h"
+#include "../geometry/quadv_intersector.h"
+#include "../geometry/quadi_intersector.h"
+#include "../geometry/curveNv_intersector.h"
+#include "../geometry/curveNi_intersector.h"
+#include "../geometry/curveNi_mb_intersector.h"
+#include "../geometry/linei_intersector.h"
+#include "../geometry/subdivpatch1_intersector.h"
+#include "../geometry/object_intersector.h"
+#include "../geometry/instance_intersector.h"
+#include "../geometry/subgrid_intersector.h"
+#include "../geometry/subgrid_mb_intersector.h"
+#include "../geometry/curve_intersector_virtual.h"
+
+#define SWITCH_DURING_DOWN_TRAVERSAL 1
+#define FORCE_SINGLE_MODE 0
+
+#define ENABLE_FAST_COHERENT_CODEPATHS 1
+
+namespace embree
+{
+ namespace isa
+ {
+ template<int N, int K, int types, bool robust, typename PrimitiveIntersectorK, bool single>
+ void BVHNIntersectorKHybrid<N, K, types, robust, PrimitiveIntersectorK, single>::intersect1(Accel::Intersectors* This,
+ const BVH* bvh,
+ NodeRef root,
+ size_t k,
+ Precalculations& pre,
+ RayHitK<K>& ray,
+ const TravRayK<K, robust>& tray,
+ IntersectContext* context)
+ {
+ /* stack state */
+ StackItemT<NodeRef> stack[stackSizeSingle]; // stack of nodes
+ StackItemT<NodeRef>* stackPtr = stack + 1; // current stack pointer
+ StackItemT<NodeRef>* stackEnd = stack + stackSizeSingle;
+ stack[0].ptr = root;
+ stack[0].dist = neg_inf;
+
+ /* load the ray into SIMD registers */
+ TravRay<N,robust> tray1;
+ tray1.template init<K>(k, tray.org, tray.dir, tray.rdir, tray.nearXYZ, tray.tnear[k], tray.tfar[k]);
+
+ /* pop loop */
+ while (true) pop:
+ {
+ /* pop next node */
+ if (unlikely(stackPtr == stack)) break;
+ stackPtr--;
+ NodeRef cur = NodeRef(stackPtr->ptr);
+
+ /* if popped node is too far, pop next one */
+ if (unlikely(*(float*)&stackPtr->dist > ray.tfar[k]))
+ continue;
+
+ /* downtraversal loop */
+ while (true)
+ {
+ /* intersect node */
+ size_t mask; vfloat<N> tNear;
+ STAT3(normal.trav_nodes, 1, 1, 1);
+ bool nodeIntersected = BVHNNodeIntersector1<N, types, robust>::intersect(cur, tray1, ray.time()[k], tNear, mask);
+ if (unlikely(!nodeIntersected)) { STAT3(normal.trav_nodes,-1,-1,-1); break; }
+
+ /* if no child is hit, pop next node */
+ if (unlikely(mask == 0))
+ goto pop;
+
+ /* select next child and push other children */
+ BVHNNodeTraverser1Hit<N, types>::traverseClosestHit(cur, mask, tNear, stackPtr, stackEnd);
+ }
+
+ /* this is a leaf node */
+ assert(cur != BVH::emptyNode);
+ STAT3(normal.trav_leaves, 1, 1, 1);
+ size_t num; Primitive* prim = (Primitive*)cur.leaf(num);
+
+ size_t lazy_node = 0;
+ PrimitiveIntersectorK::intersect(This, pre, ray, k, context, prim, num, tray1, lazy_node);
+
+ tray1.tfar = ray.tfar[k];
+
+ if (unlikely(lazy_node)) {
+ stackPtr->ptr = lazy_node;
+ stackPtr->dist = neg_inf;
+ stackPtr++;
+ }
+ }
+ }
+
+ template<int N, int K, int types, bool robust, typename PrimitiveIntersectorK, bool single>
+ void BVHNIntersectorKHybrid<N, K, types, robust, PrimitiveIntersectorK, single>::intersect(vint<K>* __restrict__ valid_i,
+ Accel::Intersectors* __restrict__ This,
+ RayHitK<K>& __restrict__ ray,
+ IntersectContext* __restrict__ context)
+ {
+ BVH* __restrict__ bvh = (BVH*)This->ptr;
+
+ /* we may traverse an empty BVH in case all geometry was invalid */
+ if (bvh->root == BVH::emptyNode)
+ return;
+
+#if ENABLE_FAST_COHERENT_CODEPATHS == 1
+ assert(context);
+ if (unlikely(types == BVH_AN1 && context->user && context->isCoherent()))
+ {
+ intersectCoherent(valid_i, This, ray, context);
+ return;
+ }
+#endif
+
+ /* filter out invalid rays */
+ vbool<K> valid = *valid_i == -1;
+#if defined(EMBREE_IGNORE_INVALID_RAYS)
+ valid &= ray.valid();
+#endif
+
+ /* return if there are no valid rays */
+ size_t valid_bits = movemask(valid);
+
+#if defined(__AVX__)
+ STAT3(normal.trav_hit_boxes[popcnt(movemask(valid))], 1, 1, 1);
+#endif
+
+ if (unlikely(valid_bits == 0)) return;
+
+ /* verify correct input */
+ assert(all(valid, ray.valid()));
+ assert(all(valid, ray.tnear() >= 0.0f));
+ assert(!(types & BVH_MB) || all(valid, (ray.time() >= 0.0f) & (ray.time() <= 1.0f)));
+ Precalculations pre(valid, ray);
+
+ /* load ray */
+ TravRayK<K, robust> tray(ray.org, ray.dir, single ? N : 0);
+ const vfloat<K> org_ray_tnear = max(ray.tnear(), 0.0f);
+ const vfloat<K> org_ray_tfar = max(ray.tfar , 0.0f);
+
+ if (single)
+ {
+ tray.tnear = select(valid, org_ray_tnear, vfloat<K>(pos_inf));
+ tray.tfar = select(valid, org_ray_tfar , vfloat<K>(neg_inf));
+
+ for (; valid_bits!=0; ) {
+ const size_t i = bscf(valid_bits);
+ intersect1(This, bvh, bvh->root, i, pre, ray, tray, context);
+ }
+ return;
+ }
+
+ /* determine switch threshold based on flags */
+ const size_t switchThreshold = (context->user && context->isCoherent()) ? 2 : switchThresholdIncoherent;
+
+ vint<K> octant = ray.octant();
+ octant = select(valid, octant, vint<K>(0xffffffff));
+
+ /* test whether we have ray with opposing direction signs in the packet */
+ bool split = false;
+ {
+ size_t bits = valid_bits;
+ vbool<K> vsplit( false );
+ do
+ {
+ const size_t valid_index = bsf(bits);
+ vbool<K> octant_valid = octant[valid_index] == octant;
+ bits &= ~(size_t)movemask(octant_valid);
+ vsplit |= vint<K>(octant[valid_index]) == (octant^vint<K>(0x7));
+ } while (bits);
+ if (any(vsplit)) split = true;
+ }
+
+ do
+ {
+ const size_t valid_index = bsf(valid_bits);
+ const vint<K> diff_octant = vint<K>(octant[valid_index])^octant;
+ const vint<K> count_diff_octant = \
+ ((diff_octant >> 2) & 1) +
+ ((diff_octant >> 1) & 1) +
+ ((diff_octant >> 0) & 1);
+
+ vbool<K> octant_valid = (count_diff_octant <= 1) & (octant != vint<K>(0xffffffff));
+ if (!single || !split) octant_valid = valid; // deactivate octant sorting in pure chunk mode, otherwise instance traversal performance goes down
+
+
+ octant = select(octant_valid,vint<K>(0xffffffff),octant);
+ valid_bits &= ~(size_t)movemask(octant_valid);
+
+ tray.tnear = select(octant_valid, org_ray_tnear, vfloat<K>(pos_inf));
+ tray.tfar = select(octant_valid, org_ray_tfar , vfloat<K>(neg_inf));
+
+ /* allocate stack and push root node */
+ vfloat<K> stack_near[stackSizeChunk];
+ NodeRef stack_node[stackSizeChunk];
+ stack_node[0] = BVH::invalidNode;
+ stack_near[0] = inf;
+ stack_node[1] = bvh->root;
+ stack_near[1] = tray.tnear;
+ NodeRef* stackEnd MAYBE_UNUSED = stack_node+stackSizeChunk;
+ NodeRef* __restrict__ sptr_node = stack_node + 2;
+ vfloat<K>* __restrict__ sptr_near = stack_near + 2;
+
+ while (1) pop:
+ {
+ /* pop next node from stack */
+ assert(sptr_node > stack_node);
+ sptr_node--;
+ sptr_near--;
+ NodeRef cur = *sptr_node;
+ if (unlikely(cur == BVH::invalidNode)) {
+ assert(sptr_node == stack_node);
+ break;
+ }
+
+ /* cull node if behind closest hit point */
+ vfloat<K> curDist = *sptr_near;
+ const vbool<K> active = curDist < tray.tfar;
+ if (unlikely(none(active)))
+ continue;
+
+ /* switch to single ray traversal */
+#if (!defined(__WIN32__) || defined(__X86_64__)) && defined(__SSE4_2__)
+#if FORCE_SINGLE_MODE == 0
+ if (single)
+#endif
+ {
+ size_t bits = movemask(active);
+#if FORCE_SINGLE_MODE == 0
+ if (unlikely(popcnt(bits) <= switchThreshold))
+#endif
+ {
+ for (; bits!=0; ) {
+ const size_t i = bscf(bits);
+ intersect1(This, bvh, cur, i, pre, ray, tray, context);
+ }
+ tray.tfar = min(tray.tfar, ray.tfar);
+ continue;
+ }
+ }
+#endif
+ while (likely(!cur.isLeaf()))
+ {
+ /* process nodes */
+ const vbool<K> valid_node = tray.tfar > curDist;
+ STAT3(normal.trav_nodes, 1, popcnt(valid_node), K);
+ const NodeRef nodeRef = cur;
+ const BaseNode* __restrict__ const node = nodeRef.baseNode();
+
+ /* set cur to invalid */
+ cur = BVH::emptyNode;
+ curDist = pos_inf;
+
+ size_t num_child_hits = 0;
+
+ for (unsigned i = 0; i < N; i++)
+ {
+ const NodeRef child = node->children[i];
+ if (unlikely(child == BVH::emptyNode)) break;
+ vfloat<K> lnearP;
+ vbool<K> lhit = valid_node;
+ BVHNNodeIntersectorK<N, K, types, robust>::intersect(nodeRef, i, tray, ray.time(), lnearP, lhit);
+
+ /* if we hit the child we choose to continue with that child if it
+ is closer than the current next child, or we push it onto the stack */
+ if (likely(any(lhit)))
+ {
+ assert(sptr_node < stackEnd);
+ assert(child != BVH::emptyNode);
+ const vfloat<K> childDist = select(lhit, lnearP, inf);
+ /* push cur node onto stack and continue with hit child */
+ if (any(childDist < curDist))
+ {
+ if (likely(cur != BVH::emptyNode)) {
+ num_child_hits++;
+ *sptr_node = cur; sptr_node++;
+ *sptr_near = curDist; sptr_near++;
+ }
+ curDist = childDist;
+ cur = child;
+ }
+
+ /* push hit child onto stack */
+ else {
+ num_child_hits++;
+ *sptr_node = child; sptr_node++;
+ *sptr_near = childDist; sptr_near++;
+ }
+ }
+ }
+
+#if defined(__AVX__)
+ //STAT3(normal.trav_hit_boxes[num_child_hits], 1, 1, 1);
+#endif
+
+ if (unlikely(cur == BVH::emptyNode))
+ goto pop;
+
+ /* improved distance sorting for 3 or more hits */
+ if (unlikely(num_child_hits >= 2))
+ {
+ if (any(sptr_near[-2] < sptr_near[-1]))
+ {
+ std::swap(sptr_near[-2],sptr_near[-1]);
+ std::swap(sptr_node[-2],sptr_node[-1]);
+ }
+ if (unlikely(num_child_hits >= 3))
+ {
+ if (any(sptr_near[-3] < sptr_near[-1]))
+ {
+ std::swap(sptr_near[-3],sptr_near[-1]);
+ std::swap(sptr_node[-3],sptr_node[-1]);
+ }
+ if (any(sptr_near[-3] < sptr_near[-2]))
+ {
+ std::swap(sptr_near[-3],sptr_near[-2]);
+ std::swap(sptr_node[-3],sptr_node[-2]);
+ }
+ }
+ }
+
+#if SWITCH_DURING_DOWN_TRAVERSAL == 1
+ if (single)
+ {
+ // seems to be the best place for testing utilization
+ if (unlikely(popcnt(tray.tfar > curDist) <= switchThreshold))
+ {
+ *sptr_node++ = cur;
+ *sptr_near++ = curDist;
+ goto pop;
+ }
+ }
+#endif
+ }
+
+ /* return if stack is empty */
+ if (unlikely(cur == BVH::invalidNode)) {
+ assert(sptr_node == stack_node);
+ break;
+ }
+
+ /* intersect leaf */
+ assert(cur != BVH::emptyNode);
+ const vbool<K> valid_leaf = tray.tfar > curDist;
+ STAT3(normal.trav_leaves, 1, popcnt(valid_leaf), K);
+ if (unlikely(none(valid_leaf))) continue;
+ size_t items; const Primitive* prim = (Primitive*)cur.leaf(items);
+
+ size_t lazy_node = 0;
+ PrimitiveIntersectorK::intersect(valid_leaf, This, pre, ray, context, prim, items, tray, lazy_node);
+ tray.tfar = select(valid_leaf, ray.tfar, tray.tfar);
+
+ if (unlikely(lazy_node)) {
+ *sptr_node = lazy_node; sptr_node++;
+ *sptr_near = neg_inf; sptr_near++;
+ }
+ }
+ } while(valid_bits);
+ }
+
+
+ template<int N, int K, int types, bool robust, typename PrimitiveIntersectorK, bool single>
+ void BVHNIntersectorKHybrid<N, K, types, robust, PrimitiveIntersectorK, single>::intersectCoherent(vint<K>* __restrict__ valid_i,
+ Accel::Intersectors* __restrict__ This,
+ RayHitK<K>& __restrict__ ray,
+ IntersectContext* context)
+ {
+ BVH* __restrict__ bvh = (BVH*)This->ptr;
+
+ /* filter out invalid rays */
+ vbool<K> valid = *valid_i == -1;
+#if defined(EMBREE_IGNORE_INVALID_RAYS)
+ valid &= ray.valid();
+#endif
+
+ /* return if there are no valid rays */
+ size_t valid_bits = movemask(valid);
+ if (unlikely(valid_bits == 0)) return;
+
+ /* verify correct input */
+ assert(all(valid, ray.valid()));
+ assert(all(valid, ray.tnear() >= 0.0f));
+ assert(!(types & BVH_MB) || all(valid, (ray.time() >= 0.0f) & (ray.time() <= 1.0f)));
+ Precalculations pre(valid, ray);
+
+ /* load ray */
+ TravRayK<K, robust> tray(ray.org, ray.dir, single ? N : 0);
+ const vfloat<K> org_ray_tnear = max(ray.tnear(), 0.0f);
+ const vfloat<K> org_ray_tfar = max(ray.tfar , 0.0f);
+
+ vint<K> octant = ray.octant();
+ octant = select(valid, octant, vint<K>(0xffffffff));
+
+ do
+ {
+ const size_t valid_index = bsf(valid_bits);
+ const vbool<K> octant_valid = octant[valid_index] == octant;
+ valid_bits &= ~(size_t)movemask(octant_valid);
+
+ tray.tnear = select(octant_valid, org_ray_tnear, vfloat<K>(pos_inf));
+ tray.tfar = select(octant_valid, org_ray_tfar , vfloat<K>(neg_inf));
+
+ Frustum<robust> frustum;
+ frustum.template init<K>(octant_valid, tray.org, tray.rdir, tray.tnear, tray.tfar, N);
+
+ StackItemT<NodeRef> stack[stackSizeSingle]; // stack of nodes
+ StackItemT<NodeRef>* stackPtr = stack + 1; // current stack pointer
+ stack[0].ptr = bvh->root;
+ stack[0].dist = neg_inf;
+
+ while (1) pop:
+ {
+ /* pop next node from stack */
+ if (unlikely(stackPtr == stack)) break;
+
+ stackPtr--;
+ NodeRef cur = NodeRef(stackPtr->ptr);
+
+ /* cull node if behind closest hit point */
+ vfloat<K> curDist = *(float*)&stackPtr->dist;
+ const vbool<K> active = curDist < tray.tfar;
+ if (unlikely(none(active))) continue;
+
+ while (likely(!cur.isLeaf()))
+ {
+ /* process nodes */
+ //STAT3(normal.trav_nodes, 1, popcnt(valid_node), K);
+ const NodeRef nodeRef = cur;
+ const AABBNode* __restrict__ const node = nodeRef.getAABBNode();
+
+ vfloat<N> fmin;
+ size_t m_frustum_node = intersectNodeFrustum<N>(node, frustum, fmin);
+
+ if (unlikely(!m_frustum_node)) goto pop;
+ cur = BVH::emptyNode;
+ curDist = pos_inf;
+
+#if defined(__AVX__)
+ //STAT3(normal.trav_hit_boxes[popcnt(m_frustum_node)], 1, 1, 1);
+#endif
+ size_t num_child_hits = 0;
+ do {
+ const size_t i = bscf(m_frustum_node);
+ vfloat<K> lnearP;
+ vbool<K> lhit = false; // motion blur is not supported, so the initial value will be ignored
+ STAT3(normal.trav_nodes, 1, 1, 1);
+ BVHNNodeIntersectorK<N, K, types, robust>::intersect(nodeRef, i, tray, ray.time(), lnearP, lhit);
+
+ if (likely(any(lhit)))
+ {
+ const vfloat<K> childDist = fmin[i];
+ const NodeRef child = node->child(i);
+ BVHN<N>::prefetch(child);
+ if (any(childDist < curDist))
+ {
+ if (likely(cur != BVH::emptyNode)) {
+ num_child_hits++;
+ stackPtr->ptr = cur;
+ *(float*)&stackPtr->dist = toScalar(curDist);
+ stackPtr++;
+ }
+ curDist = childDist;
+ cur = child;
+ }
+ /* push hit child onto stack */
+ else {
+ num_child_hits++;
+ stackPtr->ptr = child;
+ *(float*)&stackPtr->dist = toScalar(childDist);
+ stackPtr++;
+ }
+ }
+ } while(m_frustum_node);
+
+ if (unlikely(cur == BVH::emptyNode)) goto pop;
+
+ /* improved distance sorting for 3 or more hits */
+ if (unlikely(num_child_hits >= 2))
+ {
+ if (stackPtr[-2].dist < stackPtr[-1].dist)
+ std::swap(stackPtr[-2],stackPtr[-1]);
+ if (unlikely(num_child_hits >= 3))
+ {
+ if (stackPtr[-3].dist < stackPtr[-1].dist)
+ std::swap(stackPtr[-3],stackPtr[-1]);
+ if (stackPtr[-3].dist < stackPtr[-2].dist)
+ std::swap(stackPtr[-3],stackPtr[-2]);
+ }
+ }
+ }
+
+ /* intersect leaf */
+ assert(cur != BVH::invalidNode);
+ assert(cur != BVH::emptyNode);
+ const vbool<K> valid_leaf = tray.tfar > curDist;
+ STAT3(normal.trav_leaves, 1, popcnt(valid_leaf), K);
+ if (unlikely(none(valid_leaf))) continue;
+ size_t items; const Primitive* prim = (Primitive*)cur.leaf(items);
+
+ size_t lazy_node = 0;
+ PrimitiveIntersectorK::intersect(valid_leaf, This, pre, ray, context, prim, items, tray, lazy_node);
+
+ /* reduce max distance interval on successful intersection */
+ if (likely(any((ray.tfar < tray.tfar) & valid_leaf)))
+ {
+ tray.tfar = select(valid_leaf, ray.tfar, tray.tfar);
+ frustum.template updateMaxDist<K>(tray.tfar);
+ }
+
+ if (unlikely(lazy_node)) {
+ stackPtr->ptr = lazy_node;
+ stackPtr->dist = neg_inf;
+ stackPtr++;
+ }
+ }
+
+ } while(valid_bits);
+ }
+
+ // ===================================================================================================================================================================
+ // ===================================================================================================================================================================
+ // ===================================================================================================================================================================
+
+ template<int N, int K, int types, bool robust, typename PrimitiveIntersectorK, bool single>
+ bool BVHNIntersectorKHybrid<N, K, types, robust, PrimitiveIntersectorK, single>::occluded1(Accel::Intersectors* This,
+ const BVH* bvh,
+ NodeRef root,
+ size_t k,
+ Precalculations& pre,
+ RayK<K>& ray,
+ const TravRayK<K, robust>& tray,
+ IntersectContext* context)
+ {
+ /* stack state */
+ NodeRef stack[stackSizeSingle]; // stack of nodes that still need to get traversed
+ NodeRef* stackPtr = stack+1; // current stack pointer
+ NodeRef* stackEnd = stack+stackSizeSingle;
+ stack[0] = root;
+
+ /* load the ray into SIMD registers */
+ TravRay<N,robust> tray1;
+ tray1.template init<K>(k, tray.org, tray.dir, tray.rdir, tray.nearXYZ, tray.tnear[k], tray.tfar[k]);
+
+ /* pop loop */
+ while (true) pop:
+ {
+ /* pop next node */
+ if (unlikely(stackPtr == stack)) break;
+ stackPtr--;
+ NodeRef cur = (NodeRef)*stackPtr;
+
+ /* downtraversal loop */
+ while (true)
+ {
+ /* intersect node */
+ size_t mask; vfloat<N> tNear;
+ STAT3(shadow.trav_nodes, 1, 1, 1);
+ bool nodeIntersected = BVHNNodeIntersector1<N, types, robust>::intersect(cur, tray1, ray.time()[k], tNear, mask);
+ if (unlikely(!nodeIntersected)) { STAT3(shadow.trav_nodes,-1,-1,-1); break; }
+
+ /* if no child is hit, pop next node */
+ if (unlikely(mask == 0))
+ goto pop;
+
+ /* select next child and push other children */
+ BVHNNodeTraverser1Hit<N, types>::traverseAnyHit(cur, mask, tNear, stackPtr, stackEnd);
+ }
+
+ /* this is a leaf node */
+ assert(cur != BVH::emptyNode);
+ STAT3(shadow.trav_leaves, 1, 1, 1);
+ size_t num; Primitive* prim = (Primitive*)cur.leaf(num);
+
+ size_t lazy_node = 0;
+ if (PrimitiveIntersectorK::occluded(This, pre, ray, k, context, prim, num, tray1, lazy_node)) {
+ ray.tfar[k] = neg_inf;
+ return true;
+ }
+
+ if (unlikely(lazy_node)) {
+ *stackPtr = lazy_node;
+ stackPtr++;
+ }
+ }
+ return false;
+ }
+
+ template<int N, int K, int types, bool robust, typename PrimitiveIntersectorK, bool single>
+ void BVHNIntersectorKHybrid<N, K, types, robust, PrimitiveIntersectorK, single>::occluded(vint<K>* __restrict__ valid_i,
+ Accel::Intersectors* __restrict__ This,
+ RayK<K>& __restrict__ ray,
+ IntersectContext* context)
+ {
+ BVH* __restrict__ bvh = (BVH*)This->ptr;
+
+ /* we may traverse an empty BVH in case all geometry was invalid */
+ if (bvh->root == BVH::emptyNode)
+ return;
+
+#if ENABLE_FAST_COHERENT_CODEPATHS == 1
+ assert(context);
+ if (unlikely(types == BVH_AN1 && context->user && context->isCoherent()))
+ {
+ occludedCoherent(valid_i, This, ray, context);
+ return;
+ }
+#endif
+
+ /* filter out already occluded and invalid rays */
+ vbool<K> valid = (*valid_i == -1) & (ray.tfar >= 0.0f);
+#if defined(EMBREE_IGNORE_INVALID_RAYS)
+ valid &= ray.valid();
+#endif
+
+ /* return if there are no valid rays */
+ const size_t valid_bits = movemask(valid);
+ if (unlikely(valid_bits == 0)) return;
+
+ /* verify correct input */
+ assert(all(valid, ray.valid()));
+ assert(all(valid, ray.tnear() >= 0.0f));
+ assert(!(types & BVH_MB) || all(valid, (ray.time() >= 0.0f) & (ray.time() <= 1.0f)));
+ Precalculations pre(valid, ray);
+
+ /* load ray */
+ TravRayK<K, robust> tray(ray.org, ray.dir, single ? N : 0);
+ const vfloat<K> org_ray_tnear = max(ray.tnear(), 0.0f);
+ const vfloat<K> org_ray_tfar = max(ray.tfar , 0.0f);
+
+ tray.tnear = select(valid, org_ray_tnear, vfloat<K>(pos_inf));
+ tray.tfar = select(valid, org_ray_tfar , vfloat<K>(neg_inf));
+
+ vbool<K> terminated = !valid;
+ const vfloat<K> inf = vfloat<K>(pos_inf);
+
+ /* determine switch threshold based on flags */
+ const size_t switchThreshold = (context->user && context->isCoherent()) ? 2 : switchThresholdIncoherent;
+
+ /* allocate stack and push root node */
+ vfloat<K> stack_near[stackSizeChunk];
+ NodeRef stack_node[stackSizeChunk];
+ stack_node[0] = BVH::invalidNode;
+ stack_near[0] = inf;
+ stack_node[1] = bvh->root;
+ stack_near[1] = tray.tnear;
+ NodeRef* stackEnd MAYBE_UNUSED = stack_node+stackSizeChunk;
+ NodeRef* __restrict__ sptr_node = stack_node + 2;
+ vfloat<K>* __restrict__ sptr_near = stack_near + 2;
+
+ while (1) pop:
+ {
+ /* pop next node from stack */
+ assert(sptr_node > stack_node);
+ sptr_node--;
+ sptr_near--;
+ NodeRef cur = *sptr_node;
+ if (unlikely(cur == BVH::invalidNode)) {
+ assert(sptr_node == stack_node);
+ break;
+ }
+
+ /* cull node if behind closest hit point */
+ vfloat<K> curDist = *sptr_near;
+ const vbool<K> active = curDist < tray.tfar;
+ if (unlikely(none(active)))
+ continue;
+
+ /* switch to single ray traversal */
+#if (!defined(__WIN32__) || defined(__X86_64__)) && defined(__SSE4_2__)
+#if FORCE_SINGLE_MODE == 0
+ if (single)
+#endif
+ {
+ size_t bits = movemask(active);
+#if FORCE_SINGLE_MODE == 0
+ if (unlikely(popcnt(bits) <= switchThreshold))
+#endif
+ {
+ for (; bits!=0; ) {
+ const size_t i = bscf(bits);
+ if (occluded1(This, bvh, cur, i, pre, ray, tray, context))
+ set(terminated, i);
+ }
+ if (all(terminated)) break;
+ tray.tfar = select(terminated, vfloat<K>(neg_inf), tray.tfar);
+ continue;
+ }
+ }
+#endif
+
+ while (likely(!cur.isLeaf()))
+ {
+ /* process nodes */
+ const vbool<K> valid_node = tray.tfar > curDist;
+ STAT3(shadow.trav_nodes, 1, popcnt(valid_node), K);
+ const NodeRef nodeRef = cur;
+ const BaseNode* __restrict__ const node = nodeRef.baseNode();
+
+ /* set cur to invalid */
+ cur = BVH::emptyNode;
+ curDist = pos_inf;
+
+ for (unsigned i = 0; i < N; i++)
+ {
+ const NodeRef child = node->children[i];
+ if (unlikely(child == BVH::emptyNode)) break;
+ vfloat<K> lnearP;
+ vbool<K> lhit = valid_node;
+ BVHNNodeIntersectorK<N, K, types, robust>::intersect(nodeRef, i, tray, ray.time(), lnearP, lhit);
+
+ /* if we hit the child we push the previously hit node onto the stack, and continue with the currently hit child */
+ if (likely(any(lhit)))
+ {
+ assert(sptr_node < stackEnd);
+ assert(child != BVH::emptyNode);
+ const vfloat<K> childDist = select(lhit, lnearP, inf);
+
+ /* push 'cur' node onto stack and continue with hit child */
+ if (likely(cur != BVH::emptyNode)) {
+ *sptr_node = cur; sptr_node++;
+ *sptr_near = curDist; sptr_near++;
+ }
+ curDist = childDist;
+ cur = child;
+ }
+ }
+ if (unlikely(cur == BVH::emptyNode))
+ goto pop;
+
+#if SWITCH_DURING_DOWN_TRAVERSAL == 1
+ if (single)
+ {
+ // seems to be the best place for testing utilization
+ if (unlikely(popcnt(tray.tfar > curDist) <= switchThreshold))
+ {
+ *sptr_node++ = cur;
+ *sptr_near++ = curDist;
+ goto pop;
+ }
+ }
+#endif
+ }
+
+ /* return if stack is empty */
+ if (unlikely(cur == BVH::invalidNode)) {
+ assert(sptr_node == stack_node);
+ break;
+ }
+
+
+ /* intersect leaf */
+ assert(cur != BVH::emptyNode);
+ const vbool<K> valid_leaf = tray.tfar > curDist;
+ STAT3(shadow.trav_leaves, 1, popcnt(valid_leaf), K);
+ if (unlikely(none(valid_leaf))) continue;
+ size_t items; const Primitive* prim = (Primitive*) cur.leaf(items);
+
+ size_t lazy_node = 0;
+ terminated |= PrimitiveIntersectorK::occluded(!terminated, This, pre, ray, context, prim, items, tray, lazy_node);
+ if (all(terminated)) break;
+ tray.tfar = select(terminated, vfloat<K>(neg_inf), tray.tfar); // ignore node intersections for terminated rays
+
+ if (unlikely(lazy_node)) {
+ *sptr_node = lazy_node; sptr_node++;
+ *sptr_near = neg_inf; sptr_near++;
+ }
+ }
+
+ vfloat<K>::store(valid & terminated, &ray.tfar, neg_inf);
+ }
+
+
+ template<int N, int K, int types, bool robust, typename PrimitiveIntersectorK, bool single>
+ void BVHNIntersectorKHybrid<N, K, types, robust, PrimitiveIntersectorK, single>::occludedCoherent(vint<K>* __restrict__ valid_i,
+ Accel::Intersectors* __restrict__ This,
+ RayK<K>& __restrict__ ray,
+ IntersectContext* context)
+ {
+ BVH* __restrict__ bvh = (BVH*)This->ptr;
+
+ /* filter out invalid rays */
+ vbool<K> valid = *valid_i == -1;
+#if defined(EMBREE_IGNORE_INVALID_RAYS)
+ valid &= ray.valid();
+#endif
+
+ /* return if there are no valid rays */
+ size_t valid_bits = movemask(valid);
+ if (unlikely(valid_bits == 0)) return;
+
+ /* verify correct input */
+ assert(all(valid, ray.valid()));
+ assert(all(valid, ray.tnear() >= 0.0f));
+ assert(!(types & BVH_MB) || all(valid, (ray.time() >= 0.0f) & (ray.time() <= 1.0f)));
+ Precalculations pre(valid,ray);
+
+ /* load ray */
+ TravRayK<K, robust> tray(ray.org, ray.dir, single ? N : 0);
+ const vfloat<K> org_ray_tnear = max(ray.tnear(), 0.0f);
+ const vfloat<K> org_ray_tfar = max(ray.tfar , 0.0f);
+
+ vbool<K> terminated = !valid;
+
+ vint<K> octant = ray.octant();
+ octant = select(valid, octant, vint<K>(0xffffffff));
+
+ do
+ {
+ const size_t valid_index = bsf(valid_bits);
+ vbool<K> octant_valid = octant[valid_index] == octant;
+ valid_bits &= ~(size_t)movemask(octant_valid);
+
+ tray.tnear = select(octant_valid, org_ray_tnear, vfloat<K>(pos_inf));
+ tray.tfar = select(octant_valid, org_ray_tfar, vfloat<K>(neg_inf));
+
+ Frustum<robust> frustum;
+ frustum.template init<K>(octant_valid, tray.org, tray.rdir, tray.tnear, tray.tfar, N);
+
+ StackItemMaskT<NodeRef> stack[stackSizeSingle]; // stack of nodes
+ StackItemMaskT<NodeRef>* stackPtr = stack + 1; // current stack pointer
+ stack[0].ptr = bvh->root;
+ stack[0].mask = movemask(octant_valid);
+
+ while (1) pop:
+ {
+ /* pop next node from stack */
+ if (unlikely(stackPtr == stack)) break;
+
+ stackPtr--;
+ NodeRef cur = NodeRef(stackPtr->ptr);
+
+ /* cull node of active rays have already been terminated */
+ size_t m_active = (size_t)stackPtr->mask & (~(size_t)movemask(terminated));
+
+ if (unlikely(m_active == 0)) continue;
+
+ while (likely(!cur.isLeaf()))
+ {
+ /* process nodes */
+ //STAT3(normal.trav_nodes, 1, popcnt(valid_node), K);
+ const NodeRef nodeRef = cur;
+ const AABBNode* __restrict__ const node = nodeRef.getAABBNode();
+
+ vfloat<N> fmin;
+ size_t m_frustum_node = intersectNodeFrustum<N>(node, frustum, fmin);
+
+ if (unlikely(!m_frustum_node)) goto pop;
+ cur = BVH::emptyNode;
+ m_active = 0;
+
+#if defined(__AVX__)
+ //STAT3(normal.trav_hit_boxes[popcnt(m_frustum_node)], 1, 1, 1);
+#endif
+ size_t num_child_hits = 0;
+ do {
+ const size_t i = bscf(m_frustum_node);
+ vfloat<K> lnearP;
+ vbool<K> lhit = false; // motion blur is not supported, so the initial value will be ignored
+ STAT3(normal.trav_nodes, 1, 1, 1);
+ BVHNNodeIntersectorK<N, K, types, robust>::intersect(nodeRef, i, tray, ray.time(), lnearP, lhit);
+
+ if (likely(any(lhit)))
+ {
+ const NodeRef child = node->child(i);
+ assert(child != BVH::emptyNode);
+ BVHN<N>::prefetch(child);
+ if (likely(cur != BVH::emptyNode)) {
+ num_child_hits++;
+ stackPtr->ptr = cur;
+ stackPtr->mask = m_active;
+ stackPtr++;
+ }
+ cur = child;
+ m_active = movemask(lhit);
+ }
+ } while(m_frustum_node);
+
+ if (unlikely(cur == BVH::emptyNode)) goto pop;
+ }
+
+ /* intersect leaf */
+ assert(cur != BVH::invalidNode);
+ assert(cur != BVH::emptyNode);
+#if defined(__AVX__)
+ STAT3(normal.trav_leaves, 1, popcnt(m_active), K);
+#endif
+ if (unlikely(!m_active)) continue;
+ size_t items; const Primitive* prim = (Primitive*)cur.leaf(items);
+
+ size_t lazy_node = 0;
+ terminated |= PrimitiveIntersectorK::occluded(!terminated, This, pre, ray, context, prim, items, tray, lazy_node);
+ octant_valid &= !terminated;
+ if (unlikely(none(octant_valid))) break;
+ tray.tfar = select(terminated, vfloat<K>(neg_inf), tray.tfar); // ignore node intersections for terminated rays
+
+ if (unlikely(lazy_node)) {
+ stackPtr->ptr = lazy_node;
+ stackPtr->mask = movemask(octant_valid);
+ stackPtr++;
+ }
+ }
+ } while(valid_bits);
+
+ vfloat<K>::store(valid & terminated, &ray.tfar, neg_inf);
+ }
+ }
+}
diff --git a/thirdparty/embree/kernels/bvh/bvh_intersector_hybrid4_bvh4.cpp b/thirdparty/embree/kernels/bvh/bvh_intersector_hybrid4_bvh4.cpp
new file mode 100644
index 0000000000..2137da6a25
--- /dev/null
+++ b/thirdparty/embree/kernels/bvh/bvh_intersector_hybrid4_bvh4.cpp
@@ -0,0 +1,59 @@
+// Copyright 2009-2021 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "bvh_intersector_hybrid.cpp"
+
+namespace embree
+{
+ namespace isa
+ {
+ ////////////////////////////////////////////////////////////////////////////////
+ /// BVH4Intersector4 Definitions
+ ////////////////////////////////////////////////////////////////////////////////
+
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4Intersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA TriangleMIntersectorKMoeller <4 COMMA 4 COMMA true> > >));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4Intersector4HybridMoellerNoFilter, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA TriangleMIntersectorKMoeller <4 COMMA 4 COMMA false> > >));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4iIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA TriangleMiIntersectorKMoeller <4 COMMA 4 COMMA true> > >));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4vIntersector4HybridPluecker, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA true COMMA ArrayIntersectorK_1<4 COMMA TriangleMvIntersectorKPluecker<4 COMMA 4 COMMA true> > >));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4iIntersector4HybridPluecker, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA true COMMA ArrayIntersectorK_1<4 COMMA TriangleMiIntersectorKPluecker<4 COMMA 4 COMMA true> > >));
+
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4vMBIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA false COMMA ArrayIntersectorK_1<4 COMMA TriangleMvMBIntersectorKMoeller <4 COMMA 4 COMMA true> > >));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4iMBIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA false COMMA ArrayIntersectorK_1<4 COMMA TriangleMiMBIntersectorKMoeller <4 COMMA 4 COMMA true> > >));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4vMBIntersector4HybridPluecker, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA true COMMA ArrayIntersectorK_1<4 COMMA TriangleMvMBIntersectorKPluecker<4 COMMA 4 COMMA true> > >));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTOR4(BVH4Triangle4iMBIntersector4HybridPluecker, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA true COMMA ArrayIntersectorK_1<4 COMMA TriangleMiMBIntersectorKPluecker<4 COMMA 4 COMMA true> > >));
+
+ IF_ENABLED_QUADS(DEFINE_INTERSECTOR4(BVH4Quad4vIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA QuadMvIntersectorKMoeller <4 COMMA 4 COMMA true > > >));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTOR4(BVH4Quad4vIntersector4HybridMoellerNoFilter,BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA QuadMvIntersectorKMoeller <4 COMMA 4 COMMA false> > >));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTOR4(BVH4Quad4iIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA QuadMiIntersectorKMoeller <4 COMMA 4 COMMA true > > >));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTOR4(BVH4Quad4vIntersector4HybridPluecker, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA true COMMA ArrayIntersectorK_1<4 COMMA QuadMvIntersectorKPluecker<4 COMMA 4 COMMA true > > >));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTOR4(BVH4Quad4iIntersector4HybridPluecker, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA true COMMA ArrayIntersectorK_1<4 COMMA QuadMiIntersectorKPluecker<4 COMMA 4 COMMA true > > >));
+
+ IF_ENABLED_QUADS(DEFINE_INTERSECTOR4(BVH4Quad4iMBIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA false COMMA ArrayIntersectorK_1<4 COMMA QuadMiMBIntersectorKMoeller <4 COMMA 4 COMMA true > > >));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTOR4(BVH4Quad4iMBIntersector4HybridPluecker,BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA true COMMA ArrayIntersectorK_1<4 COMMA QuadMiMBIntersectorKPluecker<4 COMMA 4 COMMA true > > >));
+
+ IF_ENABLED_CURVES_OR_POINTS(DEFINE_INTERSECTOR4(BVH4OBBVirtualCurveIntersector4Hybrid, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1_UN1 COMMA false COMMA VirtualCurveIntersectorK<4> >));
+ IF_ENABLED_CURVES_OR_POINTS(DEFINE_INTERSECTOR4(BVH4OBBVirtualCurveIntersector4HybridMB,BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D_UN2 COMMA false COMMA VirtualCurveIntersectorK<4> >));
+
+ IF_ENABLED_CURVES_OR_POINTS(DEFINE_INTERSECTOR4(BVH4OBBVirtualCurveIntersectorRobust4Hybrid, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1_UN1 COMMA true COMMA VirtualCurveIntersectorK<4> >));
+ IF_ENABLED_CURVES_OR_POINTS(DEFINE_INTERSECTOR4(BVH4OBBVirtualCurveIntersectorRobust4HybridMB,BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D_UN2 COMMA true COMMA VirtualCurveIntersectorK<4> >));
+
+ //IF_ENABLED_SUBDIV(DEFINE_INTERSECTOR4(BVH4SubdivPatch1Intersector4, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA true COMMA SubdivPatch1Intersector4>));
+ IF_ENABLED_SUBDIV(DEFINE_INTERSECTOR4(BVH4SubdivPatch1Intersector4, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA true COMMA SubdivPatch1Intersector4>));
+ IF_ENABLED_SUBDIV(DEFINE_INTERSECTOR4(BVH4SubdivPatch1MBIntersector4, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA false COMMA SubdivPatch1MBIntersector4>));
+ //IF_ENABLED_SUBDIV(DEFINE_INTERSECTOR4(BVH4SubdivPatch1MBIntersector4, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA false COMMA SubdivPatch1MBIntersector4>));
+
+ IF_ENABLED_USER(DEFINE_INTERSECTOR4(BVH4VirtualIntersector4Chunk, BVHNIntersectorKChunk<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA ObjectIntersector4> >));
+ IF_ENABLED_USER(DEFINE_INTERSECTOR4(BVH4VirtualMBIntersector4Chunk, BVHNIntersectorKChunk<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA false COMMA ArrayIntersectorK_1<4 COMMA ObjectIntersector4MB> >));
+
+ IF_ENABLED_INSTANCE(DEFINE_INTERSECTOR4(BVH4InstanceIntersector4Chunk, BVHNIntersectorKChunk<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA ArrayIntersectorK_1<4 COMMA InstanceIntersectorK<4>> >));
+ IF_ENABLED_INSTANCE(DEFINE_INTERSECTOR4(BVH4InstanceMBIntersector4Chunk, BVHNIntersectorKChunk<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA false COMMA ArrayIntersectorK_1<4 COMMA InstanceIntersectorKMB<4>> >));
+
+ IF_ENABLED_GRIDS(DEFINE_INTERSECTOR4(BVH4GridIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA SubGridIntersectorKMoeller <4 COMMA 4 COMMA true> >));
+ //IF_ENABLED_GRIDS(DEFINE_INTERSECTOR4(BVH4GridIntersector4HybridMoeller, BVHNIntersectorKChunk<4 COMMA 4 COMMA BVH_AN1 COMMA false COMMA SubGridIntersectorKMoeller <4 COMMA 4 COMMA true> >));
+
+ IF_ENABLED_GRIDS(DEFINE_INTERSECTOR4(BVH4GridMBIntersector4HybridMoeller, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN2_AN4D COMMA true COMMA SubGridMBIntersectorKPluecker <4 COMMA 4 COMMA true> >));
+ IF_ENABLED_GRIDS(DEFINE_INTERSECTOR4(BVH4GridIntersector4HybridPluecker, BVHNIntersectorKHybrid<4 COMMA 4 COMMA BVH_AN1 COMMA true COMMA SubGridIntersectorKPluecker <4 COMMA 4 COMMA true> >));
+
+ }
+}
+
diff --git a/thirdparty/embree/kernels/bvh/bvh_intersector_stream.cpp b/thirdparty/embree/kernels/bvh/bvh_intersector_stream.cpp
new file mode 100644
index 0000000000..4a74d8468d
--- /dev/null
+++ b/thirdparty/embree/kernels/bvh/bvh_intersector_stream.cpp
@@ -0,0 +1,528 @@
+// Copyright 2009-2021 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "bvh_intersector_stream.h"
+
+#include "../geometry/intersector_iterators.h"
+#include "../geometry/triangle_intersector.h"
+#include "../geometry/trianglev_intersector.h"
+#include "../geometry/trianglev_mb_intersector.h"
+#include "../geometry/trianglei_intersector.h"
+#include "../geometry/quadv_intersector.h"
+#include "../geometry/quadi_intersector.h"
+#include "../geometry/linei_intersector.h"
+#include "../geometry/subdivpatch1_intersector.h"
+#include "../geometry/object_intersector.h"
+#include "../geometry/instance_intersector.h"
+
+#include "../common/scene.h"
+#include <bitset>
+
+namespace embree
+{
+ namespace isa
+ {
+ __aligned(64) static const int shiftTable[32] = {
+ (int)1 << 0, (int)1 << 1, (int)1 << 2, (int)1 << 3, (int)1 << 4, (int)1 << 5, (int)1 << 6, (int)1 << 7,
+ (int)1 << 8, (int)1 << 9, (int)1 << 10, (int)1 << 11, (int)1 << 12, (int)1 << 13, (int)1 << 14, (int)1 << 15,
+ (int)1 << 16, (int)1 << 17, (int)1 << 18, (int)1 << 19, (int)1 << 20, (int)1 << 21, (int)1 << 22, (int)1 << 23,
+ (int)1 << 24, (int)1 << 25, (int)1 << 26, (int)1 << 27, (int)1 << 28, (int)1 << 29, (int)1 << 30, (int)1 << 31
+ };
+
+ template<int N, int types, bool robust, typename PrimitiveIntersector>
+ __forceinline void BVHNIntersectorStream<N, types, robust, PrimitiveIntersector>::intersect(Accel::Intersectors* __restrict__ This,
+ RayHitN** inputPackets,
+ size_t numOctantRays,
+ IntersectContext* context)
+ {
+ /* we may traverse an empty BVH in case all geometry was invalid */
+ BVH* __restrict__ bvh = (BVH*) This->ptr;
+ if (bvh->root == BVH::emptyNode)
+ return;
+
+ // Only the coherent code path is implemented
+ assert(context->isCoherent());
+ intersectCoherent(This, (RayHitK<VSIZEL>**)inputPackets, numOctantRays, context);
+ }
+
+ template<int N, int types, bool robust, typename PrimitiveIntersector>
+ template<int K>
+ __forceinline void BVHNIntersectorStream<N, types, robust, PrimitiveIntersector>::intersectCoherent(Accel::Intersectors* __restrict__ This,
+ RayHitK<K>** inputPackets,
+ size_t numOctantRays,
+ IntersectContext* context)
+ {
+ assert(context->isCoherent());
+
+ BVH* __restrict__ bvh = (BVH*) This->ptr;
+ __aligned(64) StackItemMaskCoherent stack[stackSizeSingle]; // stack of nodes
+ assert(numOctantRays <= MAX_INTERNAL_STREAM_SIZE);
+
+ __aligned(64) TravRayKStream<K, robust> packets[MAX_INTERNAL_STREAM_SIZE/K];
+ __aligned(64) Frustum<robust> frustum;
+
+ bool commonOctant = true;
+ const size_t m_active = initPacketsAndFrustum((RayK<K>**)inputPackets, numOctantRays, packets, frustum, commonOctant);
+ if (unlikely(m_active == 0)) return;
+
+ /* case of non-common origin */
+ if (unlikely(!commonOctant))
+ {
+ const size_t numPackets = (numOctantRays+K-1)/K;
+ for (size_t i = 0; i < numPackets; i++)
+ This->intersect(inputPackets[i]->tnear() <= inputPackets[i]->tfar, *inputPackets[i], context);
+ return;
+ }
+
+ stack[0].mask = m_active;
+ stack[0].parent = 0;
+ stack[0].child = bvh->root;
+
+ ///////////////////////////////////////////////////////////////////////////////////
+ ///////////////////////////////////////////////////////////////////////////////////
+ ///////////////////////////////////////////////////////////////////////////////////
+
+ StackItemMaskCoherent* stackPtr = stack + 1;
+
+ while (1) pop:
+ {
+ if (unlikely(stackPtr == stack)) break;
+
+ STAT3(normal.trav_stack_pop,1,1,1);
+ stackPtr--;
+ /*! pop next node */
+ NodeRef cur = NodeRef(stackPtr->child);
+ size_t m_trav_active = stackPtr->mask;
+ assert(m_trav_active);
+ NodeRef parent = stackPtr->parent;
+
+ while (1)
+ {
+ if (unlikely(cur.isLeaf())) break;
+ const AABBNode* __restrict__ const node = cur.getAABBNode();
+ parent = cur;
+
+ __aligned(64) size_t maskK[N];
+ for (size_t i = 0; i < N; i++)
+ maskK[i] = m_trav_active;
+ vfloat<N> dist;
+ const size_t m_node_hit = traverseCoherentStream(m_trav_active, packets, node, frustum, maskK, dist);
+ if (unlikely(m_node_hit == 0)) goto pop;
+
+ BVHNNodeTraverserStreamHitCoherent<N, types>::traverseClosestHit(cur, m_trav_active, vbool<N>((int)m_node_hit), dist, (size_t*)maskK, stackPtr);
+ assert(m_trav_active);
+ }
+
+ /* non-root and leaf => full culling test for all rays */
+ if (unlikely(parent != 0 && cur.isLeaf()))
+ {
+ const AABBNode* __restrict__ const node = parent.getAABBNode();
+ size_t boxID = 0xff;
+ for (size_t i = 0; i < N; i++)
+ if (node->child(i) == cur) { boxID = i; break; }
+ assert(boxID < N);
+ assert(cur == node->child(boxID));
+ m_trav_active = intersectAABBNodePacket(m_trav_active, packets, node, boxID, frustum.nf);
+ }
+
+ /*! this is a leaf node */
+ assert(cur != BVH::emptyNode);
+ STAT3(normal.trav_leaves, 1, 1, 1);
+ size_t num; PrimitiveK<K>* prim = (PrimitiveK<K>*)cur.leaf(num);
+
+ size_t bits = m_trav_active;
+
+ /*! intersect stream of rays with all primitives */
+ size_t lazy_node = 0;
+#if defined(__SSE4_2__)
+ STAT_USER(1,(popcnt(bits)+K-1)/K*4);
+#endif
+ while(bits)
+ {
+ size_t i = bsf(bits) / K;
+ const size_t m_isec = ((((size_t)1 << K)-1) << (i*K));
+ assert(m_isec & bits);
+ bits &= ~m_isec;
+
+ TravRayKStream<K, robust>& p = packets[i];
+ vbool<K> m_valid = p.tnear <= p.tfar;
+ PrimitiveIntersectorK<K>::intersectK(m_valid, This, *inputPackets[i], context, prim, num, lazy_node);
+ p.tfar = min(p.tfar, inputPackets[i]->tfar);
+ };
+
+ } // traversal + intersection
+ }
+
+ template<int N, int types, bool robust, typename PrimitiveIntersector>
+ __forceinline void BVHNIntersectorStream<N, types, robust, PrimitiveIntersector>::occluded(Accel::Intersectors* __restrict__ This,
+ RayN** inputPackets,
+ size_t numOctantRays,
+ IntersectContext* context)
+ {
+ /* we may traverse an empty BVH in case all geometry was invalid */
+ BVH* __restrict__ bvh = (BVH*) This->ptr;
+ if (bvh->root == BVH::emptyNode)
+ return;
+
+ if (unlikely(context->isCoherent()))
+ occludedCoherent(This, (RayK<VSIZEL>**)inputPackets, numOctantRays, context);
+ else
+ occludedIncoherent(This, (RayK<VSIZEX>**)inputPackets, numOctantRays, context);
+ }
+
+ template<int N, int types, bool robust, typename PrimitiveIntersector>
+ template<int K>
+ __noinline void BVHNIntersectorStream<N, types, robust, PrimitiveIntersector>::occludedCoherent(Accel::Intersectors* __restrict__ This,
+ RayK<K>** inputPackets,
+ size_t numOctantRays,
+ IntersectContext* context)
+ {
+ assert(context->isCoherent());
+
+ BVH* __restrict__ bvh = (BVH*)This->ptr;
+ __aligned(64) StackItemMaskCoherent stack[stackSizeSingle]; // stack of nodes
+ assert(numOctantRays <= MAX_INTERNAL_STREAM_SIZE);
+
+ /* inactive rays should have been filtered out before */
+ __aligned(64) TravRayKStream<K, robust> packets[MAX_INTERNAL_STREAM_SIZE/K];
+ __aligned(64) Frustum<robust> frustum;
+
+ bool commonOctant = true;
+ size_t m_active = initPacketsAndFrustum(inputPackets, numOctantRays, packets, frustum, commonOctant);
+
+ /* valid rays */
+ if (unlikely(m_active == 0)) return;
+
+ /* case of non-common origin */
+ if (unlikely(!commonOctant))
+ {
+ const size_t numPackets = (numOctantRays+K-1)/K;
+ for (size_t i = 0; i < numPackets; i++)
+ This->occluded(inputPackets[i]->tnear() <= inputPackets[i]->tfar, *inputPackets[i], context);
+ return;
+ }
+
+ stack[0].mask = m_active;
+ stack[0].parent = 0;
+ stack[0].child = bvh->root;
+
+ ///////////////////////////////////////////////////////////////////////////////////
+ ///////////////////////////////////////////////////////////////////////////////////
+ ///////////////////////////////////////////////////////////////////////////////////
+
+ StackItemMaskCoherent* stackPtr = stack + 1;
+
+ while (1) pop:
+ {
+ if (unlikely(stackPtr == stack)) break;
+
+ STAT3(normal.trav_stack_pop,1,1,1);
+ stackPtr--;
+ /*! pop next node */
+ NodeRef cur = NodeRef(stackPtr->child);
+ size_t m_trav_active = stackPtr->mask & m_active;
+ if (unlikely(!m_trav_active)) continue;
+ assert(m_trav_active);
+ NodeRef parent = stackPtr->parent;
+
+ while (1)
+ {
+ if (unlikely(cur.isLeaf())) break;
+ const AABBNode* __restrict__ const node = cur.getAABBNode();
+ parent = cur;
+
+ __aligned(64) size_t maskK[N];
+ for (size_t i = 0; i < N; i++)
+ maskK[i] = m_trav_active;
+
+ vfloat<N> dist;
+ const size_t m_node_hit = traverseCoherentStream(m_trav_active, packets, node, frustum, maskK, dist);
+ if (unlikely(m_node_hit == 0)) goto pop;
+
+ BVHNNodeTraverserStreamHitCoherent<N, types>::traverseAnyHit(cur, m_trav_active, vbool<N>((int)m_node_hit), (size_t*)maskK, stackPtr);
+ assert(m_trav_active);
+ }
+
+ /* non-root and leaf => full culling test for all rays */
+ if (unlikely(parent != 0 && cur.isLeaf()))
+ {
+ const AABBNode* __restrict__ const node = parent.getAABBNode();
+ size_t boxID = 0xff;
+ for (size_t i = 0; i < N; i++)
+ if (node->child(i) == cur) { boxID = i; break; }
+ assert(boxID < N);
+ assert(cur == node->child(boxID));
+ m_trav_active = intersectAABBNodePacket(m_trav_active, packets, node, boxID, frustum.nf);
+ }
+
+ /*! this is a leaf node */
+ assert(cur != BVH::emptyNode);
+ STAT3(normal.trav_leaves, 1, 1, 1);
+ size_t num; PrimitiveK<K>* prim = (PrimitiveK<K>*)cur.leaf(num);
+
+ size_t bits = m_trav_active & m_active;
+ /*! intersect stream of rays with all primitives */
+ size_t lazy_node = 0;
+#if defined(__SSE4_2__)
+ STAT_USER(1,(popcnt(bits)+K-1)/K*4);
+#endif
+ while (bits)
+ {
+ size_t i = bsf(bits) / K;
+ const size_t m_isec = ((((size_t)1 << K)-1) << (i*K));
+ assert(m_isec & bits);
+ bits &= ~m_isec;
+ TravRayKStream<K, robust>& p = packets[i];
+ vbool<K> m_valid = p.tnear <= p.tfar;
+ vbool<K> m_hit = PrimitiveIntersectorK<K>::occludedK(m_valid, This, *inputPackets[i], context, prim, num, lazy_node);
+ inputPackets[i]->tfar = select(m_hit & m_valid, vfloat<K>(neg_inf), inputPackets[i]->tfar);
+ m_active &= ~((size_t)movemask(m_hit) << (i*K));
+ }
+
+ } // traversal + intersection
+ }
+
+
+ template<int N, int types, bool robust, typename PrimitiveIntersector>
+ template<int K>
+ __forceinline void BVHNIntersectorStream<N, types, robust, PrimitiveIntersector>::occludedIncoherent(Accel::Intersectors* __restrict__ This,
+ RayK<K>** inputPackets,
+ size_t numOctantRays,
+ IntersectContext* context)
+ {
+ assert(!context->isCoherent());
+ assert(types & BVH_FLAG_ALIGNED_NODE);
+
+ __aligned(64) TravRayKStream<K,robust> packet[MAX_INTERNAL_STREAM_SIZE/K];
+
+ assert(numOctantRays <= 32);
+ const size_t numPackets = (numOctantRays+K-1)/K;
+ size_t m_active = 0;
+ for (size_t i = 0; i < numPackets; i++)
+ {
+ const vfloat<K> tnear = inputPackets[i]->tnear();
+ const vfloat<K> tfar = inputPackets[i]->tfar;
+ vbool<K> m_valid = (tnear <= tfar) & (tnear >= 0.0f);
+ m_active |= (size_t)movemask(m_valid) << (K*i);
+ const Vec3vf<K>& org = inputPackets[i]->org;
+ const Vec3vf<K>& dir = inputPackets[i]->dir;
+ vfloat<K> packet_min_dist = max(tnear, 0.0f);
+ vfloat<K> packet_max_dist = select(m_valid, tfar, neg_inf);
+ new (&packet[i]) TravRayKStream<K,robust>(org, dir, packet_min_dist, packet_max_dist);
+ }
+
+ BVH* __restrict__ bvh = (BVH*)This->ptr;
+
+ StackItemMaskT<NodeRef> stack[stackSizeSingle]; // stack of nodes
+ StackItemMaskT<NodeRef>* stackPtr = stack + 1; // current stack pointer
+ stack[0].ptr = bvh->root;
+ stack[0].mask = m_active;
+
+ size_t terminated = ~m_active;
+
+ /* near/far offsets based on first ray */
+ const NearFarPrecalculations nf(Vec3fa(packet[0].rdir.x[0], packet[0].rdir.y[0], packet[0].rdir.z[0]), N);
+
+ while (1) pop:
+ {
+ if (unlikely(stackPtr == stack)) break;
+ STAT3(shadow.trav_stack_pop,1,1,1);
+ stackPtr--;
+ NodeRef cur = NodeRef(stackPtr->ptr);
+ size_t cur_mask = stackPtr->mask & (~terminated);
+ if (unlikely(cur_mask == 0)) continue;
+
+ while (true)
+ {
+ /*! stop if we found a leaf node */
+ if (unlikely(cur.isLeaf())) break;
+ const AABBNode* __restrict__ const node = cur.getAABBNode();
+
+ const vint<N> vmask = traverseIncoherentStream(cur_mask, packet, node, nf, shiftTable);
+
+ size_t mask = movemask(vmask != vint<N>(zero));
+ if (unlikely(mask == 0)) goto pop;
+
+ __aligned(64) unsigned int child_mask[N];
+ vint<N>::storeu(child_mask, vmask); // this explicit store here causes much better code generation
+
+ /*! one child is hit, continue with that child */
+ size_t r = bscf(mask);
+ assert(r < N);
+ cur = node->child(r);
+ BVHN<N>::prefetch(cur,types);
+ cur_mask = child_mask[r];
+
+ /* simple in order sequence */
+ assert(cur != BVH::emptyNode);
+ if (likely(mask == 0)) continue;
+ stackPtr->ptr = cur;
+ stackPtr->mask = cur_mask;
+ stackPtr++;
+
+ for (; ;)
+ {
+ r = bscf(mask);
+ assert(r < N);
+
+ cur = node->child(r);
+ BVHN<N>::prefetch(cur,types);
+ cur_mask = child_mask[r];
+ assert(cur != BVH::emptyNode);
+ if (likely(mask == 0)) break;
+ stackPtr->ptr = cur;
+ stackPtr->mask = cur_mask;
+ stackPtr++;
+ }
+ }
+
+ /*! this is a leaf node */
+ assert(cur != BVH::emptyNode);
+ STAT3(shadow.trav_leaves,1,1,1);
+ size_t num; PrimitiveK<K>* prim = (PrimitiveK<K>*)cur.leaf(num);
+
+ size_t bits = cur_mask;
+ size_t lazy_node = 0;
+
+ for (; bits != 0;)
+ {
+ const size_t rayID = bscf(bits);
+
+ RayK<K> &ray = *inputPackets[rayID / K];
+ const size_t k = rayID % K;
+ if (PrimitiveIntersectorK<K>::occluded(This, ray, k, context, prim, num, lazy_node))
+ {
+ ray.tfar[k] = neg_inf;
+ terminated |= (size_t)1 << rayID;
+ }
+
+ /* lazy node */
+ if (unlikely(lazy_node))
+ {
+ stackPtr->ptr = lazy_node;
+ stackPtr->mask = cur_mask;
+ stackPtr++;
+ }
+ }
+
+ if (unlikely(terminated == (size_t)-1)) break;
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////
+ /// ArrayIntersectorKStream Definitions
+ ////////////////////////////////////////////////////////////////////////////////
+
+ template<bool filter>
+ struct Triangle4IntersectorStreamMoeller {
+ template<int K> using Type = ArrayIntersectorKStream<K,TriangleMIntersectorKMoeller<4 COMMA K COMMA true>>;
+ };
+
+ template<bool filter>
+ struct Triangle4vIntersectorStreamPluecker {
+ template<int K> using Type = ArrayIntersectorKStream<K,TriangleMvIntersectorKPluecker<4 COMMA K COMMA true>>;
+ };
+
+ template<bool filter>
+ struct Triangle4iIntersectorStreamMoeller {
+ template<int K> using Type = ArrayIntersectorKStream<K,TriangleMiIntersectorKMoeller<4 COMMA K COMMA true>>;
+ };
+
+ template<bool filter>
+ struct Triangle4iIntersectorStreamPluecker {
+ template<int K> using Type = ArrayIntersectorKStream<K,TriangleMiIntersectorKPluecker<4 COMMA K COMMA true>>;
+ };
+
+ template<bool filter>
+ struct Quad4vIntersectorStreamMoeller {
+ template<int K> using Type = ArrayIntersectorKStream<K,QuadMvIntersectorKMoeller<4 COMMA K COMMA true>>;
+ };
+
+ template<bool filter>
+ struct Quad4iIntersectorStreamMoeller {
+ template<int K> using Type = ArrayIntersectorKStream<K,QuadMiIntersectorKMoeller<4 COMMA K COMMA true>>;
+ };
+
+ template<bool filter>
+ struct Quad4vIntersectorStreamPluecker {
+ template<int K> using Type = ArrayIntersectorKStream<K,QuadMvIntersectorKPluecker<4 COMMA K COMMA true>>;
+ };
+
+ template<bool filter>
+ struct Quad4iIntersectorStreamPluecker {
+ template<int K> using Type = ArrayIntersectorKStream<K,QuadMiIntersectorKPluecker<4 COMMA K COMMA true>>;
+ };
+
+ struct ObjectIntersectorStream {
+ template<int K> using Type = ArrayIntersectorKStream<K,ObjectIntersectorK<K COMMA false>>;
+ };
+
+ struct InstanceIntersectorStream {
+ template<int K> using Type = ArrayIntersectorKStream<K,InstanceIntersectorK<K>>;
+ };
+
+ // =====================================================================================================
+ // =====================================================================================================
+ // =====================================================================================================
+
+ template<int N>
+ void BVHNIntersectorStreamPacketFallback<N>::intersect(Accel::Intersectors* __restrict__ This,
+ RayHitN** inputRays,
+ size_t numTotalRays,
+ IntersectContext* context)
+ {
+ if (unlikely(context->isCoherent()))
+ intersectK(This, (RayHitK<VSIZEL>**)inputRays, numTotalRays, context);
+ else
+ intersectK(This, (RayHitK<VSIZEX>**)inputRays, numTotalRays, context);
+ }
+
+ template<int N>
+ void BVHNIntersectorStreamPacketFallback<N>::occluded(Accel::Intersectors* __restrict__ This,
+ RayN** inputRays,
+ size_t numTotalRays,
+ IntersectContext* context)
+ {
+ if (unlikely(context->isCoherent()))
+ occludedK(This, (RayK<VSIZEL>**)inputRays, numTotalRays, context);
+ else
+ occludedK(This, (RayK<VSIZEX>**)inputRays, numTotalRays, context);
+ }
+
+ template<int N>
+ template<int K>
+ __noinline void BVHNIntersectorStreamPacketFallback<N>::intersectK(Accel::Intersectors* __restrict__ This,
+ RayHitK<K>** inputRays,
+ size_t numTotalRays,
+ IntersectContext* context)
+ {
+ /* fallback to packets */
+ for (size_t i = 0; i < numTotalRays; i += K)
+ {
+ const vint<K> vi = vint<K>(int(i)) + vint<K>(step);
+ vbool<K> valid = vi < vint<K>(int(numTotalRays));
+ RayHitK<K>& ray = *(inputRays[i / K]);
+ valid &= ray.tnear() <= ray.tfar;
+ This->intersect(valid, ray, context);
+ }
+ }
+
+ template<int N>
+ template<int K>
+ __noinline void BVHNIntersectorStreamPacketFallback<N>::occludedK(Accel::Intersectors* __restrict__ This,
+ RayK<K>** inputRays,
+ size_t numTotalRays,
+ IntersectContext* context)
+ {
+ /* fallback to packets */
+ for (size_t i = 0; i < numTotalRays; i += K)
+ {
+ const vint<K> vi = vint<K>(int(i)) + vint<K>(step);
+ vbool<K> valid = vi < vint<K>(int(numTotalRays));
+ RayK<K>& ray = *(inputRays[i / K]);
+ valid &= ray.tnear() <= ray.tfar;
+ This->occluded(valid, ray, context);
+ }
+ }
+ }
+}
diff --git a/thirdparty/embree/kernels/bvh/bvh_intersector_stream_bvh4.cpp b/thirdparty/embree/kernels/bvh/bvh_intersector_stream_bvh4.cpp
new file mode 100644
index 0000000000..c3e5f137b8
--- /dev/null
+++ b/thirdparty/embree/kernels/bvh/bvh_intersector_stream_bvh4.cpp
@@ -0,0 +1,36 @@
+// Copyright 2009-2021 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "bvh_intersector_stream.cpp"
+
+namespace embree
+{
+ namespace isa
+ {
+
+ ////////////////////////////////////////////////////////////////////////////////
+ /// General BVHIntersectorStreamPacketFallback Intersector
+ ////////////////////////////////////////////////////////////////////////////////
+
+ DEFINE_INTERSECTORN(BVH4IntersectorStreamPacketFallback,BVHNIntersectorStreamPacketFallback<4>);
+
+ ////////////////////////////////////////////////////////////////////////////////
+ /// BVH4IntersectorStream Definitions
+ ////////////////////////////////////////////////////////////////////////////////
+
+ IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4iIntersectorStreamMoeller, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA Triangle4iIntersectorStreamMoeller<true>>));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4vIntersectorStreamPluecker, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA true COMMA Triangle4vIntersectorStreamPluecker<true>>));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4iIntersectorStreamPluecker, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA true COMMA Triangle4iIntersectorStreamPluecker<true>>));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4IntersectorStreamMoeller, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA Triangle4IntersectorStreamMoeller<true>>));
+ IF_ENABLED_TRIS(DEFINE_INTERSECTORN(BVH4Triangle4IntersectorStreamMoellerNoFilter, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA Triangle4IntersectorStreamMoeller<false>>));
+
+ IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4vIntersectorStreamMoeller, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA Quad4vIntersectorStreamMoeller<true>>));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4vIntersectorStreamMoellerNoFilter,BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA Quad4vIntersectorStreamMoeller<false>>));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4iIntersectorStreamMoeller, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA Quad4iIntersectorStreamMoeller<true>>));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4vIntersectorStreamPluecker, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA true COMMA Quad4vIntersectorStreamPluecker<true>>));
+ IF_ENABLED_QUADS(DEFINE_INTERSECTORN(BVH4Quad4iIntersectorStreamPluecker, BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA true COMMA Quad4iIntersectorStreamPluecker<true>>));
+
+ IF_ENABLED_USER(DEFINE_INTERSECTORN(BVH4VirtualIntersectorStream,BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA ObjectIntersectorStream>));
+ IF_ENABLED_INSTANCE(DEFINE_INTERSECTORN(BVH4InstanceIntersectorStream,BVHNIntersectorStream<4 COMMA BVH_AN1 COMMA false COMMA InstanceIntersectorStream>));
+ }
+}
diff --git a/thirdparty/embree/kernels/bvh/bvh_intersector_stream_filters.cpp b/thirdparty/embree/kernels/bvh/bvh_intersector_stream_filters.cpp
new file mode 100644
index 0000000000..b858eb163f
--- /dev/null
+++ b/thirdparty/embree/kernels/bvh/bvh_intersector_stream_filters.cpp
@@ -0,0 +1,657 @@
+// Copyright 2009-2021 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "bvh_intersector_stream_filters.h"
+#include "bvh_intersector_stream.h"
+
+namespace embree
+{
+ namespace isa
+ {
+ template<int K, bool intersect>
+ __noinline void RayStreamFilter::filterAOS(Scene* scene, void* _rayN, size_t N, size_t stride, IntersectContext* context)
+ {
+ RayStreamAOS rayN(_rayN);
+
+ /* use fast path for coherent ray mode */
+ if (unlikely(context->isCoherent()))
+ {
+ __aligned(64) RayTypeK<K, intersect> rays[MAX_INTERNAL_STREAM_SIZE / K];
+ __aligned(64) RayTypeK<K, intersect>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
+ {
+ const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);
+
+ /* convert from AOS to SOA */
+ for (size_t j = 0; j < size; j += K)
+ {
+ const vint<K> vij = vint<K>(int(i+j)) + vint<K>(step);
+ const vbool<K> valid = vij < vint<K>(int(N));
+ const vint<K> offset = vij * int(stride);
+ const size_t packetIndex = j / K;
+
+ RayTypeK<K, intersect> ray = rayN.getRayByOffset<K>(valid, offset);
+ ray.tnear() = select(valid, ray.tnear(), zero);
+ ray.tfar = select(valid, ray.tfar, neg_inf);
+
+ rays[packetIndex] = ray;
+ rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
+ }
+
+ /* trace stream */
+ scene->intersectors.intersectN(rayPtrs, size, context);
+
+ /* convert from SOA to AOS */
+ for (size_t j = 0; j < size; j += K)
+ {
+ const vint<K> vij = vint<K>(int(i+j)) + vint<K>(step);
+ const vbool<K> valid = vij < vint<K>(int(N));
+ const vint<K> offset = vij * int(stride);
+ const size_t packetIndex = j / K;
+ rayN.setHitByOffset(valid, offset, rays[packetIndex]);
+ }
+ }
+ }
+ else if (unlikely(!intersect))
+ {
+ /* octant sorting for occlusion rays */
+ __aligned(64) unsigned int octants[8][MAX_INTERNAL_STREAM_SIZE];
+ __aligned(64) RayK<K> rays[MAX_INTERNAL_STREAM_SIZE / K];
+ __aligned(64) RayK<K>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ unsigned int raysInOctant[8];
+ for (unsigned int i = 0; i < 8; i++)
+ raysInOctant[i] = 0;
+ size_t inputRayID = 0;
+
+ for (;;)
+ {
+ int curOctant = -1;
+
+ /* sort rays into octants */
+ for (; inputRayID < N;)
+ {
+ const Ray& ray = rayN.getRayByOffset(inputRayID * stride);
+
+ /* skip invalid rays */
+ if (unlikely(ray.tnear() > ray.tfar || ray.tfar < 0.0f)) { inputRayID++; continue; } // ignore invalid or already occluded rays
+#if defined(EMBREE_IGNORE_INVALID_RAYS)
+ if (unlikely(!ray.valid())) { inputRayID++; continue; }
+#endif
+
+ const unsigned int octantID = movemask(vfloat4(Vec3fa(ray.dir)) < 0.0f) & 0x7;
+
+ assert(octantID < 8);
+ octants[octantID][raysInOctant[octantID]++] = (unsigned int)inputRayID;
+ inputRayID++;
+ if (unlikely(raysInOctant[octantID] == MAX_INTERNAL_STREAM_SIZE))
+ {
+ curOctant = octantID;
+ break;
+ }
+ }
+
+ /* need to flush rays in octant? */
+ if (unlikely(curOctant == -1))
+ {
+ for (unsigned int i = 0; i < 8; i++)
+ if (raysInOctant[i]) { curOctant = i; break; }
+ }
+
+ /* all rays traced? */
+ if (unlikely(curOctant == -1))
+ break;
+
+ unsigned int* const rayIDs = &octants[curOctant][0];
+ const unsigned int numOctantRays = raysInOctant[curOctant];
+ assert(numOctantRays);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> offset = *(vint<K>*)&rayIDs[j] * int(stride);
+ RayK<K>& ray = rays[j/K];
+ rayPtrs[j/K] = &ray;
+ ray = rayN.getRayByOffset<K>(valid, offset);
+ ray.tnear() = select(valid, ray.tnear(), zero);
+ ray.tfar = select(valid, ray.tfar, neg_inf);
+ }
+
+ scene->intersectors.occludedN(rayPtrs, numOctantRays, context);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> offset = *(vint<K>*)&rayIDs[j] * int(stride);
+ rayN.setHitByOffset<K>(valid, offset, rays[j/K]);
+ }
+
+ raysInOctant[curOctant] = 0;
+ }
+ }
+ else
+ {
+ /* fallback to packets */
+ for (size_t i = 0; i < N; i += K)
+ {
+ const vint<K> vi = vint<K>(int(i)) + vint<K>(step);
+ vbool<K> valid = vi < vint<K>(int(N));
+ const vint<K> offset = vi * int(stride);
+
+ RayTypeK<K, intersect> ray = rayN.getRayByOffset<K>(valid, offset);
+ valid &= ray.tnear() <= ray.tfar;
+
+ scene->intersectors.intersect(valid, ray, context);
+
+ rayN.setHitByOffset<K>(valid, offset, ray);
+ }
+ }
+ }
+
+ template<int K, bool intersect>
+ __noinline void RayStreamFilter::filterAOP(Scene* scene, void** _rayN, size_t N, IntersectContext* context)
+ {
+ RayStreamAOP rayN(_rayN);
+
+ /* use fast path for coherent ray mode */
+ if (unlikely(context->isCoherent()))
+ {
+ __aligned(64) RayTypeK<K, intersect> rays[MAX_INTERNAL_STREAM_SIZE / K];
+ __aligned(64) RayTypeK<K, intersect>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
+ {
+ const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);
+
+ /* convert from AOP to SOA */
+ for (size_t j = 0; j < size; j += K)
+ {
+ const vint<K> vij = vint<K>(int(i+j)) + vint<K>(step);
+ const vbool<K> valid = vij < vint<K>(int(N));
+ const size_t packetIndex = j / K;
+
+ RayTypeK<K, intersect> ray = rayN.getRayByIndex<K>(valid, vij);
+ ray.tnear() = select(valid, ray.tnear(), zero);
+ ray.tfar = select(valid, ray.tfar, neg_inf);
+
+ rays[packetIndex] = ray;
+ rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
+ }
+
+ /* trace stream */
+ scene->intersectors.intersectN(rayPtrs, size, context);
+
+ /* convert from SOA to AOP */
+ for (size_t j = 0; j < size; j += K)
+ {
+ const vint<K> vij = vint<K>(int(i+j)) + vint<K>(step);
+ const vbool<K> valid = vij < vint<K>(int(N));
+ const size_t packetIndex = j / K;
+
+ rayN.setHitByIndex<K>(valid, vij, rays[packetIndex]);
+ }
+ }
+ }
+ else if (unlikely(!intersect))
+ {
+ /* octant sorting for occlusion rays */
+ __aligned(64) unsigned int octants[8][MAX_INTERNAL_STREAM_SIZE];
+ __aligned(64) RayK<K> rays[MAX_INTERNAL_STREAM_SIZE / K];
+ __aligned(64) RayK<K>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ unsigned int raysInOctant[8];
+ for (unsigned int i = 0; i < 8; i++)
+ raysInOctant[i] = 0;
+ size_t inputRayID = 0;
+
+ for (;;)
+ {
+ int curOctant = -1;
+
+ /* sort rays into octants */
+ for (; inputRayID < N;)
+ {
+ const Ray& ray = rayN.getRayByIndex(inputRayID);
+
+ /* skip invalid rays */
+ if (unlikely(ray.tnear() > ray.tfar || ray.tfar < 0.0f)) { inputRayID++; continue; } // ignore invalid or already occluded rays
+#if defined(EMBREE_IGNORE_INVALID_RAYS)
+ if (unlikely(!ray.valid())) { inputRayID++; continue; }
+#endif
+
+ const unsigned int octantID = movemask(lt_mask(ray.dir,Vec3fa(0.0f)));
+
+ assert(octantID < 8);
+ octants[octantID][raysInOctant[octantID]++] = (unsigned int)inputRayID;
+ inputRayID++;
+ if (unlikely(raysInOctant[octantID] == MAX_INTERNAL_STREAM_SIZE))
+ {
+ curOctant = octantID;
+ break;
+ }
+ }
+
+ /* need to flush rays in octant? */
+ if (unlikely(curOctant == -1))
+ {
+ for (unsigned int i = 0; i < 8; i++)
+ if (raysInOctant[i]) { curOctant = i; break; }
+ }
+
+ /* all rays traced? */
+ if (unlikely(curOctant == -1))
+ break;
+
+ unsigned int* const rayIDs = &octants[curOctant][0];
+ const unsigned int numOctantRays = raysInOctant[curOctant];
+ assert(numOctantRays);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> index = *(vint<K>*)&rayIDs[j];
+ RayK<K>& ray = rays[j/K];
+ rayPtrs[j/K] = &ray;
+ ray = rayN.getRayByIndex<K>(valid, index);
+ ray.tnear() = select(valid, ray.tnear(), zero);
+ ray.tfar = select(valid, ray.tfar, neg_inf);
+ }
+
+ scene->intersectors.occludedN(rayPtrs, numOctantRays, context);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> index = *(vint<K>*)&rayIDs[j];
+ rayN.setHitByIndex<K>(valid, index, rays[j/K]);
+ }
+
+ raysInOctant[curOctant] = 0;
+ }
+ }
+ else
+ {
+ /* fallback to packets */
+ for (size_t i = 0; i < N; i += K)
+ {
+ const vint<K> vi = vint<K>(int(i)) + vint<K>(step);
+ vbool<K> valid = vi < vint<K>(int(N));
+
+ RayTypeK<K, intersect> ray = rayN.getRayByIndex<K>(valid, vi);
+ valid &= ray.tnear() <= ray.tfar;
+
+ scene->intersectors.intersect(valid, ray, context);
+
+ rayN.setHitByIndex<K>(valid, vi, ray);
+ }
+ }
+ }
+
+ template<int K, bool intersect>
+ __noinline void RayStreamFilter::filterSOA(Scene* scene, char* rayData, size_t N, size_t numPackets, size_t stride, IntersectContext* context)
+ {
+ const size_t rayDataAlignment = (size_t)rayData % (K*sizeof(float));
+ const size_t offsetAlignment = (size_t)stride % (K*sizeof(float));
+
+ /* fast path for packets with the correct width and data alignment */
+ if (likely(N == K &&
+ !rayDataAlignment &&
+ !offsetAlignment))
+ {
+ if (unlikely(context->isCoherent()))
+ {
+ __aligned(64) RayTypeK<K, intersect>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ size_t packetIndex = 0;
+ for (size_t i = 0; i < numPackets; i++)
+ {
+ const size_t offset = i * stride;
+ RayTypeK<K, intersect>& ray = *(RayTypeK<K, intersect>*)(rayData + offset);
+ rayPtrs[packetIndex++] = &ray;
+
+ /* trace as stream */
+ if (unlikely(packetIndex == MAX_INTERNAL_STREAM_SIZE / K))
+ {
+ const size_t size = packetIndex*K;
+ scene->intersectors.intersectN(rayPtrs, size, context);
+ packetIndex = 0;
+ }
+ }
+
+ /* flush remaining packets */
+ if (unlikely(packetIndex > 0))
+ {
+ const size_t size = packetIndex*K;
+ scene->intersectors.intersectN(rayPtrs, size, context);
+ }
+ }
+ else if (unlikely(!intersect))
+ {
+ /* octant sorting for occlusion rays */
+ RayStreamSOA rayN(rayData, K);
+
+ __aligned(64) unsigned int octants[8][MAX_INTERNAL_STREAM_SIZE];
+ __aligned(64) RayK<K> rays[MAX_INTERNAL_STREAM_SIZE / K];
+ __aligned(64) RayK<K>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ unsigned int raysInOctant[8];
+ for (unsigned int i = 0; i < 8; i++)
+ raysInOctant[i] = 0;
+ size_t inputRayID = 0;
+
+ for (;;)
+ {
+ int curOctant = -1;
+
+ /* sort rays into octants */
+ for (; inputRayID < N*numPackets;)
+ {
+ const size_t offset = (inputRayID / K) * stride + (inputRayID % K) * sizeof(float);
+
+ /* skip invalid rays */
+ if (unlikely(!rayN.isValidByOffset(offset))) { inputRayID++; continue; } // ignore invalid or already occluded rays
+ #if defined(EMBREE_IGNORE_INVALID_RAYS)
+ __aligned(64) Ray ray = rayN.getRayByOffset(offset);
+ if (unlikely(!ray.valid())) { inputRayID++; continue; }
+ #endif
+
+ const unsigned int octantID = (unsigned int)rayN.getOctantByOffset(offset);
+
+ assert(octantID < 8);
+ octants[octantID][raysInOctant[octantID]++] = (unsigned int)offset;
+ inputRayID++;
+ if (unlikely(raysInOctant[octantID] == MAX_INTERNAL_STREAM_SIZE))
+ {
+ curOctant = octantID;
+ break;
+ }
+ }
+
+ /* need to flush rays in octant? */
+ if (unlikely(curOctant == -1))
+ {
+ for (unsigned int i = 0; i < 8; i++)
+ if (raysInOctant[i]) { curOctant = i; break; }
+ }
+
+ /* all rays traced? */
+ if (unlikely(curOctant == -1))
+ break;
+
+ unsigned int* const rayOffsets = &octants[curOctant][0];
+ const unsigned int numOctantRays = raysInOctant[curOctant];
+ assert(numOctantRays);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> offset = *(vint<K>*)&rayOffsets[j];
+ RayK<K>& ray = rays[j/K];
+ rayPtrs[j/K] = &ray;
+ ray = rayN.getRayByOffset<K>(valid, offset);
+ ray.tnear() = select(valid, ray.tnear(), zero);
+ ray.tfar = select(valid, ray.tfar, neg_inf);
+ }
+
+ scene->intersectors.occludedN(rayPtrs, numOctantRays, context);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> offset = *(vint<K>*)&rayOffsets[j];
+ rayN.setHitByOffset(valid, offset, rays[j/K]);
+ }
+ raysInOctant[curOctant] = 0;
+ }
+ }
+ else
+ {
+ /* fallback to packets */
+ for (size_t i = 0; i < numPackets; i++)
+ {
+ const size_t offset = i * stride;
+ RayTypeK<K, intersect>& ray = *(RayTypeK<K, intersect>*)(rayData + offset);
+ const vbool<K> valid = ray.tnear() <= ray.tfar;
+
+ scene->intersectors.intersect(valid, ray, context);
+ }
+ }
+ }
+ else
+ {
+ /* fallback to packets for arbitrary packet size and alignment */
+ for (size_t i = 0; i < numPackets; i++)
+ {
+ const size_t offsetN = i * stride;
+ RayStreamSOA rayN(rayData + offsetN, N);
+
+ for (size_t j = 0; j < N; j += K)
+ {
+ const size_t offset = j * sizeof(float);
+ vbool<K> valid = (vint<K>(int(j)) + vint<K>(step)) < vint<K>(int(N));
+ RayTypeK<K, intersect> ray = rayN.getRayByOffset<K>(valid, offset);
+ valid &= ray.tnear() <= ray.tfar;
+
+ scene->intersectors.intersect(valid, ray, context);
+
+ rayN.setHitByOffset(valid, offset, ray);
+ }
+ }
+ }
+ }
+
+ template<int K, bool intersect>
+ __noinline void RayStreamFilter::filterSOP(Scene* scene, const void* _rayN, size_t N, IntersectContext* context)
+ {
+ RayStreamSOP& rayN = *(RayStreamSOP*)_rayN;
+
+ /* use fast path for coherent ray mode */
+ if (unlikely(context->isCoherent()))
+ {
+ __aligned(64) RayTypeK<K, intersect> rays[MAX_INTERNAL_STREAM_SIZE / K];
+ __aligned(64) RayTypeK<K, intersect>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
+ {
+ const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);
+
+ /* convert from SOP to SOA */
+ for (size_t j = 0; j < size; j += K)
+ {
+ const vint<K> vij = vint<K>(int(i+j)) + vint<K>(step);
+ const vbool<K> valid = vij < vint<K>(int(N));
+ const size_t offset = (i+j) * sizeof(float);
+ const size_t packetIndex = j / K;
+
+ RayTypeK<K, intersect> ray = rayN.getRayByOffset<K>(valid, offset);
+ ray.tnear() = select(valid, ray.tnear(), zero);
+ ray.tfar = select(valid, ray.tfar, neg_inf);
+
+ rays[packetIndex] = ray;
+ rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
+ }
+
+ /* trace stream */
+ scene->intersectors.intersectN(rayPtrs, size, context);
+
+ /* convert from SOA to SOP */
+ for (size_t j = 0; j < size; j += K)
+ {
+ const vint<K> vij = vint<K>(int(i+j)) + vint<K>(step);
+ const vbool<K> valid = vij < vint<K>(int(N));
+ const size_t offset = (i+j) * sizeof(float);
+ const size_t packetIndex = j / K;
+
+ rayN.setHitByOffset(valid, offset, rays[packetIndex]);
+ }
+ }
+ }
+ else if (unlikely(!intersect))
+ {
+ /* octant sorting for occlusion rays */
+ __aligned(64) unsigned int octants[8][MAX_INTERNAL_STREAM_SIZE];
+ __aligned(64) RayK<K> rays[MAX_INTERNAL_STREAM_SIZE / K];
+ __aligned(64) RayK<K>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / K];
+
+ unsigned int raysInOctant[8];
+ for (unsigned int i = 0; i < 8; i++)
+ raysInOctant[i] = 0;
+ size_t inputRayID = 0;
+
+ for (;;)
+ {
+ int curOctant = -1;
+
+ /* sort rays into octants */
+ for (; inputRayID < N;)
+ {
+ const size_t offset = inputRayID * sizeof(float);
+ /* skip invalid rays */
+ if (unlikely(!rayN.isValidByOffset(offset))) { inputRayID++; continue; } // ignore invalid or already occluded rays
+#if defined(EMBREE_IGNORE_INVALID_RAYS)
+ __aligned(64) Ray ray = rayN.getRayByOffset(offset);
+ if (unlikely(!ray.valid())) { inputRayID++; continue; }
+#endif
+
+ const unsigned int octantID = (unsigned int)rayN.getOctantByOffset(offset);
+
+ assert(octantID < 8);
+ octants[octantID][raysInOctant[octantID]++] = (unsigned int)offset;
+ inputRayID++;
+ if (unlikely(raysInOctant[octantID] == MAX_INTERNAL_STREAM_SIZE))
+ {
+ curOctant = octantID;
+ break;
+ }
+ }
+
+ /* need to flush rays in octant? */
+ if (unlikely(curOctant == -1))
+ {
+ for (unsigned int i = 0; i < 8; i++)
+ if (raysInOctant[i]) { curOctant = i; break; }
+ }
+
+ /* all rays traced? */
+ if (unlikely(curOctant == -1))
+ break;
+
+ unsigned int* const rayOffsets = &octants[curOctant][0];
+ const unsigned int numOctantRays = raysInOctant[curOctant];
+ assert(numOctantRays);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> offset = *(vint<K>*)&rayOffsets[j];
+ RayK<K>& ray = rays[j/K];
+ rayPtrs[j/K] = &ray;
+ ray = rayN.getRayByOffset<K>(valid, offset);
+ ray.tnear() = select(valid, ray.tnear(), zero);
+ ray.tfar = select(valid, ray.tfar, neg_inf);
+ }
+
+ scene->intersectors.occludedN(rayPtrs, numOctantRays, context);
+
+ for (unsigned int j = 0; j < numOctantRays; j += K)
+ {
+ const vint<K> vi = vint<K>(int(j)) + vint<K>(step);
+ const vbool<K> valid = vi < vint<K>(int(numOctantRays));
+ const vint<K> offset = *(vint<K>*)&rayOffsets[j];
+ rayN.setHitByOffset(valid, offset, rays[j/K]);
+ }
+
+ raysInOctant[curOctant] = 0;
+ }
+ }
+ else
+ {
+ /* fallback to packets */
+ for (size_t i = 0; i < N; i += K)
+ {
+ const vint<K> vi = vint<K>(int(i)) + vint<K>(step);
+ vbool<K> valid = vi < vint<K>(int(N));
+ const size_t offset = i * sizeof(float);
+
+ RayTypeK<K, intersect> ray = rayN.getRayByOffset<K>(valid, offset);
+ valid &= ray.tnear() <= ray.tfar;
+
+ scene->intersectors.intersect(valid, ray, context);
+
+ rayN.setHitByOffset(valid, offset, ray);
+ }
+ }
+ }
+
+
+ void RayStreamFilter::intersectAOS(Scene* scene, RTCRayHit* _rayN, size_t N, size_t stride, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterAOS<VSIZEL, true>(scene, _rayN, N, stride, context);
+ else
+ filterAOS<VSIZEX, true>(scene, _rayN, N, stride, context);
+ }
+
+ void RayStreamFilter::occludedAOS(Scene* scene, RTCRay* _rayN, size_t N, size_t stride, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterAOS<VSIZEL, false>(scene, _rayN, N, stride, context);
+ else
+ filterAOS<VSIZEX, false>(scene, _rayN, N, stride, context);
+ }
+
+ void RayStreamFilter::intersectAOP(Scene* scene, RTCRayHit** _rayN, size_t N, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterAOP<VSIZEL, true>(scene, (void**)_rayN, N, context);
+ else
+ filterAOP<VSIZEX, true>(scene, (void**)_rayN, N, context);
+ }
+
+ void RayStreamFilter::occludedAOP(Scene* scene, RTCRay** _rayN, size_t N, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterAOP<VSIZEL, false>(scene, (void**)_rayN, N, context);
+ else
+ filterAOP<VSIZEX, false>(scene, (void**)_rayN, N, context);
+ }
+
+ void RayStreamFilter::intersectSOA(Scene* scene, char* rayData, size_t N, size_t numPackets, size_t stride, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterSOA<VSIZEL, true>(scene, rayData, N, numPackets, stride, context);
+ else
+ filterSOA<VSIZEX, true>(scene, rayData, N, numPackets, stride, context);
+ }
+
+ void RayStreamFilter::occludedSOA(Scene* scene, char* rayData, size_t N, size_t numPackets, size_t stride, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterSOA<VSIZEL, false>(scene, rayData, N, numPackets, stride, context);
+ else
+ filterSOA<VSIZEX, false>(scene, rayData, N, numPackets, stride, context);
+ }
+
+ void RayStreamFilter::intersectSOP(Scene* scene, const RTCRayHitNp* _rayN, size_t N, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterSOP<VSIZEL, true>(scene, _rayN, N, context);
+ else
+ filterSOP<VSIZEX, true>(scene, _rayN, N, context);
+ }
+
+ void RayStreamFilter::occludedSOP(Scene* scene, const RTCRayNp* _rayN, size_t N, IntersectContext* context) {
+ if (unlikely(context->isCoherent()))
+ filterSOP<VSIZEL, false>(scene, _rayN, N, context);
+ else
+ filterSOP<VSIZEX, false>(scene, _rayN, N, context);
+ }
+
+
+ RayStreamFilterFuncs rayStreamFilterFuncs() {
+ return RayStreamFilterFuncs(RayStreamFilter::intersectAOS, RayStreamFilter::intersectAOP, RayStreamFilter::intersectSOA, RayStreamFilter::intersectSOP,
+ RayStreamFilter::occludedAOS, RayStreamFilter::occludedAOP, RayStreamFilter::occludedSOA, RayStreamFilter::occludedSOP);
+ }
+ };
+};
diff --git a/thirdparty/embree/kernels/config.h b/thirdparty/embree/kernels/config.h
index 80a8ab2a56..2bf7e93587 100644
--- a/thirdparty/embree/kernels/config.h
+++ b/thirdparty/embree/kernels/config.h
@@ -16,7 +16,7 @@
/* #undef EMBREE_GEOMETRY_INSTANCE */
/* #undef EMBREE_GEOMETRY_GRID */
/* #undef EMBREE_GEOMETRY_POINT */
-/* #undef EMBREE_RAY_PACKETS */
+#define EMBREE_RAY_PACKETS
/* #undef EMBREE_COMPACT_POLYS */
#define EMBREE_CURVE_SELF_INTERSECTION_AVOIDANCE_FACTOR 2.0
diff --git a/thirdparty/embree/kernels/hash.h b/thirdparty/embree/kernels/hash.h
index 10f315cee7..470e15f03e 100644
--- a/thirdparty/embree/kernels/hash.h
+++ b/thirdparty/embree/kernels/hash.h
@@ -2,4 +2,4 @@
// Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
-#define RTC_HASH "7c53133eb21424f7f0ae1e25bf357e358feaf6ab"
+#define RTC_HASH "12b99393438a4cc9e478e33459eed78bec6233fd"
diff --git a/thirdparty/misc/stb_vorbis.c b/thirdparty/misc/stb_vorbis.c
deleted file mode 100644
index a8cbfa6c23..0000000000
--- a/thirdparty/misc/stb_vorbis.c
+++ /dev/null
@@ -1,5563 +0,0 @@
-// Ogg Vorbis audio decoder - v1.20 - public domain
-// http://nothings.org/stb_vorbis/
-//
-// Original version written by Sean Barrett in 2007.
-//
-// Originally sponsored by RAD Game Tools. Seeking implementation
-// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,
-// Elias Software, Aras Pranckevicius, and Sean Barrett.
-//
-// LICENSE
-//
-// See end of file for license information.
-//
-// Limitations:
-//
-// - floor 0 not supported (used in old ogg vorbis files pre-2004)
-// - lossless sample-truncation at beginning ignored
-// - cannot concatenate multiple vorbis streams
-// - sample positions are 32-bit, limiting seekable 192Khz
-// files to around 6 hours (Ogg supports 64-bit)
-//
-// Feature contributors:
-// Dougall Johnson (sample-exact seeking)
-//
-// Bugfix/warning contributors:
-// Terje Mathisen Niklas Frykholm Andy Hill
-// Casey Muratori John Bolton Gargaj
-// Laurent Gomila Marc LeBlanc Ronny Chevalier
-// Bernhard Wodo Evan Balster github:alxprd
-// Tom Beaumont Ingo Leitgeb Nicolas Guillemot
-// Phillip Bennefall Rohit Thiago Goulart
-// github:manxorist saga musix github:infatum
-// Timur Gagiev Maxwell Koo Peter Waller
-// github:audinowho Dougall Johnson David Reid
-// github:Clownacy Pedro J. Estebanez Remi Verschelde
-//
-// Partial history:
-// 1.20 - 2020-07-11 - several small fixes
-// 1.19 - 2020-02-05 - warnings
-// 1.18 - 2020-02-02 - fix seek bugs; parse header comments; misc warnings etc.
-// 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)
-// 1.16 - 2019-03-04 - fix warnings
-// 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
-// 1.14 - 2018-02-11 - delete bogus dealloca usage
-// 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
-// 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
-// 1.11 - 2017-07-23 - fix MinGW compilation
-// 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
-// 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version
-// 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame
-// 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const
-// 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
-// some crash fixes when out of memory or with corrupt files
-// fix some inappropriately signed shifts
-// 1.05 - 2015-04-19 - don't define __forceinline if it's redundant
-// 1.04 - 2014-08-27 - fix missing const-correct case in API
-// 1.03 - 2014-08-07 - warning fixes
-// 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows
-// 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct)
-// 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
-// (API change) report sample rate for decode-full-file funcs
-//
-// See end of file for full version history.
-
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// HEADER BEGINS HERE
-//
-
-#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
-#define STB_VORBIS_INCLUDE_STB_VORBIS_H
-
-#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
-#define STB_VORBIS_NO_STDIO 1
-#endif
-
-#ifndef STB_VORBIS_NO_STDIO
-#include <stdio.h>
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/////////// THREAD SAFETY
-
-// Individual stb_vorbis* handles are not thread-safe; you cannot decode from
-// them from multiple threads at the same time. However, you can have multiple
-// stb_vorbis* handles and decode from them independently in multiple thrads.
-
-
-/////////// MEMORY ALLOCATION
-
-// normally stb_vorbis uses malloc() to allocate memory at startup,
-// and alloca() to allocate temporary memory during a frame on the
-// stack. (Memory consumption will depend on the amount of setup
-// data in the file and how you set the compile flags for speed
-// vs. size. In my test files the maximal-size usage is ~150KB.)
-//
-// You can modify the wrapper functions in the source (setup_malloc,
-// setup_temp_malloc, temp_malloc) to change this behavior, or you
-// can use a simpler allocation model: you pass in a buffer from
-// which stb_vorbis will allocate _all_ its memory (including the
-// temp memory). "open" may fail with a VORBIS_outofmem if you
-// do not pass in enough data; there is no way to determine how
-// much you do need except to succeed (at which point you can
-// query get_info to find the exact amount required. yes I know
-// this is lame).
-//
-// If you pass in a non-NULL buffer of the type below, allocation
-// will occur from it as described above. Otherwise just pass NULL
-// to use malloc()/alloca()
-
-typedef struct
-{
- char *alloc_buffer;
- int alloc_buffer_length_in_bytes;
-} stb_vorbis_alloc;
-
-
-/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
-
-typedef struct stb_vorbis stb_vorbis;
-
-typedef struct
-{
- unsigned int sample_rate;
- int channels;
-
- unsigned int setup_memory_required;
- unsigned int setup_temp_memory_required;
- unsigned int temp_memory_required;
-
- int max_frame_size;
-} stb_vorbis_info;
-
-typedef struct
-{
- char *vendor;
-
- int comment_list_length;
- char **comment_list;
-} stb_vorbis_comment;
-
-// get general information about the file
-extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
-
-// get ogg comments
-extern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f);
-
-// get the last error detected (clears it, too)
-extern int stb_vorbis_get_error(stb_vorbis *f);
-
-// close an ogg vorbis file and free all memory in use
-extern void stb_vorbis_close(stb_vorbis *f);
-
-// this function returns the offset (in samples) from the beginning of the
-// file that will be returned by the next decode, if it is known, or -1
-// otherwise. after a flush_pushdata() call, this may take a while before
-// it becomes valid again.
-// NOT WORKING YET after a seek with PULLDATA API
-extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
-
-// returns the current seek point within the file, or offset from the beginning
-// of the memory buffer. In pushdata mode it returns 0.
-extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
-
-/////////// PUSHDATA API
-
-#ifndef STB_VORBIS_NO_PUSHDATA_API
-
-// this API allows you to get blocks of data from any source and hand
-// them to stb_vorbis. you have to buffer them; stb_vorbis will tell
-// you how much it used, and you have to give it the rest next time;
-// and stb_vorbis may not have enough data to work with and you will
-// need to give it the same data again PLUS more. Note that the Vorbis
-// specification does not bound the size of an individual frame.
-
-extern stb_vorbis *stb_vorbis_open_pushdata(
- const unsigned char * datablock, int datablock_length_in_bytes,
- int *datablock_memory_consumed_in_bytes,
- int *error,
- const stb_vorbis_alloc *alloc_buffer);
-// create a vorbis decoder by passing in the initial data block containing
-// the ogg&vorbis headers (you don't need to do parse them, just provide
-// the first N bytes of the file--you're told if it's not enough, see below)
-// on success, returns an stb_vorbis *, does not set error, returns the amount of
-// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
-// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
-// if returns NULL and *error is VORBIS_need_more_data, then the input block was
-// incomplete and you need to pass in a larger block from the start of the file
-
-extern int stb_vorbis_decode_frame_pushdata(
- stb_vorbis *f,
- const unsigned char *datablock, int datablock_length_in_bytes,
- int *channels, // place to write number of float * buffers
- float ***output, // place to write float ** array of float * buffers
- int *samples // place to write number of output samples
- );
-// decode a frame of audio sample data if possible from the passed-in data block
-//
-// return value: number of bytes we used from datablock
-//
-// possible cases:
-// 0 bytes used, 0 samples output (need more data)
-// N bytes used, 0 samples output (resynching the stream, keep going)
-// N bytes used, M samples output (one frame of data)
-// note that after opening a file, you will ALWAYS get one N-bytes,0-sample
-// frame, because Vorbis always "discards" the first frame.
-//
-// Note that on resynch, stb_vorbis will rarely consume all of the buffer,
-// instead only datablock_length_in_bytes-3 or less. This is because it wants
-// to avoid missing parts of a page header if they cross a datablock boundary,
-// without writing state-machiney code to record a partial detection.
-//
-// The number of channels returned are stored in *channels (which can be
-// NULL--it is always the same as the number of channels reported by
-// get_info). *output will contain an array of float* buffers, one per
-// channel. In other words, (*output)[0][0] contains the first sample from
-// the first channel, and (*output)[1][0] contains the first sample from
-// the second channel.
-
-extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
-// inform stb_vorbis that your next datablock will not be contiguous with
-// previous ones (e.g. you've seeked in the data); future attempts to decode
-// frames will cause stb_vorbis to resynchronize (as noted above), and
-// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
-// will begin decoding the _next_ frame.
-//
-// if you want to seek using pushdata, you need to seek in your file, then
-// call stb_vorbis_flush_pushdata(), then start calling decoding, then once
-// decoding is returning you data, call stb_vorbis_get_sample_offset, and
-// if you don't like the result, seek your file again and repeat.
-#endif
-
-
-////////// PULLING INPUT API
-
-#ifndef STB_VORBIS_NO_PULLDATA_API
-// This API assumes stb_vorbis is allowed to pull data from a source--
-// either a block of memory containing the _entire_ vorbis stream, or a
-// FILE * that you or it create, or possibly some other reading mechanism
-// if you go modify the source to replace the FILE * case with some kind
-// of callback to your code. (But if you don't support seeking, you may
-// just want to go ahead and use pushdata.)
-
-#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
-extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);
-#endif
-#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
-extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);
-#endif
-// decode an entire file and output the data interleaved into a malloc()ed
-// buffer stored in *output. The return value is the number of samples
-// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
-// When you're done with it, just free() the pointer returned in *output.
-
-extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
- int *error, const stb_vorbis_alloc *alloc_buffer);
-// create an ogg vorbis decoder from an ogg vorbis stream in memory (note
-// this must be the entire stream!). on failure, returns NULL and sets *error
-
-#ifndef STB_VORBIS_NO_STDIO
-extern stb_vorbis * stb_vorbis_open_filename(const char *filename,
- int *error, const stb_vorbis_alloc *alloc_buffer);
-// create an ogg vorbis decoder from a filename via fopen(). on failure,
-// returns NULL and sets *error (possibly to VORBIS_file_open_failure).
-
-extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
- int *error, const stb_vorbis_alloc *alloc_buffer);
-// create an ogg vorbis decoder from an open FILE *, looking for a stream at
-// the _current_ seek point (ftell). on failure, returns NULL and sets *error.
-// note that stb_vorbis must "own" this stream; if you seek it in between
-// calls to stb_vorbis, it will become confused. Moreover, if you attempt to
-// perform stb_vorbis_seek_*() operations on this file, it will assume it
-// owns the _entire_ rest of the file after the start point. Use the next
-// function, stb_vorbis_open_file_section(), to limit it.
-
-extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
- int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);
-// create an ogg vorbis decoder from an open FILE *, looking for a stream at
-// the _current_ seek point (ftell); the stream will be of length 'len' bytes.
-// on failure, returns NULL and sets *error. note that stb_vorbis must "own"
-// this stream; if you seek it in between calls to stb_vorbis, it will become
-// confused.
-#endif
-
-extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
-extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
-// these functions seek in the Vorbis file to (approximately) 'sample_number'.
-// after calling seek_frame(), the next call to get_frame_*() will include
-// the specified sample. after calling stb_vorbis_seek(), the next call to
-// stb_vorbis_get_samples_* will start with the specified sample. If you
-// do not need to seek to EXACTLY the target sample when using get_samples_*,
-// you can also use seek_frame().
-
-extern int stb_vorbis_seek_start(stb_vorbis *f);
-// this function is equivalent to stb_vorbis_seek(f,0)
-
-extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
-extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
-// these functions return the total length of the vorbis stream
-
-extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
-// decode the next frame and return the number of samples. the number of
-// channels returned are stored in *channels (which can be NULL--it is always
-// the same as the number of channels reported by get_info). *output will
-// contain an array of float* buffers, one per channel. These outputs will
-// be overwritten on the next call to stb_vorbis_get_frame_*.
-//
-// You generally should not intermix calls to stb_vorbis_get_frame_*()
-// and stb_vorbis_get_samples_*(), since the latter calls the former.
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
-extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
-#endif
-// decode the next frame and return the number of *samples* per channel.
-// Note that for interleaved data, you pass in the number of shorts (the
-// size of your array), but the return value is the number of samples per
-// channel, not the total number of samples.
-//
-// The data is coerced to the number of channels you request according to the
-// channel coercion rules (see below). You must pass in the size of your
-// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
-// The maximum buffer size needed can be gotten from get_info(); however,
-// the Vorbis I specification implies an absolute maximum of 4096 samples
-// per channel.
-
-// Channel coercion rules:
-// Let M be the number of channels requested, and N the number of channels present,
-// and Cn be the nth channel; let stereo L be the sum of all L and center channels,
-// and stereo R be the sum of all R and center channels (channel assignment from the
-// vorbis spec).
-// M N output
-// 1 k sum(Ck) for all k
-// 2 * stereo L, stereo R
-// k l k > l, the first l channels, then 0s
-// k l k <= l, the first k channels
-// Note that this is not _good_ surround etc. mixing at all! It's just so
-// you get something useful.
-
-extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
-extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
-// gets num_samples samples, not necessarily on a frame boundary--this requires
-// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
-// Returns the number of samples stored per channel; it may be less than requested
-// at the end of the file. If there are no more samples in the file, returns 0.
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
-extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
-#endif
-// gets num_samples samples, not necessarily on a frame boundary--this requires
-// buffering so you have to supply the buffers. Applies the coercion rules above
-// to produce 'channels' channels. Returns the number of samples stored per channel;
-// it may be less than requested at the end of the file. If there are no more
-// samples in the file, returns 0.
-
-#endif
-
-//////// ERROR CODES
-
-enum STBVorbisError
-{
- VORBIS__no_error,
-
- VORBIS_need_more_data=1, // not a real error
-
- VORBIS_invalid_api_mixing, // can't mix API modes
- VORBIS_outofmem, // not enough memory
- VORBIS_feature_not_supported, // uses floor 0
- VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
- VORBIS_file_open_failure, // fopen() failed
- VORBIS_seek_without_length, // can't seek in unknown-length file
-
- VORBIS_unexpected_eof=10, // file is truncated?
- VORBIS_seek_invalid, // seek past EOF
-
- // decoding errors (corrupt/invalid stream) -- you probably
- // don't care about the exact details of these
-
- // vorbis errors:
- VORBIS_invalid_setup=20,
- VORBIS_invalid_stream,
-
- // ogg errors:
- VORBIS_missing_capture_pattern=30,
- VORBIS_invalid_stream_structure_version,
- VORBIS_continued_packet_flag_invalid,
- VORBIS_incorrect_stream_serial_number,
- VORBIS_invalid_first_page,
- VORBIS_bad_packet_type,
- VORBIS_cant_find_last_page,
- VORBIS_seek_failed,
- VORBIS_ogg_skeleton_not_supported
-};
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
-//
-// HEADER ENDS HERE
-//
-//////////////////////////////////////////////////////////////////////////////
-
-#ifndef STB_VORBIS_HEADER_ONLY
-
-// global configuration settings (e.g. set these in the project/makefile),
-// or just set them in this file at the top (although ideally the first few
-// should be visible when the header file is compiled too, although it's not
-// crucial)
-
-// STB_VORBIS_NO_PUSHDATA_API
-// does not compile the code for the various stb_vorbis_*_pushdata()
-// functions
-// #define STB_VORBIS_NO_PUSHDATA_API
-
-// STB_VORBIS_NO_PULLDATA_API
-// does not compile the code for the non-pushdata APIs
-// #define STB_VORBIS_NO_PULLDATA_API
-
-// STB_VORBIS_NO_STDIO
-// does not compile the code for the APIs that use FILE *s internally
-// or externally (implied by STB_VORBIS_NO_PULLDATA_API)
-// #define STB_VORBIS_NO_STDIO
-
-// STB_VORBIS_NO_INTEGER_CONVERSION
-// does not compile the code for converting audio sample data from
-// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
-// #define STB_VORBIS_NO_INTEGER_CONVERSION
-
-// STB_VORBIS_NO_FAST_SCALED_FLOAT
-// does not use a fast float-to-int trick to accelerate float-to-int on
-// most platforms which requires endianness be defined correctly.
-//#define STB_VORBIS_NO_FAST_SCALED_FLOAT
-
-
-// STB_VORBIS_MAX_CHANNELS [number]
-// globally define this to the maximum number of channels you need.
-// The spec does not put a restriction on channels except that
-// the count is stored in a byte, so 255 is the hard limit.
-// Reducing this saves about 16 bytes per value, so using 16 saves
-// (255-16)*16 or around 4KB. Plus anything other memory usage
-// I forgot to account for. Can probably go as low as 8 (7.1 audio),
-// 6 (5.1 audio), or 2 (stereo only).
-#ifndef STB_VORBIS_MAX_CHANNELS
-#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
-#endif
-
-// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
-// after a flush_pushdata(), stb_vorbis begins scanning for the
-// next valid page, without backtracking. when it finds something
-// that looks like a page, it streams through it and verifies its
-// CRC32. Should that validation fail, it keeps scanning. But it's
-// possible that _while_ streaming through to check the CRC32 of
-// one candidate page, it sees another candidate page. This #define
-// determines how many "overlapping" candidate pages it can search
-// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
-// garbage pages could be as big as 64KB, but probably average ~16KB.
-// So don't hose ourselves by scanning an apparent 64KB page and
-// missing a ton of real ones in the interim; so minimum of 2
-#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
-#define STB_VORBIS_PUSHDATA_CRC_COUNT 4
-#endif
-
-// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
-// sets the log size of the huffman-acceleration table. Maximum
-// supported value is 24. with larger numbers, more decodings are O(1),
-// but the table size is larger so worse cache missing, so you'll have
-// to probe (and try multiple ogg vorbis files) to find the sweet spot.
-#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
-#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
-#endif
-
-// STB_VORBIS_FAST_BINARY_LENGTH [number]
-// sets the log size of the binary-search acceleration table. this
-// is used in similar fashion to the fast-huffman size to set initial
-// parameters for the binary search
-
-// STB_VORBIS_FAST_HUFFMAN_INT
-// The fast huffman tables are much more efficient if they can be
-// stored as 16-bit results instead of 32-bit results. This restricts
-// the codebooks to having only 65535 possible outcomes, though.
-// (At least, accelerated by the huffman table.)
-#ifndef STB_VORBIS_FAST_HUFFMAN_INT
-#define STB_VORBIS_FAST_HUFFMAN_SHORT
-#endif
-
-// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
-// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
-// back on binary searching for the correct one. This requires storing
-// extra tables with the huffman codes in sorted order. Defining this
-// symbol trades off space for speed by forcing a linear search in the
-// non-fast case, except for "sparse" codebooks.
-// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
-
-// STB_VORBIS_DIVIDES_IN_RESIDUE
-// stb_vorbis precomputes the result of the scalar residue decoding
-// that would otherwise require a divide per chunk. you can trade off
-// space for time by defining this symbol.
-// #define STB_VORBIS_DIVIDES_IN_RESIDUE
-
-// STB_VORBIS_DIVIDES_IN_CODEBOOK
-// vorbis VQ codebooks can be encoded two ways: with every case explicitly
-// stored, or with all elements being chosen from a small range of values,
-// and all values possible in all elements. By default, stb_vorbis expands
-// this latter kind out to look like the former kind for ease of decoding,
-// because otherwise an integer divide-per-vector-element is required to
-// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
-// trade off storage for speed.
-//#define STB_VORBIS_DIVIDES_IN_CODEBOOK
-
-#ifdef STB_VORBIS_CODEBOOK_SHORTS
-#error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
-#endif
-
-// STB_VORBIS_DIVIDE_TABLE
-// this replaces small integer divides in the floor decode loop with
-// table lookups. made less than 1% difference, so disabled by default.
-
-// STB_VORBIS_NO_INLINE_DECODE
-// disables the inlining of the scalar codebook fast-huffman decode.
-// might save a little codespace; useful for debugging
-// #define STB_VORBIS_NO_INLINE_DECODE
-
-// STB_VORBIS_NO_DEFER_FLOOR
-// Normally we only decode the floor without synthesizing the actual
-// full curve. We can instead synthesize the curve immediately. This
-// requires more memory and is very likely slower, so I don't think
-// you'd ever want to do it except for debugging.
-// #define STB_VORBIS_NO_DEFER_FLOOR
-
-
-
-
-//////////////////////////////////////////////////////////////////////////////
-
-#ifdef STB_VORBIS_NO_PULLDATA_API
- #define STB_VORBIS_NO_INTEGER_CONVERSION
- #define STB_VORBIS_NO_STDIO
-#endif
-
-#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
- #define STB_VORBIS_NO_STDIO 1
-#endif
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
-
- // only need endianness for fast-float-to-int, which we don't
- // use for pushdata
-
- #ifndef STB_VORBIS_BIG_ENDIAN
- #define STB_VORBIS_ENDIAN 0
- #else
- #define STB_VORBIS_ENDIAN 1
- #endif
-
-#endif
-#endif
-
-
-#ifndef STB_VORBIS_NO_STDIO
-#include <stdio.h>
-#endif
-
-#ifndef STB_VORBIS_NO_CRT
- #include <stdlib.h>
- #include <string.h>
- #include <assert.h>
- #include <math.h>
-
- // find definition of alloca if it's not in stdlib.h:
- #if defined(_MSC_VER) || defined(__MINGW32__)
- #include <malloc.h>
- #endif
- #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) || defined(__NEWLIB__)
- #include <alloca.h>
- #endif
-#else // STB_VORBIS_NO_CRT
- #define NULL 0
- #define malloc(s) 0
- #define free(s) ((void) 0)
- #define realloc(s) 0
-#endif // STB_VORBIS_NO_CRT
-
-#include <limits.h>
-
-#ifdef __MINGW32__
- // eff you mingw:
- // "fixed":
- // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/
- // "no that broke the build, reverted, who cares about C":
- // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/
- #ifdef __forceinline
- #undef __forceinline
- #endif
- #define __forceinline
- #ifndef alloca
- #define alloca __builtin_alloca
- #endif
-#elif !defined(_MSC_VER)
- #if __GNUC__
- #define __forceinline inline
- #else
- #define __forceinline
- #endif
-#endif
-
-#if STB_VORBIS_MAX_CHANNELS > 256
-#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
-#endif
-
-#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
-#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
-#endif
-
-
-#if 0
-#include <crtdbg.h>
-#define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
-#else
-#define CHECK(f) ((void) 0)
-#endif
-
-#define MAX_BLOCKSIZE_LOG 13 // from specification
-#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
-
-
-typedef unsigned char uint8;
-typedef signed char int8;
-typedef unsigned short uint16;
-typedef signed short int16;
-typedef unsigned int uint32;
-typedef signed int int32;
-
-#ifndef TRUE
-#define TRUE 1
-#define FALSE 0
-#endif
-
-typedef float codetype;
-
-// @NOTE
-//
-// Some arrays below are tagged "//varies", which means it's actually
-// a variable-sized piece of data, but rather than malloc I assume it's
-// small enough it's better to just allocate it all together with the
-// main thing
-//
-// Most of the variables are specified with the smallest size I could pack
-// them into. It might give better performance to make them all full-sized
-// integers. It should be safe to freely rearrange the structures or change
-// the sizes larger--nothing relies on silently truncating etc., nor the
-// order of variables.
-
-#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
-#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
-
-typedef struct
-{
- int dimensions, entries;
- uint8 *codeword_lengths;
- float minimum_value;
- float delta_value;
- uint8 value_bits;
- uint8 lookup_type;
- uint8 sequence_p;
- uint8 sparse;
- uint32 lookup_values;
- codetype *multiplicands;
- uint32 *codewords;
- #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
- int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
- #else
- int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
- #endif
- uint32 *sorted_codewords;
- int *sorted_values;
- int sorted_entries;
-} Codebook;
-
-typedef struct
-{
- uint8 order;
- uint16 rate;
- uint16 bark_map_size;
- uint8 amplitude_bits;
- uint8 amplitude_offset;
- uint8 number_of_books;
- uint8 book_list[16]; // varies
-} Floor0;
-
-typedef struct
-{
- uint8 partitions;
- uint8 partition_class_list[32]; // varies
- uint8 class_dimensions[16]; // varies
- uint8 class_subclasses[16]; // varies
- uint8 class_masterbooks[16]; // varies
- int16 subclass_books[16][8]; // varies
- uint16 Xlist[31*8+2]; // varies
- uint8 sorted_order[31*8+2];
- uint8 neighbors[31*8+2][2];
- uint8 floor1_multiplier;
- uint8 rangebits;
- int values;
-} Floor1;
-
-typedef union
-{
- Floor0 floor0;
- Floor1 floor1;
-} Floor;
-
-typedef struct
-{
- uint32 begin, end;
- uint32 part_size;
- uint8 classifications;
- uint8 classbook;
- uint8 **classdata;
- int16 (*residue_books)[8];
-} Residue;
-
-typedef struct
-{
- uint8 magnitude;
- uint8 angle;
- uint8 mux;
-} MappingChannel;
-
-typedef struct
-{
- uint16 coupling_steps;
- MappingChannel *chan;
- uint8 submaps;
- uint8 submap_floor[15]; // varies
- uint8 submap_residue[15]; // varies
-} Mapping;
-
-typedef struct
-{
- uint8 blockflag;
- uint8 mapping;
- uint16 windowtype;
- uint16 transformtype;
-} Mode;
-
-typedef struct
-{
- uint32 goal_crc; // expected crc if match
- int bytes_left; // bytes left in packet
- uint32 crc_so_far; // running crc
- int bytes_done; // bytes processed in _current_ chunk
- uint32 sample_loc; // granule pos encoded in page
-} CRCscan;
-
-typedef struct
-{
- uint32 page_start, page_end;
- uint32 last_decoded_sample;
-} ProbedPage;
-
-struct stb_vorbis
-{
- // user-accessible info
- unsigned int sample_rate;
- int channels;
-
- unsigned int setup_memory_required;
- unsigned int temp_memory_required;
- unsigned int setup_temp_memory_required;
-
- char *vendor;
- int comment_list_length;
- char **comment_list;
-
- // input config
-#ifndef STB_VORBIS_NO_STDIO
- FILE *f;
- uint32 f_start;
- int close_on_free;
-#endif
-
- uint8 *stream;
- uint8 *stream_start;
- uint8 *stream_end;
-
- uint32 stream_len;
-
- uint8 push_mode;
-
- // the page to seek to when seeking to start, may be zero
- uint32 first_audio_page_offset;
-
- // p_first is the page on which the first audio packet ends
- // (but not necessarily the page on which it starts)
- ProbedPage p_first, p_last;
-
- // memory management
- stb_vorbis_alloc alloc;
- int setup_offset;
- int temp_offset;
-
- // run-time results
- int eof;
- enum STBVorbisError error;
-
- // user-useful data
-
- // header info
- int blocksize[2];
- int blocksize_0, blocksize_1;
- int codebook_count;
- Codebook *codebooks;
- int floor_count;
- uint16 floor_types[64]; // varies
- Floor *floor_config;
- int residue_count;
- uint16 residue_types[64]; // varies
- Residue *residue_config;
- int mapping_count;
- Mapping *mapping;
- int mode_count;
- Mode mode_config[64]; // varies
-
- uint32 total_samples;
-
- // decode buffer
- float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
- float *outputs [STB_VORBIS_MAX_CHANNELS];
-
- float *previous_window[STB_VORBIS_MAX_CHANNELS];
- int previous_length;
-
- #ifndef STB_VORBIS_NO_DEFER_FLOOR
- int16 *finalY[STB_VORBIS_MAX_CHANNELS];
- #else
- float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
- #endif
-
- uint32 current_loc; // sample location of next frame to decode
- int current_loc_valid;
-
- // per-blocksize precomputed data
-
- // twiddle factors
- float *A[2],*B[2],*C[2];
- float *window[2];
- uint16 *bit_reverse[2];
-
- // current page/packet/segment streaming info
- uint32 serial; // stream serial number for verification
- int last_page;
- int segment_count;
- uint8 segments[255];
- uint8 page_flag;
- uint8 bytes_in_seg;
- uint8 first_decode;
- int next_seg;
- int last_seg; // flag that we're on the last segment
- int last_seg_which; // what was the segment number of the last seg?
- uint32 acc;
- int valid_bits;
- int packet_bytes;
- int end_seg_with_known_loc;
- uint32 known_loc_for_packet;
- int discard_samples_deferred;
- uint32 samples_output;
-
- // push mode scanning
- int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
-#ifndef STB_VORBIS_NO_PUSHDATA_API
- CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
-#endif
-
- // sample-access
- int channel_buffer_start;
- int channel_buffer_end;
-};
-
-#if defined(STB_VORBIS_NO_PUSHDATA_API)
- #define IS_PUSH_MODE(f) FALSE
-#elif defined(STB_VORBIS_NO_PULLDATA_API)
- #define IS_PUSH_MODE(f) TRUE
-#else
- #define IS_PUSH_MODE(f) ((f)->push_mode)
-#endif
-
-typedef struct stb_vorbis vorb;
-
-static int error(vorb *f, enum STBVorbisError e)
-{
- f->error = e;
- if (!f->eof && e != VORBIS_need_more_data) {
- f->error=e; // breakpoint for debugging
- }
- return 0;
-}
-
-
-// these functions are used for allocating temporary memory
-// while decoding. if you can afford the stack space, use
-// alloca(); otherwise, provide a temp buffer and it will
-// allocate out of those.
-
-#define array_size_required(count,size) (count*(sizeof(void *)+(size)))
-
-#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
-#define temp_free(f,p) (void)0
-#define temp_alloc_save(f) ((f)->temp_offset)
-#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
-
-#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
-
-// given a sufficiently large block of memory, make an array of pointers to subblocks of it
-static void *make_block_array(void *mem, int count, int size)
-{
- int i;
- void ** p = (void **) mem;
- char *q = (char *) (p + count);
- for (i=0; i < count; ++i) {
- p[i] = q;
- q += size;
- }
- return p;
-}
-
-static void *setup_malloc(vorb *f, int sz)
-{
- sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.
- f->setup_memory_required += sz;
- if (f->alloc.alloc_buffer) {
- void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
- if (f->setup_offset + sz > f->temp_offset) return NULL;
- f->setup_offset += sz;
- return p;
- }
- return sz ? malloc(sz) : NULL;
-}
-
-static void setup_free(vorb *f, void *p)
-{
- if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
- free(p);
-}
-
-static void *setup_temp_malloc(vorb *f, int sz)
-{
- sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.
- if (f->alloc.alloc_buffer) {
- if (f->temp_offset - sz < f->setup_offset) return NULL;
- f->temp_offset -= sz;
- return (char *) f->alloc.alloc_buffer + f->temp_offset;
- }
- return malloc(sz);
-}
-
-static void setup_temp_free(vorb *f, void *p, int sz)
-{
- if (f->alloc.alloc_buffer) {
- f->temp_offset += (sz+7)&~7;
- return;
- }
- free(p);
-}
-
-#define CRC32_POLY 0x04c11db7 // from spec
-
-static uint32 crc_table[256];
-static void crc32_init(void)
-{
- int i,j;
- uint32 s;
- for(i=0; i < 256; i++) {
- for (s=(uint32) i << 24, j=0; j < 8; ++j)
- s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);
- crc_table[i] = s;
- }
-}
-
-static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
-{
- return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
-}
-
-
-// used in setup, and for huffman that doesn't go fast path
-static unsigned int bit_reverse(unsigned int n)
-{
- n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
- n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
- n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
- n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
- return (n >> 16) | (n << 16);
-}
-
-static float square(float x)
-{
- return x*x;
-}
-
-// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
-// as required by the specification. fast(?) implementation from stb.h
-// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
-static int ilog(int32 n)
-{
- static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
-
- if (n < 0) return 0; // signed n returns 0
-
- // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
- if (n < (1 << 14))
- if (n < (1 << 4)) return 0 + log2_4[n ];
- else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
- else return 10 + log2_4[n >> 10];
- else if (n < (1 << 24))
- if (n < (1 << 19)) return 15 + log2_4[n >> 15];
- else return 20 + log2_4[n >> 20];
- else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
- else return 30 + log2_4[n >> 30];
-}
-
-#ifndef M_PI
- #define M_PI 3.14159265358979323846264f // from CRC
-#endif
-
-// code length assigned to a value with no huffman encoding
-#define NO_CODE 255
-
-/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
-//
-// these functions are only called at setup, and only a few times
-// per file
-
-static float float32_unpack(uint32 x)
-{
- // from the specification
- uint32 mantissa = x & 0x1fffff;
- uint32 sign = x & 0x80000000;
- uint32 exp = (x & 0x7fe00000) >> 21;
- double res = sign ? -(double)mantissa : (double)mantissa;
- return (float) ldexp((float)res, exp-788);
-}
-
-
-// zlib & jpeg huffman tables assume that the output symbols
-// can either be arbitrarily arranged, or have monotonically
-// increasing frequencies--they rely on the lengths being sorted;
-// this makes for a very simple generation algorithm.
-// vorbis allows a huffman table with non-sorted lengths. This
-// requires a more sophisticated construction, since symbols in
-// order do not map to huffman codes "in order".
-static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
-{
- if (!c->sparse) {
- c->codewords [symbol] = huff_code;
- } else {
- c->codewords [count] = huff_code;
- c->codeword_lengths[count] = len;
- values [count] = symbol;
- }
-}
-
-static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
-{
- int i,k,m=0;
- uint32 available[32];
-
- memset(available, 0, sizeof(available));
- // find the first entry
- for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
- if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
- // add to the list
- add_entry(c, 0, k, m++, len[k], values);
- // add all available leaves
- for (i=1; i <= len[k]; ++i)
- available[i] = 1U << (32-i);
- // note that the above code treats the first case specially,
- // but it's really the same as the following code, so they
- // could probably be combined (except the initial code is 0,
- // and I use 0 in available[] to mean 'empty')
- for (i=k+1; i < n; ++i) {
- uint32 res;
- int z = len[i], y;
- if (z == NO_CODE) continue;
- // find lowest available leaf (should always be earliest,
- // which is what the specification calls for)
- // note that this property, and the fact we can never have
- // more than one free leaf at a given level, isn't totally
- // trivial to prove, but it seems true and the assert never
- // fires, so!
- while (z > 0 && !available[z]) --z;
- if (z == 0) { return FALSE; }
- res = available[z];
- assert(z >= 0 && z < 32);
- available[z] = 0;
- add_entry(c, bit_reverse(res), i, m++, len[i], values);
- // propagate availability up the tree
- if (z != len[i]) {
- assert(len[i] >= 0 && len[i] < 32);
- for (y=len[i]; y > z; --y) {
- assert(available[y] == 0);
- available[y] = res + (1 << (32-y));
- }
- }
- }
- return TRUE;
-}
-
-// accelerated huffman table allows fast O(1) match of all symbols
-// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
-static void compute_accelerated_huffman(Codebook *c)
-{
- int i, len;
- for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
- c->fast_huffman[i] = -1;
-
- len = c->sparse ? c->sorted_entries : c->entries;
- #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
- if (len > 32767) len = 32767; // largest possible value we can encode!
- #endif
- for (i=0; i < len; ++i) {
- if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
- uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
- // set table entries for all bit combinations in the higher bits
- while (z < FAST_HUFFMAN_TABLE_SIZE) {
- c->fast_huffman[z] = i;
- z += 1 << c->codeword_lengths[i];
- }
- }
- }
-}
-
-#ifdef _MSC_VER
-#define STBV_CDECL __cdecl
-#else
-#define STBV_CDECL
-#endif
-
-static int STBV_CDECL uint32_compare(const void *p, const void *q)
-{
- uint32 x = * (uint32 *) p;
- uint32 y = * (uint32 *) q;
- return x < y ? -1 : x > y;
-}
-
-static int include_in_sort(Codebook *c, uint8 len)
-{
- if (c->sparse) { assert(len != NO_CODE); return TRUE; }
- if (len == NO_CODE) return FALSE;
- if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
- return FALSE;
-}
-
-// if the fast table above doesn't work, we want to binary
-// search them... need to reverse the bits
-static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
-{
- int i, len;
- // build a list of all the entries
- // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
- // this is kind of a frivolous optimization--I don't see any performance improvement,
- // but it's like 4 extra lines of code, so.
- if (!c->sparse) {
- int k = 0;
- for (i=0; i < c->entries; ++i)
- if (include_in_sort(c, lengths[i]))
- c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
- assert(k == c->sorted_entries);
- } else {
- for (i=0; i < c->sorted_entries; ++i)
- c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
- }
-
- qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
- c->sorted_codewords[c->sorted_entries] = 0xffffffff;
-
- len = c->sparse ? c->sorted_entries : c->entries;
- // now we need to indicate how they correspond; we could either
- // #1: sort a different data structure that says who they correspond to
- // #2: for each sorted entry, search the original list to find who corresponds
- // #3: for each original entry, find the sorted entry
- // #1 requires extra storage, #2 is slow, #3 can use binary search!
- for (i=0; i < len; ++i) {
- int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
- if (include_in_sort(c,huff_len)) {
- uint32 code = bit_reverse(c->codewords[i]);
- int x=0, n=c->sorted_entries;
- while (n > 1) {
- // invariant: sc[x] <= code < sc[x+n]
- int m = x + (n >> 1);
- if (c->sorted_codewords[m] <= code) {
- x = m;
- n -= (n>>1);
- } else {
- n >>= 1;
- }
- }
- assert(c->sorted_codewords[x] == code);
- if (c->sparse) {
- c->sorted_values[x] = values[i];
- c->codeword_lengths[x] = huff_len;
- } else {
- c->sorted_values[x] = i;
- }
- }
- }
-}
-
-// only run while parsing the header (3 times)
-static int vorbis_validate(uint8 *data)
-{
- static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
- return memcmp(data, vorbis, 6) == 0;
-}
-
-// called from setup only, once per code book
-// (formula implied by specification)
-static int lookup1_values(int entries, int dim)
-{
- int r = (int) floor(exp((float) log((float) entries) / dim));
- if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
- ++r; // floor() to avoid _ftol() when non-CRT
- if (pow((float) r+1, dim) <= entries)
- return -1;
- if ((int) floor(pow((float) r, dim)) > entries)
- return -1;
- return r;
-}
-
-// called twice per file
-static void compute_twiddle_factors(int n, float *A, float *B, float *C)
-{
- int n4 = n >> 2, n8 = n >> 3;
- int k,k2;
-
- for (k=k2=0; k < n4; ++k,k2+=2) {
- A[k2 ] = (float) cos(4*k*M_PI/n);
- A[k2+1] = (float) -sin(4*k*M_PI/n);
- B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
- B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
- }
- for (k=k2=0; k < n8; ++k,k2+=2) {
- C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
- C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
- }
-}
-
-static void compute_window(int n, float *window)
-{
- int n2 = n >> 1, i;
- for (i=0; i < n2; ++i)
- window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
-}
-
-static void compute_bitreverse(int n, uint16 *rev)
-{
- int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
- int i, n8 = n >> 3;
- for (i=0; i < n8; ++i)
- rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
-}
-
-static int init_blocksize(vorb *f, int b, int n)
-{
- int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
- f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
- f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
- f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
- if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
- compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
- f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
- if (!f->window[b]) return error(f, VORBIS_outofmem);
- compute_window(n, f->window[b]);
- f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
- if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
- compute_bitreverse(n, f->bit_reverse[b]);
- return TRUE;
-}
-
-static void neighbors(uint16 *x, int n, int *plow, int *phigh)
-{
- int low = -1;
- int high = 65536;
- int i;
- for (i=0; i < n; ++i) {
- if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
- if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
- }
-}
-
-// this has been repurposed so y is now the original index instead of y
-typedef struct
-{
- uint16 x,id;
-} stbv__floor_ordering;
-
-static int STBV_CDECL point_compare(const void *p, const void *q)
-{
- stbv__floor_ordering *a = (stbv__floor_ordering *) p;
- stbv__floor_ordering *b = (stbv__floor_ordering *) q;
- return a->x < b->x ? -1 : a->x > b->x;
-}
-
-//
-/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
-
-
-#if defined(STB_VORBIS_NO_STDIO)
- #define USE_MEMORY(z) TRUE
-#else
- #define USE_MEMORY(z) ((z)->stream)
-#endif
-
-static uint8 get8(vorb *z)
-{
- if (USE_MEMORY(z)) {
- if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
- return *z->stream++;
- }
-
- #ifndef STB_VORBIS_NO_STDIO
- {
- int c = fgetc(z->f);
- if (c == EOF) { z->eof = TRUE; return 0; }
- return c;
- }
- #endif
-}
-
-static uint32 get32(vorb *f)
-{
- uint32 x;
- x = get8(f);
- x += get8(f) << 8;
- x += get8(f) << 16;
- x += (uint32) get8(f) << 24;
- return x;
-}
-
-static int getn(vorb *z, uint8 *data, int n)
-{
- if (USE_MEMORY(z)) {
- if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
- memcpy(data, z->stream, n);
- z->stream += n;
- return 1;
- }
-
- #ifndef STB_VORBIS_NO_STDIO
- if (fread(data, n, 1, z->f) == 1)
- return 1;
- else {
- z->eof = 1;
- return 0;
- }
- #endif
-}
-
-static void skip(vorb *z, int n)
-{
- if (USE_MEMORY(z)) {
- z->stream += n;
- if (z->stream >= z->stream_end) z->eof = 1;
- return;
- }
- #ifndef STB_VORBIS_NO_STDIO
- {
- long x = ftell(z->f);
- fseek(z->f, x+n, SEEK_SET);
- }
- #endif
-}
-
-static int set_file_offset(stb_vorbis *f, unsigned int loc)
-{
- #ifndef STB_VORBIS_NO_PUSHDATA_API
- if (f->push_mode) return 0;
- #endif
- f->eof = 0;
- if (USE_MEMORY(f)) {
- if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
- f->stream = f->stream_end;
- f->eof = 1;
- return 0;
- } else {
- f->stream = f->stream_start + loc;
- return 1;
- }
- }
- #ifndef STB_VORBIS_NO_STDIO
- if (loc + f->f_start < loc || loc >= 0x80000000) {
- loc = 0x7fffffff;
- f->eof = 1;
- } else {
- loc += f->f_start;
- }
- if (!fseek(f->f, loc, SEEK_SET))
- return 1;
- f->eof = 1;
- fseek(f->f, f->f_start, SEEK_END);
- return 0;
- #endif
-}
-
-
-static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
-
-static int capture_pattern(vorb *f)
-{
- if (0x4f != get8(f)) return FALSE;
- if (0x67 != get8(f)) return FALSE;
- if (0x67 != get8(f)) return FALSE;
- if (0x53 != get8(f)) return FALSE;
- return TRUE;
-}
-
-#define PAGEFLAG_continued_packet 1
-#define PAGEFLAG_first_page 2
-#define PAGEFLAG_last_page 4
-
-static int start_page_no_capturepattern(vorb *f)
-{
- uint32 loc0,loc1,n;
- if (f->first_decode && !IS_PUSH_MODE(f)) {
- f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4;
- }
- // stream structure version
- if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
- // header flag
- f->page_flag = get8(f);
- // absolute granule position
- loc0 = get32(f);
- loc1 = get32(f);
- // @TODO: validate loc0,loc1 as valid positions?
- // stream serial number -- vorbis doesn't interleave, so discard
- get32(f);
- //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
- // page sequence number
- n = get32(f);
- f->last_page = n;
- // CRC32
- get32(f);
- // page_segments
- f->segment_count = get8(f);
- if (!getn(f, f->segments, f->segment_count))
- return error(f, VORBIS_unexpected_eof);
- // assume we _don't_ know any the sample position of any segments
- f->end_seg_with_known_loc = -2;
- if (loc0 != ~0U || loc1 != ~0U) {
- int i;
- // determine which packet is the last one that will complete
- for (i=f->segment_count-1; i >= 0; --i)
- if (f->segments[i] < 255)
- break;
- // 'i' is now the index of the _last_ segment of a packet that ends
- if (i >= 0) {
- f->end_seg_with_known_loc = i;
- f->known_loc_for_packet = loc0;
- }
- }
- if (f->first_decode) {
- int i,len;
- len = 0;
- for (i=0; i < f->segment_count; ++i)
- len += f->segments[i];
- len += 27 + f->segment_count;
- f->p_first.page_end = f->p_first.page_start + len;
- f->p_first.last_decoded_sample = loc0;
- }
- f->next_seg = 0;
- return TRUE;
-}
-
-static int start_page(vorb *f)
-{
- if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
- return start_page_no_capturepattern(f);
-}
-
-static int start_packet(vorb *f)
-{
- while (f->next_seg == -1) {
- if (!start_page(f)) return FALSE;
- if (f->page_flag & PAGEFLAG_continued_packet)
- return error(f, VORBIS_continued_packet_flag_invalid);
- }
- f->last_seg = FALSE;
- f->valid_bits = 0;
- f->packet_bytes = 0;
- f->bytes_in_seg = 0;
- // f->next_seg is now valid
- return TRUE;
-}
-
-static int maybe_start_packet(vorb *f)
-{
- if (f->next_seg == -1) {
- int x = get8(f);
- if (f->eof) return FALSE; // EOF at page boundary is not an error!
- if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
- if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
- if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
- if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
- if (!start_page_no_capturepattern(f)) return FALSE;
- if (f->page_flag & PAGEFLAG_continued_packet) {
- // set up enough state that we can read this packet if we want,
- // e.g. during recovery
- f->last_seg = FALSE;
- f->bytes_in_seg = 0;
- return error(f, VORBIS_continued_packet_flag_invalid);
- }
- }
- return start_packet(f);
-}
-
-static int next_segment(vorb *f)
-{
- int len;
- if (f->last_seg) return 0;
- if (f->next_seg == -1) {
- f->last_seg_which = f->segment_count-1; // in case start_page fails
- if (!start_page(f)) { f->last_seg = 1; return 0; }
- if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
- }
- len = f->segments[f->next_seg++];
- if (len < 255) {
- f->last_seg = TRUE;
- f->last_seg_which = f->next_seg-1;
- }
- if (f->next_seg >= f->segment_count)
- f->next_seg = -1;
- assert(f->bytes_in_seg == 0);
- f->bytes_in_seg = len;
- return len;
-}
-
-#define EOP (-1)
-#define INVALID_BITS (-1)
-
-static int get8_packet_raw(vorb *f)
-{
- if (!f->bytes_in_seg) { // CLANG!
- if (f->last_seg) return EOP;
- else if (!next_segment(f)) return EOP;
- }
- assert(f->bytes_in_seg > 0);
- --f->bytes_in_seg;
- ++f->packet_bytes;
- return get8(f);
-}
-
-static int get8_packet(vorb *f)
-{
- int x = get8_packet_raw(f);
- f->valid_bits = 0;
- return x;
-}
-
-static int get32_packet(vorb *f)
-{
- uint32 x;
- x = get8_packet(f);
- x += get8_packet(f) << 8;
- x += get8_packet(f) << 16;
- x += (uint32) get8_packet(f) << 24;
- return x;
-}
-
-static void flush_packet(vorb *f)
-{
- while (get8_packet_raw(f) != EOP);
-}
-
-// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
-// as the huffman decoder?
-static uint32 get_bits(vorb *f, int n)
-{
- uint32 z;
-
- if (f->valid_bits < 0) return 0;
- if (f->valid_bits < n) {
- if (n > 24) {
- // the accumulator technique below would not work correctly in this case
- z = get_bits(f, 24);
- z += get_bits(f, n-24) << 24;
- return z;
- }
- if (f->valid_bits == 0) f->acc = 0;
- while (f->valid_bits < n) {
- int z = get8_packet_raw(f);
- if (z == EOP) {
- f->valid_bits = INVALID_BITS;
- return 0;
- }
- f->acc += z << f->valid_bits;
- f->valid_bits += 8;
- }
- }
-
- assert(f->valid_bits >= n);
- z = f->acc & ((1 << n)-1);
- f->acc >>= n;
- f->valid_bits -= n;
- return z;
-}
-
-// @OPTIMIZE: primary accumulator for huffman
-// expand the buffer to as many bits as possible without reading off end of packet
-// it might be nice to allow f->valid_bits and f->acc to be stored in registers,
-// e.g. cache them locally and decode locally
-static __forceinline void prep_huffman(vorb *f)
-{
- if (f->valid_bits <= 24) {
- if (f->valid_bits == 0) f->acc = 0;
- do {
- int z;
- if (f->last_seg && !f->bytes_in_seg) return;
- z = get8_packet_raw(f);
- if (z == EOP) return;
- f->acc += (unsigned) z << f->valid_bits;
- f->valid_bits += 8;
- } while (f->valid_bits <= 24);
- }
-}
-
-enum
-{
- VORBIS_packet_id = 1,
- VORBIS_packet_comment = 3,
- VORBIS_packet_setup = 5
-};
-
-static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
-{
- int i;
- prep_huffman(f);
-
- if (c->codewords == NULL && c->sorted_codewords == NULL)
- return -1;
-
- // cases to use binary search: sorted_codewords && !c->codewords
- // sorted_codewords && c->entries > 8
- if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
- // binary search
- uint32 code = bit_reverse(f->acc);
- int x=0, n=c->sorted_entries, len;
-
- while (n > 1) {
- // invariant: sc[x] <= code < sc[x+n]
- int m = x + (n >> 1);
- if (c->sorted_codewords[m] <= code) {
- x = m;
- n -= (n>>1);
- } else {
- n >>= 1;
- }
- }
- // x is now the sorted index
- if (!c->sparse) x = c->sorted_values[x];
- // x is now sorted index if sparse, or symbol otherwise
- len = c->codeword_lengths[x];
- if (f->valid_bits >= len) {
- f->acc >>= len;
- f->valid_bits -= len;
- return x;
- }
-
- f->valid_bits = 0;
- return -1;
- }
-
- // if small, linear search
- assert(!c->sparse);
- for (i=0; i < c->entries; ++i) {
- if (c->codeword_lengths[i] == NO_CODE) continue;
- if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
- if (f->valid_bits >= c->codeword_lengths[i]) {
- f->acc >>= c->codeword_lengths[i];
- f->valid_bits -= c->codeword_lengths[i];
- return i;
- }
- f->valid_bits = 0;
- return -1;
- }
- }
-
- error(f, VORBIS_invalid_stream);
- f->valid_bits = 0;
- return -1;
-}
-
-#ifndef STB_VORBIS_NO_INLINE_DECODE
-
-#define DECODE_RAW(var, f,c) \
- if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
- prep_huffman(f); \
- var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
- var = c->fast_huffman[var]; \
- if (var >= 0) { \
- int n = c->codeword_lengths[var]; \
- f->acc >>= n; \
- f->valid_bits -= n; \
- if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
- } else { \
- var = codebook_decode_scalar_raw(f,c); \
- }
-
-#else
-
-static int codebook_decode_scalar(vorb *f, Codebook *c)
-{
- int i;
- if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
- prep_huffman(f);
- // fast huffman table lookup
- i = f->acc & FAST_HUFFMAN_TABLE_MASK;
- i = c->fast_huffman[i];
- if (i >= 0) {
- f->acc >>= c->codeword_lengths[i];
- f->valid_bits -= c->codeword_lengths[i];
- if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
- return i;
- }
- return codebook_decode_scalar_raw(f,c);
-}
-
-#define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
-
-#endif
-
-#define DECODE(var,f,c) \
- DECODE_RAW(var,f,c) \
- if (c->sparse) var = c->sorted_values[var];
-
-#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
- #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
-#else
- #define DECODE_VQ(var,f,c) DECODE(var,f,c)
-#endif
-
-
-
-
-
-
-// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
-// where we avoid one addition
-#define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
-#define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
-#define CODEBOOK_ELEMENT_BASE(c) (0)
-
-static int codebook_decode_start(vorb *f, Codebook *c)
-{
- int z = -1;
-
- // type 0 is only legal in a scalar context
- if (c->lookup_type == 0)
- error(f, VORBIS_invalid_stream);
- else {
- DECODE_VQ(z,f,c);
- if (c->sparse) assert(z < c->sorted_entries);
- if (z < 0) { // check for EOP
- if (!f->bytes_in_seg)
- if (f->last_seg)
- return z;
- error(f, VORBIS_invalid_stream);
- }
- }
- return z;
-}
-
-static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
-{
- int i,z = codebook_decode_start(f,c);
- if (z < 0) return FALSE;
- if (len > c->dimensions) len = c->dimensions;
-
-#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- float last = CODEBOOK_ELEMENT_BASE(c);
- int div = 1;
- for (i=0; i < len; ++i) {
- int off = (z / div) % c->lookup_values;
- float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
- output[i] += val;
- if (c->sequence_p) last = val + c->minimum_value;
- div *= c->lookup_values;
- }
- return TRUE;
- }
-#endif
-
- z *= c->dimensions;
- if (c->sequence_p) {
- float last = CODEBOOK_ELEMENT_BASE(c);
- for (i=0; i < len; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- output[i] += val;
- last = val + c->minimum_value;
- }
- } else {
- float last = CODEBOOK_ELEMENT_BASE(c);
- for (i=0; i < len; ++i) {
- output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- }
- }
-
- return TRUE;
-}
-
-static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
-{
- int i,z = codebook_decode_start(f,c);
- float last = CODEBOOK_ELEMENT_BASE(c);
- if (z < 0) return FALSE;
- if (len > c->dimensions) len = c->dimensions;
-
-#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- int div = 1;
- for (i=0; i < len; ++i) {
- int off = (z / div) % c->lookup_values;
- float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
- output[i*step] += val;
- if (c->sequence_p) last = val;
- div *= c->lookup_values;
- }
- return TRUE;
- }
-#endif
-
- z *= c->dimensions;
- for (i=0; i < len; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- output[i*step] += val;
- if (c->sequence_p) last = val;
- }
-
- return TRUE;
-}
-
-static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
-{
- int c_inter = *c_inter_p;
- int p_inter = *p_inter_p;
- int i,z, effective = c->dimensions;
-
- // type 0 is only legal in a scalar context
- if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
-
- while (total_decode > 0) {
- float last = CODEBOOK_ELEMENT_BASE(c);
- DECODE_VQ(z,f,c);
- #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
- assert(!c->sparse || z < c->sorted_entries);
- #endif
- if (z < 0) {
- if (!f->bytes_in_seg)
- if (f->last_seg) return FALSE;
- return error(f, VORBIS_invalid_stream);
- }
-
- // if this will take us off the end of the buffers, stop short!
- // we check by computing the length of the virtual interleaved
- // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
- // and the length we'll be using (effective)
- if (c_inter + p_inter*ch + effective > len * ch) {
- effective = len*ch - (p_inter*ch - c_inter);
- }
-
- #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- int div = 1;
- for (i=0; i < effective; ++i) {
- int off = (z / div) % c->lookup_values;
- float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
- if (outputs[c_inter])
- outputs[c_inter][p_inter] += val;
- if (++c_inter == ch) { c_inter = 0; ++p_inter; }
- if (c->sequence_p) last = val;
- div *= c->lookup_values;
- }
- } else
- #endif
- {
- z *= c->dimensions;
- if (c->sequence_p) {
- for (i=0; i < effective; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- if (outputs[c_inter])
- outputs[c_inter][p_inter] += val;
- if (++c_inter == ch) { c_inter = 0; ++p_inter; }
- last = val;
- }
- } else {
- for (i=0; i < effective; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- if (outputs[c_inter])
- outputs[c_inter][p_inter] += val;
- if (++c_inter == ch) { c_inter = 0; ++p_inter; }
- }
- }
- }
-
- total_decode -= effective;
- }
- *c_inter_p = c_inter;
- *p_inter_p = p_inter;
- return TRUE;
-}
-
-static int predict_point(int x, int x0, int x1, int y0, int y1)
-{
- int dy = y1 - y0;
- int adx = x1 - x0;
- // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
- int err = abs(dy) * (x - x0);
- int off = err / adx;
- return dy < 0 ? y0 - off : y0 + off;
-}
-
-// the following table is block-copied from the specification
-static float inverse_db_table[256] =
-{
- 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
- 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
- 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
- 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
- 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
- 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
- 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
- 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
- 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
- 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
- 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
- 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
- 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
- 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
- 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
- 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
- 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
- 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
- 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
- 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
- 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
- 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
- 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
- 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
- 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
- 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
- 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
- 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
- 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
- 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
- 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
- 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
- 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
- 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
- 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
- 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
- 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
- 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
- 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
- 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
- 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
- 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
- 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
- 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
- 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
- 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
- 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
- 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
- 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
- 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
- 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
- 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
- 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
- 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
- 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
- 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
- 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
- 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
- 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
- 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
- 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
- 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
- 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
- 0.82788260f, 0.88168307f, 0.9389798f, 1.0f
-};
-
-
-// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
-// note that you must produce bit-identical output to decode correctly;
-// this specific sequence of operations is specified in the spec (it's
-// drawing integer-quantized frequency-space lines that the encoder
-// expects to be exactly the same)
-// ... also, isn't the whole point of Bresenham's algorithm to NOT
-// have to divide in the setup? sigh.
-#ifndef STB_VORBIS_NO_DEFER_FLOOR
-#define LINE_OP(a,b) a *= b
-#else
-#define LINE_OP(a,b) a = b
-#endif
-
-#ifdef STB_VORBIS_DIVIDE_TABLE
-#define DIVTAB_NUMER 32
-#define DIVTAB_DENOM 64
-int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
-#endif
-
-static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
-{
- int dy = y1 - y0;
- int adx = x1 - x0;
- int ady = abs(dy);
- int base;
- int x=x0,y=y0;
- int err = 0;
- int sy;
-
-#ifdef STB_VORBIS_DIVIDE_TABLE
- if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
- if (dy < 0) {
- base = -integer_divide_table[ady][adx];
- sy = base-1;
- } else {
- base = integer_divide_table[ady][adx];
- sy = base+1;
- }
- } else {
- base = dy / adx;
- if (dy < 0)
- sy = base - 1;
- else
- sy = base+1;
- }
-#else
- base = dy / adx;
- if (dy < 0)
- sy = base - 1;
- else
- sy = base+1;
-#endif
- ady -= abs(base) * adx;
- if (x1 > n) x1 = n;
- if (x < x1) {
- LINE_OP(output[x], inverse_db_table[y&255]);
- for (++x; x < x1; ++x) {
- err += ady;
- if (err >= adx) {
- err -= adx;
- y += sy;
- } else
- y += base;
- LINE_OP(output[x], inverse_db_table[y&255]);
- }
- }
-}
-
-static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
-{
- int k;
- if (rtype == 0) {
- int step = n / book->dimensions;
- for (k=0; k < step; ++k)
- if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
- return FALSE;
- } else {
- for (k=0; k < n; ) {
- if (!codebook_decode(f, book, target+offset, n-k))
- return FALSE;
- k += book->dimensions;
- offset += book->dimensions;
- }
- }
- return TRUE;
-}
-
-// n is 1/2 of the blocksize --
-// specification: "Correct per-vector decode length is [n]/2"
-static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
-{
- int i,j,pass;
- Residue *r = f->residue_config + rn;
- int rtype = f->residue_types[rn];
- int c = r->classbook;
- int classwords = f->codebooks[c].dimensions;
- unsigned int actual_size = rtype == 2 ? n*2 : n;
- unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
- unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
- int n_read = limit_r_end - limit_r_begin;
- int part_read = n_read / r->part_size;
- int temp_alloc_point = temp_alloc_save(f);
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
- #else
- int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
- #endif
-
- CHECK(f);
-
- for (i=0; i < ch; ++i)
- if (!do_not_decode[i])
- memset(residue_buffers[i], 0, sizeof(float) * n);
-
- if (rtype == 2 && ch != 1) {
- for (j=0; j < ch; ++j)
- if (!do_not_decode[j])
- break;
- if (j == ch)
- goto done;
-
- for (pass=0; pass < 8; ++pass) {
- int pcount = 0, class_set = 0;
- if (ch == 2) {
- while (pcount < part_read) {
- int z = r->begin + pcount*r->part_size;
- int c_inter = (z & 1), p_inter = z>>1;
- if (pass == 0) {
- Codebook *c = f->codebooks+r->classbook;
- int q;
- DECODE(q,f,c);
- if (q == EOP) goto done;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- part_classdata[0][class_set] = r->classdata[q];
- #else
- for (i=classwords-1; i >= 0; --i) {
- classifications[0][i+pcount] = q % r->classifications;
- q /= r->classifications;
- }
- #endif
- }
- for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
- int z = r->begin + pcount*r->part_size;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- int c = part_classdata[0][class_set][i];
- #else
- int c = classifications[0][pcount];
- #endif
- int b = r->residue_books[c][pass];
- if (b >= 0) {
- Codebook *book = f->codebooks + b;
- #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
- goto done;
- #else
- // saves 1%
- if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
- goto done;
- #endif
- } else {
- z += r->part_size;
- c_inter = z & 1;
- p_inter = z >> 1;
- }
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- ++class_set;
- #endif
- }
- } else if (ch > 2) {
- while (pcount < part_read) {
- int z = r->begin + pcount*r->part_size;
- int c_inter = z % ch, p_inter = z/ch;
- if (pass == 0) {
- Codebook *c = f->codebooks+r->classbook;
- int q;
- DECODE(q,f,c);
- if (q == EOP) goto done;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- part_classdata[0][class_set] = r->classdata[q];
- #else
- for (i=classwords-1; i >= 0; --i) {
- classifications[0][i+pcount] = q % r->classifications;
- q /= r->classifications;
- }
- #endif
- }
- for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
- int z = r->begin + pcount*r->part_size;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- int c = part_classdata[0][class_set][i];
- #else
- int c = classifications[0][pcount];
- #endif
- int b = r->residue_books[c][pass];
- if (b >= 0) {
- Codebook *book = f->codebooks + b;
- if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
- goto done;
- } else {
- z += r->part_size;
- c_inter = z % ch;
- p_inter = z / ch;
- }
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- ++class_set;
- #endif
- }
- }
- }
- goto done;
- }
- CHECK(f);
-
- for (pass=0; pass < 8; ++pass) {
- int pcount = 0, class_set=0;
- while (pcount < part_read) {
- if (pass == 0) {
- for (j=0; j < ch; ++j) {
- if (!do_not_decode[j]) {
- Codebook *c = f->codebooks+r->classbook;
- int temp;
- DECODE(temp,f,c);
- if (temp == EOP) goto done;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- part_classdata[j][class_set] = r->classdata[temp];
- #else
- for (i=classwords-1; i >= 0; --i) {
- classifications[j][i+pcount] = temp % r->classifications;
- temp /= r->classifications;
- }
- #endif
- }
- }
- }
- for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
- for (j=0; j < ch; ++j) {
- if (!do_not_decode[j]) {
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- int c = part_classdata[j][class_set][i];
- #else
- int c = classifications[j][pcount];
- #endif
- int b = r->residue_books[c][pass];
- if (b >= 0) {
- float *target = residue_buffers[j];
- int offset = r->begin + pcount * r->part_size;
- int n = r->part_size;
- Codebook *book = f->codebooks + b;
- if (!residue_decode(f, book, target, offset, n, rtype))
- goto done;
- }
- }
- }
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- ++class_set;
- #endif
- }
- }
- done:
- CHECK(f);
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- temp_free(f,part_classdata);
- #else
- temp_free(f,classifications);
- #endif
- temp_alloc_restore(f,temp_alloc_point);
-}
-
-
-#if 0
-// slow way for debugging
-void inverse_mdct_slow(float *buffer, int n)
-{
- int i,j;
- int n2 = n >> 1;
- float *x = (float *) malloc(sizeof(*x) * n2);
- memcpy(x, buffer, sizeof(*x) * n2);
- for (i=0; i < n; ++i) {
- float acc = 0;
- for (j=0; j < n2; ++j)
- // formula from paper:
- //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
- // formula from wikipedia
- //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
- // these are equivalent, except the formula from the paper inverts the multiplier!
- // however, what actually works is NO MULTIPLIER!?!
- //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
- acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
- buffer[i] = acc;
- }
- free(x);
-}
-#elif 0
-// same as above, but just barely able to run in real time on modern machines
-void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
-{
- float mcos[16384];
- int i,j;
- int n2 = n >> 1, nmask = (n << 2) -1;
- float *x = (float *) malloc(sizeof(*x) * n2);
- memcpy(x, buffer, sizeof(*x) * n2);
- for (i=0; i < 4*n; ++i)
- mcos[i] = (float) cos(M_PI / 2 * i / n);
-
- for (i=0; i < n; ++i) {
- float acc = 0;
- for (j=0; j < n2; ++j)
- acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
- buffer[i] = acc;
- }
- free(x);
-}
-#elif 0
-// transform to use a slow dct-iv; this is STILL basically trivial,
-// but only requires half as many ops
-void dct_iv_slow(float *buffer, int n)
-{
- float mcos[16384];
- float x[2048];
- int i,j;
- int n2 = n >> 1, nmask = (n << 3) - 1;
- memcpy(x, buffer, sizeof(*x) * n);
- for (i=0; i < 8*n; ++i)
- mcos[i] = (float) cos(M_PI / 4 * i / n);
- for (i=0; i < n; ++i) {
- float acc = 0;
- for (j=0; j < n; ++j)
- acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
- buffer[i] = acc;
- }
-}
-
-void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
-{
- int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
- float temp[4096];
-
- memcpy(temp, buffer, n2 * sizeof(float));
- dct_iv_slow(temp, n2); // returns -c'-d, a-b'
-
- for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
- for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
- for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
-}
-#endif
-
-#ifndef LIBVORBIS_MDCT
-#define LIBVORBIS_MDCT 0
-#endif
-
-#if LIBVORBIS_MDCT
-// directly call the vorbis MDCT using an interface documented
-// by Jeff Roberts... useful for performance comparison
-typedef struct
-{
- int n;
- int log2n;
-
- float *trig;
- int *bitrev;
-
- float scale;
-} mdct_lookup;
-
-extern void mdct_init(mdct_lookup *lookup, int n);
-extern void mdct_clear(mdct_lookup *l);
-extern void mdct_backward(mdct_lookup *init, float *in, float *out);
-
-mdct_lookup M1,M2;
-
-void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
-{
- mdct_lookup *M;
- if (M1.n == n) M = &M1;
- else if (M2.n == n) M = &M2;
- else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
- else {
- if (M2.n) __asm int 3;
- mdct_init(&M2, n);
- M = &M2;
- }
-
- mdct_backward(M, buffer, buffer);
-}
-#endif
-
-
-// the following were split out into separate functions while optimizing;
-// they could be pushed back up but eh. __forceinline showed no change;
-// they're probably already being inlined.
-static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
-{
- float *ee0 = e + i_off;
- float *ee2 = ee0 + k_off;
- int i;
-
- assert((n & 3) == 0);
- for (i=(n>>2); i > 0; --i) {
- float k00_20, k01_21;
- k00_20 = ee0[ 0] - ee2[ 0];
- k01_21 = ee0[-1] - ee2[-1];
- ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
- ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
- ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
-
- k00_20 = ee0[-2] - ee2[-2];
- k01_21 = ee0[-3] - ee2[-3];
- ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
- ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
- ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
-
- k00_20 = ee0[-4] - ee2[-4];
- k01_21 = ee0[-5] - ee2[-5];
- ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
- ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
- ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
-
- k00_20 = ee0[-6] - ee2[-6];
- k01_21 = ee0[-7] - ee2[-7];
- ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
- ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
- ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
- ee0 -= 8;
- ee2 -= 8;
- }
-}
-
-static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
-{
- int i;
- float k00_20, k01_21;
-
- float *e0 = e + d0;
- float *e2 = e0 + k_off;
-
- for (i=lim >> 2; i > 0; --i) {
- k00_20 = e0[-0] - e2[-0];
- k01_21 = e0[-1] - e2[-1];
- e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
- e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
- e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
-
- A += k1;
-
- k00_20 = e0[-2] - e2[-2];
- k01_21 = e0[-3] - e2[-3];
- e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
- e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
- e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
-
- A += k1;
-
- k00_20 = e0[-4] - e2[-4];
- k01_21 = e0[-5] - e2[-5];
- e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
- e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
- e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
-
- A += k1;
-
- k00_20 = e0[-6] - e2[-6];
- k01_21 = e0[-7] - e2[-7];
- e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
- e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
- e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
-
- e0 -= 8;
- e2 -= 8;
-
- A += k1;
- }
-}
-
-static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
-{
- int i;
- float A0 = A[0];
- float A1 = A[0+1];
- float A2 = A[0+a_off];
- float A3 = A[0+a_off+1];
- float A4 = A[0+a_off*2+0];
- float A5 = A[0+a_off*2+1];
- float A6 = A[0+a_off*3+0];
- float A7 = A[0+a_off*3+1];
-
- float k00,k11;
-
- float *ee0 = e +i_off;
- float *ee2 = ee0+k_off;
-
- for (i=n; i > 0; --i) {
- k00 = ee0[ 0] - ee2[ 0];
- k11 = ee0[-1] - ee2[-1];
- ee0[ 0] = ee0[ 0] + ee2[ 0];
- ee0[-1] = ee0[-1] + ee2[-1];
- ee2[ 0] = (k00) * A0 - (k11) * A1;
- ee2[-1] = (k11) * A0 + (k00) * A1;
-
- k00 = ee0[-2] - ee2[-2];
- k11 = ee0[-3] - ee2[-3];
- ee0[-2] = ee0[-2] + ee2[-2];
- ee0[-3] = ee0[-3] + ee2[-3];
- ee2[-2] = (k00) * A2 - (k11) * A3;
- ee2[-3] = (k11) * A2 + (k00) * A3;
-
- k00 = ee0[-4] - ee2[-4];
- k11 = ee0[-5] - ee2[-5];
- ee0[-4] = ee0[-4] + ee2[-4];
- ee0[-5] = ee0[-5] + ee2[-5];
- ee2[-4] = (k00) * A4 - (k11) * A5;
- ee2[-5] = (k11) * A4 + (k00) * A5;
-
- k00 = ee0[-6] - ee2[-6];
- k11 = ee0[-7] - ee2[-7];
- ee0[-6] = ee0[-6] + ee2[-6];
- ee0[-7] = ee0[-7] + ee2[-7];
- ee2[-6] = (k00) * A6 - (k11) * A7;
- ee2[-7] = (k11) * A6 + (k00) * A7;
-
- ee0 -= k0;
- ee2 -= k0;
- }
-}
-
-static __forceinline void iter_54(float *z)
-{
- float k00,k11,k22,k33;
- float y0,y1,y2,y3;
-
- k00 = z[ 0] - z[-4];
- y0 = z[ 0] + z[-4];
- y2 = z[-2] + z[-6];
- k22 = z[-2] - z[-6];
-
- z[-0] = y0 + y2; // z0 + z4 + z2 + z6
- z[-2] = y0 - y2; // z0 + z4 - z2 - z6
-
- // done with y0,y2
-
- k33 = z[-3] - z[-7];
-
- z[-4] = k00 + k33; // z0 - z4 + z3 - z7
- z[-6] = k00 - k33; // z0 - z4 - z3 + z7
-
- // done with k33
-
- k11 = z[-1] - z[-5];
- y1 = z[-1] + z[-5];
- y3 = z[-3] + z[-7];
-
- z[-1] = y1 + y3; // z1 + z5 + z3 + z7
- z[-3] = y1 - y3; // z1 + z5 - z3 - z7
- z[-5] = k11 - k22; // z1 - z5 + z2 - z6
- z[-7] = k11 + k22; // z1 - z5 - z2 + z6
-}
-
-static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
-{
- int a_off = base_n >> 3;
- float A2 = A[0+a_off];
- float *z = e + i_off;
- float *base = z - 16 * n;
-
- while (z > base) {
- float k00,k11;
-
- k00 = z[-0] - z[-8];
- k11 = z[-1] - z[-9];
- z[-0] = z[-0] + z[-8];
- z[-1] = z[-1] + z[-9];
- z[-8] = k00;
- z[-9] = k11 ;
-
- k00 = z[ -2] - z[-10];
- k11 = z[ -3] - z[-11];
- z[ -2] = z[ -2] + z[-10];
- z[ -3] = z[ -3] + z[-11];
- z[-10] = (k00+k11) * A2;
- z[-11] = (k11-k00) * A2;
-
- k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
- k11 = z[ -5] - z[-13];
- z[ -4] = z[ -4] + z[-12];
- z[ -5] = z[ -5] + z[-13];
- z[-12] = k11;
- z[-13] = k00;
-
- k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
- k11 = z[ -7] - z[-15];
- z[ -6] = z[ -6] + z[-14];
- z[ -7] = z[ -7] + z[-15];
- z[-14] = (k00+k11) * A2;
- z[-15] = (k00-k11) * A2;
-
- iter_54(z);
- iter_54(z-8);
- z -= 16;
- }
-}
-
-static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
-{
- int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
- int ld;
- // @OPTIMIZE: reduce register pressure by using fewer variables?
- int save_point = temp_alloc_save(f);
- float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
- float *u=NULL,*v=NULL;
- // twiddle factors
- float *A = f->A[blocktype];
-
- // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
- // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
-
- // kernel from paper
-
-
- // merged:
- // copy and reflect spectral data
- // step 0
-
- // note that it turns out that the items added together during
- // this step are, in fact, being added to themselves (as reflected
- // by step 0). inexplicable inefficiency! this became obvious
- // once I combined the passes.
-
- // so there's a missing 'times 2' here (for adding X to itself).
- // this propagates through linearly to the end, where the numbers
- // are 1/2 too small, and need to be compensated for.
-
- {
- float *d,*e, *AA, *e_stop;
- d = &buf2[n2-2];
- AA = A;
- e = &buffer[0];
- e_stop = &buffer[n2];
- while (e != e_stop) {
- d[1] = (e[0] * AA[0] - e[2]*AA[1]);
- d[0] = (e[0] * AA[1] + e[2]*AA[0]);
- d -= 2;
- AA += 2;
- e += 4;
- }
-
- e = &buffer[n2-3];
- while (d >= buf2) {
- d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
- d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
- d -= 2;
- AA += 2;
- e -= 4;
- }
- }
-
- // now we use symbolic names for these, so that we can
- // possibly swap their meaning as we change which operations
- // are in place
-
- u = buffer;
- v = buf2;
-
- // step 2 (paper output is w, now u)
- // this could be in place, but the data ends up in the wrong
- // place... _somebody_'s got to swap it, so this is nominated
- {
- float *AA = &A[n2-8];
- float *d0,*d1, *e0, *e1;
-
- e0 = &v[n4];
- e1 = &v[0];
-
- d0 = &u[n4];
- d1 = &u[0];
-
- while (AA >= A) {
- float v40_20, v41_21;
-
- v41_21 = e0[1] - e1[1];
- v40_20 = e0[0] - e1[0];
- d0[1] = e0[1] + e1[1];
- d0[0] = e0[0] + e1[0];
- d1[1] = v41_21*AA[4] - v40_20*AA[5];
- d1[0] = v40_20*AA[4] + v41_21*AA[5];
-
- v41_21 = e0[3] - e1[3];
- v40_20 = e0[2] - e1[2];
- d0[3] = e0[3] + e1[3];
- d0[2] = e0[2] + e1[2];
- d1[3] = v41_21*AA[0] - v40_20*AA[1];
- d1[2] = v40_20*AA[0] + v41_21*AA[1];
-
- AA -= 8;
-
- d0 += 4;
- d1 += 4;
- e0 += 4;
- e1 += 4;
- }
- }
-
- // step 3
- ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
-
- // optimized step 3:
-
- // the original step3 loop can be nested r inside s or s inside r;
- // it's written originally as s inside r, but this is dumb when r
- // iterates many times, and s few. So I have two copies of it and
- // switch between them halfway.
-
- // this is iteration 0 of step 3
- imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
- imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
-
- // this is iteration 1 of step 3
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
-
- l=2;
- for (; l < (ld-3)>>1; ++l) {
- int k0 = n >> (l+2), k0_2 = k0>>1;
- int lim = 1 << (l+1);
- int i;
- for (i=0; i < lim; ++i)
- imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
- }
-
- for (; l < ld-6; ++l) {
- int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
- int rlim = n >> (l+6), r;
- int lim = 1 << (l+1);
- int i_off;
- float *A0 = A;
- i_off = n2-1;
- for (r=rlim; r > 0; --r) {
- imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
- A0 += k1*4;
- i_off -= 8;
- }
- }
-
- // iterations with count:
- // ld-6,-5,-4 all interleaved together
- // the big win comes from getting rid of needless flops
- // due to the constants on pass 5 & 4 being all 1 and 0;
- // combining them to be simultaneous to improve cache made little difference
- imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
-
- // output is u
-
- // step 4, 5, and 6
- // cannot be in-place because of step 5
- {
- uint16 *bitrev = f->bit_reverse[blocktype];
- // weirdly, I'd have thought reading sequentially and writing
- // erratically would have been better than vice-versa, but in
- // fact that's not what my testing showed. (That is, with
- // j = bitreverse(i), do you read i and write j, or read j and write i.)
-
- float *d0 = &v[n4-4];
- float *d1 = &v[n2-4];
- while (d0 >= v) {
- int k4;
-
- k4 = bitrev[0];
- d1[3] = u[k4+0];
- d1[2] = u[k4+1];
- d0[3] = u[k4+2];
- d0[2] = u[k4+3];
-
- k4 = bitrev[1];
- d1[1] = u[k4+0];
- d1[0] = u[k4+1];
- d0[1] = u[k4+2];
- d0[0] = u[k4+3];
-
- d0 -= 4;
- d1 -= 4;
- bitrev += 2;
- }
- }
- // (paper output is u, now v)
-
-
- // data must be in buf2
- assert(v == buf2);
-
- // step 7 (paper output is v, now v)
- // this is now in place
- {
- float *C = f->C[blocktype];
- float *d, *e;
-
- d = v;
- e = v + n2 - 4;
-
- while (d < e) {
- float a02,a11,b0,b1,b2,b3;
-
- a02 = d[0] - e[2];
- a11 = d[1] + e[3];
-
- b0 = C[1]*a02 + C[0]*a11;
- b1 = C[1]*a11 - C[0]*a02;
-
- b2 = d[0] + e[ 2];
- b3 = d[1] - e[ 3];
-
- d[0] = b2 + b0;
- d[1] = b3 + b1;
- e[2] = b2 - b0;
- e[3] = b1 - b3;
-
- a02 = d[2] - e[0];
- a11 = d[3] + e[1];
-
- b0 = C[3]*a02 + C[2]*a11;
- b1 = C[3]*a11 - C[2]*a02;
-
- b2 = d[2] + e[ 0];
- b3 = d[3] - e[ 1];
-
- d[2] = b2 + b0;
- d[3] = b3 + b1;
- e[0] = b2 - b0;
- e[1] = b1 - b3;
-
- C += 4;
- d += 4;
- e -= 4;
- }
- }
-
- // data must be in buf2
-
-
- // step 8+decode (paper output is X, now buffer)
- // this generates pairs of data a la 8 and pushes them directly through
- // the decode kernel (pushing rather than pulling) to avoid having
- // to make another pass later
-
- // this cannot POSSIBLY be in place, so we refer to the buffers directly
-
- {
- float *d0,*d1,*d2,*d3;
-
- float *B = f->B[blocktype] + n2 - 8;
- float *e = buf2 + n2 - 8;
- d0 = &buffer[0];
- d1 = &buffer[n2-4];
- d2 = &buffer[n2];
- d3 = &buffer[n-4];
- while (e >= v) {
- float p0,p1,p2,p3;
-
- p3 = e[6]*B[7] - e[7]*B[6];
- p2 = -e[6]*B[6] - e[7]*B[7];
-
- d0[0] = p3;
- d1[3] = - p3;
- d2[0] = p2;
- d3[3] = p2;
-
- p1 = e[4]*B[5] - e[5]*B[4];
- p0 = -e[4]*B[4] - e[5]*B[5];
-
- d0[1] = p1;
- d1[2] = - p1;
- d2[1] = p0;
- d3[2] = p0;
-
- p3 = e[2]*B[3] - e[3]*B[2];
- p2 = -e[2]*B[2] - e[3]*B[3];
-
- d0[2] = p3;
- d1[1] = - p3;
- d2[2] = p2;
- d3[1] = p2;
-
- p1 = e[0]*B[1] - e[1]*B[0];
- p0 = -e[0]*B[0] - e[1]*B[1];
-
- d0[3] = p1;
- d1[0] = - p1;
- d2[3] = p0;
- d3[0] = p0;
-
- B -= 8;
- e -= 8;
- d0 += 4;
- d2 += 4;
- d1 -= 4;
- d3 -= 4;
- }
- }
-
- temp_free(f,buf2);
- temp_alloc_restore(f,save_point);
-}
-
-#if 0
-// this is the original version of the above code, if you want to optimize it from scratch
-void inverse_mdct_naive(float *buffer, int n)
-{
- float s;
- float A[1 << 12], B[1 << 12], C[1 << 11];
- int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
- int n3_4 = n - n4, ld;
- // how can they claim this only uses N words?!
- // oh, because they're only used sparsely, whoops
- float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
- // set up twiddle factors
-
- for (k=k2=0; k < n4; ++k,k2+=2) {
- A[k2 ] = (float) cos(4*k*M_PI/n);
- A[k2+1] = (float) -sin(4*k*M_PI/n);
- B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
- B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
- }
- for (k=k2=0; k < n8; ++k,k2+=2) {
- C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
- C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
- }
-
- // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
- // Note there are bugs in that pseudocode, presumably due to them attempting
- // to rename the arrays nicely rather than representing the way their actual
- // implementation bounces buffers back and forth. As a result, even in the
- // "some formulars corrected" version, a direct implementation fails. These
- // are noted below as "paper bug".
-
- // copy and reflect spectral data
- for (k=0; k < n2; ++k) u[k] = buffer[k];
- for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
- // kernel from paper
- // step 1
- for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
- v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
- v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
- }
- // step 2
- for (k=k4=0; k < n8; k+=1, k4+=4) {
- w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
- w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
- w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
- w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
- }
- // step 3
- ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
- for (l=0; l < ld-3; ++l) {
- int k0 = n >> (l+2), k1 = 1 << (l+3);
- int rlim = n >> (l+4), r4, r;
- int s2lim = 1 << (l+2), s2;
- for (r=r4=0; r < rlim; r4+=4,++r) {
- for (s2=0; s2 < s2lim; s2+=2) {
- u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
- u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
- u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
- - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
- u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
- + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
- }
- }
- if (l+1 < ld-3) {
- // paper bug: ping-ponging of u&w here is omitted
- memcpy(w, u, sizeof(u));
- }
- }
-
- // step 4
- for (i=0; i < n8; ++i) {
- int j = bit_reverse(i) >> (32-ld+3);
- assert(j < n8);
- if (i == j) {
- // paper bug: original code probably swapped in place; if copying,
- // need to directly copy in this case
- int i8 = i << 3;
- v[i8+1] = u[i8+1];
- v[i8+3] = u[i8+3];
- v[i8+5] = u[i8+5];
- v[i8+7] = u[i8+7];
- } else if (i < j) {
- int i8 = i << 3, j8 = j << 3;
- v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
- v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
- v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
- v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
- }
- }
- // step 5
- for (k=0; k < n2; ++k) {
- w[k] = v[k*2+1];
- }
- // step 6
- for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
- u[n-1-k2] = w[k4];
- u[n-2-k2] = w[k4+1];
- u[n3_4 - 1 - k2] = w[k4+2];
- u[n3_4 - 2 - k2] = w[k4+3];
- }
- // step 7
- for (k=k2=0; k < n8; ++k, k2 += 2) {
- v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
- v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
- v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
- v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
- }
- // step 8
- for (k=k2=0; k < n4; ++k,k2 += 2) {
- X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
- X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
- }
-
- // decode kernel to output
- // determined the following value experimentally
- // (by first figuring out what made inverse_mdct_slow work); then matching that here
- // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
- s = 0.5; // theoretically would be n4
-
- // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
- // so it needs to use the "old" B values to behave correctly, or else
- // set s to 1.0 ]]]
- for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
- for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
- for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
-}
-#endif
-
-static float *get_window(vorb *f, int len)
-{
- len <<= 1;
- if (len == f->blocksize_0) return f->window[0];
- if (len == f->blocksize_1) return f->window[1];
- return NULL;
-}
-
-#ifndef STB_VORBIS_NO_DEFER_FLOOR
-typedef int16 YTYPE;
-#else
-typedef int YTYPE;
-#endif
-static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
-{
- int n2 = n >> 1;
- int s = map->chan[i].mux, floor;
- floor = map->submap_floor[s];
- if (f->floor_types[floor] == 0) {
- return error(f, VORBIS_invalid_stream);
- } else {
- Floor1 *g = &f->floor_config[floor].floor1;
- int j,q;
- int lx = 0, ly = finalY[0] * g->floor1_multiplier;
- for (q=1; q < g->values; ++q) {
- j = g->sorted_order[q];
- #ifndef STB_VORBIS_NO_DEFER_FLOOR
- if (finalY[j] >= 0)
- #else
- if (step2_flag[j])
- #endif
- {
- int hy = finalY[j] * g->floor1_multiplier;
- int hx = g->Xlist[j];
- if (lx != hx)
- draw_line(target, lx,ly, hx,hy, n2);
- CHECK(f);
- lx = hx, ly = hy;
- }
- }
- if (lx < n2) {
- // optimization of: draw_line(target, lx,ly, n,ly, n2);
- for (j=lx; j < n2; ++j)
- LINE_OP(target[j], inverse_db_table[ly]);
- CHECK(f);
- }
- }
- return TRUE;
-}
-
-// The meaning of "left" and "right"
-//
-// For a given frame:
-// we compute samples from 0..n
-// window_center is n/2
-// we'll window and mix the samples from left_start to left_end with data from the previous frame
-// all of the samples from left_end to right_start can be output without mixing; however,
-// this interval is 0-length except when transitioning between short and long frames
-// all of the samples from right_start to right_end need to be mixed with the next frame,
-// which we don't have, so those get saved in a buffer
-// frame N's right_end-right_start, the number of samples to mix with the next frame,
-// has to be the same as frame N+1's left_end-left_start (which they are by
-// construction)
-
-static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
-{
- Mode *m;
- int i, n, prev, next, window_center;
- f->channel_buffer_start = f->channel_buffer_end = 0;
-
- retry:
- if (f->eof) return FALSE;
- if (!maybe_start_packet(f))
- return FALSE;
- // check packet type
- if (get_bits(f,1) != 0) {
- if (IS_PUSH_MODE(f))
- return error(f,VORBIS_bad_packet_type);
- while (EOP != get8_packet(f));
- goto retry;
- }
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
-
- i = get_bits(f, ilog(f->mode_count-1));
- if (i == EOP) return FALSE;
- if (i >= f->mode_count) return FALSE;
- *mode = i;
- m = f->mode_config + i;
- if (m->blockflag) {
- n = f->blocksize_1;
- prev = get_bits(f,1);
- next = get_bits(f,1);
- } else {
- prev = next = 0;
- n = f->blocksize_0;
- }
-
-// WINDOWING
-
- window_center = n >> 1;
- if (m->blockflag && !prev) {
- *p_left_start = (n - f->blocksize_0) >> 2;
- *p_left_end = (n + f->blocksize_0) >> 2;
- } else {
- *p_left_start = 0;
- *p_left_end = window_center;
- }
- if (m->blockflag && !next) {
- *p_right_start = (n*3 - f->blocksize_0) >> 2;
- *p_right_end = (n*3 + f->blocksize_0) >> 2;
- } else {
- *p_right_start = window_center;
- *p_right_end = n;
- }
-
- return TRUE;
-}
-
-static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
-{
- Mapping *map;
- int i,j,k,n,n2;
- int zero_channel[256];
- int really_zero_channel[256];
-
-// WINDOWING
-
- n = f->blocksize[m->blockflag];
- map = &f->mapping[m->mapping];
-
-// FLOORS
- n2 = n >> 1;
-
- CHECK(f);
-
- for (i=0; i < f->channels; ++i) {
- int s = map->chan[i].mux, floor;
- zero_channel[i] = FALSE;
- floor = map->submap_floor[s];
- if (f->floor_types[floor] == 0) {
- return error(f, VORBIS_invalid_stream);
- } else {
- Floor1 *g = &f->floor_config[floor].floor1;
- if (get_bits(f, 1)) {
- short *finalY;
- uint8 step2_flag[256];
- static int range_list[4] = { 256, 128, 86, 64 };
- int range = range_list[g->floor1_multiplier-1];
- int offset = 2;
- finalY = f->finalY[i];
- finalY[0] = get_bits(f, ilog(range)-1);
- finalY[1] = get_bits(f, ilog(range)-1);
- for (j=0; j < g->partitions; ++j) {
- int pclass = g->partition_class_list[j];
- int cdim = g->class_dimensions[pclass];
- int cbits = g->class_subclasses[pclass];
- int csub = (1 << cbits)-1;
- int cval = 0;
- if (cbits) {
- Codebook *c = f->codebooks + g->class_masterbooks[pclass];
- DECODE(cval,f,c);
- }
- for (k=0; k < cdim; ++k) {
- int book = g->subclass_books[pclass][cval & csub];
- cval = cval >> cbits;
- if (book >= 0) {
- int temp;
- Codebook *c = f->codebooks + book;
- DECODE(temp,f,c);
- finalY[offset++] = temp;
- } else
- finalY[offset++] = 0;
- }
- }
- if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
- step2_flag[0] = step2_flag[1] = 1;
- for (j=2; j < g->values; ++j) {
- int low, high, pred, highroom, lowroom, room, val;
- low = g->neighbors[j][0];
- high = g->neighbors[j][1];
- //neighbors(g->Xlist, j, &low, &high);
- pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
- val = finalY[j];
- highroom = range - pred;
- lowroom = pred;
- if (highroom < lowroom)
- room = highroom * 2;
- else
- room = lowroom * 2;
- if (val) {
- step2_flag[low] = step2_flag[high] = 1;
- step2_flag[j] = 1;
- if (val >= room)
- if (highroom > lowroom)
- finalY[j] = val - lowroom + pred;
- else
- finalY[j] = pred - val + highroom - 1;
- else
- if (val & 1)
- finalY[j] = pred - ((val+1)>>1);
- else
- finalY[j] = pred + (val>>1);
- } else {
- step2_flag[j] = 0;
- finalY[j] = pred;
- }
- }
-
-#ifdef STB_VORBIS_NO_DEFER_FLOOR
- do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
-#else
- // defer final floor computation until _after_ residue
- for (j=0; j < g->values; ++j) {
- if (!step2_flag[j])
- finalY[j] = -1;
- }
-#endif
- } else {
- error:
- zero_channel[i] = TRUE;
- }
- // So we just defer everything else to later
-
- // at this point we've decoded the floor into buffer
- }
- }
- CHECK(f);
- // at this point we've decoded all floors
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
-
- // re-enable coupled channels if necessary
- memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
- for (i=0; i < map->coupling_steps; ++i)
- if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
- zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
- }
-
- CHECK(f);
-// RESIDUE DECODE
- for (i=0; i < map->submaps; ++i) {
- float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
- int r;
- uint8 do_not_decode[256];
- int ch = 0;
- for (j=0; j < f->channels; ++j) {
- if (map->chan[j].mux == i) {
- if (zero_channel[j]) {
- do_not_decode[ch] = TRUE;
- residue_buffers[ch] = NULL;
- } else {
- do_not_decode[ch] = FALSE;
- residue_buffers[ch] = f->channel_buffers[j];
- }
- ++ch;
- }
- }
- r = map->submap_residue[i];
- decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
- }
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
- CHECK(f);
-
-// INVERSE COUPLING
- for (i = map->coupling_steps-1; i >= 0; --i) {
- int n2 = n >> 1;
- float *m = f->channel_buffers[map->chan[i].magnitude];
- float *a = f->channel_buffers[map->chan[i].angle ];
- for (j=0; j < n2; ++j) {
- float a2,m2;
- if (m[j] > 0)
- if (a[j] > 0)
- m2 = m[j], a2 = m[j] - a[j];
- else
- a2 = m[j], m2 = m[j] + a[j];
- else
- if (a[j] > 0)
- m2 = m[j], a2 = m[j] + a[j];
- else
- a2 = m[j], m2 = m[j] - a[j];
- m[j] = m2;
- a[j] = a2;
- }
- }
- CHECK(f);
-
- // finish decoding the floors
-#ifndef STB_VORBIS_NO_DEFER_FLOOR
- for (i=0; i < f->channels; ++i) {
- if (really_zero_channel[i]) {
- memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
- } else {
- do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
- }
- }
-#else
- for (i=0; i < f->channels; ++i) {
- if (really_zero_channel[i]) {
- memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
- } else {
- for (j=0; j < n2; ++j)
- f->channel_buffers[i][j] *= f->floor_buffers[i][j];
- }
- }
-#endif
-
-// INVERSE MDCT
- CHECK(f);
- for (i=0; i < f->channels; ++i)
- inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
- CHECK(f);
-
- // this shouldn't be necessary, unless we exited on an error
- // and want to flush to get to the next packet
- flush_packet(f);
-
- if (f->first_decode) {
- // assume we start so first non-discarded sample is sample 0
- // this isn't to spec, but spec would require us to read ahead
- // and decode the size of all current frames--could be done,
- // but presumably it's not a commonly used feature
- f->current_loc = -n2; // start of first frame is positioned for discard
- // we might have to discard samples "from" the next frame too,
- // if we're lapping a large block then a small at the start?
- f->discard_samples_deferred = n - right_end;
- f->current_loc_valid = TRUE;
- f->first_decode = FALSE;
- } else if (f->discard_samples_deferred) {
- if (f->discard_samples_deferred >= right_start - left_start) {
- f->discard_samples_deferred -= (right_start - left_start);
- left_start = right_start;
- *p_left = left_start;
- } else {
- left_start += f->discard_samples_deferred;
- *p_left = left_start;
- f->discard_samples_deferred = 0;
- }
- } else if (f->previous_length == 0 && f->current_loc_valid) {
- // we're recovering from a seek... that means we're going to discard
- // the samples from this packet even though we know our position from
- // the last page header, so we need to update the position based on
- // the discarded samples here
- // but wait, the code below is going to add this in itself even
- // on a discard, so we don't need to do it here...
- }
-
- // check if we have ogg information about the sample # for this packet
- if (f->last_seg_which == f->end_seg_with_known_loc) {
- // if we have a valid current loc, and this is final:
- if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
- uint32 current_end = f->known_loc_for_packet;
- // then let's infer the size of the (probably) short final frame
- if (current_end < f->current_loc + (right_end-left_start)) {
- if (current_end < f->current_loc) {
- // negative truncation, that's impossible!
- *len = 0;
- } else {
- *len = current_end - f->current_loc;
- }
- *len += left_start; // this doesn't seem right, but has no ill effect on my test files
- if (*len > right_end) *len = right_end; // this should never happen
- f->current_loc += *len;
- return TRUE;
- }
- }
- // otherwise, just set our sample loc
- // guess that the ogg granule pos refers to the _middle_ of the
- // last frame?
- // set f->current_loc to the position of left_start
- f->current_loc = f->known_loc_for_packet - (n2-left_start);
- f->current_loc_valid = TRUE;
- }
- if (f->current_loc_valid)
- f->current_loc += (right_start - left_start);
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
- *len = right_end; // ignore samples after the window goes to 0
- CHECK(f);
-
- return TRUE;
-}
-
-static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
-{
- int mode, left_end, right_end;
- if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
- return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
-}
-
-static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
-{
- int prev,i,j;
- // we use right&left (the start of the right- and left-window sin()-regions)
- // to determine how much to return, rather than inferring from the rules
- // (same result, clearer code); 'left' indicates where our sin() window
- // starts, therefore where the previous window's right edge starts, and
- // therefore where to start mixing from the previous buffer. 'right'
- // indicates where our sin() ending-window starts, therefore that's where
- // we start saving, and where our returned-data ends.
-
- // mixin from previous window
- if (f->previous_length) {
- int i,j, n = f->previous_length;
- float *w = get_window(f, n);
- if (w == NULL) return 0;
- for (i=0; i < f->channels; ++i) {
- for (j=0; j < n; ++j)
- f->channel_buffers[i][left+j] =
- f->channel_buffers[i][left+j]*w[ j] +
- f->previous_window[i][ j]*w[n-1-j];
- }
- }
-
- prev = f->previous_length;
-
- // last half of this data becomes previous window
- f->previous_length = len - right;
-
- // @OPTIMIZE: could avoid this copy by double-buffering the
- // output (flipping previous_window with channel_buffers), but
- // then previous_window would have to be 2x as large, and
- // channel_buffers couldn't be temp mem (although they're NOT
- // currently temp mem, they could be (unless we want to level
- // performance by spreading out the computation))
- for (i=0; i < f->channels; ++i)
- for (j=0; right+j < len; ++j)
- f->previous_window[i][j] = f->channel_buffers[i][right+j];
-
- if (!prev)
- // there was no previous packet, so this data isn't valid...
- // this isn't entirely true, only the would-have-overlapped data
- // isn't valid, but this seems to be what the spec requires
- return 0;
-
- // truncate a short frame
- if (len < right) right = len;
-
- f->samples_output += right-left;
-
- return right - left;
-}
-
-static int vorbis_pump_first_frame(stb_vorbis *f)
-{
- int len, right, left, res;
- res = vorbis_decode_packet(f, &len, &left, &right);
- if (res)
- vorbis_finish_frame(f, len, left, right);
- return res;
-}
-
-#ifndef STB_VORBIS_NO_PUSHDATA_API
-static int is_whole_packet_present(stb_vorbis *f)
-{
- // make sure that we have the packet available before continuing...
- // this requires a full ogg parse, but we know we can fetch from f->stream
-
- // instead of coding this out explicitly, we could save the current read state,
- // read the next packet with get8() until end-of-packet, check f->eof, then
- // reset the state? but that would be slower, esp. since we'd have over 256 bytes
- // of state to restore (primarily the page segment table)
-
- int s = f->next_seg, first = TRUE;
- uint8 *p = f->stream;
-
- if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
- for (; s < f->segment_count; ++s) {
- p += f->segments[s];
- if (f->segments[s] < 255) // stop at first short segment
- break;
- }
- // either this continues, or it ends it...
- if (s == f->segment_count)
- s = -1; // set 'crosses page' flag
- if (p > f->stream_end) return error(f, VORBIS_need_more_data);
- first = FALSE;
- }
- for (; s == -1;) {
- uint8 *q;
- int n;
-
- // check that we have the page header ready
- if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
- // validate the page
- if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
- if (p[4] != 0) return error(f, VORBIS_invalid_stream);
- if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
- if (f->previous_length)
- if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
- // if no previous length, we're resynching, so we can come in on a continued-packet,
- // which we'll just drop
- } else {
- if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
- }
- n = p[26]; // segment counts
- q = p+27; // q points to segment table
- p = q + n; // advance past header
- // make sure we've read the segment table
- if (p > f->stream_end) return error(f, VORBIS_need_more_data);
- for (s=0; s < n; ++s) {
- p += q[s];
- if (q[s] < 255)
- break;
- }
- if (s == n)
- s = -1; // set 'crosses page' flag
- if (p > f->stream_end) return error(f, VORBIS_need_more_data);
- first = FALSE;
- }
- return TRUE;
-}
-#endif // !STB_VORBIS_NO_PUSHDATA_API
-
-static int start_decoder(vorb *f)
-{
- uint8 header[6], x,y;
- int len,i,j,k, max_submaps = 0;
- int longest_floorlist=0;
-
- // first page, first packet
- f->first_decode = TRUE;
-
- if (!start_page(f)) return FALSE;
- // validate page flag
- if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
- if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
- if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
- // check for expected packet length
- if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
- if (f->segments[0] != 30) {
- // check for the Ogg skeleton fishead identifying header to refine our error
- if (f->segments[0] == 64 &&
- getn(f, header, 6) &&
- header[0] == 'f' &&
- header[1] == 'i' &&
- header[2] == 's' &&
- header[3] == 'h' &&
- header[4] == 'e' &&
- header[5] == 'a' &&
- get8(f) == 'd' &&
- get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported);
- else
- return error(f, VORBIS_invalid_first_page);
- }
-
- // read packet
- // check packet header
- if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
- if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
- if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
- // vorbis_version
- if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
- f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
- if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
- f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
- get32(f); // bitrate_maximum
- get32(f); // bitrate_nominal
- get32(f); // bitrate_minimum
- x = get8(f);
- {
- int log0,log1;
- log0 = x & 15;
- log1 = x >> 4;
- f->blocksize_0 = 1 << log0;
- f->blocksize_1 = 1 << log1;
- if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
- if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
- if (log0 > log1) return error(f, VORBIS_invalid_setup);
- }
-
- // framing_flag
- x = get8(f);
- if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
-
- // second packet!
- if (!start_page(f)) return FALSE;
-
- if (!start_packet(f)) return FALSE;
-
- if (!next_segment(f)) return FALSE;
-
- if (get8_packet(f) != VORBIS_packet_comment) return error(f, VORBIS_invalid_setup);
- for (i=0; i < 6; ++i) header[i] = get8_packet(f);
- if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
- //file vendor
- len = get32_packet(f);
- f->vendor = (char*)setup_malloc(f, sizeof(char) * (len+1));
- if (f->vendor == NULL) return error(f, VORBIS_outofmem);
- for(i=0; i < len; ++i) {
- f->vendor[i] = get8_packet(f);
- }
- f->vendor[len] = (char)'\0';
- //user comments
- f->comment_list_length = get32_packet(f);
- f->comment_list = (char**)setup_malloc(f, sizeof(char*) * (f->comment_list_length));
- if (f->comment_list == NULL) return error(f, VORBIS_outofmem);
-
- for(i=0; i < f->comment_list_length; ++i) {
- len = get32_packet(f);
- f->comment_list[i] = (char*)setup_malloc(f, sizeof(char) * (len+1));
- if (f->comment_list[i] == NULL) return error(f, VORBIS_outofmem);
-
- for(j=0; j < len; ++j) {
- f->comment_list[i][j] = get8_packet(f);
- }
- f->comment_list[i][len] = (char)'\0';
- }
-
- // framing_flag
- x = get8_packet(f);
- if (!(x & 1)) return error(f, VORBIS_invalid_setup);
-
-
- skip(f, f->bytes_in_seg);
- f->bytes_in_seg = 0;
-
- do {
- len = next_segment(f);
- skip(f, len);
- f->bytes_in_seg = 0;
- } while (len);
-
- // third packet!
- if (!start_packet(f)) return FALSE;
-
- #ifndef STB_VORBIS_NO_PUSHDATA_API
- if (IS_PUSH_MODE(f)) {
- if (!is_whole_packet_present(f)) {
- // convert error in ogg header to write type
- if (f->error == VORBIS_invalid_stream)
- f->error = VORBIS_invalid_setup;
- return FALSE;
- }
- }
- #endif
-
- crc32_init(); // always init it, to avoid multithread race conditions
-
- if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
- for (i=0; i < 6; ++i) header[i] = get8_packet(f);
- if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
-
- // codebooks
-
- f->codebook_count = get_bits(f,8) + 1;
- f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
- if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
- memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
- for (i=0; i < f->codebook_count; ++i) {
- uint32 *values;
- int ordered, sorted_count;
- int total=0;
- uint8 *lengths;
- Codebook *c = f->codebooks+i;
- CHECK(f);
- x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
- x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
- x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
- x = get_bits(f, 8);
- c->dimensions = (get_bits(f, 8)<<8) + x;
- x = get_bits(f, 8);
- y = get_bits(f, 8);
- c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
- ordered = get_bits(f,1);
- c->sparse = ordered ? 0 : get_bits(f,1);
-
- if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
-
- if (c->sparse)
- lengths = (uint8 *) setup_temp_malloc(f, c->entries);
- else
- lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
-
- if (!lengths) return error(f, VORBIS_outofmem);
-
- if (ordered) {
- int current_entry = 0;
- int current_length = get_bits(f,5) + 1;
- while (current_entry < c->entries) {
- int limit = c->entries - current_entry;
- int n = get_bits(f, ilog(limit));
- if (current_length >= 32) return error(f, VORBIS_invalid_setup);
- if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
- memset(lengths + current_entry, current_length, n);
- current_entry += n;
- ++current_length;
- }
- } else {
- for (j=0; j < c->entries; ++j) {
- int present = c->sparse ? get_bits(f,1) : 1;
- if (present) {
- lengths[j] = get_bits(f, 5) + 1;
- ++total;
- if (lengths[j] == 32)
- return error(f, VORBIS_invalid_setup);
- } else {
- lengths[j] = NO_CODE;
- }
- }
- }
-
- if (c->sparse && total >= c->entries >> 2) {
- // convert sparse items to non-sparse!
- if (c->entries > (int) f->setup_temp_memory_required)
- f->setup_temp_memory_required = c->entries;
-
- c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
- if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
- memcpy(c->codeword_lengths, lengths, c->entries);
- setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
- lengths = c->codeword_lengths;
- c->sparse = 0;
- }
-
- // compute the size of the sorted tables
- if (c->sparse) {
- sorted_count = total;
- } else {
- sorted_count = 0;
- #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
- for (j=0; j < c->entries; ++j)
- if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
- ++sorted_count;
- #endif
- }
-
- c->sorted_entries = sorted_count;
- values = NULL;
-
- CHECK(f);
- if (!c->sparse) {
- c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
- if (!c->codewords) return error(f, VORBIS_outofmem);
- } else {
- unsigned int size;
- if (c->sorted_entries) {
- c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
- if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
- c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
- if (!c->codewords) return error(f, VORBIS_outofmem);
- values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
- if (!values) return error(f, VORBIS_outofmem);
- }
- size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
- if (size > f->setup_temp_memory_required)
- f->setup_temp_memory_required = size;
- }
-
- if (!compute_codewords(c, lengths, c->entries, values)) {
- if (c->sparse) setup_temp_free(f, values, 0);
- return error(f, VORBIS_invalid_setup);
- }
-
- if (c->sorted_entries) {
- // allocate an extra slot for sentinels
- c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
- if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
- // allocate an extra slot at the front so that c->sorted_values[-1] is defined
- // so that we can catch that case without an extra if
- c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
- if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
- ++c->sorted_values;
- c->sorted_values[-1] = -1;
- compute_sorted_huffman(c, lengths, values);
- }
-
- if (c->sparse) {
- setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
- setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
- setup_temp_free(f, lengths, c->entries);
- c->codewords = NULL;
- }
-
- compute_accelerated_huffman(c);
-
- CHECK(f);
- c->lookup_type = get_bits(f, 4);
- if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
- if (c->lookup_type > 0) {
- uint16 *mults;
- c->minimum_value = float32_unpack(get_bits(f, 32));
- c->delta_value = float32_unpack(get_bits(f, 32));
- c->value_bits = get_bits(f, 4)+1;
- c->sequence_p = get_bits(f,1);
- if (c->lookup_type == 1) {
- int values = lookup1_values(c->entries, c->dimensions);
- if (values < 0) return error(f, VORBIS_invalid_setup);
- c->lookup_values = (uint32) values;
- } else {
- c->lookup_values = c->entries * c->dimensions;
- }
- if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
- mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
- if (mults == NULL) return error(f, VORBIS_outofmem);
- for (j=0; j < (int) c->lookup_values; ++j) {
- int q = get_bits(f, c->value_bits);
- if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
- mults[j] = q;
- }
-
-#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- int len, sparse = c->sparse;
- float last=0;
- // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
- if (sparse) {
- if (c->sorted_entries == 0) goto skip;
- c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
- } else
- c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
- if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
- len = sparse ? c->sorted_entries : c->entries;
- for (j=0; j < len; ++j) {
- unsigned int z = sparse ? c->sorted_values[j] : j;
- unsigned int div=1;
- for (k=0; k < c->dimensions; ++k) {
- int off = (z / div) % c->lookup_values;
- float val = mults[off];
- val = mults[off]*c->delta_value + c->minimum_value + last;
- c->multiplicands[j*c->dimensions + k] = val;
- if (c->sequence_p)
- last = val;
- if (k+1 < c->dimensions) {
- if (div > UINT_MAX / (unsigned int) c->lookup_values) {
- setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
- return error(f, VORBIS_invalid_setup);
- }
- div *= c->lookup_values;
- }
- }
- }
- c->lookup_type = 2;
- }
- else
-#endif
- {
- float last=0;
- CHECK(f);
- c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
- if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
- for (j=0; j < (int) c->lookup_values; ++j) {
- float val = mults[j] * c->delta_value + c->minimum_value + last;
- c->multiplicands[j] = val;
- if (c->sequence_p)
- last = val;
- }
- }
-#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
- skip:;
-#endif
- setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
-
- CHECK(f);
- }
- CHECK(f);
- }
-
- // time domain transfers (notused)
-
- x = get_bits(f, 6) + 1;
- for (i=0; i < x; ++i) {
- uint32 z = get_bits(f, 16);
- if (z != 0) return error(f, VORBIS_invalid_setup);
- }
-
- // Floors
- f->floor_count = get_bits(f, 6)+1;
- f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
- if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
- for (i=0; i < f->floor_count; ++i) {
- f->floor_types[i] = get_bits(f, 16);
- if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
- if (f->floor_types[i] == 0) {
- Floor0 *g = &f->floor_config[i].floor0;
- g->order = get_bits(f,8);
- g->rate = get_bits(f,16);
- g->bark_map_size = get_bits(f,16);
- g->amplitude_bits = get_bits(f,6);
- g->amplitude_offset = get_bits(f,8);
- g->number_of_books = get_bits(f,4) + 1;
- for (j=0; j < g->number_of_books; ++j)
- g->book_list[j] = get_bits(f,8);
- return error(f, VORBIS_feature_not_supported);
- } else {
- stbv__floor_ordering p[31*8+2];
- Floor1 *g = &f->floor_config[i].floor1;
- int max_class = -1;
- g->partitions = get_bits(f, 5);
- for (j=0; j < g->partitions; ++j) {
- g->partition_class_list[j] = get_bits(f, 4);
- if (g->partition_class_list[j] > max_class)
- max_class = g->partition_class_list[j];
- }
- for (j=0; j <= max_class; ++j) {
- g->class_dimensions[j] = get_bits(f, 3)+1;
- g->class_subclasses[j] = get_bits(f, 2);
- if (g->class_subclasses[j]) {
- g->class_masterbooks[j] = get_bits(f, 8);
- if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
- }
- for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
- g->subclass_books[j][k] = get_bits(f,8)-1;
- if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
- }
- }
- g->floor1_multiplier = get_bits(f,2)+1;
- g->rangebits = get_bits(f,4);
- g->Xlist[0] = 0;
- g->Xlist[1] = 1 << g->rangebits;
- g->values = 2;
- for (j=0; j < g->partitions; ++j) {
- int c = g->partition_class_list[j];
- for (k=0; k < g->class_dimensions[c]; ++k) {
- g->Xlist[g->values] = get_bits(f, g->rangebits);
- ++g->values;
- }
- }
- // precompute the sorting
- for (j=0; j < g->values; ++j) {
- p[j].x = g->Xlist[j];
- p[j].id = j;
- }
- qsort(p, g->values, sizeof(p[0]), point_compare);
- for (j=0; j < g->values-1; ++j)
- if (p[j].x == p[j+1].x)
- return error(f, VORBIS_invalid_setup);
- for (j=0; j < g->values; ++j)
- g->sorted_order[j] = (uint8) p[j].id;
- // precompute the neighbors
- for (j=2; j < g->values; ++j) {
- int low = 0,hi = 0;
- neighbors(g->Xlist, j, &low,&hi);
- g->neighbors[j][0] = low;
- g->neighbors[j][1] = hi;
- }
-
- if (g->values > longest_floorlist)
- longest_floorlist = g->values;
- }
- }
-
- // Residue
- f->residue_count = get_bits(f, 6)+1;
- f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
- if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
- memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
- for (i=0; i < f->residue_count; ++i) {
- uint8 residue_cascade[64];
- Residue *r = f->residue_config+i;
- f->residue_types[i] = get_bits(f, 16);
- if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
- r->begin = get_bits(f, 24);
- r->end = get_bits(f, 24);
- if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
- r->part_size = get_bits(f,24)+1;
- r->classifications = get_bits(f,6)+1;
- r->classbook = get_bits(f,8);
- if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
- for (j=0; j < r->classifications; ++j) {
- uint8 high_bits=0;
- uint8 low_bits=get_bits(f,3);
- if (get_bits(f,1))
- high_bits = get_bits(f,5);
- residue_cascade[j] = high_bits*8 + low_bits;
- }
- r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
- if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
- for (j=0; j < r->classifications; ++j) {
- for (k=0; k < 8; ++k) {
- if (residue_cascade[j] & (1 << k)) {
- r->residue_books[j][k] = get_bits(f, 8);
- if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
- } else {
- r->residue_books[j][k] = -1;
- }
- }
- }
- // precompute the classifications[] array to avoid inner-loop mod/divide
- // call it 'classdata' since we already have r->classifications
- r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
- if (!r->classdata) return error(f, VORBIS_outofmem);
- memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
- for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
- int classwords = f->codebooks[r->classbook].dimensions;
- int temp = j;
- r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
- if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
- for (k=classwords-1; k >= 0; --k) {
- r->classdata[j][k] = temp % r->classifications;
- temp /= r->classifications;
- }
- }
- }
-
- f->mapping_count = get_bits(f,6)+1;
- f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
- if (f->mapping == NULL) return error(f, VORBIS_outofmem);
- memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
- for (i=0; i < f->mapping_count; ++i) {
- Mapping *m = f->mapping + i;
- int mapping_type = get_bits(f,16);
- if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
- m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
- if (m->chan == NULL) return error(f, VORBIS_outofmem);
- if (get_bits(f,1))
- m->submaps = get_bits(f,4)+1;
- else
- m->submaps = 1;
- if (m->submaps > max_submaps)
- max_submaps = m->submaps;
- if (get_bits(f,1)) {
- m->coupling_steps = get_bits(f,8)+1;
- if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);
- for (k=0; k < m->coupling_steps; ++k) {
- m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
- m->chan[k].angle = get_bits(f, ilog(f->channels-1));
- if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
- if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
- if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
- }
- } else
- m->coupling_steps = 0;
-
- // reserved field
- if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
- if (m->submaps > 1) {
- for (j=0; j < f->channels; ++j) {
- m->chan[j].mux = get_bits(f, 4);
- if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
- }
- } else
- // @SPECIFICATION: this case is missing from the spec
- for (j=0; j < f->channels; ++j)
- m->chan[j].mux = 0;
-
- for (j=0; j < m->submaps; ++j) {
- get_bits(f,8); // discard
- m->submap_floor[j] = get_bits(f,8);
- m->submap_residue[j] = get_bits(f,8);
- if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
- if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
- }
- }
-
- // Modes
- f->mode_count = get_bits(f, 6)+1;
- for (i=0; i < f->mode_count; ++i) {
- Mode *m = f->mode_config+i;
- m->blockflag = get_bits(f,1);
- m->windowtype = get_bits(f,16);
- m->transformtype = get_bits(f,16);
- m->mapping = get_bits(f,8);
- if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
- if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
- if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
- }
-
- flush_packet(f);
-
- f->previous_length = 0;
-
- for (i=0; i < f->channels; ++i) {
- f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
- f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
- f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
- if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
- memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
- #ifdef STB_VORBIS_NO_DEFER_FLOOR
- f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
- if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
- #endif
- }
-
- if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
- if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
- f->blocksize[0] = f->blocksize_0;
- f->blocksize[1] = f->blocksize_1;
-
-#ifdef STB_VORBIS_DIVIDE_TABLE
- if (integer_divide_table[1][1]==0)
- for (i=0; i < DIVTAB_NUMER; ++i)
- for (j=1; j < DIVTAB_DENOM; ++j)
- integer_divide_table[i][j] = i / j;
-#endif
-
- // compute how much temporary memory is needed
-
- // 1.
- {
- uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
- uint32 classify_mem;
- int i,max_part_read=0;
- for (i=0; i < f->residue_count; ++i) {
- Residue *r = f->residue_config + i;
- unsigned int actual_size = f->blocksize_1 / 2;
- unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
- unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
- int n_read = limit_r_end - limit_r_begin;
- int part_read = n_read / r->part_size;
- if (part_read > max_part_read)
- max_part_read = part_read;
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
- #else
- classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
- #endif
-
- // maximum reasonable partition size is f->blocksize_1
-
- f->temp_memory_required = classify_mem;
- if (imdct_mem > f->temp_memory_required)
- f->temp_memory_required = imdct_mem;
- }
-
-
- if (f->alloc.alloc_buffer) {
- assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
- // check if there's enough temp memory so we don't error later
- if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
- return error(f, VORBIS_outofmem);
- }
-
- // @TODO: stb_vorbis_seek_start expects first_audio_page_offset to point to a page
- // without PAGEFLAG_continued_packet, so this either points to the first page, or
- // the page after the end of the headers. It might be cleaner to point to a page
- // in the middle of the headers, when that's the page where the first audio packet
- // starts, but we'd have to also correctly skip the end of any continued packet in
- // stb_vorbis_seek_start.
- if (f->next_seg == -1) {
- f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
- } else {
- f->first_audio_page_offset = 0;
- }
-
- return TRUE;
-}
-
-static void vorbis_deinit(stb_vorbis *p)
-{
- int i,j;
-
- setup_free(p, p->vendor);
- for (i=0; i < p->comment_list_length; ++i) {
- setup_free(p, p->comment_list[i]);
- }
- setup_free(p, p->comment_list);
-
- if (p->residue_config) {
- for (i=0; i < p->residue_count; ++i) {
- Residue *r = p->residue_config+i;
- if (r->classdata) {
- for (j=0; j < p->codebooks[r->classbook].entries; ++j)
- setup_free(p, r->classdata[j]);
- setup_free(p, r->classdata);
- }
- setup_free(p, r->residue_books);
- }
- }
-
- if (p->codebooks) {
- CHECK(p);
- for (i=0; i < p->codebook_count; ++i) {
- Codebook *c = p->codebooks + i;
- setup_free(p, c->codeword_lengths);
- setup_free(p, c->multiplicands);
- setup_free(p, c->codewords);
- setup_free(p, c->sorted_codewords);
- // c->sorted_values[-1] is the first entry in the array
- setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
- }
- setup_free(p, p->codebooks);
- }
- setup_free(p, p->floor_config);
- setup_free(p, p->residue_config);
- if (p->mapping) {
- for (i=0; i < p->mapping_count; ++i)
- setup_free(p, p->mapping[i].chan);
- setup_free(p, p->mapping);
- }
- CHECK(p);
- for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
- setup_free(p, p->channel_buffers[i]);
- setup_free(p, p->previous_window[i]);
- #ifdef STB_VORBIS_NO_DEFER_FLOOR
- setup_free(p, p->floor_buffers[i]);
- #endif
- setup_free(p, p->finalY[i]);
- }
- for (i=0; i < 2; ++i) {
- setup_free(p, p->A[i]);
- setup_free(p, p->B[i]);
- setup_free(p, p->C[i]);
- setup_free(p, p->window[i]);
- setup_free(p, p->bit_reverse[i]);
- }
- #ifndef STB_VORBIS_NO_STDIO
- if (p->close_on_free) fclose(p->f);
- #endif
-}
-
-void stb_vorbis_close(stb_vorbis *p)
-{
- if (p == NULL) return;
- vorbis_deinit(p);
- setup_free(p,p);
-}
-
-static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)
-{
- memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
- if (z) {
- p->alloc = *z;
- p->alloc.alloc_buffer_length_in_bytes &= ~7;
- p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
- }
- p->eof = 0;
- p->error = VORBIS__no_error;
- p->stream = NULL;
- p->codebooks = NULL;
- p->page_crc_tests = -1;
- #ifndef STB_VORBIS_NO_STDIO
- p->close_on_free = FALSE;
- p->f = NULL;
- #endif
-}
-
-int stb_vorbis_get_sample_offset(stb_vorbis *f)
-{
- if (f->current_loc_valid)
- return f->current_loc;
- else
- return -1;
-}
-
-stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
-{
- stb_vorbis_info d;
- d.channels = f->channels;
- d.sample_rate = f->sample_rate;
- d.setup_memory_required = f->setup_memory_required;
- d.setup_temp_memory_required = f->setup_temp_memory_required;
- d.temp_memory_required = f->temp_memory_required;
- d.max_frame_size = f->blocksize_1 >> 1;
- return d;
-}
-
-stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f)
-{
- stb_vorbis_comment d;
- d.vendor = f->vendor;
- d.comment_list_length = f->comment_list_length;
- d.comment_list = f->comment_list;
- return d;
-}
-
-int stb_vorbis_get_error(stb_vorbis *f)
-{
- int e = f->error;
- f->error = VORBIS__no_error;
- return e;
-}
-
-static stb_vorbis * vorbis_alloc(stb_vorbis *f)
-{
- stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
- return p;
-}
-
-#ifndef STB_VORBIS_NO_PUSHDATA_API
-
-void stb_vorbis_flush_pushdata(stb_vorbis *f)
-{
- f->previous_length = 0;
- f->page_crc_tests = 0;
- f->discard_samples_deferred = 0;
- f->current_loc_valid = FALSE;
- f->first_decode = FALSE;
- f->samples_output = 0;
- f->channel_buffer_start = 0;
- f->channel_buffer_end = 0;
-}
-
-static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
-{
- int i,n;
- for (i=0; i < f->page_crc_tests; ++i)
- f->scan[i].bytes_done = 0;
-
- // if we have room for more scans, search for them first, because
- // they may cause us to stop early if their header is incomplete
- if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
- if (data_len < 4) return 0;
- data_len -= 3; // need to look for 4-byte sequence, so don't miss
- // one that straddles a boundary
- for (i=0; i < data_len; ++i) {
- if (data[i] == 0x4f) {
- if (0==memcmp(data+i, ogg_page_header, 4)) {
- int j,len;
- uint32 crc;
- // make sure we have the whole page header
- if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
- // only read up to this page start, so hopefully we'll
- // have the whole page header start next time
- data_len = i;
- break;
- }
- // ok, we have it all; compute the length of the page
- len = 27 + data[i+26];
- for (j=0; j < data[i+26]; ++j)
- len += data[i+27+j];
- // scan everything up to the embedded crc (which we must 0)
- crc = 0;
- for (j=0; j < 22; ++j)
- crc = crc32_update(crc, data[i+j]);
- // now process 4 0-bytes
- for ( ; j < 26; ++j)
- crc = crc32_update(crc, 0);
- // len is the total number of bytes we need to scan
- n = f->page_crc_tests++;
- f->scan[n].bytes_left = len-j;
- f->scan[n].crc_so_far = crc;
- f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
- // if the last frame on a page is continued to the next, then
- // we can't recover the sample_loc immediately
- if (data[i+27+data[i+26]-1] == 255)
- f->scan[n].sample_loc = ~0;
- else
- f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
- f->scan[n].bytes_done = i+j;
- if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
- break;
- // keep going if we still have room for more
- }
- }
- }
- }
-
- for (i=0; i < f->page_crc_tests;) {
- uint32 crc;
- int j;
- int n = f->scan[i].bytes_done;
- int m = f->scan[i].bytes_left;
- if (m > data_len - n) m = data_len - n;
- // m is the bytes to scan in the current chunk
- crc = f->scan[i].crc_so_far;
- for (j=0; j < m; ++j)
- crc = crc32_update(crc, data[n+j]);
- f->scan[i].bytes_left -= m;
- f->scan[i].crc_so_far = crc;
- if (f->scan[i].bytes_left == 0) {
- // does it match?
- if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
- // Houston, we have page
- data_len = n+m; // consumption amount is wherever that scan ended
- f->page_crc_tests = -1; // drop out of page scan mode
- f->previous_length = 0; // decode-but-don't-output one frame
- f->next_seg = -1; // start a new page
- f->current_loc = f->scan[i].sample_loc; // set the current sample location
- // to the amount we'd have decoded had we decoded this page
- f->current_loc_valid = f->current_loc != ~0U;
- return data_len;
- }
- // delete entry
- f->scan[i] = f->scan[--f->page_crc_tests];
- } else {
- ++i;
- }
- }
-
- return data_len;
-}
-
-// return value: number of bytes we used
-int stb_vorbis_decode_frame_pushdata(
- stb_vorbis *f, // the file we're decoding
- const uint8 *data, int data_len, // the memory available for decoding
- int *channels, // place to write number of float * buffers
- float ***output, // place to write float ** array of float * buffers
- int *samples // place to write number of output samples
- )
-{
- int i;
- int len,right,left;
-
- if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
-
- if (f->page_crc_tests >= 0) {
- *samples = 0;
- return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len);
- }
-
- f->stream = (uint8 *) data;
- f->stream_end = (uint8 *) data + data_len;
- f->error = VORBIS__no_error;
-
- // check that we have the entire packet in memory
- if (!is_whole_packet_present(f)) {
- *samples = 0;
- return 0;
- }
-
- if (!vorbis_decode_packet(f, &len, &left, &right)) {
- // save the actual error we encountered
- enum STBVorbisError error = f->error;
- if (error == VORBIS_bad_packet_type) {
- // flush and resynch
- f->error = VORBIS__no_error;
- while (get8_packet(f) != EOP)
- if (f->eof) break;
- *samples = 0;
- return (int) (f->stream - data);
- }
- if (error == VORBIS_continued_packet_flag_invalid) {
- if (f->previous_length == 0) {
- // we may be resynching, in which case it's ok to hit one
- // of these; just discard the packet
- f->error = VORBIS__no_error;
- while (get8_packet(f) != EOP)
- if (f->eof) break;
- *samples = 0;
- return (int) (f->stream - data);
- }
- }
- // if we get an error while parsing, what to do?
- // well, it DEFINITELY won't work to continue from where we are!
- stb_vorbis_flush_pushdata(f);
- // restore the error that actually made us bail
- f->error = error;
- *samples = 0;
- return 1;
- }
-
- // success!
- len = vorbis_finish_frame(f, len, left, right);
- for (i=0; i < f->channels; ++i)
- f->outputs[i] = f->channel_buffers[i] + left;
-
- if (channels) *channels = f->channels;
- *samples = len;
- *output = f->outputs;
- return (int) (f->stream - data);
-}
-
-stb_vorbis *stb_vorbis_open_pushdata(
- const unsigned char *data, int data_len, // the memory available for decoding
- int *data_used, // only defined if result is not NULL
- int *error, const stb_vorbis_alloc *alloc)
-{
- stb_vorbis *f, p;
- vorbis_init(&p, alloc);
- p.stream = (uint8 *) data;
- p.stream_end = (uint8 *) data + data_len;
- p.push_mode = TRUE;
- if (!start_decoder(&p)) {
- if (p.eof)
- *error = VORBIS_need_more_data;
- else
- *error = p.error;
- return NULL;
- }
- f = vorbis_alloc(&p);
- if (f) {
- *f = p;
- *data_used = (int) (f->stream - data);
- *error = 0;
- return f;
- } else {
- vorbis_deinit(&p);
- return NULL;
- }
-}
-#endif // STB_VORBIS_NO_PUSHDATA_API
-
-unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
-{
- #ifndef STB_VORBIS_NO_PUSHDATA_API
- if (f->push_mode) return 0;
- #endif
- if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);
- #ifndef STB_VORBIS_NO_STDIO
- return (unsigned int) (ftell(f->f) - f->f_start);
- #endif
-}
-
-#ifndef STB_VORBIS_NO_PULLDATA_API
-//
-// DATA-PULLING API
-//
-
-static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
-{
- for(;;) {
- int n;
- if (f->eof) return 0;
- n = get8(f);
- if (n == 0x4f) { // page header candidate
- unsigned int retry_loc = stb_vorbis_get_file_offset(f);
- int i;
- // check if we're off the end of a file_section stream
- if (retry_loc - 25 > f->stream_len)
- return 0;
- // check the rest of the header
- for (i=1; i < 4; ++i)
- if (get8(f) != ogg_page_header[i])
- break;
- if (f->eof) return 0;
- if (i == 4) {
- uint8 header[27];
- uint32 i, crc, goal, len;
- for (i=0; i < 4; ++i)
- header[i] = ogg_page_header[i];
- for (; i < 27; ++i)
- header[i] = get8(f);
- if (f->eof) return 0;
- if (header[4] != 0) goto invalid;
- goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
- for (i=22; i < 26; ++i)
- header[i] = 0;
- crc = 0;
- for (i=0; i < 27; ++i)
- crc = crc32_update(crc, header[i]);
- len = 0;
- for (i=0; i < header[26]; ++i) {
- int s = get8(f);
- crc = crc32_update(crc, s);
- len += s;
- }
- if (len && f->eof) return 0;
- for (i=0; i < len; ++i)
- crc = crc32_update(crc, get8(f));
- // finished parsing probable page
- if (crc == goal) {
- // we could now check that it's either got the last
- // page flag set, OR it's followed by the capture
- // pattern, but I guess TECHNICALLY you could have
- // a file with garbage between each ogg page and recover
- // from it automatically? So even though that paranoia
- // might decrease the chance of an invalid decode by
- // another 2^32, not worth it since it would hose those
- // invalid-but-useful files?
- if (end)
- *end = stb_vorbis_get_file_offset(f);
- if (last) {
- if (header[5] & 0x04)
- *last = 1;
- else
- *last = 0;
- }
- set_file_offset(f, retry_loc-1);
- return 1;
- }
- }
- invalid:
- // not a valid page, so rewind and look for next one
- set_file_offset(f, retry_loc);
- }
- }
-}
-
-
-#define SAMPLE_unknown 0xffffffff
-
-// seeking is implemented with a binary search, which narrows down the range to
-// 64K, before using a linear search (because finding the synchronization
-// pattern can be expensive, and the chance we'd find the end page again is
-// relatively high for small ranges)
-//
-// two initial interpolation-style probes are used at the start of the search
-// to try to bound either side of the binary search sensibly, while still
-// working in O(log n) time if they fail.
-
-static int get_seek_page_info(stb_vorbis *f, ProbedPage *z)
-{
- uint8 header[27], lacing[255];
- int i,len;
-
- // record where the page starts
- z->page_start = stb_vorbis_get_file_offset(f);
-
- // parse the header
- getn(f, header, 27);
- if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')
- return 0;
- getn(f, lacing, header[26]);
-
- // determine the length of the payload
- len = 0;
- for (i=0; i < header[26]; ++i)
- len += lacing[i];
-
- // this implies where the page ends
- z->page_end = z->page_start + 27 + header[26] + len;
-
- // read the last-decoded sample out of the data
- z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
-
- // restore file state to where we were
- set_file_offset(f, z->page_start);
- return 1;
-}
-
-// rarely used function to seek back to the preceding page while finding the
-// start of a packet
-static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset)
-{
- unsigned int previous_safe, end;
-
- // now we want to seek back 64K from the limit
- if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)
- previous_safe = limit_offset - 65536;
- else
- previous_safe = f->first_audio_page_offset;
-
- set_file_offset(f, previous_safe);
-
- while (vorbis_find_page(f, &end, NULL)) {
- if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
- return 1;
- set_file_offset(f, end);
- }
-
- return 0;
-}
-
-// implements the search logic for finding a page and starting decoding. if
-// the function succeeds, current_loc_valid will be true and current_loc will
-// be less than or equal to the provided sample number (the closer the
-// better).
-static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number)
-{
- ProbedPage left, right, mid;
- int i, start_seg_with_known_loc, end_pos, page_start;
- uint32 delta, stream_length, padding, last_sample_limit;
- double offset = 0.0, bytes_per_sample = 0.0;
- int probe = 0;
-
- // find the last page and validate the target sample
- stream_length = stb_vorbis_stream_length_in_samples(f);
- if (stream_length == 0) return error(f, VORBIS_seek_without_length);
- if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);
-
- // this is the maximum difference between the window-center (which is the
- // actual granule position value), and the right-start (which the spec
- // indicates should be the granule position (give or take one)).
- padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
- if (sample_number < padding)
- last_sample_limit = 0;
- else
- last_sample_limit = sample_number - padding;
-
- left = f->p_first;
- while (left.last_decoded_sample == ~0U) {
- // (untested) the first page does not have a 'last_decoded_sample'
- set_file_offset(f, left.page_end);
- if (!get_seek_page_info(f, &left)) goto error;
- }
-
- right = f->p_last;
- assert(right.last_decoded_sample != ~0U);
-
- // starting from the start is handled differently
- if (last_sample_limit <= left.last_decoded_sample) {
- if (stb_vorbis_seek_start(f)) {
- if (f->current_loc > sample_number)
- return error(f, VORBIS_seek_failed);
- return 1;
- }
- return 0;
- }
-
- while (left.page_end != right.page_start) {
- assert(left.page_end < right.page_start);
- // search range in bytes
- delta = right.page_start - left.page_end;
- if (delta <= 65536) {
- // there's only 64K left to search - handle it linearly
- set_file_offset(f, left.page_end);
- } else {
- if (probe < 2) {
- if (probe == 0) {
- // first probe (interpolate)
- double data_bytes = right.page_end - left.page_start;
- bytes_per_sample = data_bytes / right.last_decoded_sample;
- offset = left.page_start + bytes_per_sample * (last_sample_limit - left.last_decoded_sample);
- } else {
- // second probe (try to bound the other side)
- double error = ((double) last_sample_limit - mid.last_decoded_sample) * bytes_per_sample;
- if (error >= 0 && error < 8000) error = 8000;
- if (error < 0 && error > -8000) error = -8000;
- offset += error * 2;
- }
-
- // ensure the offset is valid
- if (offset < left.page_end)
- offset = left.page_end;
- if (offset > right.page_start - 65536)
- offset = right.page_start - 65536;
-
- set_file_offset(f, (unsigned int) offset);
- } else {
- // binary search for large ranges (offset by 32K to ensure
- // we don't hit the right page)
- set_file_offset(f, left.page_end + (delta / 2) - 32768);
- }
-
- if (!vorbis_find_page(f, NULL, NULL)) goto error;
- }
-
- for (;;) {
- if (!get_seek_page_info(f, &mid)) goto error;
- if (mid.last_decoded_sample != ~0U) break;
- // (untested) no frames end on this page
- set_file_offset(f, mid.page_end);
- assert(mid.page_start < right.page_start);
- }
-
- // if we've just found the last page again then we're in a tricky file,
- // and we're close enough (if it wasn't an interpolation probe).
- if (mid.page_start == right.page_start) {
- if (probe >= 2 || delta <= 65536)
- break;
- } else {
- if (last_sample_limit < mid.last_decoded_sample)
- right = mid;
- else
- left = mid;
- }
-
- ++probe;
- }
-
- // seek back to start of the last packet
- page_start = left.page_start;
- set_file_offset(f, page_start);
- if (!start_page(f)) return error(f, VORBIS_seek_failed);
- end_pos = f->end_seg_with_known_loc;
- assert(end_pos >= 0);
-
- for (;;) {
- for (i = end_pos; i > 0; --i)
- if (f->segments[i-1] != 255)
- break;
-
- start_seg_with_known_loc = i;
-
- if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet))
- break;
-
- // (untested) the final packet begins on an earlier page
- if (!go_to_page_before(f, page_start))
- goto error;
-
- page_start = stb_vorbis_get_file_offset(f);
- if (!start_page(f)) goto error;
- end_pos = f->segment_count - 1;
- }
-
- // prepare to start decoding
- f->current_loc_valid = FALSE;
- f->last_seg = FALSE;
- f->valid_bits = 0;
- f->packet_bytes = 0;
- f->bytes_in_seg = 0;
- f->previous_length = 0;
- f->next_seg = start_seg_with_known_loc;
-
- for (i = 0; i < start_seg_with_known_loc; i++)
- skip(f, f->segments[i]);
-
- // start decoding (optimizable - this frame is generally discarded)
- if (!vorbis_pump_first_frame(f))
- return 0;
- if (f->current_loc > sample_number)
- return error(f, VORBIS_seek_failed);
- return 1;
-
-error:
- // try to restore the file to a valid state
- stb_vorbis_seek_start(f);
- return error(f, VORBIS_seek_failed);
-}
-
-// the same as vorbis_decode_initial, but without advancing
-static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
-{
- int bits_read, bytes_read;
-
- if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))
- return 0;
-
- // either 1 or 2 bytes were read, figure out which so we can rewind
- bits_read = 1 + ilog(f->mode_count-1);
- if (f->mode_config[*mode].blockflag)
- bits_read += 2;
- bytes_read = (bits_read + 7) / 8;
-
- f->bytes_in_seg += bytes_read;
- f->packet_bytes -= bytes_read;
- skip(f, -bytes_read);
- if (f->next_seg == -1)
- f->next_seg = f->segment_count - 1;
- else
- f->next_seg--;
- f->valid_bits = 0;
-
- return 1;
-}
-
-int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
-{
- uint32 max_frame_samples;
-
- if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
-
- // fast page-level search
- if (!seek_to_sample_coarse(f, sample_number))
- return 0;
-
- assert(f->current_loc_valid);
- assert(f->current_loc <= sample_number);
-
- // linear search for the relevant packet
- max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;
- while (f->current_loc < sample_number) {
- int left_start, left_end, right_start, right_end, mode, frame_samples;
- if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
- return error(f, VORBIS_seek_failed);
- // calculate the number of samples returned by the next frame
- frame_samples = right_start - left_start;
- if (f->current_loc + frame_samples > sample_number) {
- return 1; // the next frame will contain the sample
- } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {
- // there's a chance the frame after this could contain the sample
- vorbis_pump_first_frame(f);
- } else {
- // this frame is too early to be relevant
- f->current_loc += frame_samples;
- f->previous_length = 0;
- maybe_start_packet(f);
- flush_packet(f);
- }
- }
- // the next frame should start with the sample
- if (f->current_loc != sample_number) return error(f, VORBIS_seek_failed);
- return 1;
-}
-
-int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
-{
- if (!stb_vorbis_seek_frame(f, sample_number))
- return 0;
-
- if (sample_number != f->current_loc) {
- int n;
- uint32 frame_start = f->current_loc;
- stb_vorbis_get_frame_float(f, &n, NULL);
- assert(sample_number > frame_start);
- assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);
- f->channel_buffer_start += (sample_number - frame_start);
- }
-
- return 1;
-}
-
-int stb_vorbis_seek_start(stb_vorbis *f)
-{
- if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); }
- set_file_offset(f, f->first_audio_page_offset);
- f->previous_length = 0;
- f->first_decode = TRUE;
- f->next_seg = -1;
- return vorbis_pump_first_frame(f);
-}
-
-unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
-{
- unsigned int restore_offset, previous_safe;
- unsigned int end, last_page_loc;
-
- if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
- if (!f->total_samples) {
- unsigned int last;
- uint32 lo,hi;
- char header[6];
-
- // first, store the current decode position so we can restore it
- restore_offset = stb_vorbis_get_file_offset(f);
-
- // now we want to seek back 64K from the end (the last page must
- // be at most a little less than 64K, but let's allow a little slop)
- if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
- previous_safe = f->stream_len - 65536;
- else
- previous_safe = f->first_audio_page_offset;
-
- set_file_offset(f, previous_safe);
- // previous_safe is now our candidate 'earliest known place that seeking
- // to will lead to the final page'
-
- if (!vorbis_find_page(f, &end, &last)) {
- // if we can't find a page, we're hosed!
- f->error = VORBIS_cant_find_last_page;
- f->total_samples = 0xffffffff;
- goto done;
- }
-
- // check if there are more pages
- last_page_loc = stb_vorbis_get_file_offset(f);
-
- // stop when the last_page flag is set, not when we reach eof;
- // this allows us to stop short of a 'file_section' end without
- // explicitly checking the length of the section
- while (!last) {
- set_file_offset(f, end);
- if (!vorbis_find_page(f, &end, &last)) {
- // the last page we found didn't have the 'last page' flag
- // set. whoops!
- break;
- }
- previous_safe = last_page_loc+1;
- last_page_loc = stb_vorbis_get_file_offset(f);
- }
-
- set_file_offset(f, last_page_loc);
-
- // parse the header
- getn(f, (unsigned char *)header, 6);
- // extract the absolute granule position
- lo = get32(f);
- hi = get32(f);
- if (lo == 0xffffffff && hi == 0xffffffff) {
- f->error = VORBIS_cant_find_last_page;
- f->total_samples = SAMPLE_unknown;
- goto done;
- }
- if (hi)
- lo = 0xfffffffe; // saturate
- f->total_samples = lo;
-
- f->p_last.page_start = last_page_loc;
- f->p_last.page_end = end;
- f->p_last.last_decoded_sample = lo;
-
- done:
- set_file_offset(f, restore_offset);
- }
- return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
-}
-
-float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
-{
- return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
-}
-
-
-
-int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
-{
- int len, right,left,i;
- if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
-
- if (!vorbis_decode_packet(f, &len, &left, &right)) {
- f->channel_buffer_start = f->channel_buffer_end = 0;
- return 0;
- }
-
- len = vorbis_finish_frame(f, len, left, right);
- for (i=0; i < f->channels; ++i)
- f->outputs[i] = f->channel_buffers[i] + left;
-
- f->channel_buffer_start = left;
- f->channel_buffer_end = left+len;
-
- if (channels) *channels = f->channels;
- if (output) *output = f->outputs;
- return len;
-}
-
-#ifndef STB_VORBIS_NO_STDIO
-
-stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length)
-{
- stb_vorbis *f, p;
- vorbis_init(&p, alloc);
- p.f = file;
- p.f_start = (uint32) ftell(file);
- p.stream_len = length;
- p.close_on_free = close_on_free;
- if (start_decoder(&p)) {
- f = vorbis_alloc(&p);
- if (f) {
- *f = p;
- vorbis_pump_first_frame(f);
- return f;
- }
- }
- if (error) *error = p.error;
- vorbis_deinit(&p);
- return NULL;
-}
-
-stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)
-{
- unsigned int len, start;
- start = (unsigned int) ftell(file);
- fseek(file, 0, SEEK_END);
- len = (unsigned int) (ftell(file) - start);
- fseek(file, start, SEEK_SET);
- return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
-}
-
-stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc)
-{
- FILE *f;
-#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)
- if (0 != fopen_s(&f, filename, "rb"))
- f = NULL;
-#else
- f = fopen(filename, "rb");
-#endif
- if (f)
- return stb_vorbis_open_file(f, TRUE, error, alloc);
- if (error) *error = VORBIS_file_open_failure;
- return NULL;
-}
-#endif // STB_VORBIS_NO_STDIO
-
-stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)
-{
- stb_vorbis *f, p;
- if (data == NULL) return NULL;
- vorbis_init(&p, alloc);
- p.stream = (uint8 *) data;
- p.stream_end = (uint8 *) data + len;
- p.stream_start = (uint8 *) p.stream;
- p.stream_len = len;
- p.push_mode = FALSE;
- if (start_decoder(&p)) {
- f = vorbis_alloc(&p);
- if (f) {
- *f = p;
- vorbis_pump_first_frame(f);
- if (error) *error = VORBIS__no_error;
- return f;
- }
- }
- if (error) *error = p.error;
- vorbis_deinit(&p);
- return NULL;
-}
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-#define PLAYBACK_MONO 1
-#define PLAYBACK_LEFT 2
-#define PLAYBACK_RIGHT 4
-
-#define L (PLAYBACK_LEFT | PLAYBACK_MONO)
-#define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
-#define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
-
-static int8 channel_position[7][6] =
-{
- { 0 },
- { C },
- { L, R },
- { L, C, R },
- { L, R, L, R },
- { L, C, R, L, R },
- { L, C, R, L, R, C },
-};
-
-
-#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
- typedef union {
- float f;
- int i;
- } float_conv;
- typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
- #define FASTDEF(x) float_conv x
- // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
- #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
- #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
- #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
- #define check_endianness()
-#else
- #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
- #define check_endianness()
- #define FASTDEF(x)
-#endif
-
-static void copy_samples(short *dest, float *src, int len)
-{
- int i;
- check_endianness();
- for (i=0; i < len; ++i) {
- FASTDEF(temp);
- int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- dest[i] = v;
- }
-}
-
-static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
-{
- #define BUFFER_SIZE 32
- float buffer[BUFFER_SIZE];
- int i,j,o,n = BUFFER_SIZE;
- check_endianness();
- for (o = 0; o < len; o += BUFFER_SIZE) {
- memset(buffer, 0, sizeof(buffer));
- if (o + n > len) n = len - o;
- for (j=0; j < num_c; ++j) {
- if (channel_position[num_c][j] & mask) {
- for (i=0; i < n; ++i)
- buffer[i] += data[j][d_offset+o+i];
- }
- }
- for (i=0; i < n; ++i) {
- FASTDEF(temp);
- int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- output[o+i] = v;
- }
- }
-}
-
-static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
-{
- #define BUFFER_SIZE 32
- float buffer[BUFFER_SIZE];
- int i,j,o,n = BUFFER_SIZE >> 1;
- // o is the offset in the source data
- check_endianness();
- for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
- // o2 is the offset in the output data
- int o2 = o << 1;
- memset(buffer, 0, sizeof(buffer));
- if (o + n > len) n = len - o;
- for (j=0; j < num_c; ++j) {
- int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
- if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
- for (i=0; i < n; ++i) {
- buffer[i*2+0] += data[j][d_offset+o+i];
- buffer[i*2+1] += data[j][d_offset+o+i];
- }
- } else if (m == PLAYBACK_LEFT) {
- for (i=0; i < n; ++i) {
- buffer[i*2+0] += data[j][d_offset+o+i];
- }
- } else if (m == PLAYBACK_RIGHT) {
- for (i=0; i < n; ++i) {
- buffer[i*2+1] += data[j][d_offset+o+i];
- }
- }
- }
- for (i=0; i < (n<<1); ++i) {
- FASTDEF(temp);
- int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- output[o2+i] = v;
- }
- }
-}
-
-static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
-{
- int i;
- if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
- static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
- for (i=0; i < buf_c; ++i)
- compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
- } else {
- int limit = buf_c < data_c ? buf_c : data_c;
- for (i=0; i < limit; ++i)
- copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
- for ( ; i < buf_c; ++i)
- memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
- }
-}
-
-int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
-{
- float **output = NULL;
- int len = stb_vorbis_get_frame_float(f, NULL, &output);
- if (len > num_samples) len = num_samples;
- if (len)
- convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
- return len;
-}
-
-static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
-{
- int i;
- check_endianness();
- if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
- assert(buf_c == 2);
- for (i=0; i < buf_c; ++i)
- compute_stereo_samples(buffer, data_c, data, d_offset, len);
- } else {
- int limit = buf_c < data_c ? buf_c : data_c;
- int j;
- for (j=0; j < len; ++j) {
- for (i=0; i < limit; ++i) {
- FASTDEF(temp);
- float f = data[i][d_offset+j];
- int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- *buffer++ = v;
- }
- for ( ; i < buf_c; ++i)
- *buffer++ = 0;
- }
- }
-}
-
-int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
-{
- float **output;
- int len;
- if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
- len = stb_vorbis_get_frame_float(f, NULL, &output);
- if (len) {
- if (len*num_c > num_shorts) len = num_shorts / num_c;
- convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
- }
- return len;
-}
-
-int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
-{
- float **outputs;
- int len = num_shorts / channels;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < len) {
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= len) k = len - n;
- if (k)
- convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
- buffer += k*channels;
- n += k;
- f->channel_buffer_start += k;
- if (n == len) break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
- }
- return n;
-}
-
-int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
-{
- float **outputs;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < len) {
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= len) k = len - n;
- if (k)
- convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
- n += k;
- f->channel_buffer_start += k;
- if (n == len) break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
- }
- return n;
-}
-
-#ifndef STB_VORBIS_NO_STDIO
-int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)
-{
- int data_len, offset, total, limit, error;
- short *data;
- stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
- if (v == NULL) return -1;
- limit = v->channels * 4096;
- *channels = v->channels;
- if (sample_rate)
- *sample_rate = v->sample_rate;
- offset = data_len = 0;
- total = limit;
- data = (short *) malloc(total * sizeof(*data));
- if (data == NULL) {
- stb_vorbis_close(v);
- return -2;
- }
- for (;;) {
- int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
- if (n == 0) break;
- data_len += n;
- offset += n * v->channels;
- if (offset + limit > total) {
- short *data2;
- total *= 2;
- data2 = (short *) realloc(data, total * sizeof(*data));
- if (data2 == NULL) {
- free(data);
- stb_vorbis_close(v);
- return -2;
- }
- data = data2;
- }
- }
- *output = data;
- stb_vorbis_close(v);
- return data_len;
-}
-#endif // NO_STDIO
-
-int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)
-{
- int data_len, offset, total, limit, error;
- short *data;
- stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
- if (v == NULL) return -1;
- limit = v->channels * 4096;
- *channels = v->channels;
- if (sample_rate)
- *sample_rate = v->sample_rate;
- offset = data_len = 0;
- total = limit;
- data = (short *) malloc(total * sizeof(*data));
- if (data == NULL) {
- stb_vorbis_close(v);
- return -2;
- }
- for (;;) {
- int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
- if (n == 0) break;
- data_len += n;
- offset += n * v->channels;
- if (offset + limit > total) {
- short *data2;
- total *= 2;
- data2 = (short *) realloc(data, total * sizeof(*data));
- if (data2 == NULL) {
- free(data);
- stb_vorbis_close(v);
- return -2;
- }
- data = data2;
- }
- }
- *output = data;
- stb_vorbis_close(v);
- return data_len;
-}
-#endif // STB_VORBIS_NO_INTEGER_CONVERSION
-
-int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
-{
- float **outputs;
- int len = num_floats / channels;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < len) {
- int i,j;
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= len) k = len - n;
- for (j=0; j < k; ++j) {
- for (i=0; i < z; ++i)
- *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
- for ( ; i < channels; ++i)
- *buffer++ = 0;
- }
- n += k;
- f->channel_buffer_start += k;
- if (n == len)
- break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
- break;
- }
- return n;
-}
-
-int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
-{
- float **outputs;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < num_samples) {
- int i;
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= num_samples) k = num_samples - n;
- if (k) {
- for (i=0; i < z; ++i)
- memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);
- for ( ; i < channels; ++i)
- memset(buffer[i]+n, 0, sizeof(float) * k);
- }
- n += k;
- f->channel_buffer_start += k;
- if (n == num_samples)
- break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
- break;
- }
- return n;
-}
-#endif // STB_VORBIS_NO_PULLDATA_API
-
-/* Version history
- 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223
- found with Mayhem by ForAllSecure
- 1.16 - 2019-03-04 - fix warnings
- 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
- 1.14 - 2018-02-11 - delete bogus dealloca usage
- 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
- 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
- 1.11 - 2017-07-23 - fix MinGW compilation
- 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
- 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version
- 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks;
- avoid discarding last frame of audio data
- 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API
- some more crash fixes when out of memory or with corrupt files
- 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
- some crash fixes when out of memory or with corrupt files
- 1.05 - 2015-04-19 - don't define __forceinline if it's redundant
- 1.04 - 2014-08-27 - fix missing const-correct case in API
- 1.03 - 2014-08-07 - Warning fixes
- 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows
- 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float
- 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel
- (API change) report sample rate for decode-full-file funcs
- 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
- 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
- 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
- 0.99993 - remove assert that fired on legal files with empty tables
- 0.99992 - rewind-to-start
- 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
- 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
- 0.9998 - add a full-decode function with a memory source
- 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
- 0.9996 - query length of vorbis stream in samples/seconds
- 0.9995 - bugfix to another optimization that only happened in certain files
- 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
- 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
- 0.9992 - performance improvement of IMDCT; now performs close to reference implementation
- 0.9991 - performance improvement of IMDCT
- 0.999 - (should have been 0.9990) performance improvement of IMDCT
- 0.998 - no-CRT support from Casey Muratori
- 0.997 - bugfixes for bugs found by Terje Mathisen
- 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
- 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
- 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
- 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
- 0.992 - fixes for MinGW warning
- 0.991 - turn fast-float-conversion on by default
- 0.990 - fix push-mode seek recovery if you seek into the headers
- 0.98b - fix to bad release of 0.98
- 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
- 0.97 - builds under c++ (typecasting, don't use 'class' keyword)
- 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
- 0.95 - clamping code for 16-bit functions
- 0.94 - not publically released
- 0.93 - fixed all-zero-floor case (was decoding garbage)
- 0.92 - fixed a memory leak
- 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
- 0.90 - first public release
-*/
-
-#endif // STB_VORBIS_HEADER_ONLY
-
-
-/*
-------------------------------------------------------------------------------
-This software is available under 2 licenses -- choose whichever you prefer.
-------------------------------------------------------------------------------
-ALTERNATIVE A - MIT License
-Copyright (c) 2017 Sean Barrett
-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.
-------------------------------------------------------------------------------
-ALTERNATIVE B - Public Domain (www.unlicense.org)
-This is free and unencumbered software released into the public domain.
-Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
-software, either in source code form or as a compiled binary, for any purpose,
-commercial or non-commercial, and by any means.
-In jurisdictions that recognize copyright laws, the author or authors of this
-software dedicate any and all copyright interest in the software to the public
-domain. We make this dedication for the benefit of the public at large and to
-the detriment of our heirs and successors. We intend this dedication to be an
-overt act of relinquishment in perpetuity of all present and future rights to
-this software under copyright law.
-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 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.
-------------------------------------------------------------------------------
-*/
diff --git a/thirdparty/misc/stb_vorbis.h b/thirdparty/misc/stb_vorbis.h
deleted file mode 100644
index 357efcd5fc..0000000000
--- a/thirdparty/misc/stb_vorbis.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#define STB_VORBIS_HEADER_ONLY
-#include "stb_vorbis.c"