在 QML 中控制带纹理的 3D 对象不透明度

Posted

技术标签:

【中文标题】在 QML 中控制带纹理的 3D 对象不透明度【英文标题】:Control a textured 3D object opacity in QML 【发布时间】:2020-04-18 14:52:20 【问题描述】:

我对 QML 中的 Qt 3D 有点陌生,我正在尝试控制 textured 3D 对象的不透明度。 我正在使用simpleqml3d 测试项目来做到这一点。

我玩过这些材料,但无法让它发挥作用。 这是我在simpleqml3d 测试项目中修改的IronMan.qml 实体:

import Qt3D.Core 2.0
import Qt3D.Render 2.0
import Qt3D.Extras 2.0

Entity 
    id: root

    property real x: 0
    property real y: 0
    property real z: 0
    property real scale: 1.0

    Texture2D
        id: texture
        TextureImage 
            source: "qrc:/man.png"
        
    

    //COPY RenderableEntity.qml in your project!!!!!!
    RenderableEntity
        id: chest
        source: "qrc:/man.obj" //Path to iron man model. You can open it with 3D Builder on Windows 10
        position: Qt.vector3d(root.x, root.y, root.z)
        scale:  root.scale

//        material: DiffuseMapMaterial 
//            id: material
//            diffuse:  texture
//            specular: Qt.rgba( 0.2, 0.2, 0.2, 1.0 )
//            shininess: 2.0
//        

//        material: DiffuseMapMaterial 
//            diffuse:  texture
//            specular: Qt.rgba( 0.2, 0.2, 0.2, 1.0 )
//            shininess: 2.0
//        

//        material: DiffuseSpecularMaterial 
//            alphaBlending: true
//            diffuse: Qt.rgba(0.2, 0.2, 0.2, 0.0)//texture
//            specular: texture//Qt.rgba(0.2, 0.2, 0.2, 0.5)
//            shininess: 2.0
//        

//        material: PhongMaterial 
//            ambient: Qt.rgba( 1, 0, 0, 0 )
//            diffuse: Qt.rgba( 1, 0, 0, 0 )
//            shininess: 50
//        

//        material: PhongAlphaMaterial 
//            alpha: 0.0
//            diffuse: Qt.rgba(0.2, 0.2, 0.2, 0.0)//texture
//            specular: Qt.rgba(0.2, 0.2, 0.2, 0.0)
//            shininess: 2.0
//        

        material: PhongAlphaMaterial 
            alpha: 0.0
            ambient: Qt.rgba( 1, 0, 0, 0 )
            diffuse: Qt.rgba( 1, 0, 0, 0 )
            shininess: 50
        
    

评论的素材是我玩过的素材。即使使用PhongAlphaMaterial,我也无法开始工作,当不透明度设置为 0.0 时,模型仍然显示如下:

谁能帮我控制带纹理的 3D 对象不透明度,但又不会丢失纹理?

编辑:

我已经接受了 Florian Blume 的回答,因为答案基于 Github 存储库,所以我认为最好将代码也放在 *** 上,以防他的分叉存储库分支出现问题。因此,我将在此处发布使该项目充分发挥作用的资源。

simpleqml3d.pro

TEMPLATE = app

QT += core gui widgets 3dcore 3drender 3dinput 3dquick qml quick 3dquickextras
CONFIG += c++11

SOURCES += main.cpp

RESOURCES += resources.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

# Default rules for deployment.
qnx: target.path = /tmp/$$TARGET/bin
else: unix:!android: target.path = /opt/$$TARGET/bin
!isEmpty(target.path): INSTALLS += target

ma​​in.cpp

/****************************************************************************
**
** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <Qt3DQuickExtras/qt3dquickwindow.h>
#include <Qt3DQuick/QQmlAspectEngine>
#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>

int main(int argc, char* argv[])

    QGuiApplication app(argc, argv);
    Qt3DExtras::Quick::Qt3DQuickWindow view;

        // Expose the window as a context property so we can set the aspect ratio
    view.engine()->qmlEngine()->rootContext()->setContextProperty("_window", &view);
    view.setSource(QUrl("qrc:/main.qml"));
    view.show();

    return app.exec();

resources.qrc

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>IronMan.qml</file>
        <file>man.obj</file>
        <file>man.png</file>
        <file>TextureAlphaMaterial.qml</file>
    </qresource>
    <qresource prefix="/shaders">
        <file>unlittexture.frag</file>
        <file>unlittexture.vert</file>
    </qresource>
</RCC>

ma​​in.qml

/****************************************************************************
**
** Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB).
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

import QtQuick 2.1
import Qt3D.Core 2.0
import Qt3D.Render 2.9
import Qt3D.Input 2.0
import Qt3D.Extras 2.9

Entity 
    id: root
    objectName: "root"

    // Use the renderer configuration specified in ForwardRenderer.qml
    // and render from the mainCamera
    components: [
        RenderSettings 
            activeFrameGraph: RenderSurfaceSelector 
                id: renderSurfaceSelector

                CameraSelector 
                    id: cameraSelector
                    camera: camera
                    Viewport 
                        id: viewport
                        normalizedRect: Qt.rect(0, 0, 1, 1)
                        ClearBuffers 
                            buffers: ClearBuffers.AllBuffers
                            clearColor: "white"
                            NoDraw
                        
                        LayerFilter 
                            layers: [opaqueLayer]

                        
                        LayerFilter 
                            layers: [opaqueLayer]
                            filterMode: LayerFilter.DiscardAllMatchingLayers
                            NoDepthMask 
                        
                    
                
            
        ,
        InputSettings  
    ]

    Camera 
        id: camera
        projectionType: CameraLens.PerspectiveProjection
        fieldOfView: 45
        nearPlane : 0.1
        farPlane : 1000.0
        position: Qt.vector3d( 0.0, 4.0, -5.0 )
        upVector: Qt.vector3d( 0.0, 1.0, 0.0 )
        viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
    

    FirstPersonCameraController  camera: camera 

    Entity 
        components: [
            PointLight 
                enabled: parent.enabled
                color: "black"
                intensity: 0
            
        ]
    

    Entity 
        PlaneMesh 
            id: groundMesh
            width: 50
            height: width
            meshResolution: Qt.size(2, 2)
        

        Transform 
            id: groundTransform
            translation: Qt.vector3d(0, 0, 0)
        

        Layer 
            id: opaqueLayer
        

        PhongMaterial 
            id: material
            diffuse: Qt.rgba( 0.5, 0.5, 0.5, 1 )
            ambient: Qt.rgba( 0.5, 0.5, 0.5, 1 )
        

        components: [
            groundMesh,
            groundTransform,
            material,
            opaqueLayer
        ]
    
    IronMan 
        id: ironMan
    

IronMan.qml

import Qt3D.Core 2.0
import Qt3D.Render 2.0
import Qt3D.Extras 2.0

import QtQml 2.14

Entity 
    id: root

    property vector3d position: Qt.vector3d(0, 0, 0)
    property real scale: 1.0
    property real rotationAngle: 0.0
    property vector3d rotationAxis: Qt.vector3d(1, 0, 0)
    property alias source: mesh.source
    property Material material

    components: [ transform, mesh, material ]

    Transform 
        id: transform
        scale: root.scale
        rotation: fromAxisAndAngle(root.rotationAxis, root.rotationAngle)
        translation: root.position
    

    Mesh 
        id: mesh
        source: "qrc:/man.obj"
    

    material: TextureAlphaMaterial 
        id: material

        opacity: 0.5
    

TextureAlphaMaterial.qml

import Qt3D.Core 2.0
import Qt3D.Render 2.0

Material 
    id: root

    property real opacity: 1.

    parameters: [
        Parameter 
            name: "diffuseTexture"
            value: Texture2D 
                textureImages: [
                    TextureImage 
                        source: "qrc:/man.png"
                    
                ]
            
        
    ]

    effect: Effect 
        id: rootEffect

        parameters: [
            Parameter
            
                name: "opacity"
                value: root.opacity
            
        ]
        techniques: [
            Technique 
                graphicsApiFilter 
                    api: GraphicsApiFilter.OpenGL
                    profile: GraphicsApiFilter.CoreProfile
                    majorVersion: 3
                    minorVersion: 1
                

                filterKeys: [ FilterKey  name: "renderingStyle"; value: "forward"  ]

                renderPasses: [
                    RenderPass 
                        shaderProgram: ShaderProgram 
                            vertexShaderCode:   loadSource("qrc:/shaders/unlittexture.vert")
                            fragmentShaderCode: loadSource("qrc:/shaders/unlittexture.frag")
                         
                        renderStates: [
                            DepthTest 
                                depthFunction: DepthTest.LessOrEqual
                            ,
                            NoDepthMask 
                            ,
                            BlendEquation 
                                blendFunction: BlendEquation.Add
                            ,
                            BlendEquationArguments 
                                sourceRgb: BlendEquationArguments.One
                                destinationRgb: BlendEquationArguments.OneMinusSourceAlpha
                                sourceAlpha: BlendEquationArguments.One
                                destinationAlpha: BlendEquationArguments.OneMinusSourceAlpha
                            
                        ]
                    
                ]
            
        ]
    

unlittexture.frag

#version 150 core

uniform sampler2D diffuseTexture;
uniform float opacity;

in vec3 position;
in vec2 texCoord;

out vec4 fragColor;


void main()

    fragColor = vec4(texture(diffuseTexture, texCoord).xyz * opacity, opacity);

unlittexture.vert

#version 150 core

in vec3 vertexPosition;
in vec2 vertexTexCoord;

out vec3 position;
out vec2 texCoord;

uniform mat4 modelView;
uniform mat4 mvp;

void main()

    vec3 t = vec3(vertexTexCoord, 1.0);
    texCoord = (t / t.z).xy;
    position = vec3(modelView * vec4(vertexPosition, 1.0));

    gl_Position = mvp * vec4(vertexPosition, 1.0);

注意:

您可以将 man.obj 和 man.png 分别替换为任何 3D 模型(使用 Blender 或任何其他 3D 软件导出到 obj)或映射纹理。不过可以在Florian's repository 或tripolskypetr's repository 上找到它们。

这是最终结果:

【问题讨论】:

【参考方案1】:

编辑 2

我修改了你的项目。它现在显示具有透明纹理的模型,您可以在 GitHub 上找到它。请务必查看分支transparent_texture

我没有实现允许动态设置透明度的功能,但我认为您可以从示例开始自己执行此操作。该模型也是无光照的,即只显示纹理而没有任何闪电,但通过查看其他 Qt3D 材质应该很容易实现一些简单的 phong 闪电。


原答案

Qt3D 没有为透明纹理对象提供材质,这意味着您必须自己实现它。我稍后再谈。

简单透明

关于您的透明度问题,我使用了代码并得到了以下工作但没有按钮:

main.cpp:

#include <Qt3DQuickExtras/qt3dquickwindow.h>
#include <Qt3DQuick/QQmlAspectEngine>
#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>

int main(int argc, char* argv[])

    QGuiApplication app(argc, argv);
    Qt3DExtras::Quick::Qt3DQuickWindow view;

    view.engine()->qmlEngine()->rootContext()->setContextProperty("_window", &view);
    view.setSource(QUrl("qrc:/main.qml"));
    view.show();

    return app.exec();

main.qml:

import QtQuick 2.1
import Qt3D.Core 2.0
import Qt3D.Render 2.9
import Qt3D.Input 2.0
import Qt3D.Extras 2.9

Entity 
    id: root
    objectName: "root"

    // Use the renderer configuration specified in ForwardRenderer.qml
    // and render from the mainCamera
    components: [
        RenderSettings 
            activeFrameGraph: RenderSurfaceSelector 
                id: renderSurfaceSelector

                CameraSelector 
                    id: cameraSelector
                    camera: camera
                    Viewport 
                        id: viewport
                        normalizedRect: Qt.rect(0, 0, 1, 1)
                        ClearBuffers 
                            buffers: ClearBuffers.AllBuffers
                            clearColor: "white"
                            NoDraw
                        
                        LayerFilter 
                            layers: [opaqueLayer]

                        
                        LayerFilter 
                            layers: [opaqueLayer]
                            filterMode: LayerFilter.DiscardAllMatchingLayers
                        
                    
                
            
        ,
        // Event Source will be set by the Qt3DQuickWindow
        InputSettings  
    ]

    Camera 
        id: camera
        projectionType: CameraLens.PerspectiveProjection
        fieldOfView: 45
        nearPlane : 0.1
        farPlane : 1000.0
        position: Qt.vector3d( 0.0, 4.0, -5.0 )
        upVector: Qt.vector3d( 0.0, 1.0, 0.0 )
        viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
    

    FirstPersonCameraController  camera: camera 

    Entity 
        components: [
            PointLight 
                enabled: parent.enabled
                color: "black"
                intensity: 0
            
        ]
    

    Entity 
        PlaneMesh 
            id: groundMesh
            width: 50
            height: width
            meshResolution: Qt.size(2, 2)
        

        Transform 
            id: groundTransform
            translation: Qt.vector3d(0, 0, 0)
        

        Layer 
            id: opaqueLayer
        

        PhongMaterial 
            id: material
            diffuse: Qt.rgba( 0.5, 0.5, 0.5, 1 )
            ambient: Qt.rgba( 0.5, 0.5, 0.5, 1 )
        

        components: [
            groundMesh,
            groundTransform,
            material,
            opaqueLayer
        ]
    

    Entity 
        id: sphere1

        Mesh 
            id: man
            source: "qrc:/man.obj"
        

        components: [
            man,
            matSphere1Material
        ]

        PhongAlphaMaterial 
            id: matSphere1Material
            alpha: 0.1
            ambient: Qt.rgba( 1, 1, 0, 0.0 )
            diffuse: Qt.rgba( 1, 1, 0, 0.0 )
            shininess: 50
        
    

我简化了您的示例以找出问题所在,看起来您在 main.cpp 中使用了错误的 QML 引擎。但我建议您尝试 Scene3DView 示例,因为透明度适用于与您类似的设置(如果您需要 UI 中的按钮)。我经常使用这些示例并根据我的需要对其进行修改。我只是想让你开始使用我提供的代码。

如果你问自己为什么我有LayerFilters,请查看我的answer,它解释了为什么当你的场景中有透明对象时这是必要的。

透明纹理对象

这更加困难(不幸的是,我没有时间提供示例代码,也许开始然后在某些东西不起作用时提出问题)。在这里,您必须实现自己的着色器。 Qt3D 根本不提供任何考虑到 alpha 的已读实现。一个对我帮助很大的存储库是q3dpostproc repository。您可以了解如何构建自己的 Qt3D 材质、加载自己的着色器并将参数传递给它们。

还有高级自定义材质示例,它可以为如何创建自定义着色器和传递参数提供很多帮助。

如果您想了解如何在着色器中为对象设置纹理,请查看shader of QTextureMaterial 及其code。我尝试在 QML 中重新创建它,但它没有立即工作。

我建议您使用 q3dpostproc 代码并尝试对其中的一个对象进行纹理处理(该项目的结构有点复杂,因为它是一个展示,但过了一段时间后一切都变得有意义了)。它已经有一个使用纹理的着色器,因为它首先将所有内容绘制到屏幕外缓冲区,然后使用该纹理来绘制屏幕。在您使用自己的着色器成功地对其中一个对象进行纹理化后,您可以在其中执行以下操作:

fragColor = vec4(texture(...).xyz, 0.5);

这应该会给你一个透明的纹理。当您想要纹理正确点亮时,您可能只需要最后用更精细的东西替换texture(...).xyz。但为此,您可以查看我链接的 Qt3D GitHub 存储库中的 phong 着色器,或者从 this repository 或互联网的其他地方获取一个。

我希望这些信息对您有所帮助。


编辑 1

我修改了 q3dpostproc 代码以在 GitHub branch 中显示透明纹理。对象尚未点亮,但这应该可以使功能清晰。

【讨论】:

非常感谢您的帮助。没关系,我可以自己实现动态设置不透明度的功能,但不幸的是,当我将不透明度设置为 0.0 时,我仍然可以看到模型(i.imgur.com/qILMsUW.png)。任何想法可以做什么,以便当不透明度为 0.0 时,角色完全透明且根本不可见?我知道这可能很简单,但我对 3D 和着色器还很陌生,我需要这个简单的东西来做一个项目。我还在学习,但这对我来说仍然是一门火箭科学,我需要先了解很多东西。非常感谢! 我用你的代码玩了一下,我把fragColor = vec4(texture( diffuseTexture, texCoord ).xyz, 0.5);改成了fragColor = vec4(texture( diffuseTexture, texCoord ).xyz * 0.5, 0.5);。我认为将xyz 与不透明度值相乘可以得到我想要的结果。老实说,我不明白这意味着什么以及它为什么起作用。我想xyz 是空间中xyz 位置的rgb 值,但是将rgb0.5 相乘对我来说不太有意义……知道那里会发生什么吗?为什么会这样? 这听起来很奇怪。我很高兴你设法让它以适合你的方式工作。将来我自己的项目需要类似的材料,所以我想我会尝试进一步研究这个问题,也许通过检查现成的 Phong alpha 材料。快速搜索这个与 OpenGL 相关的问题没有给我任何结果。

以上是关于在 QML 中控制带纹理的 3D 对象不透明度的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Xcode 中渲染具有半透明纹理的 3D 模型?

【Three.js】请问如何显示带纹理的三维模型?

“dae” 3D 模型端在 iOS 应用程序中变得透明

使用透明度时渲染到纹理时渲染覆盖透明度

unity3D 调用外部alpha,控制透明度谁知道怎么做

跟诸子学游戏 unity3d Rendering Mode和Render Mode