Qt 3D:简单的自定义材质 QML 示例
演示在Qt 3D 中创建自定义材质。
本例演示创建一个简单的自定义材质。
运行示例
要运行来自 Qt Creator,打开Welcome 模式,然后从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行。
指定场景
该示例使用 Scene3D 渲染一个使用自定义材质的场景。该场景包含一个使用自定义材质的平面模型。
Entity { id: root components: [transform, mesh, material] SimpleMaterial { id: material maincolor: "red" } Transform { id: transform rotationX: 45 } PlaneMesh { id: mesh width: 1.0 height: 1.0 meshResolution: Qt.size(2, 2) } }
指定材质
材质是在simplecustommaterial/SimpleMaterial.qml
中使用Material 类型指定的。首先,材质指定了参数,这些参数会映射到着色器中相应的制服,以便从 qml 中进行更改。
property color maincolor: Qt.rgba(0.0, 0.0, 0.0, 1.0) parameters: [ Parameter { name: "maincolor" value: Qt.vector3d(root.maincolor.r, root.maincolor.g, root.maincolor.b) } ]
接下来,我们指定加载哪些着色器。我们为 OpenGL ES 2 和 OpenGL 渲染器分别提供了不同版本的着色器。
property string vertex: "qrc:/shaders/gl3/simpleColor.vert" property string fragment: "qrc:/shaders/gl3/simpleColor.frag" property string vertexRHI: "qrc:/shaders/gl45/simpleColor.vert" property string fragmentRHI: "qrc:/shaders/gl45/simpleColor.frag" property string vertexES: "qrc:/shaders/es2/simpleColor.vert" property string fragmentES: "qrc:/shaders/es2/simpleColor.frag"
在顶点着色器中,我们只需通过变换矩阵变换位置。
void main() { // Transform position, normal, and tangent to world coords worldPosition = vec3(modelMatrix * vec4(vertexPosition, 1.0)); // Calculate vertex position in clip coordinates gl_Position = mvp * vec4(worldPosition, 1.0); }
在片段着色器中,我们只需将片段颜色设置为材质中指定的主色调。
uniform vec3 maincolor; void main() { //output color from material fragColor = vec4(maincolor,1.0); }
接下来,我们通过着色器创建ShaderPrograms 。
ShaderProgram { id: gl3Shader vertexShaderCode: loadSource(parent.vertex) fragmentShaderCode: loadSource(parent.fragment) } ShaderProgram { id: es2Shader vertexShaderCode: loadSource(parent.vertexES) fragmentShaderCode: loadSource(parent.fragmentES) } ShaderProgram { id: rhiShader vertexShaderCode: loadSource(parent.vertexRHI) fragmentShaderCode: loadSource(parent.fragmentRHI) }
最后,在与特定 Api 配置文件相对应的 Techniques 中使用着色器程序。
// OpenGL 3.1 Technique { filterKeys: [forward] graphicsApiFilter { api: GraphicsApiFilter.OpenGL profile: GraphicsApiFilter.CoreProfile majorVersion: 3 minorVersion: 1 } renderPasses: RenderPass { shaderProgram: gl3Shader } },
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.