diff options
Diffstat (limited to 'modules/gltf')
50 files changed, 1410 insertions, 586 deletions
diff --git a/modules/gltf/SCsub b/modules/gltf/SCsub index 71f3ba58d9..d1f337715f 100644 --- a/modules/gltf/SCsub +++ b/modules/gltf/SCsub @@ -7,7 +7,7 @@ env_gltf = env_modules.Clone() # Godot source files env_gltf.add_source_files(env.modules_sources, "*.cpp") -env_gltf.add_source_files(env.modules_sources, "extensions/*.cpp") env_gltf.add_source_files(env.modules_sources, "structures/*.cpp") -if env["tools"]: +SConscript("extensions/SCsub") +if env.editor_build: env_gltf.add_source_files(env.modules_sources, "editor/*.cpp") diff --git a/modules/gltf/config.py b/modules/gltf/config.py index 189b5a831a..130c06d264 100644 --- a/modules/gltf/config.py +++ b/modules/gltf/config.py @@ -26,6 +26,7 @@ def get_doc_classes(): "GLTFSpecGloss", "GLTFState", "GLTFTexture", + "GLTFTextureSampler", ] diff --git a/modules/gltf/doc_classes/GLTFCamera.xml b/modules/gltf/doc_classes/GLTFCamera.xml index 9b9eff6141..49efaa1564 100644 --- a/modules/gltf/doc_classes/GLTFCamera.xml +++ b/modules/gltf/doc_classes/GLTFCamera.xml @@ -1,19 +1,58 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFCamera" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + Represents a GLTF camera. </brief_description> <description> + Represents a camera as defined by the base GLTF spec. </description> <tutorials> + <link title="GLTF camera detailed specification">https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-camera</link> + <link title="GLTF camera spec and example file">https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_015_SimpleCameras.md</link> </tutorials> + <methods> + <method name="from_dictionary" qualifiers="static"> + <return type="GLTFCamera" /> + <param index="0" name="dictionary" type="Dictionary" /> + <description> + Creates a new GLTFCamera instance by parsing the given [Dictionary]. + </description> + </method> + <method name="from_node" qualifiers="static"> + <return type="GLTFCamera" /> + <param index="0" name="camera_node" type="Camera3D" /> + <description> + Create a new GLTFCamera instance from the given Godot [Camera3D] node. + </description> + </method> + <method name="to_dictionary" qualifiers="const"> + <return type="Dictionary" /> + <description> + Serializes this GLTFCamera instance into a [Dictionary]. + </description> + </method> + <method name="to_node" qualifiers="const"> + <return type="Camera3D" /> + <description> + Converts this GLTFCamera instance into a Godot [Camera3D] node. + </description> + </method> + </methods> <members> <member name="depth_far" type="float" setter="set_depth_far" getter="get_depth_far" default="4000.0"> + The distance to the far culling boundary for this camera relative to its local Z axis, in meters. This maps to GLTF's [code]zfar[/code] property. </member> <member name="depth_near" type="float" setter="set_depth_near" getter="get_depth_near" default="0.05"> + The distance to the near culling boundary for this camera relative to its local Z axis, in meters. This maps to GLTF's [code]znear[/code] property. </member> - <member name="fov_size" type="float" setter="set_fov_size" getter="get_fov_size" default="75.0"> + <member name="fov" type="float" setter="set_fov" getter="get_fov" default="1.309"> + The FOV of the camera. This class and GLTF define the camera FOV in radians, while Godot uses degrees. This maps to GLTF's [code]yfov[/code] property. This value is only used for perspective cameras, when [member perspective] is true. </member> <member name="perspective" type="bool" setter="set_perspective" getter="get_perspective" default="true"> + Whether or not the camera is in perspective mode. If false, the camera is in orthographic/orthogonal mode. This maps to GLTF's camera [code]type[/code] property. See [member Camera3D.projection] and the GLTF spec for more information. + </member> + <member name="size_mag" type="float" setter="set_size_mag" getter="get_size_mag" default="0.5"> + The size of the camera. This class and GLTF define the camera size magnitude as a radius in meters, while Godot defines it as a diameter in meters. This maps to GLTF's [code]ymag[/code] property. This value is only used for orthographic/orthogonal cameras, when [member perspective] is false. </member> </members> </class> diff --git a/modules/gltf/doc_classes/GLTFDocument.xml b/modules/gltf/doc_classes/GLTFDocument.xml index 3cd0f5c0f9..1967df5218 100644 --- a/modules/gltf/doc_classes/GLTFDocument.xml +++ b/modules/gltf/doc_classes/GLTFDocument.xml @@ -16,6 +16,8 @@ <param index="3" name="flags" type="int" default="0" /> <param index="4" name="bake_fps" type="int" default="30" /> <description> + Takes a [PackedByteArray] defining a gLTF and returns a [GLTFState] object through the [param state] parameter. + [b]Note:[/b] The [param base_path] tells [method append_from_buffer] where to find dependencies and can be empty. </description> </method> <method name="append_from_file"> @@ -26,6 +28,8 @@ <param index="3" name="bake_fps" type="int" default="30" /> <param index="4" name="base_path" type="String" default="""" /> <description> + Takes a path to a gLTF file and returns a [GLTFState] object through the [param state] parameter. + [b]Note:[/b] The [param base_path] tells [method append_from_file] where to find dependencies and can be empty. </description> </method> <method name="append_from_scene"> @@ -35,12 +39,14 @@ <param index="2" name="flags" type="int" default="0" /> <param index="3" name="bake_fps" type="int" default="30" /> <description> + Takes a Godot Engine scene node and returns a [GLTFState] object through the [param state] parameter. </description> </method> <method name="generate_buffer"> <return type="PackedByteArray" /> <param index="0" name="state" type="GLTFState" /> <description> + Takes a [GLTFState] object through the [param state] parameter and returns a gLTF [PackedByteArray]. </description> </method> <method name="generate_scene"> @@ -48,6 +54,16 @@ <param index="0" name="state" type="GLTFState" /> <param index="1" name="bake_fps" type="int" default="30" /> <description> + Takes a [GLTFState] object through the [param state] parameter and returns a Godot Engine scene node. + </description> + </method> + <method name="register_gltf_document_extension" qualifiers="static"> + <return type="void" /> + <param index="0" name="extension" type="GLTFDocumentExtension" /> + <param index="1" name="first_priority" type="bool" default="false" /> + <description> + Registers this GLTFDocumentExtension instance with GLTFDocument. If [param first_priority] is true, this extension will be ran first. Otherwise, it will be ran last. + [b]Note:[/b] Like GLTFDocument itself, all GLTFDocumentExtension classes must be stateless in order to function properly. If you need to store data, use the [code]set_additional_data[/code] and [code]get_additional_data[/code] methods in [GLTFState] or [GLTFNode]. </description> </method> <method name="write_to_filesystem"> @@ -55,11 +71,9 @@ <param index="0" name="state" type="GLTFState" /> <param index="1" name="path" type="String" /> <description> + Takes a [GLTFState] object through the [param state] parameter and writes a glTF file to the filesystem. + [b]Note:[/b] The extension of the glTF file determines if it is a .glb binary file or a .gltf file. </description> </method> </methods> - <members> - <member name="extensions" type="GLTFDocumentExtension[]" setter="set_extensions" getter="get_extensions" default="[]"> - </member> - </members> </class> diff --git a/modules/gltf/doc_classes/GLTFDocumentExtension.xml b/modules/gltf/doc_classes/GLTFDocumentExtension.xml index d2a9022445..87d3d9bcb0 100644 --- a/modules/gltf/doc_classes/GLTFDocumentExtension.xml +++ b/modules/gltf/doc_classes/GLTFDocumentExtension.xml @@ -1,12 +1,26 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFDocumentExtension" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + [GLTFDocument] extension class. </brief_description> <description> + Extends the functionality of the [GLTFDocument] class by allowing you to run arbitrary code at various stages of GLTF import or export. + To use, make a new class extending GLTFDocumentExtension, override any methods you need, make an instance of your class, and register it using [method GLTFDocument.register_gltf_document_extension]. + [b]Note:[/b] Like GLTFDocument itself, all GLTFDocumentExtension classes must be stateless in order to function properly. If you need to store data, use the [code]set_additional_data[/code] and [code]get_additional_data[/code] methods in [GLTFState] or [GLTFNode]. </description> <tutorials> </tutorials> <methods> + <method name="_convert_scene_node" qualifiers="virtual"> + <return type="void" /> + <param index="0" name="state" type="GLTFState" /> + <param index="1" name="gltf_node" type="GLTFNode" /> + <param index="2" name="scene_node" type="Node" /> + <description> + Part of the export process. This method is run after [method _export_preflight] and before [method _export_node]. + Runs when converting the data from a Godot scene node. This method can be used to process the Godot scene node data into a format that can be used by [method _export_node]. + </description> + </method> <method name="_export_node" qualifiers="virtual"> <return type="int" /> <param index="0" name="state" type="GLTFState" /> @@ -14,18 +28,41 @@ <param index="2" name="json" type="Dictionary" /> <param index="3" name="node" type="Node" /> <description> + Part of the export process. This method is run after [method _convert_scene_node] and before [method _export_post]. + This method can be used to modify the final JSON of each node. </description> </method> <method name="_export_post" qualifiers="virtual"> <return type="int" /> <param index="0" name="state" type="GLTFState" /> <description> + Part of the export process. This method is run last, after all other parts of the export process. + This method can be used to modify the final JSON of the generated GLTF file. </description> </method> <method name="_export_preflight" qualifiers="virtual"> <return type="int" /> <param index="0" name="root" type="Node" /> <description> + Part of the export process. This method is run first, before all other parts of the export process. + The return value is used to determine if this GLTFDocumentExtension class should be used for exporting a given GLTF file. If [constant OK], the export will use this GLTFDocumentExtension class. If not overridden, [constant OK] is returned. + </description> + </method> + <method name="_generate_scene_node" qualifiers="virtual"> + <return type="Node3D" /> + <param index="0" name="state" type="GLTFState" /> + <param index="1" name="gltf_node" type="GLTFNode" /> + <param index="2" name="scene_parent" type="Node" /> + <description> + Part of the import process. This method is run after [method _parse_node_extensions] and before [method _import_post_parse]. + Runs when generating a Godot scene node from a GLTFNode. The returned node will be added to the scene tree. Multiple nodes can be generated in this step if they are added as a child of the returned node. + </description> + </method> + <method name="_get_supported_extensions" qualifiers="virtual"> + <return type="PackedStringArray" /> + <description> + Part of the import process. This method is run after [method _import_preflight] and before [method _parse_node_extensions]. + Returns an array of the GLTF extensions supported by this GLTFDocumentExtension class. This is used to validate if a GLTF file with required extensions can be loaded. </description> </method> <method name="_import_node" qualifiers="virtual"> @@ -35,6 +72,8 @@ <param index="2" name="json" type="Dictionary" /> <param index="3" name="node" type="Node" /> <description> + Part of the import process. This method is run after [method _import_post_parse] and before [method _import_post]. + This method can be used to make modifications to each of the generated Godot scene nodes. </description> </method> <method name="_import_post" qualifiers="virtual"> @@ -42,18 +81,35 @@ <param index="0" name="state" type="GLTFState" /> <param index="1" name="root" type="Node" /> <description> + Part of the import process. This method is run last, after all other parts of the import process. + This method can be used to modify the final Godot scene generated by the import process. </description> </method> <method name="_import_post_parse" qualifiers="virtual"> <return type="int" /> <param index="0" name="state" type="GLTFState" /> <description> + Part of the import process. This method is run after [method _generate_scene_node] and before [method _import_node]. + This method can be used to modify any of the data imported so far, including any scene nodes, before running the final per-node import step. </description> </method> <method name="_import_preflight" qualifiers="virtual"> <return type="int" /> <param index="0" name="state" type="GLTFState" /> + <param index="1" name="extensions" type="PackedStringArray" /> + <description> + Part of the import process. This method is run first, before all other parts of the import process. + The return value is used to determine if this GLTFDocumentExtension class should be used for importing a given GLTF file. If [constant OK], the import will use this GLTFDocumentExtension class. If not overridden, [constant OK] is returned. + </description> + </method> + <method name="_parse_node_extensions" qualifiers="virtual"> + <return type="int" /> + <param index="0" name="state" type="GLTFState" /> + <param index="1" name="gltf_node" type="GLTFNode" /> + <param index="2" name="extensions" type="Dictionary" /> <description> + Part of the import process. This method is run after [method _get_supported_extensions] and before [method _generate_scene_node]. + Runs when parsing the node extensions of a GLTFNode. This method can be used to process the extension JSON data into a format that can be used by [method _generate_scene_node]. </description> </method> </methods> diff --git a/modules/gltf/doc_classes/GLTFLight.xml b/modules/gltf/doc_classes/GLTFLight.xml index 354cd48a06..7fd59e14bc 100644 --- a/modules/gltf/doc_classes/GLTFLight.xml +++ b/modules/gltf/doc_classes/GLTFLight.xml @@ -1,11 +1,42 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFLight" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + Represents a GLTF light. </brief_description> <description> + Represents a light as defined by the [code]KHR_lights_punctual[/code] GLTF extension. </description> <tutorials> + <link title="KHR_lights_punctual GLTF extension spec">https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_lights_punctual</link> </tutorials> + <methods> + <method name="from_dictionary" qualifiers="static"> + <return type="GLTFLight" /> + <param index="0" name="dictionary" type="Dictionary" /> + <description> + Creates a new GLTFLight instance by parsing the given [Dictionary]. + </description> + </method> + <method name="from_node" qualifiers="static"> + <return type="GLTFLight" /> + <param index="0" name="light_node" type="Light3D" /> + <description> + Create a new GLTFLight instance from the given Godot [Light3D] node. + </description> + </method> + <method name="to_dictionary" qualifiers="const"> + <return type="Dictionary" /> + <description> + Serializes this GLTFLight instance into a [Dictionary]. + </description> + </method> + <method name="to_node" qualifiers="const"> + <return type="Light3D" /> + <description> + Converts this GLTFLight instance into a Godot [Light3D] node. + </description> + </method> + </methods> <members> <member name="color" type="Color" setter="set_color" getter="get_color" default="Color(1, 1, 1, 1)"> The [Color] of the light. Defaults to white. A black color causes the light to have no effect. diff --git a/modules/gltf/doc_classes/GLTFMesh.xml b/modules/gltf/doc_classes/GLTFMesh.xml index bac351cc20..4d2df872ea 100644 --- a/modules/gltf/doc_classes/GLTFMesh.xml +++ b/modules/gltf/doc_classes/GLTFMesh.xml @@ -9,7 +9,7 @@ <members> <member name="blend_weights" type="PackedFloat32Array" setter="set_blend_weights" getter="get_blend_weights" default="PackedFloat32Array()"> </member> - <member name="instance_materials" type="Array" setter="set_instance_materials" getter="get_instance_materials" default="[]"> + <member name="instance_materials" type="Material[]" setter="set_instance_materials" getter="get_instance_materials" default="[]"> </member> <member name="mesh" type="ImporterMesh" setter="set_mesh" getter="get_mesh"> </member> diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml index e933e6046a..8e48066623 100644 --- a/modules/gltf/doc_classes/GLTFNode.xml +++ b/modules/gltf/doc_classes/GLTFNode.xml @@ -1,11 +1,33 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFNode" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + GLTF node class. </brief_description> <description> + Represents a GLTF node. GLTF nodes may have names, transforms, children (other GLTF nodes), and more specialized properties (represented by their own classes). </description> <tutorials> + <link title="GLTF scene and node spec">https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_004_ScenesNodes.md"</link> </tutorials> + <methods> + <method name="get_additional_data"> + <return type="Variant" /> + <param index="0" name="extension_name" type="StringName" /> + <description> + Gets additional arbitrary data in this [GLTFNode] instance. This can be used to keep per-node state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the return value can be anything you set. If nothing was set, the return value is null. + </description> + </method> + <method name="set_additional_data"> + <return type="void" /> + <param index="0" name="extension_name" type="StringName" /> + <param index="1" name="additional_data" type="Variant" /> + <description> + Sets additional arbitrary data in this [GLTFNode] instance. This can be used to keep per-node state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The first argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the second argument can be anything you want. + </description> + </method> + </methods> <members> <member name="camera" type="int" setter="set_camera" getter="get_camera" default="-1"> </member> diff --git a/modules/gltf/doc_classes/GLTFSkeleton.xml b/modules/gltf/doc_classes/GLTFSkeleton.xml index e1276d0e21..d6ec09f113 100644 --- a/modules/gltf/doc_classes/GLTFSkeleton.xml +++ b/modules/gltf/doc_classes/GLTFSkeleton.xml @@ -29,7 +29,7 @@ </description> </method> <method name="get_unique_names"> - <return type="Array" /> + <return type="String[]" /> <description> </description> </method> @@ -41,7 +41,7 @@ </method> <method name="set_unique_names"> <return type="void" /> - <param index="0" name="unique_names" type="Array" /> + <param index="0" name="unique_names" type="String[]" /> <description> </description> </method> diff --git a/modules/gltf/doc_classes/GLTFSkin.xml b/modules/gltf/doc_classes/GLTFSkin.xml index 5abdf33360..4de32857b5 100644 --- a/modules/gltf/doc_classes/GLTFSkin.xml +++ b/modules/gltf/doc_classes/GLTFSkin.xml @@ -8,7 +8,7 @@ </tutorials> <methods> <method name="get_inverse_binds"> - <return type="Array" /> + <return type="Transform3D[]" /> <description> </description> </method> @@ -24,7 +24,7 @@ </method> <method name="set_inverse_binds"> <return type="void" /> - <param index="0" name="inverse_binds" type="Array" /> + <param index="0" name="inverse_binds" type="Transform3D[]" /> <description> </description> </method> diff --git a/modules/gltf/doc_classes/GLTFSpecGloss.xml b/modules/gltf/doc_classes/GLTFSpecGloss.xml index 8433cf8dd7..8882e48257 100644 --- a/modules/gltf/doc_classes/GLTFSpecGloss.xml +++ b/modules/gltf/doc_classes/GLTFSpecGloss.xml @@ -1,21 +1,29 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFSpecGloss" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + Archived GLTF extension for specular/glossy materials. </brief_description> <description> + KHR_materials_pbrSpecularGlossiness is an archived GLTF extension. This means that it is deprecated and not recommended for new files. However, it is still supported for loading old files. </description> <tutorials> + <link title="KHR_materials_pbrSpecularGlossiness GLTF extension spec">https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness</link> </tutorials> <members> <member name="diffuse_factor" type="Color" setter="set_diffuse_factor" getter="get_diffuse_factor" default="Color(1, 1, 1, 1)"> + The reflected diffuse factor of the material. </member> <member name="diffuse_img" type="Image" setter="set_diffuse_img" getter="get_diffuse_img"> + The diffuse texture. </member> <member name="gloss_factor" type="float" setter="set_gloss_factor" getter="get_gloss_factor" default="1.0"> + The glossiness or smoothness of the material. </member> <member name="spec_gloss_img" type="Image" setter="set_spec_gloss_img" getter="get_spec_gloss_img"> + The specular-glossiness texture. </member> <member name="specular_factor" type="Color" setter="set_specular_factor" getter="get_specular_factor" default="Color(1, 1, 1, 1)"> + The specular RGB color of the material. The alpha channel is unused. </member> </members> </class> diff --git a/modules/gltf/doc_classes/GLTFState.xml b/modules/gltf/doc_classes/GLTFState.xml index adf51ab59e..d0740cf7ca 100644 --- a/modules/gltf/doc_classes/GLTFState.xml +++ b/modules/gltf/doc_classes/GLTFState.xml @@ -7,11 +7,27 @@ <tutorials> </tutorials> <methods> + <method name="add_used_extension"> + <return type="void" /> + <param index="0" name="extension_name" type="String" /> + <param index="1" name="required" type="bool" /> + <description> + Appends an extension to the list of extensions used by this GLTF file during serialization. If [param required] is true, the extension will also be added to the list of required extensions. Do not run this in [method GLTFDocumentExtension._export_post], as that stage is too late to add extensions. The final list is sorted alphabetically. + </description> + </method> <method name="get_accessors"> - <return type="Array" /> + <return type="GLTFAccessor[]" /> <description> </description> </method> + <method name="get_additional_data"> + <return type="Variant" /> + <param index="0" name="extension_name" type="StringName" /> + <description> + Gets additional arbitrary data in this [GLTFState] instance. This can be used to keep per-file state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the return value can be anything you set. If nothing was set, the return value is null. + </description> + </method> <method name="get_animation_player"> <return type="AnimationPlayer" /> <param index="0" name="idx" type="int" /> @@ -25,42 +41,42 @@ </description> </method> <method name="get_animations"> - <return type="Array" /> + <return type="GLTFAnimation[]" /> <description> </description> </method> <method name="get_buffer_views"> - <return type="Array" /> + <return type="GLTFBufferView[]" /> <description> </description> </method> <method name="get_cameras"> - <return type="Array" /> + <return type="GLTFCamera[]" /> <description> </description> </method> <method name="get_images"> - <return type="Array" /> + <return type="Texture2D[]" /> <description> </description> </method> <method name="get_lights"> - <return type="Array" /> + <return type="GLTFLight[]" /> <description> </description> </method> <method name="get_materials"> - <return type="Array" /> + <return type="BaseMaterial3D[]" /> <description> </description> </method> <method name="get_meshes"> - <return type="Array" /> + <return type="GLTFMesh[]" /> <description> </description> </method> <method name="get_nodes"> - <return type="Array" /> + <return type="GLTFNode[]" /> <description> </description> </method> @@ -76,81 +92,96 @@ </description> </method> <method name="get_skeletons"> - <return type="Array" /> + <return type="GLTFSkeleton[]" /> <description> </description> </method> <method name="get_skins"> - <return type="Array" /> + <return type="GLTFSkin[]" /> + <description> + </description> + </method> + <method name="get_texture_samplers"> + <return type="GLTFTextureSampler[]" /> <description> + Retrieves the array of texture samplers that are used by the textures contained in the GLTF. </description> </method> <method name="get_textures"> - <return type="Array" /> + <return type="GLTFTexture[]" /> <description> </description> </method> <method name="get_unique_animation_names"> - <return type="Array" /> + <return type="String[]" /> <description> </description> </method> <method name="get_unique_names"> - <return type="Array" /> + <return type="String[]" /> <description> </description> </method> <method name="set_accessors"> <return type="void" /> - <param index="0" name="accessors" type="Array" /> + <param index="0" name="accessors" type="GLTFAccessor[]" /> + <description> + </description> + </method> + <method name="set_additional_data"> + <return type="void" /> + <param index="0" name="extension_name" type="StringName" /> + <param index="1" name="additional_data" type="Variant" /> <description> + Sets additional arbitrary data in this [GLTFState] instance. This can be used to keep per-file state data in [GLTFDocumentExtension] classes, which is important because they are stateless. + The first argument should be the [GLTFDocumentExtension] name (does not have to match the extension name in the GLTF file), and the second argument can be anything you want. </description> </method> <method name="set_animations"> <return type="void" /> - <param index="0" name="animations" type="Array" /> + <param index="0" name="animations" type="GLTFAnimation[]" /> <description> </description> </method> <method name="set_buffer_views"> <return type="void" /> - <param index="0" name="buffer_views" type="Array" /> + <param index="0" name="buffer_views" type="GLTFBufferView[]" /> <description> </description> </method> <method name="set_cameras"> <return type="void" /> - <param index="0" name="cameras" type="Array" /> + <param index="0" name="cameras" type="GLTFCamera[]" /> <description> </description> </method> <method name="set_images"> <return type="void" /> - <param index="0" name="images" type="Array" /> + <param index="0" name="images" type="Texture2D[]" /> <description> </description> </method> <method name="set_lights"> <return type="void" /> - <param index="0" name="lights" type="Array" /> + <param index="0" name="lights" type="GLTFLight[]" /> <description> </description> </method> <method name="set_materials"> <return type="void" /> - <param index="0" name="materials" type="Array" /> + <param index="0" name="materials" type="BaseMaterial3D[]" /> <description> </description> </method> <method name="set_meshes"> <return type="void" /> - <param index="0" name="meshes" type="Array" /> + <param index="0" name="meshes" type="GLTFMesh[]" /> <description> </description> </method> <method name="set_nodes"> <return type="void" /> - <param index="0" name="nodes" type="Array" /> + <param index="0" name="nodes" type="GLTFNode[]" /> <description> </description> </method> @@ -162,31 +193,38 @@ </method> <method name="set_skeletons"> <return type="void" /> - <param index="0" name="skeletons" type="Array" /> + <param index="0" name="skeletons" type="GLTFSkeleton[]" /> <description> </description> </method> <method name="set_skins"> <return type="void" /> - <param index="0" name="skins" type="Array" /> + <param index="0" name="skins" type="GLTFSkin[]" /> + <description> + </description> + </method> + <method name="set_texture_samplers"> + <return type="void" /> + <param index="0" name="texture_samplers" type="GLTFTextureSampler[]" /> <description> + Sets the array of texture samplers that are used by the textures contained in the GLTF. </description> </method> <method name="set_textures"> <return type="void" /> - <param index="0" name="textures" type="Array" /> + <param index="0" name="textures" type="GLTFTexture[]" /> <description> </description> </method> <method name="set_unique_animation_names"> <return type="void" /> - <param index="0" name="unique_animation_names" type="Array" /> + <param index="0" name="unique_animation_names" type="String[]" /> <description> </description> </method> <method name="set_unique_names"> <return type="void" /> - <param index="0" name="unique_names" type="Array" /> + <param index="0" name="unique_names" type="String[]" /> <description> </description> </method> @@ -194,7 +232,7 @@ <members> <member name="base_path" type="String" setter="set_base_path" getter="get_base_path" default=""""> </member> - <member name="buffers" type="Array" setter="set_buffers" getter="get_buffers" default="[]"> + <member name="buffers" type="PackedByteArray[]" setter="set_buffers" getter="get_buffers" default="[]"> </member> <member name="create_animations" type="bool" setter="set_create_animations" getter="get_create_animations" default="true"> </member> @@ -206,7 +244,7 @@ </member> <member name="minor_version" type="int" setter="set_minor_version" getter="get_minor_version" default="0"> </member> - <member name="root_nodes" type="Array" setter="set_root_nodes" getter="get_root_nodes" default="[]"> + <member name="root_nodes" type="PackedInt32Array" setter="set_root_nodes" getter="get_root_nodes" default="PackedInt32Array()"> </member> <member name="scene_name" type="String" setter="set_scene_name" getter="get_scene_name" default=""""> </member> diff --git a/modules/gltf/doc_classes/GLTFTexture.xml b/modules/gltf/doc_classes/GLTFTexture.xml index c0bc424168..f4486fd504 100644 --- a/modules/gltf/doc_classes/GLTFTexture.xml +++ b/modules/gltf/doc_classes/GLTFTexture.xml @@ -7,6 +7,9 @@ <tutorials> </tutorials> <members> + <member name="sampler" type="int" setter="set_sampler" getter="get_sampler" default="-1"> + ID of the texture sampler to use when sampling the image. If -1, then the default texture sampler is used (linear filtering, and repeat wrapping in both axes). + </member> <member name="src_image" type="int" setter="set_src_image" getter="get_src_image" default="0"> </member> </members> diff --git a/modules/gltf/doc_classes/GLTFTextureSampler.xml b/modules/gltf/doc_classes/GLTFTextureSampler.xml new file mode 100644 index 0000000000..1cc69bfe73 --- /dev/null +++ b/modules/gltf/doc_classes/GLTFTextureSampler.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GLTFTextureSampler" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> + <brief_description> + Represents a GLTF texture sampler + </brief_description> + <description> + Represents a texture sampler as defined by the base GLTF spec. Texture samplers in GLTF specify how to sample data from the texture's base image, when rendering the texture on an object. + </description> + <tutorials> + </tutorials> + <members> + <member name="mag_filter" type="int" setter="set_mag_filter" getter="get_mag_filter" default="9729"> + Texture's magnification filter, used when texture appears larger on screen than the source image. + </member> + <member name="min_filter" type="int" setter="set_min_filter" getter="get_min_filter" default="9987"> + Texture's minification filter, used when the texture appears smaller on screen than the source image. + </member> + <member name="wrap_s" type="int" setter="set_wrap_s" getter="get_wrap_s" default="10497"> + Wrapping mode to use for S-axis (horizontal) texture coordinates. + </member> + <member name="wrap_t" type="int" setter="set_wrap_t" getter="get_wrap_t" default="10497"> + Wrapping mode to use for T-axis (vertical) texture coordinates. + </member> + </members> +</class> diff --git a/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h b/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h index 5af46bc752..66fd27b449 100644 --- a/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h +++ b/modules/gltf/editor/editor_scene_exporter_gltf_plugin.h @@ -36,6 +36,8 @@ #include "editor/editor_plugin.h" #include "editor_scene_importer_gltf.h" +class EditorFileDialog; + class SceneExporterGLTFPlugin : public EditorPlugin { GDCLASS(SceneExporterGLTFPlugin, EditorPlugin); diff --git a/modules/gltf/editor/editor_scene_importer_blend.cpp b/modules/gltf/editor/editor_scene_importer_blend.cpp index 8002c185c7..20c9508474 100644 --- a/modules/gltf/editor/editor_scene_importer_blend.cpp +++ b/modules/gltf/editor/editor_scene_importer_blend.cpp @@ -64,7 +64,7 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ // Escape paths to be valid Python strings to embed in the script. const String source_global = ProjectSettings::get_singleton()->globalize_path(p_path).c_escape(); - const String sink = ProjectSettings::get_singleton()->get_imported_files_path().plus_file( + const String sink = ProjectSettings::get_singleton()->get_imported_files_path().path_join( vformat("%s-%s.gltf", p_path.get_file().get_basename(), p_path.md5_text())); const String sink_global = ProjectSettings::get_singleton()->globalize_path(sink).c_escape(); @@ -77,20 +77,19 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ } else { parameters_arg += "export_extras=False,"; } - if (p_options.has(SNAME("blender/meshes/skins")) && p_options[SNAME("blender/meshes/skins")]) { + if (p_options.has(SNAME("blender/meshes/skins"))) { int32_t skins = p_options["blender/meshes/skins"]; if (skins == BLEND_BONE_INFLUENCES_NONE) { - parameters_arg += "export_all_influences=False,"; + parameters_arg += "export_skins=False,"; } else if (skins == BLEND_BONE_INFLUENCES_COMPATIBLE) { - parameters_arg += "export_all_influences=False,"; + parameters_arg += "export_all_influences=False,export_skins=True,"; } else if (skins == BLEND_BONE_INFLUENCES_ALL) { - parameters_arg += "export_all_influences=True,"; + parameters_arg += "export_all_influences=True,export_skins=True,"; } - parameters_arg += "export_skins=True,"; } else { parameters_arg += "export_skins=False,"; } - if (p_options.has(SNAME("blender/materials/export_materials")) && p_options[SNAME("blender/materials/export_materials")]) { + if (p_options.has(SNAME("blender/materials/export_materials"))) { int32_t exports = p_options["blender/materials/export_materials"]; if (exports == BLEND_MATERIAL_EXPORT_PLACEHOLDER) { parameters_arg += "export_materials='PLACEHOLDER',"; @@ -115,7 +114,7 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ } else { parameters_arg += "export_colors=False,"; } - if (p_options.has(SNAME("blender/nodes/visible")) && p_options[SNAME("blender/nodes/visible")]) { + if (p_options.has(SNAME("blender/nodes/visible"))) { int32_t visible = p_options["blender/nodes/visible"]; if (visible == BLEND_VISIBLE_VISIBLE_ONLY) { parameters_arg += "use_visible=True,"; @@ -180,28 +179,28 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ "export_format='GLTF_SEPARATE'," "export_yup=True," + parameters_arg; - String script = + String export_script = String("import bpy, sys;") + "print('Blender 3.0 or higher is required.', file=sys.stderr) if bpy.app.version < (3, 0, 0) else None;" + vformat("bpy.ops.wm.open_mainfile(filepath='%s');", source_global) + unpack_all + vformat("bpy.ops.export_scene.gltf(export_keep_originals=True,%s);", common_args); - print_verbose(script); + print_verbose(export_script); // Run script with configured Blender binary. String blender_path = EDITOR_GET("filesystem/import/blender/blender3_path"); #ifdef WINDOWS_ENABLED - blender_path = blender_path.plus_file("blender.exe"); + blender_path = blender_path.path_join("blender.exe"); #else - blender_path = blender_path.plus_file("blender"); + blender_path = blender_path.path_join("blender"); #endif List<String> args; args.push_back("--background"); args.push_back("--python-expr"); - args.push_back(script); + args.push_back(export_script); String standard_out; int ret; @@ -261,7 +260,7 @@ void EditorSceneFormatImporterBlend::get_import_options(const String &p_path, Li #define ADD_OPTION_ENUM(PATH, ENUM_HINT, VALUE) \ r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::INT, SNAME(PATH), PROPERTY_HINT_ENUM, ENUM_HINT), VALUE)); - ADD_OPTION_ENUM("blender/nodes/visible", "Visible Only,Renderable,All", BLEND_VISIBLE_ALL); + ADD_OPTION_ENUM("blender/nodes/visible", "All,Visible Only,Renderable", BLEND_VISIBLE_ALL); ADD_OPTION_BOOL("blender/nodes/punctual_lights", true); ADD_OPTION_BOOL("blender/nodes/cameras", true); ADD_OPTION_BOOL("blender/nodes/custom_properties", true); @@ -287,14 +286,14 @@ void EditorSceneFormatImporterBlend::get_import_options(const String &p_path, Li static bool _test_blender_path(const String &p_path, String *r_err = nullptr) { String path = p_path; #ifdef WINDOWS_ENABLED - path = path.plus_file("blender.exe"); + path = path.path_join("blender.exe"); #else - path = path.plus_file("blender"); + path = path.path_join("blender"); #endif #if defined(MACOS_ENABLED) if (!FileAccess::exists(path)) { - path = path.plus_file("Blender"); + path = path.path_join("Blender"); } #endif @@ -350,9 +349,7 @@ static bool _test_blender_path(const String &p_path, String *r_err = nullptr) { bool EditorFileSystemImportFormatSupportQueryBlend::is_active() const { bool blend_enabled = GLOBAL_GET("filesystem/import/blender/enabled"); - String blender_path = EDITOR_GET("filesystem/import/blender/blender3_path"); - - if (blend_enabled && !_test_blender_path(blender_path)) { + if (blend_enabled && !_test_blender_path(EDITOR_GET("filesystem/import/blender/blender3_path").operator String())) { // Intending to import Blender, but blend not configured. return true; } @@ -451,7 +448,7 @@ bool EditorFileSystemImportFormatSupportQueryBlend::query() { configure_blender_dialog->set_ok_button_text(TTR("Confirm Path")); configure_blender_dialog->set_cancel_button_text(TTR("Disable '.blend' Import")); - configure_blender_dialog->get_cancel_button()->set_tooltip(TTR("Disables Blender '.blend' files import for this project. Can be re-enabled in Project Settings.")); + configure_blender_dialog->get_cancel_button()->set_tooltip_text(TTR("Disables Blender '.blend' files import for this project. Can be re-enabled in Project Settings.")); configure_blender_dialog->connect("confirmed", callable_mp(this, &EditorFileSystemImportFormatSupportQueryBlend::_path_confirmed)); browse_dialog = memnew(EditorFileDialog); @@ -485,7 +482,7 @@ bool EditorFileSystemImportFormatSupportQueryBlend::query() { bool found = false; for (const String &path : mdfind_paths) { - found = _autodetect_path(path.plus_file("Contents/MacOS")); + found = _autodetect_path(path.path_join("Contents/MacOS")); if (found) { break; } diff --git a/modules/gltf/editor/editor_scene_importer_blend.h b/modules/gltf/editor/editor_scene_importer_blend.h index dd1c1b9889..a1485ff82e 100644 --- a/modules/gltf/editor/editor_scene_importer_blend.h +++ b/modules/gltf/editor/editor_scene_importer_blend.h @@ -45,9 +45,9 @@ class EditorSceneFormatImporterBlend : public EditorSceneFormatImporter { public: enum { + BLEND_VISIBLE_ALL, BLEND_VISIBLE_VISIBLE_ONLY, - BLEND_VISIBLE_RENDERABLE, - BLEND_VISIBLE_ALL + BLEND_VISIBLE_RENDERABLE }; enum { BLEND_BONE_INFLUENCES_NONE, diff --git a/modules/gltf/editor/editor_scene_importer_fbx.cpp b/modules/gltf/editor/editor_scene_importer_fbx.cpp index faad2d315d..017a44cccf 100644 --- a/modules/gltf/editor/editor_scene_importer_fbx.cpp +++ b/modules/gltf/editor/editor_scene_importer_fbx.cpp @@ -57,7 +57,7 @@ Node *EditorSceneFormatImporterFBX::import_scene(const String &p_path, uint32_t // enclosed in double quotes by OS::execute(), so we only need to escape those. // `c_escape_multiline()` seems to do this (escapes `\` and `"` only). const String source_global = ProjectSettings::get_singleton()->globalize_path(p_path).c_escape_multiline(); - const String sink = ProjectSettings::get_singleton()->get_imported_files_path().plus_file( + const String sink = ProjectSettings::get_singleton()->get_imported_files_path().path_join( vformat("%s-%s.glb", p_path.get_file().get_basename(), p_path.md5_text())); const String sink_global = ProjectSettings::get_singleton()->globalize_path(sink).c_escape_multiline(); diff --git a/modules/gltf/editor/editor_scene_importer_gltf.h b/modules/gltf/editor/editor_scene_importer_gltf.h index b17a1e4eaa..edca038532 100644 --- a/modules/gltf/editor/editor_scene_importer_gltf.h +++ b/modules/gltf/editor/editor_scene_importer_gltf.h @@ -33,9 +33,6 @@ #ifdef TOOLS_ENABLED -#include "../gltf_document_extension.h" -#include "../gltf_state.h" - #include "editor/import/resource_importer_scene.h" class Animation; diff --git a/modules/gltf/extensions/SCsub b/modules/gltf/extensions/SCsub new file mode 100644 index 0000000000..ad214bb79c --- /dev/null +++ b/modules/gltf/extensions/SCsub @@ -0,0 +1,9 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +env_gltf = env_modules.Clone() + +# Godot source files +env_gltf.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/gltf/gltf_document_extension.cpp b/modules/gltf/extensions/gltf_document_extension.cpp index d0bd7651e0..f997fe8f66 100644 --- a/modules/gltf/gltf_document_extension.cpp +++ b/modules/gltf/extensions/gltf_document_extension.cpp @@ -31,78 +31,103 @@ #include "gltf_document_extension.h" void GLTFDocumentExtension::_bind_methods() { - GDVIRTUAL_BIND(_import_preflight, "state"); + // Import process. + GDVIRTUAL_BIND(_import_preflight, "state", "extensions"); + GDVIRTUAL_BIND(_get_supported_extensions); + GDVIRTUAL_BIND(_parse_node_extensions, "state", "gltf_node", "extensions"); + GDVIRTUAL_BIND(_generate_scene_node, "state", "gltf_node", "scene_parent"); GDVIRTUAL_BIND(_import_post_parse, "state"); GDVIRTUAL_BIND(_import_node, "state", "gltf_node", "json", "node"); GDVIRTUAL_BIND(_import_post, "state", "root"); + // Export process. GDVIRTUAL_BIND(_export_preflight, "root"); + GDVIRTUAL_BIND(_convert_scene_node, "state", "gltf_node", "scene_node"); GDVIRTUAL_BIND(_export_node, "state", "gltf_node", "json", "node"); GDVIRTUAL_BIND(_export_post, "state"); } -Error GLTFDocumentExtension::import_post(Ref<GLTFState> p_state, Node *p_root) { - ERR_FAIL_NULL_V(p_root, ERR_INVALID_PARAMETER); +// Import process. +Error GLTFDocumentExtension::import_preflight(Ref<GLTFState> p_state, Vector<String> p_extensions) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_post, p_state, p_root, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_import_preflight, p_state, p_extensions, err); + return Error(err); +} + +Vector<String> GLTFDocumentExtension::get_supported_extensions() { + Vector<String> ret; + GDVIRTUAL_CALL(_get_supported_extensions, ret); + return ret; } -Error GLTFDocumentExtension::import_preflight(Ref<GLTFState> p_state) { +Error GLTFDocumentExtension::parse_node_extensions(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &p_extensions) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); + ERR_FAIL_NULL_V(p_gltf_node, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_preflight, p_state, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_parse_node_extensions, p_state, p_gltf_node, p_extensions, err); + return Error(err); +} + +Node3D *GLTFDocumentExtension::generate_scene_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent) { + ERR_FAIL_NULL_V(p_state, nullptr); + ERR_FAIL_NULL_V(p_gltf_node, nullptr); + ERR_FAIL_NULL_V(p_scene_parent, nullptr); + Node3D *ret_node = nullptr; + GDVIRTUAL_CALL(_generate_scene_node, p_state, p_gltf_node, p_scene_parent, ret_node); + return ret_node; } Error GLTFDocumentExtension::import_post_parse(Ref<GLTFState> p_state) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_post_parse, p_state, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_import_post_parse, p_state, err); + return Error(err); } -Error GLTFDocumentExtension::export_post(Ref<GLTFState> p_state) { +Error GLTFDocumentExtension::import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_dict, Node *p_node) { + ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); + ERR_FAIL_NULL_V(p_gltf_node, ERR_INVALID_PARAMETER); + ERR_FAIL_NULL_V(p_node, ERR_INVALID_PARAMETER); + int err = OK; + GDVIRTUAL_CALL(_import_node, p_state, p_gltf_node, r_dict, p_node, err); + return Error(err); +} + +Error GLTFDocumentExtension::import_post(Ref<GLTFState> p_state, Node *p_root) { + ERR_FAIL_NULL_V(p_root, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_export_post, p_state, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_import_post, p_state, p_root, err); + return Error(err); } + +// Export process. Error GLTFDocumentExtension::export_preflight(Node *p_root) { ERR_FAIL_NULL_V(p_root, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_export_preflight, p_root, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_export_preflight, p_root, err); + return Error(err); } -Error GLTFDocumentExtension::import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_dict, Node *p_node) { +void GLTFDocumentExtension::convert_scene_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Node *p_scene_node) { + ERR_FAIL_NULL(p_state); + ERR_FAIL_NULL(p_gltf_node); + ERR_FAIL_NULL(p_scene_node); + GDVIRTUAL_CALL(_convert_scene_node, p_state, p_gltf_node, p_scene_node); +} + +Error GLTFDocumentExtension::export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_dict, Node *p_node) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(p_gltf_node, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(p_node, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_import_node, p_state, p_gltf_node, r_dict, p_node, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_export_node, p_state, p_gltf_node, r_dict, p_node, err); + return Error(err); } -Error GLTFDocumentExtension::export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_dict, Node *p_node) { +Error GLTFDocumentExtension::export_post(Ref<GLTFState> p_state) { ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); - ERR_FAIL_NULL_V(p_gltf_node, ERR_INVALID_PARAMETER); - ERR_FAIL_NULL_V(p_node, ERR_INVALID_PARAMETER); int err = OK; - if (GDVIRTUAL_CALL(_export_node, p_state, p_gltf_node, r_dict, p_node, err)) { - return Error(err); - } - return OK; + GDVIRTUAL_CALL(_export_post, p_state, err); + return Error(err); } diff --git a/modules/gltf/gltf_document_extension.h b/modules/gltf/extensions/gltf_document_extension.h index 0ef9109584..7cc9ca592f 100644 --- a/modules/gltf/gltf_document_extension.h +++ b/modules/gltf/extensions/gltf_document_extension.h @@ -31,8 +31,7 @@ #ifndef GLTF_DOCUMENT_EXTENSION_H #define GLTF_DOCUMENT_EXTENSION_H -#include "gltf_state.h" -#include "structures/gltf_node.h" +#include "../gltf_state.h" class GLTFDocumentExtension : public Resource { GDCLASS(GLTFDocumentExtension, Resource); @@ -41,18 +40,31 @@ protected: static void _bind_methods(); public: - virtual Error import_preflight(Ref<GLTFState> p_state); + // Import process. + virtual Error import_preflight(Ref<GLTFState> p_state, Vector<String> p_extensions); + virtual Vector<String> get_supported_extensions(); + virtual Error parse_node_extensions(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &p_extensions); + virtual Node3D *generate_scene_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent); virtual Error import_post_parse(Ref<GLTFState> p_state); - virtual Error export_post(Ref<GLTFState> p_state); + virtual Error import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_json, Node *p_node); virtual Error import_post(Ref<GLTFState> p_state, Node *p_node); + // Export process. virtual Error export_preflight(Node *p_state); - virtual Error import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_json, Node *p_node); + virtual void convert_scene_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Node *p_scene_node); virtual Error export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_json, Node *p_node); - GDVIRTUAL1R(int, _import_preflight, Ref<GLTFState>); + virtual Error export_post(Ref<GLTFState> p_state); + + // Import process. + GDVIRTUAL2R(int, _import_preflight, Ref<GLTFState>, Vector<String>); + GDVIRTUAL0R(Vector<String>, _get_supported_extensions); + GDVIRTUAL3R(int, _parse_node_extensions, Ref<GLTFState>, Ref<GLTFNode>, Dictionary); + GDVIRTUAL3R(Node3D *, _generate_scene_node, Ref<GLTFState>, Ref<GLTFNode>, Node *); GDVIRTUAL1R(int, _import_post_parse, Ref<GLTFState>); GDVIRTUAL4R(int, _import_node, Ref<GLTFState>, Ref<GLTFNode>, Dictionary, Node *); GDVIRTUAL2R(int, _import_post, Ref<GLTFState>, Node *); + // Export process. GDVIRTUAL1R(int, _export_preflight, Node *); + GDVIRTUAL3(_convert_scene_node, Ref<GLTFState>, Ref<GLTFNode>, Node *); GDVIRTUAL4R(int, _export_node, Ref<GLTFState>, Ref<GLTFNode>, Dictionary, Node *); GDVIRTUAL1R(int, _export_post, Ref<GLTFState>); }; diff --git a/modules/gltf/gltf_document_extension_convert_importer_mesh.cpp b/modules/gltf/extensions/gltf_document_extension_convert_importer_mesh.cpp index 1620900a04..49496afb62 100644 --- a/modules/gltf/gltf_document_extension_convert_importer_mesh.cpp +++ b/modules/gltf/extensions/gltf_document_extension_convert_importer_mesh.cpp @@ -30,7 +30,7 @@ #include "gltf_document_extension_convert_importer_mesh.h" -#include "gltf_state.h" +#include "../gltf_state.h" #include "core/error/error_macros.h" #include "scene/3d/mesh_instance_3d.h" diff --git a/modules/gltf/gltf_document_extension_convert_importer_mesh.h b/modules/gltf/extensions/gltf_document_extension_convert_importer_mesh.h index 00e664e73f..00e664e73f 100644 --- a/modules/gltf/gltf_document_extension_convert_importer_mesh.h +++ b/modules/gltf/extensions/gltf_document_extension_convert_importer_mesh.h diff --git a/modules/gltf/extensions/gltf_light.cpp b/modules/gltf/extensions/gltf_light.cpp index af21a4e804..d00bead61c 100644 --- a/modules/gltf/extensions/gltf_light.cpp +++ b/modules/gltf/extensions/gltf_light.cpp @@ -31,6 +31,12 @@ #include "gltf_light.h" void GLTFLight::_bind_methods() { + ClassDB::bind_static_method("GLTFLight", D_METHOD("from_node", "light_node"), &GLTFLight::from_node); + ClassDB::bind_method(D_METHOD("to_node"), &GLTFLight::to_node); + + ClassDB::bind_static_method("GLTFLight", D_METHOD("from_dictionary", "dictionary"), &GLTFLight::from_dictionary); + ClassDB::bind_method(D_METHOD("to_dictionary"), &GLTFLight::to_dictionary); + ClassDB::bind_method(D_METHOD("get_color"), &GLTFLight::get_color); ClassDB::bind_method(D_METHOD("set_color", "color"), &GLTFLight::set_color); ClassDB::bind_method(D_METHOD("get_intensity"), &GLTFLight::get_intensity); @@ -99,3 +105,116 @@ float GLTFLight::get_outer_cone_angle() { void GLTFLight::set_outer_cone_angle(float p_outer_cone_angle) { outer_cone_angle = p_outer_cone_angle; } + +Ref<GLTFLight> GLTFLight::from_node(const Light3D *p_light) { + Ref<GLTFLight> l; + l.instantiate(); + ERR_FAIL_COND_V_MSG(!p_light, l, "Tried to create a GLTFLight from a Light3D node, but the given node was null."); + l->color = p_light->get_color(); + if (cast_to<DirectionalLight3D>(p_light)) { + l->light_type = "directional"; + const DirectionalLight3D *light = cast_to<const 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<const OmniLight3D>(p_light)) { + l->light_type = "point"; + const OmniLight3D *light = cast_to<const OmniLight3D>(p_light); + l->range = light->get_param(OmniLight3D::PARAM_RANGE); + l->intensity = light->get_param(OmniLight3D::PARAM_ENERGY); + } else if (cast_to<const SpotLight3D>(p_light)) { + l->light_type = "spot"; + const SpotLight3D *light = cast_to<const SpotLight3D>(p_light); + l->range = light->get_param(SpotLight3D::PARAM_RANGE); + l->intensity = light->get_param(SpotLight3D::PARAM_ENERGY); + l->outer_cone_angle = Math::deg_to_rad(light->get_param(SpotLight3D::PARAM_SPOT_ANGLE)); + // This equation is the inverse of the import equation (which has a desmos link). + float angle_ratio = 1 - (0.2 / (0.1 + light->get_param(SpotLight3D::PARAM_SPOT_ATTENUATION))); + angle_ratio = MAX(0, angle_ratio); + l->inner_cone_angle = l->outer_cone_angle * angle_ratio; + } + return l; +} + +Light3D *GLTFLight::to_node() const { + if (light_type == "directional") { + DirectionalLight3D *light = memnew(DirectionalLight3D); + light->set_param(Light3D::PARAM_ENERGY, intensity); + light->set_color(color); + return light; + } + if (light_type == "point") { + OmniLight3D *light = memnew(OmniLight3D); + light->set_param(OmniLight3D::PARAM_ENERGY, intensity); + light->set_param(OmniLight3D::PARAM_RANGE, CLAMP(range, 0, 4096)); + light->set_color(color); + return light; + } + if (light_type == "spot") { + SpotLight3D *light = memnew(SpotLight3D); + light->set_param(SpotLight3D::PARAM_ENERGY, intensity); + light->set_param(SpotLight3D::PARAM_RANGE, CLAMP(range, 0, 4096)); + light->set_param(SpotLight3D::PARAM_SPOT_ANGLE, Math::rad_to_deg(outer_cone_angle)); + light->set_color(color); + // Line of best fit derived from guessing, see https://www.desmos.com/calculator/biiflubp8b + // The points in desmos are not exact, except for (1, infinity). + float angle_ratio = inner_cone_angle / outer_cone_angle; + float angle_attenuation = 0.2 / (1 - angle_ratio) - 0.1; + light->set_param(SpotLight3D::PARAM_SPOT_ATTENUATION, angle_attenuation); + return light; + } + return memnew(Light3D); +} + +Ref<GLTFLight> GLTFLight::from_dictionary(const Dictionary p_dictionary) { + ERR_FAIL_COND_V_MSG(!p_dictionary.has("type"), Ref<GLTFLight>(), "Failed to parse GLTF light, missing required field 'type'."); + Ref<GLTFLight> light; + light.instantiate(); + const String &type = p_dictionary["type"]; + light->light_type = type; + + if (p_dictionary.has("color")) { + const Array &arr = p_dictionary["color"]; + if (arr.size() == 3) { + light->color = Color(arr[0], arr[1], arr[2]).linear_to_srgb(); + } else { + ERR_PRINT("Error parsing GLTF light: The color must have exactly 3 numbers."); + } + } + if (p_dictionary.has("intensity")) { + light->intensity = p_dictionary["intensity"]; + } + if (p_dictionary.has("range")) { + light->range = p_dictionary["range"]; + } + if (type == "spot") { + const Dictionary &spot = p_dictionary["spot"]; + light->inner_cone_angle = spot["innerConeAngle"]; + light->outer_cone_angle = spot["outerConeAngle"]; + if (light->inner_cone_angle >= light->outer_cone_angle) { + ERR_PRINT("Error parsing GLTF light: The inner angle must be smaller than the outer angle."); + } + } else if (type != "point" && type != "directional") { + ERR_PRINT("Error parsing GLTF light: Light type '" + type + "' is unknown."); + } + return light; +} + +Dictionary GLTFLight::to_dictionary() const { + Dictionary d; + Array color_array; + color_array.resize(3); + color_array[0] = color.r; + color_array[1] = color.g; + color_array[2] = color.b; + d["color"] = color_array; + d["type"] = light_type; + if (light_type == "spot") { + Dictionary spot_dict; + spot_dict["innerConeAngle"] = inner_cone_angle; + spot_dict["outerConeAngle"] = outer_cone_angle; + d["spot"] = spot_dict; + } + d["intensity"] = intensity; + d["range"] = range; + return d; +} diff --git a/modules/gltf/extensions/gltf_light.h b/modules/gltf/extensions/gltf_light.h index 58fa299dfd..04980e144c 100644 --- a/modules/gltf/extensions/gltf_light.h +++ b/modules/gltf/extensions/gltf_light.h @@ -35,6 +35,8 @@ #include "core/io/resource.h" #include "scene/3d/light_3d.h" +// https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_lights_punctual + class GLTFLight : public Resource { GDCLASS(GLTFLight, Resource) friend class GLTFDocument; @@ -68,6 +70,12 @@ public: float get_outer_cone_angle(); void set_outer_cone_angle(float p_outer_cone_angle); + + static Ref<GLTFLight> from_node(const Light3D *p_light); + Light3D *to_node() const; + + static Ref<GLTFLight> from_dictionary(const Dictionary p_dictionary); + Dictionary to_dictionary() const; }; #endif // GLTF_LIGHT_H diff --git a/modules/gltf/extensions/gltf_spec_gloss.h b/modules/gltf/extensions/gltf_spec_gloss.h index a45fa4296c..2b4d3ee609 100644 --- a/modules/gltf/extensions/gltf_spec_gloss.h +++ b/modules/gltf/extensions/gltf_spec_gloss.h @@ -34,6 +34,11 @@ #include "core/io/image.h" #include "core/io/resource.h" +// KHR_materials_pbrSpecularGlossiness is an archived GLTF extension. +// This means that it is deprecated and not recommended for new files. +// However, it is still supported for loading old files. +// https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness + class GLTFSpecGloss : public Resource { GDCLASS(GLTFSpecGloss, Resource); friend class GLTFDocument; diff --git a/modules/gltf/gltf_defines.h b/modules/gltf/gltf_defines.h index c20c87f798..23bf33869e 100644 --- a/modules/gltf/gltf_defines.h +++ b/modules/gltf/gltf_defines.h @@ -58,6 +58,7 @@ class GLTFSkin; class GLTFSpecGloss; class GLTFState; class GLTFTexture; +class GLTFTextureSampler; // GLTF index aliases. using GLTFAccessorIndex = int; @@ -66,13 +67,14 @@ using GLTFBufferIndex = int; using GLTFBufferViewIndex = int; using GLTFCameraIndex = int; using GLTFImageIndex = int; +using GLTFLightIndex = int; using GLTFMaterialIndex = int; using GLTFMeshIndex = int; -using GLTFLightIndex = int; using GLTFNodeIndex = int; using GLTFSkeletonIndex = int; using GLTFSkinIndex = int; using GLTFTextureIndex = int; +using GLTFTextureSamplerIndex = int; enum GLTFType { TYPE_SCALAR, diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index d102970932..faa8ed267a 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -31,8 +31,6 @@ #include "gltf_document.h" #include "extensions/gltf_spec_gloss.h" -#include "gltf_document_extension.h" -#include "gltf_document_extension_convert_importer_mesh.h" #include "gltf_state.h" #include "core/crypto/crypto_core.h" @@ -50,7 +48,6 @@ #include "core/version.h" #include "drivers/png/png_driver_common.h" #include "scene/2d/node_2d.h" -#include "scene/3d/camera_3d.h" #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/multimesh_instance_3d.h" #include "scene/3d/node_3d.h" @@ -146,6 +143,12 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return Error::FAILED; } + /* STEP SERIALIZE TEXTURE SAMPLERS */ + err = _serialize_texture_samplers(state); + if (err != OK) { + return Error::FAILED; + } + /* STEP SERIALIZE ANIMATIONS */ err = _serialize_animations(state); if (err != OK) { @@ -192,14 +195,14 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return Error::FAILED; } - /* STEP SERIALIZE SCENE */ + /* STEP SERIALIZE LIGHTS */ err = _serialize_lights(state); if (err != OK) { return Error::FAILED; } /* STEP SERIALIZE EXTENSIONS */ - err = _serialize_extensions(state); + err = _serialize_gltf_extensions(state); if (err != OK) { return Error::FAILED; } @@ -210,8 +213,7 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return Error::FAILED; } - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + for (Ref<GLTFDocumentExtension> ext : document_extensions) { ERR_CONTINUE(ext.is_null()); err = ext->export_post(state); ERR_FAIL_COND_V(err != OK, err); @@ -220,9 +222,9 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return OK; } -Error GLTFDocument::_serialize_extensions(Ref<GLTFState> state) const { - Array extensions_used; - Array extensions_required; +Error GLTFDocument::_serialize_gltf_extensions(Ref<GLTFState> state) const { + Vector<String> extensions_used = state->extensions_used; + Vector<String> extensions_required = state->extensions_required; if (!state->lights.is_empty()) { extensions_used.push_back("KHR_lights_punctual"); } @@ -231,9 +233,11 @@ Error GLTFDocument::_serialize_extensions(Ref<GLTFState> state) const { extensions_required.push_back("KHR_texture_transform"); } if (!extensions_used.is_empty()) { + extensions_used.sort(); state->json["extensionsUsed"] = extensions_used; } if (!extensions_required.is_empty()) { + extensions_required.sort(); state->json["extensionsRequired"] = extensions_required; } return OK; @@ -402,56 +406,55 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { Array nodes; for (int i = 0; i < state->nodes.size(); i++) { Dictionary node; - Ref<GLTFNode> n = state->nodes[i]; + Ref<GLTFNode> gltf_node = state->nodes[i]; Dictionary extensions; node["extensions"] = extensions; - if (!n->get_name().is_empty()) { - node["name"] = n->get_name(); + if (!gltf_node->get_name().is_empty()) { + node["name"] = gltf_node->get_name(); } - if (n->camera != -1) { - node["camera"] = n->camera; + if (gltf_node->camera != -1) { + node["camera"] = gltf_node->camera; } - if (n->light != -1) { + if (gltf_node->light != -1) { Dictionary lights_punctual; extensions["KHR_lights_punctual"] = lights_punctual; - lights_punctual["light"] = n->light; + lights_punctual["light"] = gltf_node->light; } - if (n->mesh != -1) { - node["mesh"] = n->mesh; + if (gltf_node->mesh != -1) { + node["mesh"] = gltf_node->mesh; } - if (n->skin != -1) { - node["skin"] = n->skin; + if (gltf_node->skin != -1) { + node["skin"] = gltf_node->skin; } - if (n->skeleton != -1 && n->skin < 0) { + if (gltf_node->skeleton != -1 && gltf_node->skin < 0) { } - if (n->xform != Transform3D()) { - node["matrix"] = _xform_to_array(n->xform); + if (gltf_node->xform != Transform3D()) { + node["matrix"] = _xform_to_array(gltf_node->xform); } - if (!n->rotation.is_equal_approx(Quaternion())) { - node["rotation"] = _quaternion_to_array(n->rotation); + if (!gltf_node->rotation.is_equal_approx(Quaternion())) { + node["rotation"] = _quaternion_to_array(gltf_node->rotation); } - if (!n->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) { - node["scale"] = _vec3_to_arr(n->scale); + if (!gltf_node->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) { + node["scale"] = _vec3_to_arr(gltf_node->scale); } - if (!n->position.is_equal_approx(Vector3())) { - node["translation"] = _vec3_to_arr(n->position); + if (!gltf_node->position.is_zero_approx()) { + node["translation"] = _vec3_to_arr(gltf_node->position); } - if (n->children.size()) { + if (gltf_node->children.size()) { Array children; - for (int j = 0; j < n->children.size(); j++) { - children.push_back(n->children[j]); + for (int j = 0; j < gltf_node->children.size(); j++) { + children.push_back(gltf_node->children[j]); } node["children"] = children; } - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + for (Ref<GLTFDocumentExtension> ext : document_extensions) { ERR_CONTINUE(ext.is_null()); ERR_CONTINUE(!state->scene_nodes.find(i)); - Error err = ext->export_node(state, n, state->json, state->scene_nodes[i]); + Error err = ext->export_node(state, gltf_node, node, state->scene_nodes[i]); ERR_CONTINUE(err != OK); } @@ -464,23 +467,23 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { String GLTFDocument::_gen_unique_name(Ref<GLTFState> state, const String &p_name) { const String s_name = p_name.validate_node_name(); - String name; + String u_name; int index = 1; while (true) { - name = s_name; + u_name = s_name; if (index > 1) { - name += itos(index); + u_name += itos(index); } - if (!state->unique_names.has(name)) { + if (!state->unique_names.has(u_name)) { break; } index++; } - state->unique_names.insert(name); + state->unique_names.insert(u_name); - return name; + return u_name; } String GLTFDocument::_sanitize_animation_name(const String &p_name) { @@ -488,39 +491,39 @@ String GLTFDocument::_sanitize_animation_name(const String &p_name) { // (See animation/animation_player.cpp::add_animation) // TODO: Consider adding invalid_characters or a validate_animation_name to animation_player to mirror Node. - String name = p_name.validate_node_name(); - name = name.replace(",", ""); - name = name.replace("[", ""); - return name; + String anim_name = p_name.validate_node_name(); + anim_name = anim_name.replace(",", ""); + anim_name = anim_name.replace("[", ""); + return anim_name; } String GLTFDocument::_gen_unique_animation_name(Ref<GLTFState> state, const String &p_name) { const String s_name = _sanitize_animation_name(p_name); - String name; + String u_name; int index = 1; while (true) { - name = s_name; + u_name = s_name; if (index > 1) { - name += itos(index); + u_name += itos(index); } - if (!state->unique_animation_names.has(name)) { + if (!state->unique_animation_names.has(u_name)) { break; } index++; } - state->unique_animation_names.insert(name); + state->unique_animation_names.insert(u_name); - return name; + return u_name; } String GLTFDocument::_sanitize_bone_name(const String &p_name) { - String name = p_name; - name = name.replace(":", "_"); - name = name.replace("/", "_"); - return name; + String bone_name = p_name; + bone_name = bone_name.replace(":", "_"); + bone_name = bone_name.replace("/", "_"); + return bone_name; } String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> state, const GLTFSkeletonIndex skel_i, const String &p_name) { @@ -528,23 +531,23 @@ String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> state, const GLTFSkele if (s_name.is_empty()) { s_name = "bone"; } - String name; + String u_name; int index = 1; while (true) { - name = s_name; + u_name = s_name; if (index > 1) { - name += "_" + itos(index); + u_name += "_" + itos(index); } - if (!state->skeletons[skel_i]->unique_names.has(name)) { + if (!state->skeletons[skel_i]->unique_names.has(u_name)) { break; } index++; } - state->skeletons.write[skel_i]->unique_names.insert(name); + state->skeletons.write[skel_i]->unique_names.insert(u_name); - return name; + return u_name; } Error GLTFDocument::_parse_scenes(Ref<GLTFState> state) { @@ -622,6 +625,11 @@ Error GLTFDocument::_parse_nodes(Ref<GLTFState> state) { node->light = light; } } + for (Ref<GLTFDocumentExtension> ext : document_extensions) { + ERR_CONTINUE(ext.is_null()); + Error err = ext->parse_node_extensions(state, node, extensions); + ERR_CONTINUE_MSG(err != OK, "GLTF: Encountered error " + itos(err) + " when parsing node extensions for node " + node->get_name() + " in file " + state->filename + ". Continuing."); + } } if (n.has("children")) { @@ -787,7 +795,7 @@ Error GLTFDocument::_parse_buffers(Ref<GLTFState> state, const String &p_base_pa } else { // Relative path to an external image file. ERR_FAIL_COND_V(p_base_path.is_empty(), ERR_INVALID_PARAMETER); uri = uri.uri_decode(); - uri = p_base_path.plus_file(uri).replace("\\", "/"); // Fix for Windows. + uri = p_base_path.path_join(uri).replace("\\", "/"); // Fix for Windows. buffer_data = FileAccess::get_file_as_array(uri); ERR_FAIL_COND_V_MSG(buffer.size() == 0, ERR_PARSE_ERROR, "glTF: Couldn't load binary file as an array: " + uri); } @@ -2583,10 +2591,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { Mesh::PRIMITIVE_TRIANGLES, // 4 TRIANGLES Mesh::PRIMITIVE_TRIANGLE_STRIP, // 5 TRIANGLE_STRIP Mesh::PRIMITIVE_TRIANGLES, // 6 TRIANGLE_FAN fan not supported, should be converted -#ifndef _MSC_VER -#warning line loop and triangle fan are not supported and need to be converted to lines and triangles -#endif - + // TODO: Line loop and triangle fan are not supported and need to be converted to lines and triangles. }; primitive = primitives2[mode]; @@ -2674,7 +2679,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { } else if (a.has("JOINTS_0") && a.has("JOINTS_1")) { PackedInt32Array joints_0 = _decode_accessor_as_ints(state, a["JOINTS_0"], true); 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); + ERR_FAIL_COND_V(joints_0.size() != joints_1.size(), ERR_INVALID_DATA); int32_t weight_8_count = JOINT_GROUP_SIZE * 2; Vector<int> joints; joints.resize(vertex_num * weight_8_count); @@ -2817,8 +2822,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { if (j == 0) { const Array &target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array(); for (int k = 0; k < targets.size(); k++) { - const String name = k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k); - import_mesh->add_blend_shape(name); + import_mesh->add_blend_shape(k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k)); } } @@ -3027,12 +3031,12 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path d["mimeType"] = "image/png"; } else { ERR_FAIL_COND_V(p_path.is_empty(), ERR_INVALID_PARAMETER); - String name = state->images[i]->get_name(); - if (name.is_empty()) { - name = itos(i); + String img_name = state->images[i]->get_name(); + if (img_name.is_empty()) { + img_name = itos(i); } - name = _gen_unique_name(state, name); - name = name.pad_zeros(3) + ".png"; + img_name = _gen_unique_name(state, img_name); + img_name = img_name.pad_zeros(3) + ".png"; String texture_dir = "textures"; String path = p_path.get_base_dir(); String new_texture_dir = path + "/" + texture_dir; @@ -3040,8 +3044,8 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path if (!da->dir_exists(new_texture_dir)) { da->make_dir(new_texture_dir); } - image->save_png(new_texture_dir.plus_file(name)); - d["uri"] = texture_dir.plus_file(name).uri_encode(); + image->save_png(new_texture_dir.path_join(img_name)); + d["uri"] = texture_dir.path_join(img_name).uri_encode(); } images.push_back(d); } @@ -3119,7 +3123,7 @@ Error GLTFDocument::_parse_images(Ref<GLTFState> state, const String &p_base_pat } else { // Relative path to an external image file. ERR_FAIL_COND_V(p_base_path.is_empty(), ERR_INVALID_PARAMETER); uri = uri.uri_decode(); - uri = p_base_path.plus_file(uri).replace("\\", "/"); // Fix for Windows. + uri = p_base_path.path_join(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. // there could be a `.png` image which is actually JPEG), but there's no easy @@ -3218,6 +3222,11 @@ Error GLTFDocument::_serialize_textures(Ref<GLTFState> state) { Ref<GLTFTexture> t = state->textures[i]; ERR_CONTINUE(t->get_src_image() == -1); d["source"] = t->get_src_image(); + + GLTFTextureSamplerIndex sampler_index = t->get_sampler(); + if (sampler_index != -1) { + d["sampler"] = sampler_index; + } textures.push_back(d); } state->json["textures"] = textures; @@ -3239,13 +3248,18 @@ Error GLTFDocument::_parse_textures(Ref<GLTFState> state) { Ref<GLTFTexture> t; t.instantiate(); t->set_src_image(d["source"]); + if (d.has("sampler")) { + t->set_sampler(d["sampler"]); + } else { + t->set_sampler(-1); + } state->textures.push_back(t); } return OK; } -GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture) { +GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) { ERR_FAIL_COND_V(p_texture.is_null(), -1); Ref<GLTFTexture> gltf_texture; gltf_texture.instantiate(); @@ -3253,6 +3267,7 @@ GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> GLTFImageIndex gltf_src_image_i = state->images.size(); state->images.push_back(p_texture); gltf_texture->set_src_image(gltf_src_image_i); + gltf_texture->set_sampler(_set_sampler_for_mode(state, p_filter_mode, p_repeats)); GLTFTextureIndex gltf_texture_i = state->textures.size(); state->textures.push_back(gltf_texture); return gltf_texture_i; @@ -3267,6 +3282,102 @@ Ref<Texture2D> GLTFDocument::_get_texture(Ref<GLTFState> state, const GLTFTextur return state->images[image]; } +GLTFTextureSamplerIndex GLTFDocument::_set_sampler_for_mode(Ref<GLTFState> state, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) { + for (int i = 0; i < state->texture_samplers.size(); ++i) { + if (state->texture_samplers[i]->get_filter_mode() == p_filter_mode) { + return i; + } + } + + GLTFTextureSamplerIndex gltf_sampler_i = state->texture_samplers.size(); + Ref<GLTFTextureSampler> gltf_sampler; + gltf_sampler.instantiate(); + gltf_sampler->set_filter_mode(p_filter_mode); + gltf_sampler->set_wrap_mode(p_repeats); + state->texture_samplers.push_back(gltf_sampler); + return gltf_sampler_i; +} + +Ref<GLTFTextureSampler> GLTFDocument::_get_sampler_for_texture(Ref<GLTFState> state, const GLTFTextureIndex p_texture) { + ERR_FAIL_INDEX_V(p_texture, state->textures.size(), Ref<Texture2D>()); + const GLTFTextureSamplerIndex sampler = state->textures[p_texture]->get_sampler(); + + if (sampler == -1) { + return state->default_texture_sampler; + } else { + ERR_FAIL_INDEX_V(sampler, state->texture_samplers.size(), Ref<GLTFTextureSampler>()); + + return state->texture_samplers[sampler]; + } +} + +Error GLTFDocument::_serialize_texture_samplers(Ref<GLTFState> state) { + if (!state->texture_samplers.size()) { + return OK; + } + + Array samplers; + for (int32_t i = 0; i < state->texture_samplers.size(); ++i) { + Dictionary d; + Ref<GLTFTextureSampler> s = state->texture_samplers[i]; + d["magFilter"] = s->get_mag_filter(); + d["minFilter"] = s->get_min_filter(); + d["wrapS"] = s->get_wrap_s(); + d["wrapT"] = s->get_wrap_t(); + samplers.push_back(d); + } + state->json["samplers"] = samplers; + + return OK; +} + +Error GLTFDocument::_parse_texture_samplers(Ref<GLTFState> state) { + state->default_texture_sampler.instantiate(); + state->default_texture_sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR); + state->default_texture_sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR); + state->default_texture_sampler->set_wrap_s(GLTFTextureSampler::WrapMode::REPEAT); + state->default_texture_sampler->set_wrap_t(GLTFTextureSampler::WrapMode::REPEAT); + + if (!state->json.has("samplers")) { + return OK; + } + + const Array &samplers = state->json["samplers"]; + for (int i = 0; i < samplers.size(); ++i) { + const Dictionary &d = samplers[i]; + + Ref<GLTFTextureSampler> sampler; + sampler.instantiate(); + + if (d.has("minFilter")) { + sampler->set_min_filter(d["minFilter"]); + } else { + sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR); + } + if (d.has("magFilter")) { + sampler->set_mag_filter(d["magFilter"]); + } else { + sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR); + } + + if (d.has("wrapS")) { + sampler->set_wrap_s(d["wrapS"]); + } else { + sampler->set_wrap_s(GLTFTextureSampler::WrapMode::DEFAULT); + } + + if (d.has("wrapT")) { + sampler->set_wrap_t(d["wrapT"]); + } else { + sampler->set_wrap_t(GLTFTextureSampler::WrapMode::DEFAULT); + } + + state->texture_samplers.push_back(sampler); + } + + return OK; +} + Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { Array materials; for (int32_t i = 0; i < state->materials.size(); i++) { @@ -3298,7 +3409,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { if (albedo_texture.is_valid() && albedo_texture->get_image().is_valid()) { albedo_texture->set_name(material->get_name() + "_albedo"); - gltf_texture_index = _set_texture(state, albedo_texture); + gltf_texture_index = _set_texture(state, albedo_texture, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } if (gltf_texture_index != -1) { bct["index"] = gltf_texture_index; @@ -3374,7 +3485,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { height = albedo_texture->get_height(); width = albedo_texture->get_width(); } - orm_image->create(width, height, false, Image::FORMAT_RGBA8); + orm_image->initialize_data(width, height, false, Image::FORMAT_RGBA8); if (ao_image.is_valid() && ao_image->get_size() != Vector2(width, height)) { ao_image->resize(width, height, Image::INTERPOLATE_LANCZOS); } @@ -3428,7 +3539,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { GLTFTextureIndex orm_texture_index = -1; if (has_ao || has_roughness || has_metalness) { orm_texture->set_name(material->get_name() + "_orm"); - orm_texture_index = _set_texture(state, orm_texture); + orm_texture_index = _set_texture(state, orm_texture, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } if (has_ao) { Dictionary occt; @@ -3483,7 +3594,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { GLTFTextureIndex gltf_texture_index = -1; if (tex.is_valid() && tex->get_image().is_valid()) { tex->set_name(material->get_name() + "_normal"); - gltf_texture_index = _set_texture(state, tex); + gltf_texture_index = _set_texture(state, tex, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } nt["scale"] = material->get_normal_scale(); if (gltf_texture_index != -1) { @@ -3506,7 +3617,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { GLTFTextureIndex gltf_texture_index = -1; if (emission_texture.is_valid() && emission_texture->get_image().is_valid()) { emission_texture->set_name(material->get_name() + "_emission"); - gltf_texture_index = _set_texture(state, emission_texture); + gltf_texture_index = _set_texture(state, emission_texture, material->get_texture_filter(), material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT)); } if (gltf_texture_index != -1) { @@ -3565,6 +3676,11 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { if (sgm.has("diffuseTexture")) { const Dictionary &diffuse_texture_dict = sgm["diffuseTexture"]; if (diffuse_texture_dict.has("index")) { + Ref<GLTFTextureSampler> diffuse_sampler = _get_sampler_for_texture(state, diffuse_texture_dict["index"]); + if (diffuse_sampler.is_valid()) { + material->set_texture_filter(diffuse_sampler->get_filter_mode()); + material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, diffuse_sampler->get_wrap_mode()); + } Ref<Texture2D> diffuse_texture = _get_texture(state, diffuse_texture_dict["index"]); if (diffuse_texture.is_valid()) { spec_gloss->diffuse_img = diffuse_texture->get_image(); @@ -3613,6 +3729,9 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { if (mr.has("baseColorTexture")) { const Dictionary &bct = mr["baseColorTexture"]; if (bct.has("index")) { + Ref<GLTFTextureSampler> bct_sampler = _get_sampler_for_texture(state, bct["index"]); + material->set_texture_filter(bct_sampler->get_filter_mode()); + material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, bct_sampler->get_wrap_mode()); material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, _get_texture(state, bct["index"])); } if (!mr.has("baseColorFactor")) { @@ -3742,13 +3861,11 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re if (r_spec_gloss->diffuse_img.is_null()) { return; } - Ref<Image> rm_img; - rm_img.instantiate(); bool has_roughness = false; bool has_metal = false; p_material->set_roughness(1.0f); p_material->set_metallic(1.0f); - rm_img->create(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8); + Ref<Image> rm_img = Image::create_empty(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8); r_spec_gloss->spec_gloss_img->decompress(); if (r_spec_gloss->diffuse_img.is_valid()) { r_spec_gloss->diffuse_img->decompress(); @@ -4300,14 +4417,14 @@ Error GLTFDocument::_determine_skeleton_roots(Ref<GLTFState> state, const GLTFSk Ref<GLTFSkeleton> skeleton = state->skeletons.write[skel_i]; - Vector<GLTFNodeIndex> owners; - disjoint_set.get_representatives(owners); + Vector<GLTFNodeIndex> representatives; + disjoint_set.get_representatives(representatives); Vector<GLTFNodeIndex> roots; - for (int i = 0; i < owners.size(); ++i) { + for (int i = 0; i < representatives.size(); ++i) { Vector<GLTFNodeIndex> set; - disjoint_set.get_members(set, owners[i]); + disjoint_set.get_members(set, representatives[i]); const GLTFNodeIndex root = _find_highest_node(state, set); ERR_FAIL_COND_V(root < 0, FAILED); roots.push_back(root); @@ -4535,28 +4652,7 @@ Error GLTFDocument::_serialize_lights(Ref<GLTFState> state) { } Array lights; for (GLTFLightIndex i = 0; i < state->lights.size(); i++) { - Dictionary d; - Ref<GLTFLight> light = state->lights[i]; - Array color; - color.resize(3); - color[0] = light->color.r; - color[1] = light->color.g; - color[2] = light->color.b; - d["color"] = color; - 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; - float outer_cone_angle = light->outer_cone_angle; - s["outerConeAngle"] = outer_cone_angle; - d["spot"] = s; - } - float intensity = light->intensity; - d["intensity"] = intensity; - float range = light->range; - d["range"] = range; - lights.push_back(d); + lights.push_back(state->lights[i]->to_dictionary()); } Dictionary extensions; @@ -4578,28 +4674,7 @@ Error GLTFDocument::_serialize_cameras(Ref<GLTFState> state) { Array cameras; cameras.resize(state->cameras.size()); for (GLTFCameraIndex i = 0; i < state->cameras.size(); i++) { - Dictionary d; - - Ref<GLTFCamera> camera = state->cameras[i]; - - if (camera->get_perspective() == false) { - Dictionary og; - og["ymag"] = Math::deg2rad(camera->get_fov_size()); - og["xmag"] = Math::deg2rad(camera->get_fov_size()); - 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_depth_far(); - ppt["znear"] = camera->get_depth_near(); - d["perspective"] = ppt; - d["type"] = "perspective"; - } - cameras[i] = d; + cameras[i] = state->cameras[i]->to_dictionary(); } if (!state->cameras.size()) { @@ -4629,35 +4704,10 @@ Error GLTFDocument::_parse_lights(Ref<GLTFState> state) { const Array &lights = lights_punctual["lights"]; for (GLTFLightIndex light_i = 0; light_i < lights.size(); light_i++) { - const Dictionary &d = lights[light_i]; - - Ref<GLTFLight> light; - light.instantiate(); - ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR); - const String &type = d["type"]; - light->light_type = type; - - if (d.has("color")) { - const Array &arr = d["color"]; - ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR); - const Color c = Color(arr[0], arr[1], arr[2]).linear_to_srgb(); - light->color = c; - } - if (d.has("intensity")) { - light->intensity = d["intensity"]; - } - if (d.has("range")) { - light->range = d["range"]; - } - if (type == "spot") { - const Dictionary &spot = d["spot"]; - light->inner_cone_angle = spot["innerConeAngle"]; - light->outer_cone_angle = spot["outerConeAngle"]; - ERR_CONTINUE_MSG(light->inner_cone_angle >= light->outer_cone_angle, "The inner angle must be smaller than the outer angle."); - } else if (type != "point" && type != "directional") { - ERR_CONTINUE_MSG(true, "Light type is unknown."); + Ref<GLTFLight> light = GLTFLight::from_dictionary(lights[light_i]); + if (light.is_null()) { + return Error::ERR_PARSE_ERROR; } - state->lights.push_back(light); } @@ -4674,39 +4724,7 @@ Error GLTFDocument::_parse_cameras(Ref<GLTFState> state) { const Array cameras = state->json["cameras"]; for (GLTFCameraIndex i = 0; i < cameras.size(); i++) { - const Dictionary &d = cameras[i]; - - Ref<GLTFCamera> camera; - camera.instantiate(); - ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR); - const String &type = d["type"]; - if (type == "orthographic") { - camera->set_perspective(false); - if (d.has("orthographic")) { - 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_depth_far(og["zfar"]); - camera->set_depth_near(og["znear"]); - } else { - camera->set_fov_size(10); - } - } else if (type == "perspective") { - camera->set_perspective(true); - if (d.has("perspective")) { - 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_depth_far(ppt["zfar"]); - camera->set_depth_near(ppt["znear"]); - } else { - camera->set_fov_size(10); - } - } else { - ERR_FAIL_V_MSG(ERR_PARSE_ERROR, "Camera3D should be in 'orthographic' or 'perspective'"); - } - - state->cameras.push_back(camera); + state->cameras.push_back(GLTFCamera::from_dictionary(cameras[i])); } print_verbose("glTF: Total cameras: " + itos(state->cameras.size())); @@ -4937,12 +4955,12 @@ Error GLTFDocument::_parse_animations(Ref<GLTFState> state) { Array samplers = d["samplers"]; if (d.has("name")) { - const String name = d["name"]; - const String name_lower = name.to_lower(); - if (name_lower.begins_with("loop") || name_lower.ends_with("loop") || name_lower.begins_with("cycle") || name_lower.ends_with("cycle")) { + const String anim_name = d["name"]; + const String anim_name_lower = anim_name.to_lower(); + if (anim_name_lower.begins_with("loop") || anim_name_lower.ends_with("loop") || anim_name_lower.begins_with("cycle") || anim_name_lower.ends_with("cycle")) { animation->set_loop(true); } - animation->set_name(_gen_unique_animation_name(state, name)); + animation->set_name(_gen_unique_animation_name(state, anim_name)); } for (int j = 0; j < channels.size(); j++) { @@ -5107,7 +5125,7 @@ GLTFMeshIndex GLTFDocument::_convert_mesh_to_gltf(Ref<GLTFState> state, MeshInst Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); - Array instance_materials; + TypedArray<Material> instance_materials; for (int32_t surface_i = 0; surface_i < current_mesh->get_surface_count(); surface_i++) { Ref<Material> mat = current_mesh->get_surface_material(surface_i); if (p_mesh_instance->get_surface_override_material(surface_i).is_valid()) { @@ -5146,7 +5164,7 @@ ImporterMeshInstance3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> sta return mi; } -Node3D *GLTFDocument::_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index) { +Light3D *GLTFDocument::_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index) { Ref<GLTFNode> gltf_node = state->nodes[node_index]; ERR_FAIL_INDEX_V(gltf_node->light, state->lights.size(), nullptr); @@ -5154,45 +5172,7 @@ Node3D *GLTFDocument::_generate_light(Ref<GLTFState> state, const GLTFNodeIndex print_verbose("glTF: Creating light for: " + gltf_node->get_name()); Ref<GLTFLight> l = state->lights[gltf_node->light]; - - float intensity = l->intensity; - if (intensity > 10) { - // GLTF spec has the default around 1, but Blender defaults lights to 100. - // The only sane way to handle this is to check where it came from and - // handle it accordingly. If it's over 10, it probably came from Blender. - intensity /= 100; - } - - if (l->light_type == "directional") { - DirectionalLight3D *light = memnew(DirectionalLight3D); - light->set_param(Light3D::PARAM_ENERGY, intensity); - light->set_color(l->color); - return light; - } - - const float range = CLAMP(l->range, 0, 4096); - if (l->light_type == "point") { - OmniLight3D *light = memnew(OmniLight3D); - light->set_param(OmniLight3D::PARAM_ENERGY, intensity); - light->set_param(OmniLight3D::PARAM_RANGE, range); - light->set_color(l->color); - return light; - } - if (l->light_type == "spot") { - SpotLight3D *light = memnew(SpotLight3D); - light->set_param(SpotLight3D::PARAM_ENERGY, intensity); - light->set_param(SpotLight3D::PARAM_RANGE, range); - light->set_param(SpotLight3D::PARAM_SPOT_ANGLE, Math::rad2deg(l->outer_cone_angle)); - light->set_color(l->color); - - // Line of best fit derived from guessing, see https://www.desmos.com/calculator/biiflubp8b - // The points in desmos are not exact, except for (1, infinity). - float angle_ratio = l->inner_cone_angle / l->outer_cone_angle; - float angle_attenuation = 0.2 / (1 - angle_ratio) - 0.1; - light->set_param(SpotLight3D::PARAM_SPOT_ATTENUATION, angle_attenuation); - return light; - } - return memnew(Node3D); + return l->to_node(); } Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> state, const GLTFNodeIndex node_index) { @@ -5200,31 +5180,16 @@ Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> state, const GLTFNodeInd ERR_FAIL_INDEX_V(gltf_node->camera, state->cameras.size(), nullptr); - Camera3D *camera = memnew(Camera3D); print_verbose("glTF: Creating camera for: " + gltf_node->get_name()); Ref<GLTFCamera> c = state->cameras[gltf_node->camera]; - if (c->get_perspective()) { - 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_depth_near(), c->get_depth_far()); - } - - return camera; + return c->to_node(); } GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> state, Camera3D *p_camera) { print_verbose("glTF: Converting camera: " + p_camera->get_name()); - Ref<GLTFCamera> c; - c.instantiate(); - - if (p_camera->get_projection() == Camera3D::ProjectionType::PROJECTION_PERSPECTIVE) { - c->set_perspective(true); - } - c->set_fov_size(p_camera->get_fov()); - c->set_depth_far(p_camera->get_far()); - c->set_depth_near(p_camera->get_near()); + Ref<GLTFCamera> c = GLTFCamera::from_node(p_camera); GLTFCameraIndex camera_index = state->cameras.size(); state->cameras.push_back(c); return camera_index; @@ -5233,31 +5198,7 @@ GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> state, Camera3D *p_ GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> state, Light3D *p_light) { print_verbose("glTF: Converting light: " + p_light->get_name()); - Ref<GLTFLight> l; - l.instantiate(); - l->color = p_light->get_color(); - if (cast_to<DirectionalLight3D>(p_light)) { - 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->light_type = "point"; - OmniLight3D *light = cast_to<OmniLight3D>(p_light); - l->range = light->get_param(OmniLight3D::PARAM_RANGE); - l->intensity = light->get_param(OmniLight3D::PARAM_ENERGY); - } else if (cast_to<SpotLight3D>(p_light)) { - l->light_type = "spot"; - SpotLight3D *light = cast_to<SpotLight3D>(p_light); - l->range = light->get_param(SpotLight3D::PARAM_RANGE); - l->intensity = light->get_param(SpotLight3D::PARAM_ENERGY); - l->outer_cone_angle = Math::deg2rad(light->get_param(SpotLight3D::PARAM_SPOT_ANGLE)); - - // This equation is the inverse of the import equation (which has a desmos link). - float angle_ratio = 1 - (0.2 / (0.1 + light->get_param(SpotLight3D::PARAM_SPOT_ATTENUATION))); - angle_ratio = MAX(0, angle_ratio); - l->inner_cone_angle = l->outer_cone_angle * angle_ratio; - } + Ref<GLTFLight> l = GLTFLight::from_node(p_light); GLTFLightIndex light_index = state->lights.size(); state->lights.push_back(l); @@ -5279,6 +5220,7 @@ Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> state, const GLTFNodeInde return spatial; } + void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) { bool retflag = true; _check_visibility(p_current, retflag); @@ -5329,6 +5271,10 @@ void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, co AnimationPlayer *animation_player = Object::cast_to<AnimationPlayer>(p_current); _convert_animation_player_to_gltf(animation_player, state, p_gltf_parent, p_gltf_root, gltf_node, p_current); } + for (Ref<GLTFDocumentExtension> ext : document_extensions) { + ERR_CONTINUE(ext.is_null()); + ext->convert_scene_node(state, gltf_node, p_current); + } GLTFNodeIndex current_node_i = state->nodes.size(); GLTFNodeIndex gltf_root = p_gltf_root; if (gltf_root == -1) { @@ -5442,13 +5388,13 @@ void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex int32_t cell = p_grid_map->get_cell_item( Vector3(cell_location.x, cell_location.y, cell_location.z)); Transform3D cell_xform; - cell_xform.basis.set_orthogonal_index( + cell_xform.basis = p_grid_map->get_basis_with_orthogonal_index( p_grid_map->get_cell_item_orientation( Vector3(cell_location.x, cell_location.y, cell_location.z))); cell_xform.basis.scale(Vector3(p_grid_map->get_cell_scale(), p_grid_map->get_cell_scale(), p_grid_map->get_cell_scale())); - cell_xform.set_origin(p_grid_map->map_to_world( + cell_xform.set_origin(p_grid_map->map_to_local( Vector3(cell_location.x, cell_location.y, cell_location.z))); Ref<GLTFMesh> gltf_mesh; gltf_mesh.instantiate(); @@ -5652,21 +5598,32 @@ void GLTFDocument::_generate_scene_node(Ref<GLTFState> state, Node *scene_parent // and attach it to the bone_attachment scene_parent = bone_attachment; } - if (gltf_node->mesh >= 0) { - current_node = _generate_mesh_instance(state, node_index); - } else if (gltf_node->camera >= 0) { - current_node = _generate_camera(state, node_index); - } else if (gltf_node->light >= 0) { - current_node = _generate_light(state, node_index); + // Check if any GLTFDocumentExtension classes want to generate a node for us. + for (Ref<GLTFDocumentExtension> ext : document_extensions) { + ERR_CONTINUE(ext.is_null()); + current_node = ext->generate_scene_node(state, gltf_node, scene_parent); + if (current_node) { + break; + } } - - // We still have not managed to make a node. + // If none of our GLTFDocumentExtension classes generated us a node, we generate one. if (!current_node) { - current_node = _generate_spatial(state, node_index); + if (gltf_node->mesh >= 0) { + current_node = _generate_mesh_instance(state, node_index); + } else if (gltf_node->camera >= 0) { + current_node = _generate_camera(state, node_index); + } else if (gltf_node->light >= 0) { + current_node = _generate_light(state, node_index); + } else { + current_node = _generate_spatial(state, node_index); + } } + // Add the node we generated and set the owner to the scene root. scene_parent->add_child(current_node, true); if (current_node != scene_root) { - current_node->set_owner(scene_root); + Array args; + args.append(scene_root); + current_node->propagate_call(StringName("set_owner"), args); } current_node->set_transform(gltf_node->xform); current_node->set_name(gltf_node->get_name()); @@ -5732,19 +5689,32 @@ void GLTFDocument::_generate_skeleton_bone_node(Ref<GLTFState> state, Node *scen // and attach it to the bone_attachment scene_parent = bone_attachment; } - - // We still have not managed to make a node - if (gltf_node->mesh >= 0) { - current_node = _generate_mesh_instance(state, node_index); - } else if (gltf_node->camera >= 0) { - current_node = _generate_camera(state, node_index); - } else if (gltf_node->light >= 0) { - current_node = _generate_light(state, node_index); + // Check if any GLTFDocumentExtension classes want to generate a node for us. + for (Ref<GLTFDocumentExtension> ext : document_extensions) { + ERR_CONTINUE(ext.is_null()); + current_node = ext->generate_scene_node(state, gltf_node, scene_parent); + if (current_node) { + break; + } + } + // If none of our GLTFDocumentExtension classes generated us a node, we generate one. + if (!current_node) { + if (gltf_node->mesh >= 0) { + current_node = _generate_mesh_instance(state, node_index); + } else if (gltf_node->camera >= 0) { + current_node = _generate_camera(state, node_index); + } else if (gltf_node->light >= 0) { + current_node = _generate_light(state, node_index); + } else { + current_node = _generate_spatial(state, node_index); + } } - + // Add the node we generated and set the owner to the scene root. scene_parent->add_child(current_node, true); if (current_node != scene_root) { - current_node->set_owner(scene_root); + Array args; + args.append(scene_root); + current_node->propagate_call(StringName("set_owner"), args); } // Do not set transform here. Transform is already applied to our bone. current_node->set_name(gltf_node->get_name()); @@ -5881,15 +5851,15 @@ T GLTFDocument::_interpolate_track(const Vector<real_t> &p_times, const Vector<T void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, const GLTFAnimationIndex index, const int bake_fps) { Ref<GLTFAnimation> anim = state->animations[index]; - String name = anim->get_name(); - if (name.is_empty()) { + String anim_name = anim->get_name(); + if (anim_name.is_empty()) { // No node represent these, and they are not in the hierarchy, so just make a unique name - name = _gen_unique_name(state, "Animation"); + anim_name = _gen_unique_name(state, "Animation"); } Ref<Animation> animation; animation.instantiate(); - animation->set_name(name); + animation->set_name(anim_name); if (anim->get_loop()) { animation->set_loop_mode(Animation::LOOP_LINEAR); @@ -6112,7 +6082,7 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, } else { library = ap->get_animation_library(""); } - library->add_animation(name, animation); + library->add_animation(anim_name, animation); } void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { @@ -6348,7 +6318,7 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state for (int32_t key_i = 0; key_i < key_count; key_i++) { Vector3 rotation_radian = p_animation->track_get_key_value(p_track_i, key_i); - p_track.rotation_track.values.write[key_i] = Quaternion(rotation_radian); + p_track.rotation_track.values.write[key_i] = Quaternion::from_euler(rotation_radian); } } else if (path.contains(":scale")) { p_track.scale_track.times = times; @@ -6645,14 +6615,18 @@ Error GLTFDocument::_parse(Ref<GLTFState> state, String p_path, Ref<FileAccess> state->major_version = version.get_slice(".", 0).to_int(); state->minor_version = version.get_slice(".", 1).to_int(); - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + document_extensions.clear(); + for (Ref<GLTFDocumentExtension> ext : all_document_extensions) { ERR_CONTINUE(ext.is_null()); - err = ext->import_preflight(state); - ERR_FAIL_COND_V(err != OK, err); + err = ext->import_preflight(state, state->json["extensionsUsed"]); + if (err == OK) { + document_extensions.push_back(ext); + } } + err = _parse_gltf_state(state, p_path, p_bake_fps); ERR_FAIL_COND_V(err != OK, err); + return OK; } @@ -6785,14 +6759,8 @@ void GLTFDocument::_bind_methods() { ClassDB::bind_method(D_METHOD("write_to_filesystem", "state", "path"), &GLTFDocument::write_to_filesystem); - ClassDB::bind_method(D_METHOD("set_extensions", "extensions"), - &GLTFDocument::set_extensions); - ClassDB::bind_method(D_METHOD("get_extensions"), - &GLTFDocument::get_extensions); - ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "extensions", PROPERTY_HINT_ARRAY_TYPE, - vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "GLTFDocumentExtension"), - PROPERTY_USAGE_DEFAULT), - "set_extensions", "get_extensions"); + ClassDB::bind_static_method("GLTFDocument", D_METHOD("register_gltf_document_extension", "extension", "first_priority"), + &GLTFDocument::register_gltf_document_extension, DEFVAL(false)); } void GLTFDocument::_build_parent_hierachy(Ref<GLTFState> state) { @@ -6809,22 +6777,20 @@ void GLTFDocument::_build_parent_hierachy(Ref<GLTFState> state) { } } -void GLTFDocument::set_extensions(TypedArray<GLTFDocumentExtension> p_extensions) { - document_extensions = p_extensions; -} +Vector<Ref<GLTFDocumentExtension>> GLTFDocument::all_document_extensions; -TypedArray<GLTFDocumentExtension> GLTFDocument::get_extensions() const { - return document_extensions; +void GLTFDocument::register_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension, bool p_first_priority) { + if (all_document_extensions.find(p_extension) == -1) { + if (p_first_priority) { + all_document_extensions.insert(0, p_extension); + } else { + all_document_extensions.push_back(p_extension); + } + } } -GLTFDocument::GLTFDocument() { - bool is_editor = ::Engine::get_singleton()->is_editor_hint(); - if (is_editor) { - return; - } - Ref<GLTFDocumentExtensionConvertImporterMesh> extension_editor; - extension_editor.instantiate(); - document_extensions.push_back(extension_editor); +void GLTFDocument::unregister_all_gltf_document_extensions() { + all_document_extensions.clear(); } PackedByteArray GLTFDocument::_serialize_glb_buffer(Ref<GLTFState> state, Error *r_err) { @@ -6909,8 +6875,7 @@ Node *GLTFDocument::generate_scene(Ref<GLTFState> state, int32_t p_bake_fps) { } for (KeyValue<GLTFNodeIndex, Node *> E : state->scene_nodes) { ERR_CONTINUE(!E.value); - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + for (Ref<GLTFDocumentExtension> ext : document_extensions) { ERR_CONTINUE(ext.is_null()); ERR_CONTINUE(!state->json.has("nodes")); Array nodes = state->json["nodes"]; @@ -6922,8 +6887,7 @@ Node *GLTFDocument::generate_scene(Ref<GLTFState> state, int32_t p_bake_fps) { ERR_CONTINUE(err != OK); } } - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + for (Ref<GLTFDocumentExtension> ext : document_extensions) { ERR_CONTINUE(ext.is_null()); err = ext->import_post(state, root); ERR_CONTINUE(err != OK); @@ -6937,11 +6901,13 @@ Error GLTFDocument::append_from_scene(Node *p_node, Ref<GLTFState> state, uint32 state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS; state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS; - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + document_extensions.clear(); + for (Ref<GLTFDocumentExtension> ext : all_document_extensions) { ERR_CONTINUE(ext.is_null()); Error err = ext->export_preflight(p_node); - ERR_FAIL_COND_V(err != OK, FAILED); + if (err == OK) { + document_extensions.push_back(ext); + } } _convert_scene_node(state, p_node, -1, -1); if (!state->buffers.size()) { @@ -6963,8 +6929,7 @@ Error GLTFDocument::append_from_buffer(PackedByteArray p_bytes, String p_base_pa state->base_path = p_base_path.get_base_dir(); err = _parse(state, state->base_path, file_access, p_bake_fps); ERR_FAIL_COND_V(err != OK, err); - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + for (Ref<GLTFDocumentExtension> ext : document_extensions) { ERR_CONTINUE(ext.is_null()); err = ext->import_post_parse(state); ERR_FAIL_COND_V(err != OK, err); @@ -7008,6 +6973,11 @@ Error GLTFDocument::_parse_gltf_state(Ref<GLTFState> state, const String &p_sear ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR); + /* PARSE TEXTURE SAMPLERS */ + err = _parse_texture_samplers(state); + + ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR); + /* PARSE TEXTURES */ err = _parse_textures(state); @@ -7082,8 +7052,7 @@ Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> r_state, uint r_state->base_path = base_path; err = _parse(r_state, base_path, f, p_bake_fps); ERR_FAIL_COND_V(err != OK, err); - for (int32_t ext_i = 0; ext_i < document_extensions.size(); ext_i++) { - Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + for (Ref<GLTFDocumentExtension> ext : document_extensions) { ERR_CONTINUE(ext.is_null()); err = ext->import_post_parse(r_state); ERR_FAIL_COND_V(err != OK, err); @@ -7093,12 +7062,31 @@ Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> r_state, uint Error GLTFDocument::_parse_gltf_extensions(Ref<GLTFState> state) { ERR_FAIL_NULL_V(state, ERR_PARSE_ERROR); - if (state->json.has("extensionsRequired") && state->json["extensionsRequired"].get_type() == Variant::ARRAY) { - Array extensions_required = state->json["extensionsRequired"]; - if (extensions_required.find("KHR_draco_mesh_compression") != -1) { - ERR_PRINT("glTF2 extension KHR_draco_mesh_compression is not supported."); - return ERR_UNAVAILABLE; + if (state->json.has("extensionsUsed")) { + Vector<String> ext_array = state->json["extensionsUsed"]; + state->extensions_used = ext_array; + } + if (state->json.has("extensionsRequired")) { + Vector<String> ext_array = state->json["extensionsRequired"]; + state->extensions_required = ext_array; + } + HashSet<String> supported_extensions; + supported_extensions.insert("KHR_lights_punctual"); + supported_extensions.insert("KHR_materials_pbrSpecularGlossiness"); + supported_extensions.insert("KHR_texture_transform"); + for (Ref<GLTFDocumentExtension> ext : document_extensions) { + ERR_CONTINUE(ext.is_null()); + Vector<String> ext_supported_extensions = ext->get_supported_extensions(); + for (int i = 0; i < ext_supported_extensions.size(); ++i) { + supported_extensions.insert(ext_supported_extensions[i]); } } - return OK; + Error ret = Error::OK; + for (int i = 0; i < state->extensions_required.size(); i++) { + if (!supported_extensions.has(state->extensions_required[i])) { + ERR_PRINT("GLTF: Can't import file '" + state->filename + "', required extension '" + String(state->extensions_required[i]) + "' is not supported. Are you missing a GLTFDocumentExtension plugin?"); + ret = ERR_UNAVAILABLE; + } + } + return ret; } diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h index 36a2f94a4e..15099efe33 100644 --- a/modules/gltf/gltf_document.h +++ b/modules/gltf/gltf_document.h @@ -31,7 +31,7 @@ #ifndef GLTF_DOCUMENT_H #define GLTF_DOCUMENT_H -#include "gltf_defines.h" +#include "extensions/gltf_document_extension.h" #include "structures/gltf_animation.h" #include "scene/3d/bone_attachment_3d.h" @@ -44,13 +44,13 @@ class GLTFDocument : public Resource { GDCLASS(GLTFDocument, Resource); - TypedArray<GLTFDocumentExtension> document_extensions; + static Vector<Ref<GLTFDocumentExtension>> all_document_extensions; + Vector<Ref<GLTFDocumentExtension>> document_extensions; private: const float BAKE_FPS = 30.0f; public: - GLTFDocument(); const int32_t JOINT_GROUP_SIZE = 4; enum { @@ -76,8 +76,8 @@ protected: static void _bind_methods(); public: - void set_extensions(TypedArray<GLTFDocumentExtension> p_extensions); - TypedArray<GLTFDocumentExtension> get_extensions() const; + static void register_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension, bool p_first_priority = false); + static void unregister_all_gltf_document_extensions(); private: void _build_parent_hierachy(Ref<GLTFState> state); @@ -95,9 +95,14 @@ private: String _gen_unique_bone_name(Ref<GLTFState> state, const GLTFSkeletonIndex skel_i, const String &p_name); - GLTFTextureIndex _set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture); + GLTFTextureIndex _set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture, + StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats); Ref<Texture2D> _get_texture(Ref<GLTFState> state, const GLTFTextureIndex p_texture); + GLTFTextureSamplerIndex _set_sampler_for_mode(Ref<GLTFState> state, + StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats); + Ref<GLTFTextureSampler> _get_sampler_for_texture(Ref<GLTFState> state, + const GLTFTextureIndex p_texture); Error _parse_json(const String &p_path, Ref<GLTFState> state); Error _parse_glb(Ref<FileAccess> f, Ref<GLTFState> state); void _compute_node_heights(Ref<GLTFState> state); @@ -145,10 +150,12 @@ private: const bool p_for_vertex); Error _parse_meshes(Ref<GLTFState> state); Error _serialize_textures(Ref<GLTFState> state); + Error _serialize_texture_samplers(Ref<GLTFState> state); Error _serialize_images(Ref<GLTFState> state, const String &p_path); Error _serialize_lights(Ref<GLTFState> state); Error _parse_images(Ref<GLTFState> state, const String &p_base_path); Error _parse_textures(Ref<GLTFState> state); + Error _parse_texture_samplers(Ref<GLTFState> state); Error _parse_materials(Ref<GLTFState> state); void _set_texture_transform_uv1(const Dictionary &d, Ref<BaseMaterial3D> material); void spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, @@ -188,7 +195,7 @@ private: const GLTFNodeIndex bone_index); ImporterMeshInstance3D *_generate_mesh_instance(Ref<GLTFState> state, const GLTFNodeIndex node_index); Camera3D *_generate_camera(Ref<GLTFState> state, const GLTFNodeIndex node_index); - Node3D *_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index); + Light3D *_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index); Node3D *_generate_spatial(Ref<GLTFState> state, const GLTFNodeIndex node_index); void _assign_scene_names(Ref<GLTFState> state); template <class T> @@ -265,7 +272,7 @@ private: Dictionary _serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material); Error _serialize_version(Ref<GLTFState> state); Error _serialize_file(Ref<GLTFState> state, const String p_path); - Error _serialize_extensions(Ref<GLTFState> state) const; + Error _serialize_gltf_extensions(Ref<GLTFState> state) const; public: // https://www.itu.int/rec/R-REC-BT.601 diff --git a/modules/gltf/gltf_state.cpp b/modules/gltf/gltf_state.cpp index 8212e4c22f..ac5665e396 100644 --- a/modules/gltf/gltf_state.cpp +++ b/modules/gltf/gltf_state.cpp @@ -31,6 +31,7 @@ #include "gltf_state.h" void GLTFState::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_used_extension", "extension_name", "required"), &GLTFState::add_used_extension); ClassDB::bind_method(D_METHOD("get_json"), &GLTFState::get_json); ClassDB::bind_method(D_METHOD("set_json", "json"), &GLTFState::set_json); ClassDB::bind_method(D_METHOD("get_major_version"), &GLTFState::get_major_version); @@ -63,6 +64,8 @@ void GLTFState::_bind_methods() { ClassDB::bind_method(D_METHOD("set_root_nodes", "root_nodes"), &GLTFState::set_root_nodes); ClassDB::bind_method(D_METHOD("get_textures"), &GLTFState::get_textures); ClassDB::bind_method(D_METHOD("set_textures", "textures"), &GLTFState::set_textures); + ClassDB::bind_method(D_METHOD("get_texture_samplers"), &GLTFState::get_texture_samplers); + ClassDB::bind_method(D_METHOD("set_texture_samplers", "texture_samplers"), &GLTFState::set_texture_samplers); ClassDB::bind_method(D_METHOD("get_images"), &GLTFState::get_images); ClassDB::bind_method(D_METHOD("set_images", "images"), &GLTFState::set_images); ClassDB::bind_method(D_METHOD("get_skins"), &GLTFState::get_skins); @@ -84,6 +87,8 @@ void GLTFState::_bind_methods() { ClassDB::bind_method(D_METHOD("get_animations"), &GLTFState::get_animations); ClassDB::bind_method(D_METHOD("set_animations", "animations"), &GLTFState::set_animations); ClassDB::bind_method(D_METHOD("get_scene_node", "idx"), &GLTFState::get_scene_node); + ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFState::get_additional_data); + ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFState::set_additional_data); ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "json"), "set_json", "get_json"); // Dictionary ADD_PROPERTY(PropertyInfo(Variant::INT, "major_version"), "set_major_version", "get_major_version"); // int @@ -100,6 +105,7 @@ void GLTFState::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_path"), "set_base_path", "get_base_path"); // String ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "root_nodes"), "set_root_nodes", "get_root_nodes"); // Vector<int> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_textures", "get_textures"); // Vector<Ref<GLTFTexture>> + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "texture_samplers", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_texture_samplers", "get_texture_samplers"); //Vector<Ref<GLTFTextureSampler>> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "images", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_images", "get_images"); // Vector<Ref<Texture> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "skins", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_skins", "get_skins"); // Vector<Ref<GLTFSkin>> ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "cameras", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_cameras", "get_cameras"); // Vector<Ref<GLTFCamera>> @@ -112,6 +118,17 @@ void GLTFState::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "animations", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_animations", "get_animations"); // Vector<Ref<GLTFAnimation>> } +void GLTFState::add_used_extension(const String &p_extension_name, bool p_required) { + if (!extensions_used.has(p_extension_name)) { + extensions_used.push_back(p_extension_name); + } + if (p_required) { + if (!extensions_required.has(p_extension_name)) { + extensions_required.push_back(p_extension_name); + } + } +} + Dictionary GLTFState::get_json() { return json; } @@ -152,51 +169,51 @@ void GLTFState::set_use_named_skin_binds(bool p_use_named_skin_binds) { use_named_skin_binds = p_use_named_skin_binds; } -Array GLTFState::get_nodes() { +TypedArray<GLTFNode> GLTFState::get_nodes() { return GLTFTemplateConvert::to_array(nodes); } -void GLTFState::set_nodes(Array p_nodes) { +void GLTFState::set_nodes(TypedArray<GLTFNode> p_nodes) { GLTFTemplateConvert::set_from_array(nodes, p_nodes); } -Array GLTFState::get_buffers() { +TypedArray<PackedByteArray> GLTFState::get_buffers() { return GLTFTemplateConvert::to_array(buffers); } -void GLTFState::set_buffers(Array p_buffers) { +void GLTFState::set_buffers(TypedArray<PackedByteArray> p_buffers) { GLTFTemplateConvert::set_from_array(buffers, p_buffers); } -Array GLTFState::get_buffer_views() { +TypedArray<GLTFBufferView> GLTFState::get_buffer_views() { return GLTFTemplateConvert::to_array(buffer_views); } -void GLTFState::set_buffer_views(Array p_buffer_views) { +void GLTFState::set_buffer_views(TypedArray<GLTFBufferView> p_buffer_views) { GLTFTemplateConvert::set_from_array(buffer_views, p_buffer_views); } -Array GLTFState::get_accessors() { +TypedArray<GLTFAccessor> GLTFState::get_accessors() { return GLTFTemplateConvert::to_array(accessors); } -void GLTFState::set_accessors(Array p_accessors) { +void GLTFState::set_accessors(TypedArray<GLTFAccessor> p_accessors) { GLTFTemplateConvert::set_from_array(accessors, p_accessors); } -Array GLTFState::get_meshes() { +TypedArray<GLTFMesh> GLTFState::get_meshes() { return GLTFTemplateConvert::to_array(meshes); } -void GLTFState::set_meshes(Array p_meshes) { +void GLTFState::set_meshes(TypedArray<GLTFMesh> p_meshes) { GLTFTemplateConvert::set_from_array(meshes, p_meshes); } -Array GLTFState::get_materials() { +TypedArray<BaseMaterial3D> GLTFState::get_materials() { return GLTFTemplateConvert::to_array(materials); } -void GLTFState::set_materials(Array p_materials) { +void GLTFState::set_materials(TypedArray<BaseMaterial3D> p_materials) { GLTFTemplateConvert::set_from_array(materials, p_materials); } @@ -208,75 +225,83 @@ void GLTFState::set_scene_name(String p_scene_name) { scene_name = p_scene_name; } -Array GLTFState::get_root_nodes() { - return GLTFTemplateConvert::to_array(root_nodes); +PackedInt32Array GLTFState::get_root_nodes() { + return root_nodes; } -void GLTFState::set_root_nodes(Array p_root_nodes) { - GLTFTemplateConvert::set_from_array(root_nodes, p_root_nodes); +void GLTFState::set_root_nodes(PackedInt32Array p_root_nodes) { + root_nodes = p_root_nodes; } -Array GLTFState::get_textures() { +TypedArray<GLTFTexture> GLTFState::get_textures() { return GLTFTemplateConvert::to_array(textures); } -void GLTFState::set_textures(Array p_textures) { +void GLTFState::set_textures(TypedArray<GLTFTexture> p_textures) { GLTFTemplateConvert::set_from_array(textures, p_textures); } -Array GLTFState::get_images() { +TypedArray<GLTFTextureSampler> GLTFState::get_texture_samplers() { + return GLTFTemplateConvert::to_array(texture_samplers); +} + +void GLTFState::set_texture_samplers(TypedArray<GLTFTextureSampler> p_texture_samplers) { + GLTFTemplateConvert::set_from_array(texture_samplers, p_texture_samplers); +} + +TypedArray<Texture2D> GLTFState::get_images() { return GLTFTemplateConvert::to_array(images); } -void GLTFState::set_images(Array p_images) { +void GLTFState::set_images(TypedArray<Texture2D> p_images) { GLTFTemplateConvert::set_from_array(images, p_images); } -Array GLTFState::get_skins() { +TypedArray<GLTFSkin> GLTFState::get_skins() { return GLTFTemplateConvert::to_array(skins); } -void GLTFState::set_skins(Array p_skins) { +void GLTFState::set_skins(TypedArray<GLTFSkin> p_skins) { GLTFTemplateConvert::set_from_array(skins, p_skins); } -Array GLTFState::get_cameras() { +TypedArray<GLTFCamera> GLTFState::get_cameras() { return GLTFTemplateConvert::to_array(cameras); } -void GLTFState::set_cameras(Array p_cameras) { +void GLTFState::set_cameras(TypedArray<GLTFCamera> p_cameras) { GLTFTemplateConvert::set_from_array(cameras, p_cameras); } -Array GLTFState::get_lights() { +TypedArray<GLTFLight> GLTFState::get_lights() { return GLTFTemplateConvert::to_array(lights); } -void GLTFState::set_lights(Array p_lights) { +void GLTFState::set_lights(TypedArray<GLTFLight> p_lights) { GLTFTemplateConvert::set_from_array(lights, p_lights); } -Array GLTFState::get_unique_names() { +TypedArray<String> GLTFState::get_unique_names() { return GLTFTemplateConvert::to_array(unique_names); } -void GLTFState::set_unique_names(Array p_unique_names) { +void GLTFState::set_unique_names(TypedArray<String> p_unique_names) { GLTFTemplateConvert::set_from_array(unique_names, p_unique_names); } -Array GLTFState::get_unique_animation_names() { +TypedArray<String> GLTFState::get_unique_animation_names() { return GLTFTemplateConvert::to_array(unique_animation_names); } -void GLTFState::set_unique_animation_names(Array p_unique_animation_names) { +void GLTFState::set_unique_animation_names(TypedArray<String> p_unique_animation_names) { GLTFTemplateConvert::set_from_array(unique_animation_names, p_unique_animation_names); } -Array GLTFState::get_skeletons() { +TypedArray<GLTFSkeleton> GLTFState::get_skeletons() { return GLTFTemplateConvert::to_array(skeletons); } -void GLTFState::set_skeletons(Array p_skeletons) { +void GLTFState::set_skeletons(TypedArray<GLTFSkeleton> p_skeletons) { GLTFTemplateConvert::set_from_array(skeletons, p_skeletons); } @@ -296,11 +321,11 @@ void GLTFState::set_create_animations(bool p_create_animations) { create_animations = p_create_animations; } -Array GLTFState::get_animations() { +TypedArray<GLTFAnimation> GLTFState::get_animations() { return GLTFTemplateConvert::to_array(animations); } -void GLTFState::set_animations(Array p_animations) { +void GLTFState::set_animations(TypedArray<GLTFAnimation> p_animations) { GLTFTemplateConvert::set_from_array(animations, p_animations); } @@ -335,3 +360,11 @@ String GLTFState::get_base_path() { void GLTFState::set_base_path(String p_base_path) { base_path = p_base_path; } + +Variant GLTFState::get_additional_data(const StringName &p_extension_name) { + return additional_data[p_extension_name]; +} + +void GLTFState::set_additional_data(const StringName &p_extension_name, Variant p_additional_data) { + additional_data[p_extension_name] = p_additional_data; +} diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h index c08132f874..e24017b0fd 100644 --- a/modules/gltf/gltf_state.h +++ b/modules/gltf/gltf_state.h @@ -42,6 +42,7 @@ #include "structures/gltf_skeleton.h" #include "structures/gltf_skin.h" #include "structures/gltf_texture.h" +#include "structures/gltf_texture_sampler.h" #include "core/templates/rb_map.h" #include "scene/animation/animation_player.h" @@ -77,7 +78,11 @@ class GLTFState : public Resource { String scene_name; Vector<int> root_nodes; Vector<Ref<GLTFTexture>> textures; + Vector<Ref<GLTFTextureSampler>> texture_samplers; + Ref<GLTFTextureSampler> default_texture_sampler; Vector<Ref<Texture2D>> images; + Vector<String> extensions_used; + Vector<String> extensions_required; Vector<Ref<GLTFSkin>> skins; Vector<Ref<GLTFCamera>> cameras; @@ -92,11 +97,14 @@ class GLTFState : public Resource { HashMap<ObjectID, GLTFSkeletonIndex> skeleton3d_to_gltf_skeleton; HashMap<ObjectID, HashMap<ObjectID, GLTFSkinIndex>> skin_and_skeleton3d_to_gltf_skin; + Dictionary additional_data; protected: static void _bind_methods(); public: + void add_used_extension(const String &p_extension, bool p_required = false); + Dictionary get_json(); void set_json(Dictionary p_json); @@ -115,23 +123,23 @@ public: bool get_discard_meshes_and_materials(); void set_discard_meshes_and_materials(bool p_discard_meshes_and_materials); - Array get_nodes(); - void set_nodes(Array p_nodes); + TypedArray<GLTFNode> get_nodes(); + void set_nodes(TypedArray<GLTFNode> p_nodes); - Array get_buffers(); - void set_buffers(Array p_buffers); + TypedArray<PackedByteArray> get_buffers(); + void set_buffers(TypedArray<PackedByteArray> p_buffers); - Array get_buffer_views(); - void set_buffer_views(Array p_buffer_views); + TypedArray<GLTFBufferView> get_buffer_views(); + void set_buffer_views(TypedArray<GLTFBufferView> p_buffer_views); - Array get_accessors(); - void set_accessors(Array p_accessors); + TypedArray<GLTFAccessor> get_accessors(); + void set_accessors(TypedArray<GLTFAccessor> p_accessors); - Array get_meshes(); - void set_meshes(Array p_meshes); + TypedArray<GLTFMesh> get_meshes(); + void set_meshes(TypedArray<GLTFMesh> p_meshes); - Array get_materials(); - void set_materials(Array p_materials); + TypedArray<BaseMaterial3D> get_materials(); + void set_materials(TypedArray<BaseMaterial3D> p_materials); String get_scene_name(); void set_scene_name(String p_scene_name); @@ -139,32 +147,35 @@ public: String get_base_path(); void set_base_path(String p_base_path); - Array get_root_nodes(); - void set_root_nodes(Array p_root_nodes); + PackedInt32Array get_root_nodes(); + void set_root_nodes(PackedInt32Array p_root_nodes); + + TypedArray<GLTFTexture> get_textures(); + void set_textures(TypedArray<GLTFTexture> p_textures); - Array get_textures(); - void set_textures(Array p_textures); + TypedArray<GLTFTextureSampler> get_texture_samplers(); + void set_texture_samplers(TypedArray<GLTFTextureSampler> p_texture_samplers); - Array get_images(); - void set_images(Array p_images); + TypedArray<Texture2D> get_images(); + void set_images(TypedArray<Texture2D> p_images); - Array get_skins(); - void set_skins(Array p_skins); + TypedArray<GLTFSkin> get_skins(); + void set_skins(TypedArray<GLTFSkin> p_skins); - Array get_cameras(); - void set_cameras(Array p_cameras); + TypedArray<GLTFCamera> get_cameras(); + void set_cameras(TypedArray<GLTFCamera> p_cameras); - Array get_lights(); - void set_lights(Array p_lights); + TypedArray<GLTFLight> get_lights(); + void set_lights(TypedArray<GLTFLight> p_lights); - Array get_unique_names(); - void set_unique_names(Array p_unique_names); + TypedArray<String> get_unique_names(); + void set_unique_names(TypedArray<String> p_unique_names); - Array get_unique_animation_names(); - void set_unique_animation_names(Array p_unique_names); + TypedArray<String> get_unique_animation_names(); + void set_unique_animation_names(TypedArray<String> p_unique_names); - Array get_skeletons(); - void set_skeletons(Array p_skeletons); + TypedArray<GLTFSkeleton> get_skeletons(); + void set_skeletons(TypedArray<GLTFSkeleton> p_skeletons); Dictionary get_skeleton_to_node(); void set_skeleton_to_node(Dictionary p_skeleton_to_node); @@ -172,8 +183,8 @@ public: bool get_create_animations(); void set_create_animations(bool p_create_animations); - Array get_animations(); - void set_animations(Array p_animations); + TypedArray<GLTFAnimation> get_animations(); + void set_animations(TypedArray<GLTFAnimation> p_animations); Node *get_scene_node(GLTFNodeIndex idx); @@ -181,6 +192,9 @@ public: AnimationPlayer *get_animation_player(int idx); + Variant get_additional_data(const StringName &p_extension_name); + void set_additional_data(const StringName &p_extension_name, Variant p_additional_data); + //void set_scene_nodes(RBMap<GLTFNodeIndex, Node *> p_scene_nodes) { // this->scene_nodes = p_scene_nodes; //} diff --git a/modules/gltf/gltf_template_convert.h b/modules/gltf/gltf_template_convert.h index c915d3deb0..8a4b595c9f 100644 --- a/modules/gltf/gltf_template_convert.h +++ b/modules/gltf/gltf_template_convert.h @@ -46,8 +46,8 @@ static Array to_array(const Vector<T> &p_inp) { } template <class T> -static Array to_array(const HashSet<T> &p_inp) { - Array ret; +static TypedArray<T> to_array(const HashSet<T> &p_inp) { + TypedArray<T> ret; typename HashSet<T>::Iterator elem = p_inp.begin(); while (elem) { ret.push_back(*elem); @@ -65,7 +65,7 @@ static void set_from_array(Vector<T> &r_out, const Array &p_inp) { } template <class T> -static void set_from_array(HashSet<T> &r_out, const Array &p_inp) { +static void set_from_array(HashSet<T> &r_out, const TypedArray<T> &p_inp) { r_out.clear(); for (int i = 0; i < p_inp.size(); i++) { r_out.insert(p_inp[i]); diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp index 1e1204aa57..a7abf256ce 100644 --- a/modules/gltf/register_types.cpp +++ b/modules/gltf/register_types.cpp @@ -32,11 +32,10 @@ #ifndef _3D_DISABLED +#include "extensions/gltf_document_extension_convert_importer_mesh.h" #include "extensions/gltf_light.h" #include "extensions/gltf_spec_gloss.h" #include "gltf_document.h" -#include "gltf_document_extension.h" -#include "gltf_document_extension_convert_importer_mesh.h" #include "gltf_state.h" #include "structures/gltf_accessor.h" #include "structures/gltf_animation.h" @@ -47,6 +46,7 @@ #include "structures/gltf_skeleton.h" #include "structures/gltf_skin.h" #include "structures/gltf_texture.h" +#include "structures/gltf_texture_sampler.h" #ifdef TOOLS_ENABLED #include "core/config/project_settings.h" @@ -66,17 +66,24 @@ static void _editor_init() { bool blend_enabled = GLOBAL_GET("filesystem/import/blender/enabled"); // Defined here because EditorSettings doesn't exist in `register_gltf_types` yet. - EDITOR_DEF_RST("filesystem/import/blender/blender3_path", ""); + String blender3_path = EDITOR_DEF_RST("filesystem/import/blender/blender3_path", ""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "filesystem/import/blender/blender3_path", PROPERTY_HINT_GLOBAL_DIR)); if (blend_enabled) { - Ref<EditorSceneFormatImporterBlend> importer; - importer.instantiate(); - ResourceImporterScene::add_importer(importer); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (blender3_path.is_empty()) { + WARN_PRINT("Blend file import is enabled in the project settings, but no Blender path is configured in the editor settings. Blend files will not be imported."); + } else if (!da->dir_exists(blender3_path)) { + WARN_PRINT("Blend file import is enabled, but the Blender path doesn't point to an accessible directory. Blend files will not be imported."); + } else { + Ref<EditorSceneFormatImporterBlend> importer; + importer.instantiate(); + ResourceImporterScene::add_importer(importer); - Ref<EditorFileSystemImportFormatSupportQueryBlend> blend_import_query; - blend_import_query.instantiate(); - EditorFileSystem::get_singleton()->add_import_format_support_query(blend_import_query); + Ref<EditorFileSystemImportFormatSupportQueryBlend> blend_import_query; + blend_import_query.instantiate(); + EditorFileSystem::get_singleton()->add_import_format_support_query(blend_import_query); + } } // FBX to glTF importer. @@ -89,9 +96,9 @@ static void _editor_init() { if (fbx_enabled) { Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (fbx2gltf_path.is_empty()) { - WARN_PRINT("FBX file import is enabled, but no FBX2glTF path is configured. FBX files will not be imported."); + WARN_PRINT("FBX file import is enabled in the project settings, but no FBX2glTF path is configured in the editor settings. FBX files will not be imported."); } else if (!da->file_exists(fbx2gltf_path)) { - WARN_PRINT("FBX file import is enabled, but the FBX2glTF path doesn't point to a valid FBX2glTF executable. FBX files will not be imported."); + WARN_PRINT("FBX file import is enabled, but the FBX2glTF path doesn't point to an accessible file. FBX files will not be imported."); } else { Ref<EditorSceneFormatImporterFBX> importer; importer.instantiate(); @@ -101,6 +108,11 @@ static void _editor_init() { } #endif // TOOLS_ENABLED +#define GLTF_REGISTER_DOCUMENT_EXTENSION(m_doc_ext_class) \ + Ref<m_doc_ext_class> extension_##m_doc_ext_class; \ + extension_##m_doc_ext_class.instantiate(); \ + GLTFDocument::register_gltf_document_extension(extension_##m_doc_ext_class); + void initialize_gltf_module(ModuleInitializationLevel p_level) { if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) { // glTF API available at runtime. @@ -119,6 +131,12 @@ void initialize_gltf_module(ModuleInitializationLevel p_level) { GDREGISTER_CLASS(GLTFSpecGloss); GDREGISTER_CLASS(GLTFState); GDREGISTER_CLASS(GLTFTexture); + GDREGISTER_CLASS(GLTFTextureSampler); + // Register GLTFDocumentExtension classes with GLTFDocument. + bool is_editor = ::Engine::get_singleton()->is_editor_hint(); + if (!is_editor) { + GLTF_REGISTER_DOCUMENT_EXTENSION(GLTFDocumentExtensionConvertImporterMesh); + } } #ifdef TOOLS_ENABLED @@ -135,6 +153,11 @@ void initialize_gltf_module(ModuleInitializationLevel p_level) { GLOBAL_DEF_RST("filesystem/import/fbx/enabled", true); GDREGISTER_CLASS(EditorSceneFormatImporterBlend); GDREGISTER_CLASS(EditorSceneFormatImporterFBX); + // Can't (a priori) run external app on these platforms. + GLOBAL_DEF_RST("filesystem/import/blender/enabled.android", false); + GLOBAL_DEF_RST("filesystem/import/blender/enabled.web", false); + GLOBAL_DEF_RST("filesystem/import/fbx/enabled.android", false); + GLOBAL_DEF_RST("filesystem/import/fbx/enabled.web", false); ClassDB::set_current_api(prev_api); EditorNode::add_init_callback(_editor_init); @@ -147,6 +170,7 @@ void uninitialize_gltf_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } + GLTFDocument::unregister_all_gltf_document_extensions(); } #endif // _3D_DISABLED diff --git a/modules/gltf/register_types.h b/modules/gltf/register_types.h index 90b9a83c88..bf2730d2ef 100644 --- a/modules/gltf/register_types.h +++ b/modules/gltf/register_types.h @@ -28,7 +28,12 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#ifndef GLTF_REGISTER_TYPES_H +#define GLTF_REGISTER_TYPES_H + #include "modules/register_module_types.h" void initialize_gltf_module(ModuleInitializationLevel p_level); void uninitialize_gltf_module(ModuleInitializationLevel p_level); + +#endif // GLTF_REGISTER_TYPES_H diff --git a/modules/gltf/structures/gltf_buffer_view.cpp b/modules/gltf/structures/gltf_buffer_view.cpp index ba19ed8628..a15141225b 100644 --- a/modules/gltf/structures/gltf_buffer_view.cpp +++ b/modules/gltf/structures/gltf_buffer_view.cpp @@ -30,8 +30,6 @@ #include "gltf_buffer_view.h" -#include "../gltf_document_extension.h" - void GLTFBufferView::_bind_methods() { ClassDB::bind_method(D_METHOD("get_buffer"), &GLTFBufferView::get_buffer); ClassDB::bind_method(D_METHOD("set_buffer", "buffer"), &GLTFBufferView::set_buffer); diff --git a/modules/gltf/structures/gltf_camera.cpp b/modules/gltf/structures/gltf_camera.cpp index f3ea6a1c4c..212b9b80c8 100644 --- a/modules/gltf/structures/gltf_camera.cpp +++ b/modules/gltf/structures/gltf_camera.cpp @@ -31,17 +31,102 @@ #include "gltf_camera.h" void GLTFCamera::_bind_methods() { + ClassDB::bind_static_method("GLTFCamera", D_METHOD("from_node", "camera_node"), &GLTFCamera::from_node); + ClassDB::bind_method(D_METHOD("to_node"), &GLTFCamera::to_node); + + ClassDB::bind_static_method("GLTFCamera", D_METHOD("from_dictionary", "dictionary"), &GLTFCamera::from_dictionary); + ClassDB::bind_method(D_METHOD("to_dictionary"), &GLTFCamera::to_dictionary); + ClassDB::bind_method(D_METHOD("get_perspective"), &GLTFCamera::get_perspective); 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_fov"), &GLTFCamera::get_fov); + ClassDB::bind_method(D_METHOD("set_fov", "fov"), &GLTFCamera::set_fov); + ClassDB::bind_method(D_METHOD("get_size_mag"), &GLTFCamera::get_size_mag); + ClassDB::bind_method(D_METHOD("set_size_mag", "size_mag"), &GLTFCamera::set_size_mag); 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, "depth_far"), "set_depth_far", "get_depth_far"); // float - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_near"), "set_depth_near", "get_depth_near"); // float + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "perspective"), "set_perspective", "get_perspective"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov"), "set_fov", "get_fov"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size_mag"), "set_size_mag", "get_size_mag"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_far"), "set_depth_far", "get_depth_far"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth_near"), "set_depth_near", "get_depth_near"); +} + +Ref<GLTFCamera> GLTFCamera::from_node(const Camera3D *p_camera) { + Ref<GLTFCamera> c; + c.instantiate(); + ERR_FAIL_COND_V_MSG(!p_camera, c, "Tried to create a GLTFCamera from a Camera3D node, but the given node was null."); + c->set_perspective(p_camera->get_projection() == Camera3D::ProjectionType::PROJECTION_PERSPECTIVE); + // GLTF spec (yfov) is in radians, Godot's camera (fov) is in degrees. + c->set_fov(Math::deg_to_rad(p_camera->get_fov())); + // GLTF spec (xmag and ymag) is a radius in meters, Godot's camera (size) is a diameter in meters. + c->set_size_mag(p_camera->get_size() * 0.5f); + c->set_depth_far(p_camera->get_far()); + c->set_depth_near(p_camera->get_near()); + return c; +} + +Camera3D *GLTFCamera::to_node() const { + Camera3D *camera = memnew(Camera3D); + camera->set_projection(perspective ? Camera3D::PROJECTION_PERSPECTIVE : Camera3D::PROJECTION_ORTHOGONAL); + // GLTF spec (yfov) is in radians, Godot's camera (fov) is in degrees. + camera->set_fov(Math::rad_to_deg(fov)); + // GLTF spec (xmag and ymag) is a radius in meters, Godot's camera (size) is a diameter in meters. + camera->set_size(size_mag * 2.0f); + camera->set_near(depth_near); + camera->set_far(depth_far); + return camera; +} + +Ref<GLTFCamera> GLTFCamera::from_dictionary(const Dictionary p_dictionary) { + ERR_FAIL_COND_V_MSG(!p_dictionary.has("type"), Ref<GLTFCamera>(), "Failed to parse GLTF camera, missing required field 'type'."); + Ref<GLTFCamera> camera; + camera.instantiate(); + const String &type = p_dictionary["type"]; + if (type == "perspective") { + camera->set_perspective(true); + if (p_dictionary.has("perspective")) { + const Dictionary &persp = p_dictionary["perspective"]; + camera->set_fov(persp["yfov"]); + if (persp.has("zfar")) { + camera->set_depth_far(persp["zfar"]); + } + camera->set_depth_near(persp["znear"]); + } + } else if (type == "orthographic") { + camera->set_perspective(false); + if (p_dictionary.has("orthographic")) { + const Dictionary &ortho = p_dictionary["orthographic"]; + camera->set_size_mag(ortho["ymag"]); + camera->set_depth_far(ortho["zfar"]); + camera->set_depth_near(ortho["znear"]); + } + } else { + ERR_PRINT("Error parsing GLTF camera: Camera type '" + type + "' is unknown, should be perspective or orthographic."); + } + return camera; +} + +Dictionary GLTFCamera::to_dictionary() const { + Dictionary d; + if (perspective) { + Dictionary persp; + persp["yfov"] = fov; + persp["zfar"] = depth_far; + persp["znear"] = depth_near; + d["perspective"] = persp; + d["type"] = "perspective"; + } else { + Dictionary ortho; + ortho["ymag"] = size_mag; + ortho["xmag"] = size_mag; + ortho["zfar"] = depth_far; + ortho["znear"] = depth_near; + d["orthographic"] = ortho; + d["type"] = "orthographic"; + } + return d; } diff --git a/modules/gltf/structures/gltf_camera.h b/modules/gltf/structures/gltf_camera.h index b7df741825..50ae10e17a 100644 --- a/modules/gltf/structures/gltf_camera.h +++ b/modules/gltf/structures/gltf_camera.h @@ -32,15 +32,22 @@ #define GLTF_CAMERA_H #include "core/io/resource.h" +#include "scene/3d/camera_3d.h" + +// Reference and test file: +// https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_015_SimpleCameras.md class GLTFCamera : public Resource { GDCLASS(GLTFCamera, Resource); private: + // GLTF has no default camera values, they should always be specified in + // the GLTF file. Here we default to Godot's default camera settings. bool perspective = true; - float fov_size = 75.0; - float depth_far = 4000.0; - float depth_near = 0.05; + real_t fov = Math::deg_to_rad(75.0); + real_t size_mag = 0.5; + real_t depth_far = 4000.0; + real_t depth_near = 0.05; protected: static void _bind_methods(); @@ -48,12 +55,20 @@ protected: public: bool get_perspective() const { return perspective; } 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_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; } + real_t get_fov() const { return fov; } + void set_fov(real_t p_val) { fov = p_val; } + real_t get_size_mag() const { return size_mag; } + void set_size_mag(real_t p_val) { size_mag = p_val; } + real_t get_depth_far() const { return depth_far; } + void set_depth_far(real_t p_val) { depth_far = p_val; } + real_t get_depth_near() const { return depth_near; } + void set_depth_near(real_t p_val) { depth_near = p_val; } + + static Ref<GLTFCamera> from_node(const Camera3D *p_light); + Camera3D *to_node() const; + + static Ref<GLTFCamera> from_dictionary(const Dictionary p_dictionary); + Dictionary to_dictionary() const; }; #endif // GLTF_CAMERA_H diff --git a/modules/gltf/structures/gltf_mesh.cpp b/modules/gltf/structures/gltf_mesh.cpp index 3add8304b1..3893f56626 100644 --- a/modules/gltf/structures/gltf_mesh.cpp +++ b/modules/gltf/structures/gltf_mesh.cpp @@ -53,11 +53,11 @@ void GLTFMesh::set_mesh(Ref<ImporterMesh> p_mesh) { mesh = p_mesh; } -Array GLTFMesh::get_instance_materials() { +TypedArray<Material> GLTFMesh::get_instance_materials() { return instance_materials; } -void GLTFMesh::set_instance_materials(Array p_instance_materials) { +void GLTFMesh::set_instance_materials(TypedArray<Material> p_instance_materials) { instance_materials = p_instance_materials; } diff --git a/modules/gltf/structures/gltf_mesh.h b/modules/gltf/structures/gltf_mesh.h index dc26120b48..2fa37fd727 100644 --- a/modules/gltf/structures/gltf_mesh.h +++ b/modules/gltf/structures/gltf_mesh.h @@ -42,7 +42,7 @@ class GLTFMesh : public Resource { private: Ref<ImporterMesh> mesh; Vector<float> blend_weights; - Array instance_materials; + TypedArray<Material> instance_materials; protected: static void _bind_methods(); @@ -52,8 +52,8 @@ public: void set_mesh(Ref<ImporterMesh> p_mesh); Vector<float> get_blend_weights(); void set_blend_weights(Vector<float> p_blend_weights); - Array get_instance_materials(); - void set_instance_materials(Array p_instance_materials); + TypedArray<Material> get_instance_materials(); + void set_instance_materials(TypedArray<Material> p_instance_materials); }; #endif // GLTF_MESH_H diff --git a/modules/gltf/structures/gltf_node.cpp b/modules/gltf/structures/gltf_node.cpp index 86280603fa..6fd36f93b7 100644 --- a/modules/gltf/structures/gltf_node.cpp +++ b/modules/gltf/structures/gltf_node.cpp @@ -57,6 +57,8 @@ void GLTFNode::_bind_methods() { ClassDB::bind_method(D_METHOD("set_children", "children"), &GLTFNode::set_children); ClassDB::bind_method(D_METHOD("get_light"), &GLTFNode::get_light); ClassDB::bind_method(D_METHOD("set_light", "light"), &GLTFNode::set_light); + ClassDB::bind_method(D_METHOD("get_additional_data", "extension_name"), &GLTFNode::get_additional_data); + ClassDB::bind_method(D_METHOD("set_additional_data", "extension_name", "additional_data"), &GLTFNode::set_additional_data); ADD_PROPERTY(PropertyInfo(Variant::INT, "parent"), "set_parent", "get_parent"); // GLTFNodeIndex ADD_PROPERTY(PropertyInfo(Variant::INT, "height"), "set_height", "get_height"); // int @@ -176,3 +178,11 @@ GLTFLightIndex GLTFNode::get_light() { void GLTFNode::set_light(GLTFLightIndex p_light) { light = p_light; } + +Variant GLTFNode::get_additional_data(const StringName &p_extension_name) { + return additional_data[p_extension_name]; +} + +void GLTFNode::set_additional_data(const StringName &p_extension_name, Variant p_additional_data) { + additional_data[p_extension_name] = p_additional_data; +} diff --git a/modules/gltf/structures/gltf_node.h b/modules/gltf/structures/gltf_node.h index 1a57ea32e2..90a4fa99ed 100644 --- a/modules/gltf/structures/gltf_node.h +++ b/modules/gltf/structures/gltf_node.h @@ -53,6 +53,7 @@ private: Vector3 scale = Vector3(1, 1, 1); Vector<int> children; GLTFLightIndex light = -1; + Dictionary additional_data; protected: static void _bind_methods(); @@ -96,6 +97,9 @@ public: GLTFLightIndex get_light(); void set_light(GLTFLightIndex p_light); + + Variant get_additional_data(const StringName &p_extension_name); + void set_additional_data(const StringName &p_extension_name, Variant p_additional_data); }; #endif // GLTF_NODE_H diff --git a/modules/gltf/structures/gltf_skeleton.cpp b/modules/gltf/structures/gltf_skeleton.cpp index 90a6b0f50f..0073357eda 100644 --- a/modules/gltf/structures/gltf_skeleton.cpp +++ b/modules/gltf/structures/gltf_skeleton.cpp @@ -72,11 +72,11 @@ Skeleton3D *GLTFSkeleton::get_godot_skeleton() { return godot_skeleton; } -Array GLTFSkeleton::get_unique_names() { +TypedArray<String> GLTFSkeleton::get_unique_names() { return GLTFTemplateConvert::to_array(unique_names); } -void GLTFSkeleton::set_unique_names(Array p_unique_names) { +void GLTFSkeleton::set_unique_names(TypedArray<String> p_unique_names) { GLTFTemplateConvert::set_from_array(unique_names, p_unique_names); } diff --git a/modules/gltf/structures/gltf_skeleton.h b/modules/gltf/structures/gltf_skeleton.h index db88623213..0f20b493b6 100644 --- a/modules/gltf/structures/gltf_skeleton.h +++ b/modules/gltf/structures/gltf_skeleton.h @@ -75,8 +75,8 @@ public: // this->godot_skeleton = p_godot_skeleton; // } - Array get_unique_names(); - void set_unique_names(Array p_unique_names); + TypedArray<String> get_unique_names(); + void set_unique_names(TypedArray<String> p_unique_names); //RBMap<int32_t, GLTFNodeIndex> get_godot_bone_node() { // return this->godot_bone_node; diff --git a/modules/gltf/structures/gltf_skin.cpp b/modules/gltf/structures/gltf_skin.cpp index 2e46ee3be2..9717a66048 100644 --- a/modules/gltf/structures/gltf_skin.cpp +++ b/modules/gltf/structures/gltf_skin.cpp @@ -31,6 +31,7 @@ #include "gltf_skin.h" #include "../gltf_template_convert.h" +#include "core/variant/typed_array.h" #include "scene/resources/skin.h" void GLTFSkin::_bind_methods() { @@ -83,11 +84,11 @@ void GLTFSkin::set_joints_original(Vector<GLTFNodeIndex> p_joints_original) { joints_original = p_joints_original; } -Array GLTFSkin::get_inverse_binds() { +TypedArray<Transform3D> GLTFSkin::get_inverse_binds() { return GLTFTemplateConvert::to_array(inverse_binds); } -void GLTFSkin::set_inverse_binds(Array p_inverse_binds) { +void GLTFSkin::set_inverse_binds(TypedArray<Transform3D> p_inverse_binds) { GLTFTemplateConvert::set_from_array(inverse_binds, p_inverse_binds); } diff --git a/modules/gltf/structures/gltf_skin.h b/modules/gltf/structures/gltf_skin.h index 59b6a300ac..1a4d54b380 100644 --- a/modules/gltf/structures/gltf_skin.h +++ b/modules/gltf/structures/gltf_skin.h @@ -34,6 +34,9 @@ #include "../gltf_defines.h" #include "core/io/resource.h" +template <typename T> +class TypedArray; + class GLTFSkin : public Resource { GDCLASS(GLTFSkin, Resource); friend class GLTFDocument; @@ -82,8 +85,8 @@ public: Vector<GLTFNodeIndex> get_joints_original(); void set_joints_original(Vector<GLTFNodeIndex> p_joints_original); - Array get_inverse_binds(); - void set_inverse_binds(Array p_inverse_binds); + TypedArray<Transform3D> get_inverse_binds(); + void set_inverse_binds(TypedArray<Transform3D> p_inverse_binds); Vector<GLTFNodeIndex> get_joints(); void set_joints(Vector<GLTFNodeIndex> p_joints); diff --git a/modules/gltf/structures/gltf_texture.cpp b/modules/gltf/structures/gltf_texture.cpp index 2a21cb3df8..5cc96e3221 100644 --- a/modules/gltf/structures/gltf_texture.cpp +++ b/modules/gltf/structures/gltf_texture.cpp @@ -33,8 +33,11 @@ void GLTFTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("get_src_image"), &GLTFTexture::get_src_image); ClassDB::bind_method(D_METHOD("set_src_image", "src_image"), &GLTFTexture::set_src_image); + ClassDB::bind_method(D_METHOD("get_sampler"), &GLTFTexture::get_sampler); + ClassDB::bind_method(D_METHOD("set_sampler", "sampler"), &GLTFTexture::set_sampler); ADD_PROPERTY(PropertyInfo(Variant::INT, "src_image"), "set_src_image", "get_src_image"); // int + ADD_PROPERTY(PropertyInfo(Variant::INT, "sampler"), "set_sampler", "get_sampler"); // int } GLTFImageIndex GLTFTexture::get_src_image() const { @@ -44,3 +47,11 @@ GLTFImageIndex GLTFTexture::get_src_image() const { void GLTFTexture::set_src_image(GLTFImageIndex val) { src_image = val; } + +GLTFTextureSamplerIndex GLTFTexture::get_sampler() const { + return sampler; +} + +void GLTFTexture::set_sampler(GLTFTextureSamplerIndex val) { + sampler = val; +} diff --git a/modules/gltf/structures/gltf_texture.h b/modules/gltf/structures/gltf_texture.h index b1d12dddfa..b26c8a7b07 100644 --- a/modules/gltf/structures/gltf_texture.h +++ b/modules/gltf/structures/gltf_texture.h @@ -39,6 +39,7 @@ class GLTFTexture : public Resource { private: GLTFImageIndex src_image = 0; + GLTFTextureSamplerIndex sampler = -1; protected: static void _bind_methods(); @@ -46,6 +47,8 @@ protected: public: GLTFImageIndex get_src_image() const; void set_src_image(GLTFImageIndex val); + GLTFTextureSamplerIndex get_sampler() const; + void set_sampler(GLTFTextureSamplerIndex val); }; #endif // GLTF_TEXTURE_H diff --git a/modules/gltf/structures/gltf_texture_sampler.cpp b/modules/gltf/structures/gltf_texture_sampler.cpp new file mode 100644 index 0000000000..6cf615b6cc --- /dev/null +++ b/modules/gltf/structures/gltf_texture_sampler.cpp @@ -0,0 +1,47 @@ +/*************************************************************************/ +/* gltf_texture_sampler.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "gltf_texture_sampler.h" + +void GLTFTextureSampler::_bind_methods() { + ClassDB::bind_method(D_METHOD("get_mag_filter"), &GLTFTextureSampler::get_mag_filter); + ClassDB::bind_method(D_METHOD("set_mag_filter", "filter_mode"), &GLTFTextureSampler::set_mag_filter); + ClassDB::bind_method(D_METHOD("get_min_filter"), &GLTFTextureSampler::get_min_filter); + ClassDB::bind_method(D_METHOD("set_min_filter", "filter_mode"), &GLTFTextureSampler::set_min_filter); + ClassDB::bind_method(D_METHOD("get_wrap_s"), &GLTFTextureSampler::get_wrap_s); + ClassDB::bind_method(D_METHOD("set_wrap_s", "wrap_mode"), &GLTFTextureSampler::set_wrap_s); + ClassDB::bind_method(D_METHOD("get_wrap_t"), &GLTFTextureSampler::get_wrap_t); + ClassDB::bind_method(D_METHOD("set_wrap_t", "wrap_mode"), &GLTFTextureSampler::set_wrap_t); + + ADD_PROPERTY(PropertyInfo(Variant::INT, "mag_filter"), "set_mag_filter", "get_mag_filter"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "min_filter"), "set_min_filter", "get_min_filter"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "wrap_s"), "set_wrap_s", "get_wrap_s"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "wrap_t"), "set_wrap_t", "get_wrap_t"); +} diff --git a/modules/gltf/structures/gltf_texture_sampler.h b/modules/gltf/structures/gltf_texture_sampler.h new file mode 100644 index 0000000000..3fad31bbee --- /dev/null +++ b/modules/gltf/structures/gltf_texture_sampler.h @@ -0,0 +1,163 @@ +/*************************************************************************/ +/* gltf_texture_sampler.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef GLTF_TEXTURE_SAMPLER_H +#define GLTF_TEXTURE_SAMPLER_H + +#include "core/io/resource.h" +#include "scene/resources/material.h" + +class GLTFTextureSampler : public Resource { + GDCLASS(GLTFTextureSampler, Resource); + +public: + enum FilterMode { + NEAREST = 9728, + LINEAR = 9729, + NEAREST_MIPMAP_NEAREST = 9984, + LINEAR_MIPMAP_NEAREST = 9985, + NEAREST_MIPMAP_LINEAR = 9986, + LINEAR_MIPMAP_LINEAR = 9987 + }; + + enum WrapMode { + CLAMP_TO_EDGE = 33071, + MIRRORED_REPEAT = 33648, + REPEAT = 10497, + DEFAULT = REPEAT + }; + + int get_mag_filter() const { + return mag_filter; + } + + void set_mag_filter(const int filter_mode) { + mag_filter = (FilterMode)filter_mode; + } + + int get_min_filter() const { + return min_filter; + } + + void set_min_filter(const int filter_mode) { + min_filter = (FilterMode)filter_mode; + } + + int get_wrap_s() const { + return wrap_s; + } + + void set_wrap_s(const int wrap_mode) { + wrap_s = (WrapMode)wrap_mode; + } + + int get_wrap_t() const { + return wrap_t; + } + + void set_wrap_t(const int wrap_mode) { + wrap_s = (WrapMode)wrap_mode; + } + + StandardMaterial3D::TextureFilter get_filter_mode() const { + using TextureFilter = StandardMaterial3D::TextureFilter; + + switch (min_filter) { + case NEAREST: + return TextureFilter::TEXTURE_FILTER_NEAREST; + case LINEAR: + return TextureFilter::TEXTURE_FILTER_LINEAR; + case NEAREST_MIPMAP_NEAREST: + case NEAREST_MIPMAP_LINEAR: + return TextureFilter::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS; + case LINEAR_MIPMAP_NEAREST: + case LINEAR_MIPMAP_LINEAR: + default: + return TextureFilter::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS; + } + } + + void set_filter_mode(StandardMaterial3D::TextureFilter mode) { + using TextureFilter = StandardMaterial3D::TextureFilter; + + switch (mode) { + case TextureFilter::TEXTURE_FILTER_NEAREST: + min_filter = FilterMode::NEAREST; + mag_filter = FilterMode::NEAREST; + break; + case TextureFilter::TEXTURE_FILTER_LINEAR: + min_filter = FilterMode::LINEAR; + mag_filter = FilterMode::LINEAR; + break; + case TextureFilter::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS: + case TextureFilter::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC: + min_filter = FilterMode::NEAREST_MIPMAP_LINEAR; + mag_filter = FilterMode::NEAREST; + break; + case TextureFilter::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS: + case TextureFilter::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC: + default: + min_filter = FilterMode::LINEAR_MIPMAP_LINEAR; + mag_filter = FilterMode::LINEAR; + break; + } + } + + bool get_wrap_mode() const { + // BaseMaterial3D presents wrapping as a boolean property. Either the texture is repeated + // in both dimensions, non-mirrored, or it isn't repeated at all. This will cause oddities + // when people import models having other wrapping mode combinations. + return (wrap_s == WrapMode::REPEAT) && (wrap_t == WrapMode::REPEAT); + } + + void set_wrap_mode(bool mat_repeats) { + if (mat_repeats) { + wrap_s = WrapMode::REPEAT; + wrap_t = WrapMode::REPEAT; + } else { + wrap_s = WrapMode::CLAMP_TO_EDGE; + wrap_t = WrapMode::CLAMP_TO_EDGE; + } + } + +protected: + static void _bind_methods(); + +private: + FilterMode mag_filter = FilterMode::LINEAR; + FilterMode min_filter = FilterMode::LINEAR_MIPMAP_LINEAR; + WrapMode wrap_s = WrapMode::REPEAT; + WrapMode wrap_t = WrapMode::REPEAT; +}; + +VARIANT_ENUM_CAST(GLTFTextureSampler::FilterMode); +VARIANT_ENUM_CAST(GLTFTextureSampler::WrapMode); + +#endif // GLTF_TEXTURE_SAMPLER_H |