Importing 3D scenes

Godot scene importer

Ao lidar com assets 3D, Godot tem um flexível e configurável importador.

Godot trabalha com cenas. Isso significa que a cena inteira sendo trabalhada na sua favorita 3D

Godot supports the following 3D scene file formats:

  • glTF 2.0. Godot has full support for text and binary formats.
  • DAE (COLLADA), an older format that is fully supported.
  • Formatos OBJ (Wavefront). Também é oferecido suporte completo, mas bastante limitado (sem suporte para pivots, esqueletos, etc).
  • ESCN, a Godot specific format that Blender can export with a plugin.
  • FBX, supported via the Open Asset Import library. However, FBX is proprietary so we recommend using other formats listed above, if suitable for your workflow.

Simplesmente copie o arquivo todo da cena com a textura para o repositório do projeto, e o Godot fará uma importação completa.

É importante que a malha não esteja deformada pelos ossos quando for exportar. Tenha certeza que o esqueleto esteja setado em pose tipo T ou pose de descanso padrão antes de exportar usando seu editor 3D favorito.

Exportando arquivos DAE do Maya e 3DS Max

A Autodesk adicionou suporte nativo ao formato COLLADA no Maya e no 3DS Max, mas ele não funciona por padrão e não deveria ser utilizado. A menlhor maneira de exportar esse formado é usando os plugins OpenCollada. Eles funcionam bem, apesar de que nem sempre estão atualizados com a última versão do software.

Exporting glTF 2.0 files from Blender

There are three ways to export glTF files from Blender. As a glTF binary (.glb file), glTF embedded (.gltf file), and with textures (gltf + .bin + textures).

glTF binary files are the smallest of the three options. They include the mesh and textures set up in Blender. When brought into Godot the textures are part of the object’s material file.

glTF embedded files function the same way as binary files. They don’t provide extra functionality in Godot, and shouldn’t be used since they have a larger file size.

There are two reasons to use glTF with the textures separate. One is to have the scene description in a text based format and the binary data in a separate binary file. This can be useful for version control if you want to review changes in a text based format. The second is you need the texture files separate from the material file. If you don’t need either of those glTF binary files are fine.

Nota

Blender does not export emissive textures with the glTF file. If your model uses one it must be brought in separately.

Exportando arquivos DAE no Blender

Blender has built-in COLLADA support, but it does not work properly for the needs of game engines and should not be used as is.

Godot provides a Blender plugin that will correctly export COLLADA scenes for use in Godot.

Exportando arquivos ESCN do Blender

O mais poderoso, chamado godot-blender-exporter. Ele usa um arquivo .escn, o qual é uma espécie de arquivo .tscn (arquivo Godot Scene); ele retém o máximo de informações possível sobre uma Blender Scene.

O exportador ESCN tem um detalhado document descrevendo seu uso e funcionalidade.

Importar fluxos de trabalho

O importador de cenas do Godot permite diferentes fluxos de trabalho a respeito de como os dados são importados. Dependendo de muitas opções, é possível importar a cena usando:

  • Materiais externos (padrão): Onde cada material é salvado em um arquivo. Modificações serão mantidas.
  • Malhas externas: Onde cada malha é salva em diferentes arquivos. Vários usuários preferem lidar com malhas diretamente.
  • Animações externas: Permitir que animações salvas sejam modificadas e mescladas quando fonte for alterada.
  • Cenas externas: Salve cada um dos nós raiz das cenas importadas em uma cena separada.
  • Cena única: Um único arquivo de cena com tudo configurado.
../../../_images/scene_import1.png

O processo de importação é altamente customizável, já que diferentes desenvolvedores possuem diferentes necessidades.

Import options

O importador possui diversas opções, que serão discutidas logo abaixo:

../../../_images/scene_import2.png

Nós

Tipo da Raiz

Por padrão, o tipo do nó raiz nas cenas importadas é “Espacial”, mas isso pode ser modificado.

Nome da Raiz

Permite setar um nome específico para o nó raiz gerado.

Root Scale

The scale of the root node.

Script Personalizado

Um script especial para processar a cena inteira após ser importada pode ser provido. Isso é ótimo para pós processamento, mudando materiais, fazendo coisas divertidas com geometrias, etc.

Crie um script dessa forma:

tool # needed so it runs in the editor
extends EditorScenePostImport

func post_import(scene):
  # do your stuff here
  return scene # remember to return the imported scene

A função post_import recebe a cena importada como argumento (o parâmetro é o nó raiz da cena). A cena que será utilizada tem que ser retornada. Pode ser uma diferente.

Armazenamento

Por padrão, o Godot importa uma única cena. Essa opção permite especificar que cada um dos nós abaixo da raiz serão uma cena separada e a instancia na cena importada.

Claro, instanciar essas cenas importadas em outros lugares manualmente também funciona.

Materiais

Localização

Godot tem suporte a materiais em malha ou em nós. Por padrão, materiais serão colocados em cada um dos nós.

Armazenamento

Materiais podem ser armazenados na cena ou em um arquivo externo. Por padrão, eles são armazenados em arquivos externos para que seja possível editá-los. Isso acontece porquê a maioria dos DCCs 3D não possuem as mesmas opções de material que o Godot.

Quando os materiais são compilados, eles serão perdidos toda vez que a cena principal for modificada ou importada.

Manter ao Reimportar

Uma vez que materiais são editados para usar as ferramentas da Godot, o importador vai manter os que foram editados e ignorar os que vieram da cena inicial. Essa opção está presente somente se os materiais são salvos como arquivos.

Meshes

Compress

Makes meshes use less precise numbers for multiple aspects of the mesh in order to save space.

These are:
  • Transform Matrix (Location, rotation, and scale) : 32-bit float to 16-bit signed integer.
  • Vertices : 32-bit float to 16-bit signed integer.
  • Normals : 32-bit float to 32-bit unsigned integer.
  • Tangents : 32-bit float to 32-bit unsigned integer.
  • Vertex Colors : 32-bit float to 32-bit unsigned integer.
  • UV : 32-bit float to 32-bit unsigned integer.
  • UV2 : 32-bit float to 32-bit unsigned integer.
  • Vertex weights : 32-bit float to 16-bit unsigned integer.
  • Armature bones : 32-bit float to 16-bit unsigned integer.
  • Array index : 32-bit or 16-bit unsigned integer based on how many elements there are.
Informação adicional:
  • UV2 = The second UV channel for detail textures and baked lightmap textures.
  • Array index = An array of numbers that number each element of the arrays above; i.e. they number the vertices and normals.

In some cases, this might lead to loss of precision, so disabling this option may be needed. For instance, if a mesh is very big or there are multiple meshes being imported that cover a large area, compressing the import of this mesh(es) may lead to gaps in geometry or vertices not being exactly where they should be.

Ensure Tangents

If textures with normal mapping are to be used, meshes need to have tangent arrays. This option ensures that these are generated if not present in the source scene. Godot uses Mikktspace for this, but it’s always better to have them generated in the exporter.

Armazenamento

Meshes can be stored in separate files (resources) instead of built-in. This does not have much practical use unless one wants to build objects with them directly.

This option is provided to help those who prefer working directly with meshes instead of scenes.

Light Baking

Whether or not the mesh is used in baked lightmaps.

  • Disabled: The mesh is not used in baked lightmaps.
  • Enable: The mesh is used in baked lightmaps.
  • Gen Lightmaps: The mesh is used in baked lightmaps, and unwraps a second UV layer for lightmaps.

Nota

For more information on light baking see Baked lightmaps.

External Files

Generated meshes and materials can be optionally stored in a subdirectory with the name of the scene.

Animation options

Godot provides many options regarding how animation data is dealt with. Some exporters (such as Blender) can generate many animations in a single file. Others, such as 3DS Max or Maya, need many animations put into the same timeline or, at worst, put each animation in a separate file.

../../../_images/scene_import3.png

Import of animations is enabled by default.

FPS

Most 3D export formats store animation timeline in seconds instead of frames. To ensure animations are imported as faithfully as possible, please specify the frames per second used to edit them. Failing to do this may result in shaky animations.

Filter Script

It is possible to specify a filter script in a special syntax to decide which tracks from which animations should be kept.

The filter script is executed against each imported animation. The syntax consists of two types of statements, the first for choosing which animations to filter, and the second for filtering individual tracks within the matched animation. All name patterns are performed using a case insensitive expression match, using ? and * wildcards (using String.matchn() under the hood).

The script must start with an animation filter statement (as denoted by the line beginning with an @). For example, if we would like to apply filters to all imported animations which have a name ending in "_Loop":

@+*_Loop

Similarly, additional patterns can be added to the same line, separated by commas. Here is a modified example to additionally include all animations with names that begin with "Arm_Left", but also exclude all animations which have names ending in "Attack":

@+*_Loop, +Arm_Left*, -*Attack

Following the animation selection filter statement, we add track filtering patterns to indicate which animation tracks should be kept or discarded. If no track filter patterns are specified, then all tracks within the matched animations will be discarded!

It’s important to note that track filter statements are applied in order for each track within the animation, this means that one line may include a track, a later rule can still discard it. Similarly, a track excluded by an early rule may then be re-included once again by a filter rule further down in the filter script.

For example: include all tracks in animations with names ending in "_Loop", but discard any tracks affecting a "Skeleton" which end in "Control", unless they have "Arm" in their name:

@+*_Loop
+*
-Skeleton:*Control
+*Arm*

In the above example, tracks like "Skeleton:Leg_Control" would be discarded, while tracks such as "Skeleton:Head" or "Skeleton:Arm_Left_Control" would be retained.

Any track filter lines that do not begin with a + or - are ignored.

Armazenamento

By default, animations are saved as built-in. It is possible to save them to a file instead. This allows adding custom tracks to the animations and keeping them after a reimport.

Optimizer

When animations are imported, an optimizer is run, which reduces the size of the animation considerably. In general, this should always be turned on unless you suspect that an animation might be broken due to it being enabled.

Clips

It is possible to specify multiple animations from a single timeline as clips. Specify from which frame to which frame each clip must be taken (and, of course, don’t forget to specify the FPS option above).

Scene inheritance

In many cases, it may be desired to make modifications to the imported scene. By default, this is not possible because if the source asset changes (source .dae, .gltf, .obj file re-exported from 3D modelling app), Godot will re-import the whole scene.

It is possible, however, to make local modifications by using Scene Inheritance. Try to open the imported scene and the following dialog will appear:

../../../_images/scene_import4.png

In inherited scenes, the only limitations for modifications are:

  • Nodes can’t be removed (but can be added anywhere).
  • Sub-Resources can’t be edited (save them externally as described above for this)

Other than that, everything is allowed!

Import hints

Many times, when editing a scene, there are common tasks that need to be done after exporting:

  • Adding collision detection to objects
  • Setting objects as navigation meshes
  • Deleting nodes that are not used in the game engine (like specific lights used for modelling)

To simplify this workflow, Godot offers a few suffixes that can be added to the names of the objects in your 3D modelling software. When imported, Godot will detect them and perform actions automatically:

Remove nodes (-noimp)

Node names that have this suffix will be removed at import time, no matter what their type is. They will not appear in the imported scene.

Create collisions (-col, -colonly, -convcolonly)

Option “-col” will work only for Mesh nodes. If it is detected, a child static collision node will be added, using the same geometry as the mesh.

However, it is often the case that the visual geometry is too complex or too un-smooth for collisions, which ends up not working well.

To solve this, the “-colonly” modifier exists, which will remove the mesh upon import and create a class_staticbody collision instead. This helps the visual mesh and actual collision to be separated.

Option “-convcolonly” will create a class_convexpolygonshape instead of a class_concavepolygonshape.

Option “-colonly” can also be used with Blender’s empty objects. On import, it will create a class_staticbody with a collision node as a child. The collision node will have one of a number of predefined shapes, depending on Blender’s empty draw type:

../../../_images/3dimp_BlenderEmptyDrawTypes.png
  • Single arrow will create a class_rayshape
  • Cube will create a class_boxshape
  • Image will create a class_planeshape
  • Sphere (and the others not listed) will create a class_sphereshape

For better visibility in Blender’s editor, the user can set “X-Ray” option on collision empties and set some distinct color for them in User Preferences / Themes / 3D View / Empty.

Create navigation (-navmesh)

A mesh node with this suffix will be converted to a navigation mesh. Original Mesh node will be removed.

Create a VehicleBody (-vehicle)

A mesh node with this suffix will be imported as a child to a VehicleBody node.

Create a VehicleWheel (-wheel)

A mesh node with this suffix will be imported as a child to a VehicleWheel node.

Rigid Body (-rigid)

Creates a rigid body from this mesh.

Animation loop (-loop, -cycle)

Animation clips in the COLLADA document that start or end with the token “loop” or “cycle” will be imported as a Godot Animation with the loop flag set. This is case-sensitive and does not require a hyphen.

In Blender, this requires using the NLA Editor and naming the Action with the “loop” or “cycle” prefix or suffix.