At the heart of every 3D application is geometry. Qt 3D-based 3D applications are no different and require the user to either generate geometry or provide asset files for Qt 3D to load. This blog post demonstrates how Blender and its Python API could be used to write an exporter that generates geometry for Qt 3D.
For those of you not yet too familiar with Qt 3D, let me remind you that Qt 3D is based on an Entity Component System. A given Entity gets its behavior defined by the various components it aggregates.
Assuming you want to render some 3D content, a renderable entity would be composed like so:
Entity { components:[ GeometryRenderer { geometry:...}, Material {}]}
Loading Geometries with Qt 3D
There are currently 3 ways to incorporate geometry in a Qt 3D application:
These are all QGeometryRenderer subclasses which take care of generating geometry based on configurable properties. It's up to you to provide a Material that will shade your geometry.
Several backend plugins are available for .obj, .fbx and gltf version 1. The list of plugins will likely grow in the future (work on a gltf version 2 importer is currently ongoing). QMesh is also a QGeometryRenderer subclass, you also need to provide a Material.
The subtelty between QMesh and QSceneLoader is that QMesh loads only a single mesh whereas QSceneLoader will load an entire scene. Essentially QSceneLoader will generate a subtree of QEntity with QGeometryRenderer and QMaterial components. The nice thing is that QSceneLoader will also instantiate matching Materials to go with each mesh.
In most cases you'll either use QSceneLoader to load a rather complex scene or, if you know how the scene content is structured, decide yourself on which parts you need and use several QMesh components.
Issues
Now this is all fine but you'll often end up with one of these issues:
Geometry is generated at run-time which can be costly
Many 3D formats are text-based (takes up space on disk, slow parsing at run time)
Loading a scene subtree requires traversing said subtree to retrieve entities composed of components of interest
QSceneLoader may duplicate materials, effects, attributes depending on the scene file
Declaring several QEntity with QMesh components can be tedious
Import plugins for QMesh/QSceneLoader are not available on all platforms and may not cover all formats.
From a general perspective, the current mechanisms make it tedious for the developer to control a complex scene. They either completely hide away the structure of a loaded subtree or, on the contrary, force you to know exactly what composes your scene and let you do the heavy lifting of deciding which meshes you care about.
If you are after performance, you need to know how your scene is structured, which materials are in use and how large your geometries are. With this information you can decide if you need to:
rework you geometry to reduce the number of vertices to be drawn
group several parts together so that they can all be drawn at once
reduce the amount of materials required.
So what if instead of loading something blindly, we generated Qt 3D content in advance, as part of our tooling or asset conditioning work?
Blender
Blender is a free and opensource 3D creation suite. I wouldn't go as far as saying that it's intuitive to use for a newcomer, but it's a really powerful tool. In addition, it provides a powerful Python API which can be used to write importers, exporters or simply automate processes (importing and exporting geometries offline). The nice thing is that the API is documented, the bad thing is that the documentation is mostly a list of methods and members...
How could Blender solve any of the issues we have?
Instead of generating or loading geometry at runtime, I therefore decided I would try to experiment and write an exporter plugin for Blender. The goal for it would be to generate the QML content for an application (though we could easily extend it to cover C++ as well) and export the geometry buffers to binary files that just need to be read at runtime without requiring any parsing.
This could solve the issues of slow startup caused by parsing text-based files and possibly duplicating effects and materials. This also solves the case of import plugins deployment (as we are now performing this offline) and only shipping binary files that can be read with the readBinaryFile functions on the QML Buffer element. Finally this also gives us the complete structure of our scene.
References objects and render settings for the scene
Now that we know what we care about, the next part is traversing these collections and converting them to Qt 3D content.
Meshes
First we need to go over all the meshes in the scene and gather information required to convert these to QGeometryRenderers, QGeometry, QAttributes and QBuffers.
The idea is to go over each Blender mesh and process then as follows:
Triangulate
Apply the modifiers it references
Retrieve vertex data (position, normals, texture coordinates, colors)
Write data into a binary file
Record description of attributes
Compute the indices
For each material being referenced by the blender mesh
compute list of indices based on the loops of the polygon
generate and record the IndexAttribute for the submesh
Generate the IndexBuffer based on the sub meshes
Write data into a binary file.
We keep the data we have produced here for later.
Materials
Next, we need to gather information about each instance of Material of the scene to later on create and instantiate QMaterial subclasses.
For now the exporter is only recording the name, ambient, diffuse and specular color. Later on I'd like to extend that to either export a shader directly or switch to PBR materials.
Objects
Once we've created an intermediary representation for our mesh data and material data, we can proceed with the actual exporting of the scene.
The idea is to retrieve all the objects references by the BlenderScene. Then, from these objects, we can create a hierarchy.
Finally it's just a matter of traversing the tree.
All of the above work has been implemented in a dedicated Exporter class. It is instantiated and called in the execute function of our addon which looks like below:
defexecute(self, context): exportSettings = self.as_keywords() exportSettings["global_matrix"]= axis_conversion(to_forward=self.axis_forward, to_up=self.axis_up).to_4x4() self.binaryDirectoryName ="assets/binaries/" self.shadersDirectoryName ="assets/shaders/" self.qmlDirectoryName ="qml" self.userpath = self.properties.filepath
ifnot os.path.isdir(self.userpath): self.userpath = os.path.dirname(self.userpath) msg ="Selecting directory: "+ self.userpath
self.report({"INFO"}, msg)# switch to work dir and create directories os.chdir(self.userpath)ifnot os.path.exists(self.binaryDirectoryName): os.makedirs(self.binaryDirectoryName)ifnot os.path.exists(self.shadersDirectoryName): os.makedirs(self.shadersDirectoryName)ifnot os.path.exists(self.qmlDirectoryName): os.makedirs(self.qmlDirectoryName)# Save scene into scene scene = bpy.context.scene
exporter = Exporter(scene, exportSettings) exporter.export()# Create QML Files exporter.createQMLNodeTree()# Create .qrc file exporter.generateQRCFiles()# Create main.cpp exporter.generateMainCppFile()# Create .pro exporter.generateProjectFile(self.userpath)
Here. Usage instructions are provided on the repository. It should work with pretty much any blender scene. Just make sure you have assigned a material to the elements you want to export.
Next steps
Export Animations
Export Armatures
Better Material support
export textures
generate shader when possible
investigate if the QShaderProgramBuilder could be used to export node trees from blender
Good job! But when I run the export project ,it crashed with output: "The process was ended forcefully."
I use Qt5.9.4 and Blender2.79 .
26 - Feb - 2018
Paul Lemire
I have only tried with 5.10/5.11 so far. Would you be able to try with any of these versions as well? I'll try to check if I have a 5.9 build around to test with.
5 - Mar - 2018
modir
Thank you ever so for you post.Much thanks again.
6 - Mar - 2018
Pirngadi
It seem the "Additional Dependencies option of "Qt Resource Compiler section doesn"t work as expected (or, at leats, how to used to work before plugin change). In my case I created a .qrc file for contain the .qml file sources to embed into resource format inside the executable. To automatically "force recompilation of the .qrc file every time some .qml files inside is changed I set the each .qml file name into the Visual Studio file property "Additional Dependencies field and this work as expected using standard VS custom compilation mode. Now, after the pluguin project update, this feature seem still present in the "new interface but making same operation by insert the .qml sources file name doesn"t sort any effect an no compilation was executed. I"m misunderstading the use of this field?
4 - Aug - 2020
hamdi
Is the exporting armatures available?
12 - Aug - 2020
Paul Lemire
The above post was more an experiment than a fully-featured exporter. If you need advanced features such as animations, skinning, pbr... I'd recommend you take a look at https://github.com/KDAB/kuesa which together with the Blender 2.80 gltf 2.0 exporter allows you to export and load skeletons.
Paul Lemire
Senior Software Engineer
Senior software engineer at KDAB, Paul is a Qt approver and active contributor to the Qt 3D module where he is one of the main developers. He has been developing Qt based C++ and QML applications since 2010 and has particular interest and expertise in OpenGL and GPU assisted computing. Paul holds a Master’s degree in Computer Science.
6 Comments
26 - Feb - 2018
xuin
Good job! But when I run the export project ,it crashed with output: "The process was ended forcefully." I use Qt5.9.4 and Blender2.79 .
26 - Feb - 2018
Paul Lemire
I have only tried with 5.10/5.11 so far. Would you be able to try with any of these versions as well? I'll try to check if I have a 5.9 build around to test with.
5 - Mar - 2018
modir
Thank you ever so for you post.Much thanks again.
6 - Mar - 2018
Pirngadi
It seem the "Additional Dependencies option of "Qt Resource Compiler section doesn"t work as expected (or, at leats, how to used to work before plugin change). In my case I created a .qrc file for contain the .qml file sources to embed into resource format inside the executable. To automatically "force recompilation of the .qrc file every time some .qml files inside is changed I set the each .qml file name into the Visual Studio file property "Additional Dependencies field and this work as expected using standard VS custom compilation mode. Now, after the pluguin project update, this feature seem still present in the "new interface but making same operation by insert the .qml sources file name doesn"t sort any effect an no compilation was executed. I"m misunderstading the use of this field?
4 - Aug - 2020
hamdi
Is the exporting armatures available?
12 - Aug - 2020
Paul Lemire
The above post was more an experiment than a fully-featured exporter. If you need advanced features such as animations, skinning, pbr... I'd recommend you take a look at https://github.com/KDAB/kuesa which together with the Blender 2.80 gltf 2.0 exporter allows you to export and load skeletons.