在 QML 中控制带纹理的 3D 对象不透明度
Control a textured 3D object opacity in QML
我对 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 存储库,所以我认为最好将代码也放在 Whosebug 上,以防他的分叉存储库分支出现问题。因此,我将 post 此处提供完全使项目正常运行的资源。
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
main.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>
main.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);
}
注:
您可以分别用任何 3D 模型(使用 Blender 或任何其他 3D 软件导出到 obj)或贴图纹理替换 man.obj 和 man.png。然而,它们可以在 Florian's repository or on tripolskypetr's repository.
上找到
这是最终结果:
编辑 2
我修改了你的项目。它现在以透明纹理显示模型,您可以在 GitHub 上找到它。请务必查看分支 transparent_texture
.
我没有实现允许动态设置透明度的功能,但我认为您可以从示例开始自己实现。该模型也未点亮,即仅显示纹理而没有任何闪电,但通过查看其他 Qt3D materials.
应该很容易实现一些简单的 phong 闪电
原答案
Qt3D 没有为透明纹理对象提供 material,这意味着您必须自己实现它。我稍后再讲。
简单透明
关于您的透明度问题,我尝试了代码并使以下内容正常工作但没有按钮:
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
,请查看我的 这解释了为什么当你的场景中有透明物体时这是必要的。
透明纹理对象
这更难(不幸的是我没有时间提供示例代码,也许开始然后在某些事情不起作用时提出问题)。在这里你必须实现你自己的着色器。 Qt3D 根本不提供任何考虑 alpha 的现成实现。 q3dpostproc repository 是一个对我帮助很大的存储库。您可以看到如何构建自己的 Qt3D materials,加载自己的着色器并将参数传递给它们。
还有 Advanced Custom Material 示例,它可以为如何创建自定义着色器和传递参数提供很多帮助。
如果您想了解如何在着色器中为对象添加纹理,请查看 shader of QTextureMaterial and its code。我试图在 QML 中重新创建它,但它并没有立即起作用。
我建议您尝试使用 q3dpostproc 代码并尝试对其中一个对象进行纹理处理(该项目的结构有点复杂,因为它是一个展示柜,但过了一段时间后一切都变得有意义了)。它已经有一个使用纹理的着色器,因为它首先将所有内容绘制到屏幕外缓冲区,然后使用该纹理绘制屏幕。在您使用自己的着色器成功地对其中一个对象进行纹理处理后,您可以在其中执行类似的操作:
fragColor = vec4(texture(...).xyz, 0.5);
这应该会给你一个透明的纹理。当您希望纹理正确点亮时,您可能只需要在最后用更精细的东西替换 texture(...).xyz
。但是为此,您可以查看我链接的 Qt3D GitHub 存储库中的 phong 着色器,或者从 this repository 或互联网上的其他地方获取一个。
希望这些信息对您有所帮助。
编辑 1
我修改了 q3dpostproc 代码以在 GitHub branch 中显示透明纹理。对象尚未点亮,但这应该使功能清晰。
我对 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 存储库,所以我认为最好将代码也放在 Whosebug 上,以防他的分叉存储库分支出现问题。因此,我将 post 此处提供完全使项目正常运行的资源。
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
main.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>
main.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);
}
注:
您可以分别用任何 3D 模型(使用 Blender 或任何其他 3D 软件导出到 obj)或贴图纹理替换 man.obj 和 man.png。然而,它们可以在 Florian's repository or on tripolskypetr's repository.
上找到这是最终结果:
编辑 2
我修改了你的项目。它现在以透明纹理显示模型,您可以在 GitHub 上找到它。请务必查看分支 transparent_texture
.
我没有实现允许动态设置透明度的功能,但我认为您可以从示例开始自己实现。该模型也未点亮,即仅显示纹理而没有任何闪电,但通过查看其他 Qt3D materials.
应该很容易实现一些简单的 phong 闪电原答案
Qt3D 没有为透明纹理对象提供 material,这意味着您必须自己实现它。我稍后再讲。
简单透明
关于您的透明度问题,我尝试了代码并使以下内容正常工作但没有按钮:
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
,请查看我的
透明纹理对象
这更难(不幸的是我没有时间提供示例代码,也许开始然后在某些事情不起作用时提出问题)。在这里你必须实现你自己的着色器。 Qt3D 根本不提供任何考虑 alpha 的现成实现。 q3dpostproc repository 是一个对我帮助很大的存储库。您可以看到如何构建自己的 Qt3D materials,加载自己的着色器并将参数传递给它们。
还有 Advanced Custom Material 示例,它可以为如何创建自定义着色器和传递参数提供很多帮助。
如果您想了解如何在着色器中为对象添加纹理,请查看 shader of QTextureMaterial and its code。我试图在 QML 中重新创建它,但它并没有立即起作用。
我建议您尝试使用 q3dpostproc 代码并尝试对其中一个对象进行纹理处理(该项目的结构有点复杂,因为它是一个展示柜,但过了一段时间后一切都变得有意义了)。它已经有一个使用纹理的着色器,因为它首先将所有内容绘制到屏幕外缓冲区,然后使用该纹理绘制屏幕。在您使用自己的着色器成功地对其中一个对象进行纹理处理后,您可以在其中执行类似的操作:
fragColor = vec4(texture(...).xyz, 0.5);
这应该会给你一个透明的纹理。当您希望纹理正确点亮时,您可能只需要在最后用更精细的东西替换 texture(...).xyz
。但是为此,您可以查看我链接的 Qt3D GitHub 存储库中的 phong 着色器,或者从 this repository 或互联网上的其他地方获取一个。
希望这些信息对您有所帮助。
编辑 1
我修改了 q3dpostproc 代码以在 GitHub branch 中显示透明纹理。对象尚未点亮,但这应该使功能清晰。