Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Toggle main menu visibility
Loading...
Searching...
No Matches
qtquick3d-custom.qdoc
Go to the documentation of this file.
1
// Copyright (C) 2020 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4
/*!
5
\page qtquick3d-custom.html
6
\title Programmable Materials, Effects, Geometry, and Texture data
7
\brief Custom materials, effects, geometry and texture data providers in Qt Quick 3D
8
9
While the built-in materials of Qt Quick 3D, \l DefaultMaterial and \l PrincipledMaterial,
10
allow a wide degree of customization via their properties, they do not provide
11
programmability on the vertex and fragment shader level. To allow that, the \l
12
CustomMaterial type is provided.
13
14
\table
15
\header
16
\li A model with PrincipledMaterial
17
\li With a CustomMaterial transforming the vertices
18
\row
19
\li \image quick3d-custom-mat1.jpg {Teapot rendered with standard material}
20
\li \image quick3d-custom-mat2.jpg
21
{Teapot with vertices transformed by custom material}
22
\endtable
23
24
Post-processing effects, where one or more passes of processing on the color buffer are
25
performed, optionally taking the depth buffer into account, before the View3D's output is
26
passed on to Qt Quick, also exist in two varieties:
27
\list
28
\li built-in post-processing steps that can be configured via \l ExtendedSceneEnvironment, such as
29
glow/bloom, depth of field, vignette, lens flare,
30
\li \c custom effects implemented by the application in form of fragment shader code and a
31
specification of the processing passes in an \l Effect object.
32
\endlist
33
34
In practice there is a third category of post-processing effects: 2D effects
35
implemented via Qt Quick, operating on the output of the \l View3D item without
36
any involvement from the 3D renderer. For example, to apply a blur to a \l
37
View3D item, the simplest approach is to use Qt Quick's existing facilities,
38
such as \l MultiEffect. The 3D post-processing system becomes beneficial for
39
complex effects that involve 3D scene concepts such as the depth buffer or the
40
screen texture, or need to deal with HDR tonemapping or need multiple passes
41
with intermediate buffers, etc. Simple 2D effects that do not require any
42
insight into the 3D scene and renderer can always be implemented with \l
43
ShaderEffect or \l MultiEffect instead.
44
45
\table
46
\header
47
\li Scene without effect
48
\li The same scene with a custom post-processing effect applied
49
\row
50
\li \image quick3d-custom-effect1.jpg
51
{Scene with sphere, cone, and cube without post-processing effect}
52
\li \image quick3d-custom-effect2.jpg
53
{Scene with warped geometry from custom post-processing effect}
54
\endtable
55
56
In addition to programmable materials and post-processing, there are two types of data that is
57
normally provided in form of files (\c{.mesh} files or images such as \c{.png}):
58
59
\list
60
61
\li vertex data, including the geometry for the mesh to be rendered, texture coordinates,
62
normals, colors, and other data,
63
64
\li the content for textures that are then used as texture maps for the rendered
65
objects, or used with skybox or image based lighting.
66
67
\endlist
68
69
If they so wish, applications can provide such data from C++ in form of a QByteArray. Such
70
data can also be changed over time, allowing to procedurally generate and later alter the
71
data for a \l Model or \l Texture.
72
73
\table
74
\header
75
\li A grid, rendered by specifying vertex data dynamically from C++
76
\li A cube textured with image data generated from C++
77
\row
78
\li \image quick3d-custom-geom.jpg {Grid generated from custom geometry data}
79
\li \image quick3d-custom-tex.jpg
80
{Cube with procedurally generated gradient texture}
81
\endtable
82
83
These four approaches to customizing and making materials, effects, geometry, and textures
84
dynamic enable the programmability of shading and procedural generation of the data the
85
shaders get as their input. The following sections provide an overview of these
86
features. The full reference is available in the documentation pages for the respective
87
types:
88
89
\note For complete control over the entire rendering pipeline, including multiple
90
render passes and custom render targets, see \l{User-Defined Render Passes in Qt Quick 3D}.
91
User-defined render passes complement the features described on this page by allowing you
92
to define the entire rendering pipeline architecture, while CustomMaterial and Effect focus
93
on customizing individual materials and post-processing steps within the pipeline.
94
95
\table
96
\header
97
\li Feature
98
\li Reference Documentation
99
\li Relevant Examples
100
\row
101
\li Custom materials
102
\li \l CustomMaterial
103
\li \l {Qt Quick 3D - Custom Shaders Example}, \l {Qt Quick 3D - Custom Materials
104
Example}
105
\row
106
\li Custom post-processing effects
107
\li \l Effect
108
\li \l {Qt Quick 3D - Custom Effect Example}
109
\row
110
\li Custom geometry
111
\li \l QQuick3DGeometry, \l{Model::geometry}
112
\li \l {Qt Quick 3D - Custom Geometry Example}
113
\row
114
\li Custom texture data
115
\li \l QQuick3DTextureData, \l{Texture::textureData}
116
\li \l {Qt Quick 3D - Procedural Texture Example}
117
\endtable
118
119
\section1 Programmability for Materials
120
121
Let's have a scene with a cube, and start with a default \l PrincipledMaterial and
122
\l CustomMaterial:
123
124
\table
125
\header
126
\li PrincipledMaterial
127
\li CustomMaterial
128
\row
129
\li
130
\qml
131
import QtQuick
132
import QtQuick3D
133
Item {
134
View3D {
135
anchors.fill: parent
136
environment: SceneEnvironment {
137
backgroundMode: SceneEnvironment.Color
138
clearColor: "black"
139
}
140
PerspectiveCamera { z: 600 }
141
DirectionalLight { }
142
Model {
143
source: "#Cube"
144
scale: Qt.vector3d(2, 2, 2)
145
eulerRotation.x: 30
146
materials: PrincipledMaterial { }
147
}
148
}
149
}
150
\endqml
151
\li
152
\qml
153
import QtQuick
154
import QtQuick3D
155
Item {
156
View3D {
157
anchors.fill: parent
158
environment: SceneEnvironment {
159
backgroundMode: SceneEnvironment.Color
160
clearColor: "black"
161
}
162
PerspectiveCamera { z: 600 }
163
DirectionalLight { }
164
Model {
165
source: "#Cube"
166
scale: Qt.vector3d(2, 2, 2)
167
eulerRotation.x: 30
168
materials: CustomMaterial { }
169
}
170
}
171
}
172
\endqml
173
\endtable
174
175
These both lead to the exact same result, because a \l CustomMaterial is effectively a \l
176
PrincipledMaterial, when no vertex or fragment shader code is added to it.
177
178
\image quick3d-custom-cube1.jpg {White cube with default material}
179
180
\note Properties, such as, \l{PrincipledMaterial::baseColor}{baseColor},
181
\l{PrincipledMaterial::metalness}{metalness},
182
\l{PrincipledMaterial::baseColorMap}{baseColorMap}, and many others, have no equivalent
183
properties in the \l CustomMaterial QML type. This is by design: customizing the material
184
is done via shader code, not by merely providing a few fixed values.
185
186
\section2 Our first vertex shader
187
188
Let's add a custom vertex shader snippet. This is done by referencing a file in the
189
\l{CustomMaterial::vertexShader}{vertexShader} property. The approach will be the same for
190
fragment shaders. These references work like \l{Image::source}{Image.source} or
191
\l{ShaderEffect::vertexShader}{ShaderEffect.vertexShader}: they are local or \c qrc URLs,
192
and a relative path is treated relative to the \c{.qml} file's location. The common
193
approach is therefore to place the \c{.vert} and \c{.frag} files into the Qt resource
194
system (\c qt_add_resources when using CMake) and reference them using a relative path.
195
196
In Qt 6.0 inline shader strings are no longer supported, neither in Qt Quick nor in Qt
197
Quick 3D. (make note of the fact that these properties are URLs, not strings) However, due
198
to their intrinsically dynamic nature, custom materials and post-processing effects in Qt
199
Quick 3D still provide shader snippets in source form in the referenced files. This is a
200
difference to \l ShaderEffect where the shaders are complete on their own, with no further
201
amending by the engine, and so are expected to be provided as pre-conditioned \c{.qsb}
202
shader packs.
203
204
\note In Qt Quick 3D URLs can only refer to local resources. Schemes for remote content
205
are not supported.
206
207
\note The shading language used is Vulkan-compatible GLSL. The \c{.vert} and \c{.frag}
208
files are not complete shaders on their own, hence being often called \c snippets. That is
209
why there are no uniform blocks, input and output variables, or sampler uniforms provided
210
directly by these snippets. Rather, the Qt Quick 3D engine will amend them as appropriate.
211
212
\table
213
\header
214
\li Change in main.qml, material.vert
215
\li Result
216
\row
217
\li \qml
218
materials: CustomMaterial {
219
vertexShader: "material.vert"
220
}
221
\endqml
222
\badcode
223
void MAIN()
224
{
225
}
226
\endcode
227
\li \image quick3d-custom-cube1-small.jpg {White cube with default material}
228
\endtable
229
230
A custom vertex or fragment shader snippet is expected to provide one or more functions
231
with pre-defined names, such as \c MAIN, \c DIRECTIONAL_LIGHT, \c POINT_LIGHT, \c
232
SPOT_LIGHT, \c AMBIENT_LIGHT, \c SPECULAR_LIGHT. For now let's focus on \c MAIN.
233
234
As shown here, the end result with an empty MAIN() is exactly the same as before.
235
236
Before making it more interesting, let's look at an overview of the most commonly used
237
special keywords in custom vertex shader snippets. This is not the full list. For a full
238
reference, check the \l CustomMaterial page.
239
240
\table
241
\header
242
\li Keyword
243
\li Type
244
\li Description
245
\row
246
\li MAIN
247
\li
248
\li void MAIN() is the entry point. This function must always be present in a custom
249
vertex shader snippet, there is no point in providing one otherwise.
250
\row
251
\li VERTEX
252
\li vec3
253
\li The vertex position the shader receives as input. A common use case for vertex shaders
254
in custom materials is to change (displace) the x, y, or z values of this vector, by simply
255
assigning a value to the whole vector, or some of its components.
256
\row
257
\li NORMAL
258
\li vec3
259
\li The vertex normal from the input mesh data, or all zeroes if there were no normals provided.
260
As with VERTEX, the shader is free to alter the value as it sees fit. The altered value is then
261
used by the rest of the pipeline, including the lighting calculations in the fragment stage.
262
\row
263
\li UV0
264
\li vec2
265
\li The first set of texture coordinates from the input mesh data, or all zeroes if there
266
were no UV values provided. As with VERTEX and NORMAL, the value can altered.
267
\row
268
\li MODELVIEWPROJECTION_MATRIX
269
\li mat4
270
\li The model-view-projection matrix. To unify the behavior regardless of which graphics API
271
rendering happens with, all vertex data and transformation matrices follow OpenGL conventions
272
on this level. (Y axis pointing up, OpenGL-compatible projection matrix) Read only.
273
\row
274
\li MODEL_MATRIX
275
\li mat4
276
\li The model (world) matrix. Read only.
277
\row
278
\li NORMAL_MATRIX
279
\li mat3
280
\li The transposed inverse of the top-left 3x3 slice of the model matrix. Read only.
281
\row
282
\li CAMERA_POSITION
283
\li vec3
284
\li The camera position in world space. In the examples on this page this is \c{(0, 0, 600)}. Read only.
285
\row
286
\li CAMERA_DIRECTION
287
\li vec3
288
\li The camera direction vector. In the examples on this page this is \c{(0, 0, -1)}. Read only.
289
\row
290
\li CAMERA_PROPERTIES
291
\li vec2
292
\li The near and far clip values of the camera. In the examples on this page this is \c{(10, 10000)}. Read only.
293
\row
294
\li POINT_SIZE
295
\li float
296
\li Relevant only when rendering with a topology of points, for example because the
297
\l{QQuick3DGeometry}{custom geometry} provides such a geometry for the mesh. Writing to
298
this value is equivalent to setting \l{PrincipledMaterial::pointSize}{pointSize on a
299
PrincipledMaterial}.
300
\row
301
\li POSITION
302
\li vec4
303
\li Like \c gl_Position. When not present, a default assignment statement is generated
304
automatically using \c MODELVIEWPROJECTION_MATRIX and \c VERTEX. This is why an empty
305
MAIN() is functional, and in most cases there will be no need to assign a custom value to
306
it.
307
\endtable
308
309
Let's make a custom material that displaces the vertices according to some pattern. To
310
make it more interesting, have some animated QML properties, the values of which end up
311
being exposed as uniforms in the shader code. (to be precise, most properties are going to
312
be mapped to members in a uniform block, backed by a uniform buffer at run time, but Qt
313
Quick 3D conveniently makes such details transparent to the custom material author)
314
315
\table
316
\header
317
\li Change in main.qml, material.vert
318
\li Result
319
\row
320
\li \qml
321
materials: CustomMaterial {
322
vertexShader: "material.vert"
323
property real uAmplitude: 0
324
NumberAnimation on uAmplitude {
325
from: 0; to: 100; duration: 5000; loops: -1
326
}
327
property real uTime: 0
328
NumberAnimation on uTime {
329
from: 0; to: 100; duration: 10000; loops: -1
330
}
331
}
332
\endqml
333
\badcode
334
void MAIN()
335
{
336
VERTEX.x += sin(uTime + VERTEX.y) * uAmplitude;
337
}
338
\endcode
339
\li \image quick3d-custom-cube2-anim.gif
340
{Cube with ground plane showing vertex displacement animation}
341
\endtable
342
343
\section2 Uniforms from QML properties
344
345
Custom properties in the CustomMaterial object get mapped to uniforms. In the above
346
example this includes \c uAmplitude and \c uTime. Any time the values change, the updated
347
value will become visible in the shader. This concept may already be familiar from \l
348
ShaderEffect.
349
350
The name of the QML property and the GLSL variable must match. There is no separate
351
declaration in the shader code for the individual uniforms. Rather, the QML property name
352
can be used as-is. This is why the example above can just reference \c uTime and \c
353
uAmplitude in the vertex shader snippet without any previous declaration for them.
354
355
The following table lists how the types are mapped:
356
357
\table
358
\header
359
\li QML Type
360
\li Shader Type
361
\li Notes
362
\row
363
\li real, int, bool
364
\li float, int, bool
365
\li
366
\row
367
\li color
368
\li vec4
369
\li sRGB to linear conversion is performed implicitly
370
\row
371
\li vector2d
372
\li vec2
373
\li
374
\row
375
\li vector3d
376
\li vec3
377
\li
378
\row
379
\li vector4d
380
\li vec4
381
\li
382
\row
383
\li matrix4x4
384
\li mat4
385
\li
386
\row
387
\li quaternion
388
\li vec4
389
\li scalar value is \c w
390
\row
391
\li rect
392
\li vec4
393
\li
394
\row
395
\li point, size
396
\li vec2
397
\li
398
\row
399
\li Texture
400
\li sampler2D
401
\li samplerCube for a \l CubeMapTexture
402
\endtable
403
404
\section2 Improving the example
405
406
Before moving further, let's make the example somewhat better looking. By adding a rotated
407
rectangle mesh and making the \l DirectionalLight cast shadows, we can verify that the
408
alteration to the cube's vertices is correctly reflected in all rendering passes,
409
including shadow maps. To get a visible shadow, the light is now placed a bit higher on
410
the Y axis, and a rotation is applied to have it pointing partly downwards. (this being a
411
\c directional light, the rotation matters)
412
413
\table
414
\header
415
\li main.qml, material.vert
416
\li Result
417
\row \li \qml
418
import QtQuick
419
import QtQuick3D
420
Item {
421
View3D {
422
anchors.fill: parent
423
environment: SceneEnvironment { backgroundMode: SceneEnvironment.Color; clearColor: "black" }
424
PerspectiveCamera { z: 600 }
425
DirectionalLight {
426
y: 200
427
eulerRotation.x: -45
428
castsShadow: true
429
}
430
Model {
431
source: "#Rectangle"
432
y: -250
433
scale: Qt.vector3d(5, 5, 5)
434
eulerRotation.x: -45
435
materials: PrincipledMaterial { baseColor: "lightBlue" }
436
}
437
Model {
438
source: "#Cube"
439
scale: Qt.vector3d(2, 2, 2)
440
eulerRotation.x: 30
441
materials: CustomMaterial {
442
vertexShader: "material.vert"
443
property real uAmplitude: 0
444
NumberAnimation on uAmplitude {
445
from: 0; to: 100; duration: 5000; loops: -1
446
}
447
property real uTime: 0
448
NumberAnimation on uTime {
449
from: 0; to: 100; duration: 10000; loops: -1
450
}
451
}
452
}
453
}
454
}
455
\endqml
456
\badcode
457
void MAIN()
458
{
459
VERTEX.x += sin(uTime + VERTEX.y) * uAmplitude;
460
}
461
\endcode
462
\li \image quick3d-custom-cube3-anim.gif
463
{Cube with ground plane showing vertex displacement animation}
464
\endtable
465
466
\section2 Adding a fragment shader
467
468
Many custom materials will want to have a fragment shader as well. In fact, many will want
469
only a fragment shader. If there is no extra data to be passed from the vertex to fragment
470
stage, and the default vertex transformation is sufficient, setting the \c vertexShader
471
property can be left out from the \l CustomMaterial.
472
473
\table
474
\header
475
\li Change in main.qml, material.frag
476
\li Result
477
\row \li \qml
478
materials: CustomMaterial {
479
fragmentShader: "material.frag"
480
}
481
\endqml
482
\badcode
483
void MAIN()
484
{
485
}
486
\endcode
487
\li \image quick3d-custom-cube4.jpg {White cube with empty fragment shader}
488
\endtable
489
490
Our first fragment shader contains an empty MAIN() function. This is no different than not
491
specifying a fragment shader snippet at all: what we get looks like what we get with a
492
default PrincipledMaterial.
493
494
Let's look at some of the commonly used keywords in fragment shaders. This is not the full
495
list, refer to the \l CustomMaterial documentation for a complete reference. Many of these
496
are read-write, meaning they have a default value, but the shader can, and often will want
497
to, assign a different value to them.
498
499
As the names suggest, many of these map to similarly named \l PrincipledMaterial
500
properties, with the same meaning and semantics, following the
501
\l{https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material}{metallic-roughness
502
material model}. It is up the custom material implementation to decide how these values
503
are calculated: for example, a value for BASE_COLOR can be hard coded in the shader, can
504
be based on sampling a texture, or can be calculated based on QML properties exposed as
505
uniforms or on interpolated data passed along from the vertex shader.
506
507
\table
508
\header
509
\li Keyword
510
\li Type
511
\li Description
512
\row
513
\li BASE_COLOR
514
\li vec4
515
\li The base color and alpha value. Corresponds to \l{PrincipledMaterial::baseColor}. The
516
final alpha value of the fragment is the model opacity multiplied by the base color
517
alpha. The default value is \c{(1.0, 1.0, 1.0, 1.0)}.
518
\row
519
\li EMISSIVE_COLOR
520
\li vec3
521
\li The color of self-illumination. Corresponds to
522
\l{PrincipledMaterial::emissiveFactor}. The default value is \c{(0.0, 0.0, 0.0)}.
523
\row
524
\li METALNESS
525
\li float
526
\li \l{PrincipledMaterial::metalness}{Metalness} value in range 0-1. Default to 0, which
527
means the material is dielectric (non-metallic).
528
\row
529
\li ROUGHNESS
530
\li float
531
\li \l{PrincipledMaterial::roughness}{Roughness} value in range 0-1. The default value is
532
0. Larger values soften specular highlights and blur reflections.
533
\row
534
\li SPECULAR_AMOUNT
535
\li float
536
\li \l{PrincipledMaterial::specularAmount}{The strength of specularity} in range 0-1. The
537
default value is \c 0.5. For metallic objects with \c metalness set to \c 1 this value
538
will have no effect. When both \c SPECULAR_AMOUNT and \c METALNESS have values larger than
539
0 but smaller than 1, the result is a blend between the two material models.
540
\row
541
\li NORMAL
542
\li vec3
543
\li The interpolated normal in world space, adjusted for double-sidedness when face culling is disabled. Read only.
544
\row
545
\li UV0
546
\li vec2
547
\li The interpolated texture coordinates. Read only.
548
\row
549
\li VAR_WORLD_POSITION
550
\li vec3
551
\li Interpolated vertex position in world space. Read only.
552
\endtable
553
554
Let's make the cube's base color red:
555
556
\table
557
\header
558
\li Change in main.qml, material.frag
559
\li Result
560
\row \li \qml
561
materials: CustomMaterial {
562
fragmentShader: "material.frag"
563
}
564
\endqml
565
\badcode
566
void MAIN()
567
{
568
BASE_COLOR = vec4(1.0, 0.0, 0.0, 1.0);
569
}
570
\endcode
571
\li \image quick3d-custom-cube5.jpg {Red cube with custom base color}
572
\endtable
573
574
Now strengthen the level of self-illumination a bit:
575
576
\table
577
\header
578
\li Change in main.qml, material.frag
579
\li Result
580
\row \li \qml
581
materials: CustomMaterial {
582
fragmentShader: "material.frag"
583
}
584
\endqml
585
\badcode
586
void MAIN()
587
{
588
BASE_COLOR = vec4(1.0, 0.0, 0.0, 1.0);
589
EMISSIVE_COLOR = vec3(0.4);
590
}
591
\endcode
592
\li \image quick3d-custom-cube6.jpg {Bright red cube with emissive color}
593
\endtable
594
595
Instead of having values hardcoded in the shader, we could also use QML properties exposed
596
as uniforms, even animated ones:
597
598
\table
599
\header
600
\li Change in main.qml, material.frag
601
\li Result
602
\row \li \qml
603
materials: CustomMaterial {
604
fragmentShader: "material.frag"
605
property color baseColor: "black"
606
ColorAnimation on baseColor {
607
from: "black"; to: "purple"; duration: 5000; loops: -1
608
}
609
}
610
\endqml
611
\badcode
612
void MAIN()
613
{
614
BASE_COLOR = vec4(baseColor.rgb, 1.0);
615
EMISSIVE_COLOR = vec3(0.4);
616
}
617
\endcode
618
\li \image quick3d-custom-cube7-anim.gif
619
{Cube with animated color transition from black to purple}
620
\endtable
621
622
Let's do something less trivial, something that is not implementable with a
623
PrincipledMaterial and its standard, built-in properties. The following material
624
visualizes the texture UV coordinates of the cube mesh. U runs 0 to 1, so from black to
625
red, while V is also 0 to 1, black to green.
626
627
\table
628
\header
629
\li Change in main.qml, material.frag
630
\li Result
631
\row \li \qml
632
materials: CustomMaterial {
633
fragmentShader: "material.frag"
634
}
635
\endqml
636
\badcode
637
void MAIN()
638
{
639
BASE_COLOR = vec4(UV0, 0.0, 1.0);
640
}
641
\endcode
642
\li \image quick3d-custom-cube8.jpg
643
{Cube showing UV coordinates as red and green color gradient}
644
\endtable
645
646
While we are at it, why not visualize normals as well, this time on a sphere. Like with
647
UVs, if a custom vertex shader snippet were to alter the value of NORMAL, the interpolated
648
per-fragment value in the fragment shader, also exposed under the name NORMAL, would
649
reflect those adjustments.
650
651
\table
652
\header
653
\li Change in main.qml, material.frag
654
\li Result
655
\row \li \qml
656
Model {
657
source: "#Sphere"
658
scale: Qt.vector3d(2, 2, 2)
659
materials: CustomMaterial {
660
fragmentShader: "material.frag"
661
}
662
}
663
\endqml
664
\badcode
665
void MAIN()
666
{
667
BASE_COLOR = vec4(NORMAL, 1.0);
668
}
669
\endcode
670
\li \image quick3d-custom-cube9.jpg
671
{Sphere visualizing surface normals as RGB colors}
672
\endtable
673
674
\section2 Colors
675
676
Let's switch over to a teapot model for a moment, make the material a blend of metallic
677
and dielectric, and try to set a green base color for it. The \c green QColor value maps
678
to \c{(0, 128, 0)}, based on which our first attempt could be:
679
680
\table
681
\header
682
\li main.qml, material.frag
683
\row \li \qml
684
import QtQuick
685
import QtQuick3D
686
Item {
687
View3D {
688
anchors.fill: parent
689
environment: SceneEnvironment { backgroundMode: SceneEnvironment.Color; clearColor: "black" }
690
PerspectiveCamera { z: 600 }
691
DirectionalLight { }
692
Model {
693
source: "teapot.mesh"
694
scale: Qt.vector3d(60, 60, 60)
695
eulerRotation.x: 30
696
materials: CustomMaterial {
697
fragmentShader: "material.frag"
698
}
699
}
700
}
701
}
702
\endqml
703
\badcode
704
void MAIN()
705
{
706
BASE_COLOR = vec4(0.0, 0.5, 0.0, 1.0);
707
METALNESS = 0.6;
708
SPECULAR_AMOUNT = 0.4;
709
ROUGHNESS = 0.4;
710
}
711
\endcode
712
\endtable
713
714
\image quick3d-custom-color1.jpg {Green teapot with direct RGB color values}
715
716
This does not look entirely right. Compare with the second approach:
717
718
\table
719
\header
720
\li Change in main.qml, material.frag
721
\li Result
722
\row \li \qml
723
materials: CustomMaterial {
724
fragmentShader: "material.frag"
725
property color uColor: "green"
726
}
727
\endqml
728
\badcode
729
void MAIN()
730
{
731
BASE_COLOR = vec4(uColor.rgb, 1.0);
732
METALNESS = 0.6;
733
SPECULAR_AMOUNT = 0.4;
734
ROUGHNESS = 0.4;
735
}
736
\endcode
737
\li \image quick3d-custom-color2.jpg
738
{Green teapot with QML color property and sRGB conversion}
739
\endtable
740
741
Switching to a PrincipledMaterial, we can confirm that setting the
742
\l{PrincipledMaterial::baseColor} to "green" and following the metalness and other
743
properties, the result is identical to our second approach:
744
745
\table
746
\header
747
\li Change in main.qml
748
\li Result
749
\row \li \qml
750
materials: PrincipledMaterial {
751
baseColor: "green"
752
metalness: 0.6
753
specularAmount: 0.4
754
roughness: 0.4
755
}
756
\endqml
757
\li \image quick3d-custom-color3.jpg
758
{Green teapot with standard material showing correct color}
759
\endtable
760
761
If the type of the \c uColor property was changed to \c vector4d, or any type other than
762
\c color, the results would suddenly change and become identical to our first approach.
763
764
Why is this?
765
766
The answer lies in the sRGB to linear conversion that is performed implicitly for color
767
properties of DefaultMaterial, PrincipledMaterial, and also for custom properties with a
768
\c color type in a CustomMaterial. Such conversion is not performed for any other value,
769
so if the shader hardcodes a color value, or bases it on a QML property with a type
770
different from \c color, it will be up to the shader to perform linearization in case the
771
source value was in sRGB color space. Converting to linear is important since Qt Quick 3D
772
performs \l{SceneEnvironment::tonemapMode}{tonemapping} on the results of fragment
773
shading, and that process assumes values in the sRGB space as its input.
774
775
The built-in QColor constants, such as, \c{"green"}, are all given in sRGB
776
space. Therefore, just assigning \c{vec4(0.0, 0.5, 0.0, 1.0)} to BASE_COLOR in the first
777
attempt is insufficient if we wanted a result that matches an RGB value \c{(0, 128, 0)} in
778
the sRGB space. See the \c BASE_COLOR documentation in \l CustomMaterial for a formula for
779
linearizing such color values. The same applies to color values retrieved by sampling
780
textures: if the source image data is not in the sRGB color space, a conversion is needed
781
(unless \l{SceneEnvironment::tonemapMode}{tonemapping} is disabled).
782
783
\section2 Blending
784
785
Just writing a value less than \c 1.0 to \c{BASE_COLOR.a} is not sufficient if the
786
expectation is to get alpha blending. Such materials will very often change the values of
787
\l{CustomMaterial::sourceBlend}{sourceBlend} and
788
\l{CustomMaterial::destinationBlend}{destinationBlend} properties to get the desired
789
results.
790
791
Also keep in mind that the combined alpha value is the \l{Node::opacity}{Node opacity}
792
multiplied by the material alpha.
793
794
To visualize, let's use a shader that assigns red with alpha \c 0.5 to \c BASE_COLOR:
795
796
\table
797
\header
798
\li main.qml, material.frag
799
\li Result
800
\row \li \qml
801
import QtQuick
802
import QtQuick3D
803
Item {
804
View3D {
805
anchors.fill: parent
806
environment: SceneEnvironment {
807
backgroundMode: SceneEnvironment.Color
808
clearColor: "white"
809
}
810
PerspectiveCamera {
811
id: camera
812
z: 600
813
}
814
DirectionalLight { }
815
Model {
816
source: "#Cube"
817
x: -150
818
eulerRotation.x: 60
819
eulerRotation.y: 20
820
materials: CustomMaterial {
821
fragmentShader: "material.frag"
822
}
823
}
824
Model {
825
source: "#Cube"
826
eulerRotation.x: 60
827
eulerRotation.y: 20
828
materials: CustomMaterial {
829
sourceBlend: CustomMaterial.SrcAlpha
830
destinationBlend: CustomMaterial.OneMinusSrcAlpha
831
fragmentShader: "material.frag"
832
}
833
}
834
Model {
835
source: "#Cube"
836
x: 150
837
eulerRotation.x: 60
838
eulerRotation.y: 20
839
materials: CustomMaterial {
840
sourceBlend: CustomMaterial.SrcAlpha
841
destinationBlend: CustomMaterial.OneMinusSrcAlpha
842
fragmentShader: "material.frag"
843
}
844
opacity: 0.5
845
}
846
}
847
}
848
\endqml
849
\badcode
850
void MAIN()
851
{
852
BASE_COLOR = vec4(1.0, 0.0, 0.0, 0.5);
853
}
854
\endcode
855
\li \image quick3d-custom-blend.jpg
856
{Three cubes showing blend mode opacity variations}
857
\endtable
858
859
The first cube is writing 0.5 to the alpha value of the color but it does not bring
860
visible results since alpha blending is not enabled. The second cube enables simple alpha
861
blending via the CustomMaterial properties. The third one also assigns an opacity of 0.5
862
to the Model, which means that the effective opacity is 0.25.
863
864
\section2 Passing data between the vertex and fragment shader
865
866
Calculating a value per vertex (for example, assuming a single triangle, for the 3 corners
867
of the triangle), and then passing it on to the fragment stage, where for each fragment
868
(for example, every fragment covered by the rasterized triangle) an interpolated value is
869
made accessible. In custom material shader snippets this is made possible by the \c
870
VARYING keyword. This provides a syntax similar to GLSL 120 and GLSL ES 100, but will work
871
regardless of the graphics API used at run time. The engine will take care of rewriting
872
the varying declaration as appropriate.
873
874
Let's see how the classic texture sampling with UV coordinates would look like. Textures
875
are going to be covered in an upcoming section, for now let's focus on how we get the UV
876
coordinates that can be passed to the \c{texture()} function in the shader.
877
878
\table
879
\header
880
\li main.qml, material.vert, material.frag
881
\row \li \qml
882
import QtQuick
883
import QtQuick3D
884
Item {
885
View3D {
886
anchors.fill: parent
887
environment: SceneEnvironment { backgroundMode: SceneEnvironment.Color; clearColor: "black" }
888
PerspectiveCamera { z: 600 }
889
DirectionalLight { }
890
Model {
891
source: "#Sphere"
892
scale: Qt.vector3d(4, 4, 4)
893
eulerRotation.x: 30
894
materials: CustomMaterial {
895
vertexShader: "material.vert"
896
fragmentShader: "material.frag"
897
property Texture someTextureMap: Texture {
898
source: "qt_logo_rect.png"
899
}
900
}
901
}
902
}
903
}
904
\endqml
905
\badcode
906
VARYING vec2 uv;
907
void MAIN()
908
{
909
uv = UV0;
910
}
911
\endcode
912
\badcode
913
VARYING vec2 uv;
914
void MAIN()
915
{
916
BASE_COLOR = texture(someTextureMap, uv);
917
}
918
\endcode
919
\endtable
920
921
\table
922
\header
923
\li qt_logo_rect.png
924
\li Result
925
\row \li \image quick3d-custom-varying-map.png
926
{Qt logo texture used as source data}
927
\li \image quick3d-custom-varying1.jpg
928
{Cube with Qt logo texture applied to faces}
929
\endtable
930
931
Note that \c VARYING declarations. The name and type must match, \c uv in the fragment
932
shader will expose the interpolated UV coordinate for the current fragment.
933
934
Any other type of data can be passed on to the fragment stage in a similar manner. It is
935
worth noting that in many cases setting up the material's own varyings is not necessary
936
because there are builtins provided that cover many of typical needs. This includes making
937
the (interpolated) normals, UVs, world position (\c VAR_WORLD_POSITION), or the vector
938
pointing towards the camera (\c VIEW_VECTOR).
939
940
The above example can in fact be simplified to the following as \c UV0 is automatically
941
available in the fragment stage as well:
942
943
\table
944
\header
945
\li Change in main.qml, material.frag
946
\li Result
947
\row \li \qml
948
materials: CustomMaterial {
949
fragmentShader: "material.frag"
950
property Texture someTextureMap: Texture {
951
source: "qt_logo_rect.png"
952
}
953
}
954
\endqml
955
\badcode
956
void MAIN()
957
{
958
BASE_COLOR = texture(someTextureMap, UV0);
959
}
960
\endcode
961
\li \image quick3d-custom-varying1.jpg
962
{Cube with Qt logo texture applied to faces}
963
\endtable
964
965
To disable interpolation for a variable, use the \c flat keyword in both the
966
vertex and fragment shader snippet. For example:
967
\badcode
968
VARYING flat vec2 v;
969
\endcode
970
971
\section2 Textures
972
973
A \l CustomMaterial has no built-in texture maps, meaning there is no equivalent of, for
974
example, \l{PrincipledMaterial::baseColorMap}. This is because implementing the same is
975
often trivial, while giving a lot more flexibility than what DefaultMaterial and
976
PrincipledMaterial has built in. Besides simply sampling a texture, custom fragment shader
977
snippets are free to combine and blend data from various sources when calculating the
978
values they assign to \c BASE_COLOR, \c EMISSIVE_COLOR, \c ROUGHNESS, etc. They can base
979
these calculations on data provided via QML properties, interpolated data sent on from the
980
vertex stage, values retrieved from sampling textures, and on hardcoded values.
981
982
As the previous example shows, exposing a texture to the vertex, fragment, or both shaders
983
is very similar to scalar and vector uniform values: a QML property with the type \l
984
Texture will automatically get associated with a \c sampler2D in the shader code. As
985
always, there is no need to declare this sampler in the shader code. Properties of the \l
986
TextureInput type, which references a \l Texture, are also supported for compatibility.
987
988
A \l Texture can source its data in three ways: \l{Texture::source}{from an image file},
989
\l{Texture::sourceItem}{from a texture with live Qt Quick content}, or
990
\l{Texture::textureData}{can be provided from C++} via QQuick3DTextureData.
991
992
\note When it comes to \l Texture properties, the source, tiling, and filtering related
993
ones are the only ones that are taken into account implicitly with custom materials, as
994
the rest (such as, UV transformations) is up to the custom shaders to implement as they
995
see fit.
996
997
Let's see an example where a model, a sphere in this case, is textured using live Qt Quick
998
content:
999
1000
\table
1001
\header
1002
\li main.qml, material.frag
1003
\row \li \qml
1004
import QtQuick
1005
import QtQuick3D
1006
Item {
1007
View3D {
1008
anchors.fill: parent
1009
environment: SceneEnvironment { backgroundMode: SceneEnvironment.Color; clearColor: "black" }
1010
PerspectiveCamera { z: 600 }
1011
DirectionalLight { }
1012
Model {
1013
source: "#Sphere"
1014
scale: Qt.vector3d(4, 4, 4)
1015
eulerRotation.x: 30
1016
materials: CustomMaterial {
1017
fragmentShader: "material.frag"
1018
property Texture someTextureMap: Texture {
1019
sourceItem: Rectangle {
1020
width: 512; height: 512
1021
color: "red"
1022
Rectangle {
1023
width: 32; height: 32
1024
anchors.horizontalCenter: parent.horizontalCenter
1025
y: 150
1026
color: "gray";
1027
NumberAnimation on rotation { from: 0; to: 360; duration: 3000; loops: -1 }
1028
}
1029
Text {
1030
anchors.centerIn: parent
1031
text: "Texture Map"
1032
font.pointSize: 16
1033
}
1034
}
1035
}
1036
}
1037
}
1038
}
1039
}
1040
\endqml
1041
\badcode
1042
void MAIN()
1043
{
1044
vec2 uv = vec2(UV0.x, 1.0 - UV0.y);
1045
vec4 c = texture(someTextureMap, uv);
1046
BASE_COLOR = c;
1047
}
1048
\endcode
1049
\endtable
1050
1051
\image quick3d-custmat-tex1-anim.gif {Red sphere with animated texture map}
1052
1053
Here the 2D subtree (Rectangle with two children: another Rectangle and the Text) is
1054
rendered in to an 512x512 2D texture every time this mini-scene changes. The texture is
1055
then exposed to the custom material under the name of \c someTextureMap.
1056
1057
Note the flipping of the V coordinate in the shader. As noted above, custom materials,
1058
where there is full programmability on shader level, do not offer the "fixed" features of
1059
\l Texture and \l PrincipledMaterial. This means that any transformations to the UV
1060
coordinates will need to be applied by the shader. Here we know that the texture is
1061
generated via \l{Texture::sourceItem} and so V needs to be flipped to get something that
1062
matches the UV set of the mesh we are using.
1063
1064
What this example shows is possible to do with a \l PrincipledMaterial too. Let's make it
1065
more interesting by doing a simple emboss effect in addition:
1066
1067
\table
1068
\header
1069
\li material.frag
1070
\li Result
1071
\row \li \badcode
1072
void MAIN()
1073
{
1074
vec2 uv = vec2(UV0.x, 1.0 - UV0.y);
1075
vec2 size = vec2(textureSize(someTextureMap, 0));
1076
vec2 d = vec2(1.0 / size.x, 1.0 / size.y);
1077
vec4 diff = texture(someTextureMap, uv + d) - texture(someTextureMap, uv - d);
1078
float c = (diff.x + diff.y + diff.z) + 0.5;
1079
BASE_COLOR = vec4(c, c, c, 1.0);
1080
}
1081
\endcode
1082
\li \image quick3d-custmat-tex2-anim.gif
1083
{Sphere with animated procedural texture}
1084
\endtable
1085
1086
With the features covered so far a wide range of possibilities are open for creating
1087
materials that shade the meshes in visually impressive ways. To finish the basic tour,
1088
let's look at an example that applies height and normal maps to a plane mesh. (a dedicated
1089
\c{.mesh} file is used here because the builtin \c{#Rectangle} does not have enough
1090
subdivisions) For better lighting results, we will use image based lighting with a 360
1091
degree HDR image. The image is also set as the skybox to make it more clear what is
1092
happening.
1093
1094
First let's start with an empty CustomMaterial:
1095
1096
\table
1097
\header
1098
\li main.qml
1099
\li Result
1100
\row \li \qml
1101
import QtQuick
1102
import QtQuick3D
1103
Item {
1104
View3D {
1105
anchors.fill: parent
1106
environment: SceneEnvironment {
1107
backgroundMode: SceneEnvironment.SkyBox
1108
lightProbe: Texture {
1109
source: "00489_OpenfootageNET_snowfield_low.hdr"
1110
}
1111
}
1112
PerspectiveCamera {
1113
z: 600
1114
}
1115
Model {
1116
source: "plane.mesh"
1117
scale: Qt.vector3d(400, 400, 400)
1118
z: 400
1119
y: -50
1120
eulerRotation.x: -90
1121
materials: CustomMaterial { }
1122
}
1123
}
1124
}
1125
\endqml
1126
\li \image quick3d-custom-tex3.jpg
1127
{Plane with winter landscape from custom texture data}
1128
\endtable
1129
1130
Now let's make some shaders that apply a height and normal map to the mesh:
1131
1132
\table
1133
\header
1134
\li Height map
1135
\li Normap map
1136
\row
1137
\li \image quick3d-custom-heightmap.png {Grayscale height map texture}
1138
\li \image quick3d-custom-normalmap.jpg
1139
{Plane with height map applied as displacement}
1140
\endtable
1141
1142
\table
1143
\header
1144
\li material.vert, material.frag
1145
\row
1146
\li \badcode
1147
float getHeight(vec2 pos)
1148
{
1149
return texture(heightMap, pos).r;
1150
}
1151
1152
void MAIN()
1153
{
1154
const float offset = 0.004;
1155
VERTEX.y += getHeight(UV0);
1156
TANGENT = normalize(vec3(0.0, getHeight(UV0 + vec2(0.0, offset)) - getHeight(UV0 + vec2(0.0, -offset)), offset * 2.0));
1157
BINORMAL = normalize(vec3(offset * 2.0, getHeight(UV0 + vec2(offset, 0.0)) - getHeight(UV0 + vec2(-offset, 0.0)), 0.0));
1158
NORMAL = cross(TANGENT, BINORMAL);
1159
}
1160
\endcode
1161
\badcode
1162
void MAIN()
1163
{
1164
vec3 normalValue = texture(normalMap, UV0).rgb;
1165
normalValue.xy = normalValue.xy * 2.0 - 1.0;
1166
normalValue.z = sqrt(max(0.0, 1.0 - dot(normalValue.xy, normalValue.xy)));
1167
NORMAL = normalize(mix(NORMAL, TANGENT * normalValue.x + BINORMAL * normalValue.y + NORMAL * normalValue.z, 1.0));
1168
}
1169
\endcode
1170
\endtable
1171
1172
\table
1173
\header
1174
\li Change in main.qml
1175
\li Result
1176
\row
1177
\li \qml
1178
materials: CustomMaterial {
1179
vertexShader: "material.vert"
1180
fragmentShader: "material.frag"
1181
property Texture normalMap: Texture { source: "normalmap.jpg" }
1182
property Texture heightMap: Texture { source: "heightmap.png" }
1183
}
1184
\endqml
1185
\li \image quick3d-custom-tex4.jpg
1186
{Plane with normal map showing surface detail}
1187
\endtable
1188
1189
\note The \l WasdController object can be immensely helpful during development and
1190
troubleshooting as it allows navigating and looking around in the scene with the keyboard
1191
and mouse in a familiar manner. Having a camera controlled by the WasdController is as
1192
simple as:
1193
1194
\qml
1195
import QtQuick3D.Helpers
1196
View3D {
1197
PerspectiveCamera {
1198
id: camera
1199
}
1200
// ...
1201
}
1202
WasdController {
1203
controlledObject: camera
1204
}
1205
\endqml
1206
1207
\section2 Depth and screen textures
1208
1209
When a custom shader snippet uses the \c DEPTH_TEXTURE or \c SCREEN_TEXTURE keywords, it
1210
opts in to generating the corresponding textures in a separate render pass, which is not
1211
necessarily a cheap operation, but allows implementing a variety of techniques, such as
1212
refraction for glass-like materials.
1213
1214
\c DEPTH_TEXTURE is a \c sampler2D that allows sampling a texture with the contents of the
1215
depth buffer with all the \c opaque objects in the scene rendered. Similarly, \c
1216
SCREEN_TEXTURE is a \c sampler2D that allows sampling a texture containing the contents of
1217
the scene excluding any transparent materials or any materials also using the
1218
SCREEN_TEXTURE. The texture can be used for materials that require the contents of the
1219
framebuffer they are being rendered to. The SCREEN_TEXTURE texture uses the same clear mode
1220
as the View3D. The size of these textures matches the size of the View3D in pixels.
1221
1222
Let's have a simple demonstration by visualizing the depth buffer contents via \c
1223
DEPTH_TEXTURE. The camera's \l{PerspectiveCamera::clipFar}{far clip value} is reduced here from the
1224
default 10000 to 2000, in order to have a smaller range, and so have the visualized depth
1225
value differences more obvious. The result is a rectangle that happens to visualize the
1226
depth buffer for the scene over its surface.
1227
1228
\table
1229
\header
1230
\li main.qml, material.frag
1231
\li Result
1232
\row
1233
\li \qml
1234
import QtQuick
1235
import QtQuick3D
1236
import QtQuick3D.Helpers
1237
Rectangle {
1238
width: 400
1239
height: 400
1240
color: "black"
1241
View3D {
1242
anchors.fill: parent
1243
PerspectiveCamera {
1244
id: camera
1245
z: 600
1246
clipNear: 1
1247
clipFar: 2000
1248
}
1249
DirectionalLight { }
1250
Model {
1251
source: "#Cube"
1252
scale: Qt.vector3d(2, 2, 2)
1253
position: Qt.vector3d(150, 200, -1000)
1254
eulerRotation.x: 60
1255
eulerRotation.y: 20
1256
materials: PrincipledMaterial { }
1257
}
1258
Model {
1259
source: "#Cylinder"
1260
scale: Qt.vector3d(2, 2, 2)
1261
position: Qt.vector3d(400, 200, -1000)
1262
materials: PrincipledMaterial { }
1263
opacity: 0.3
1264
}
1265
Model {
1266
source: "#Sphere"
1267
scale: Qt.vector3d(2, 2, 2)
1268
position: Qt.vector3d(-150, 200, -600)
1269
materials: PrincipledMaterial { }
1270
}
1271
Model {
1272
source: "#Cone"
1273
scale: Qt.vector3d(2, 2, 2)
1274
position: Qt.vector3d(0, 400, -1200)
1275
materials: PrincipledMaterial { }
1276
}
1277
Model {
1278
source: "#Rectangle"
1279
scale: Qt.vector3d(3, 3, 3)
1280
y: -150
1281
materials: CustomMaterial {
1282
fragmentShader: "material.frag"
1283
}
1284
}
1285
}
1286
WasdController {
1287
controlledObject: camera
1288
}
1289
}
1290
\endqml
1291
\badcode
1292
void MAIN()
1293
{
1294
float zNear = CAMERA_PROPERTIES.x;
1295
float zFar = CAMERA_PROPERTIES.y;
1296
float zRange = zFar - zNear;
1297
vec4 depthSample = texture(DEPTH_TEXTURE, vec2(UV0.x, 1.0 - UV0.y));
1298
float zn = 2.0 * depthSample.r - 1.0;
1299
float d = 2.0 * zNear * zFar / (zFar + zNear - zn * zRange);
1300
d /= zFar;
1301
BASE_COLOR = vec4(d, d, d, 1.0);
1302
}
1303
\endcode
1304
\li \image quick3d-custom-depth-anim.gif
1305
{Animation showing depth buffer values as grayscale}
1306
\endtable
1307
1308
Note how the cylinder is not present in \c DEPTH_TEXTURE due to its reliance on
1309
semi-transparency, which puts it into a different category than the other objects that are
1310
all opaque. These objects do not write into the depth buffer, although they do test
1311
against the depth values written by opaque objects, and rely on being rendered in back to
1312
front order. Hence they are not present in \c DEPTH_TEXTURE either.
1313
1314
What happens if we switch the shader to sample \c SCREEN_TEXTURE instead?
1315
1316
\table
1317
\header
1318
\li material.frag
1319
\li Result
1320
\row \li \badcode
1321
void MAIN()
1322
{
1323
vec4 c = texture(SCREEN_TEXTURE, vec2(UV0.x, 1.0 - UV0.y));
1324
if (c.a == 0.0)
1325
c.rgb = vec3(0.2, 0.1, 0.3);
1326
BASE_COLOR = c;
1327
}
1328
\endcode
1329
\li \image quick3d-custom-screen.jpg
1330
{Scene showing screen texture with distortion effect}
1331
\endtable
1332
1333
Here the rectangle is textured with \c SCREEN_TEXTURE, while replacing transparent pixels
1334
with purple.
1335
1336
\section2 Light processor functions
1337
1338
An advanced feature of \l CustomMaterial is the ability to define functions in the
1339
fragment shader that reimplement the lighting equations that are used to calculate the
1340
fragment color. A light processor function, when present, is called once per each light in
1341
the scene, for each fragment. There is a dedicated function for different light types, as
1342
well as the ambient and specular contribution. When no corresponding light processor
1343
function is present, the standard calculations are used, just like a PrincipledMaterial
1344
would do. When a light processor is present, but the function body is empty, it means
1345
there will be no contribution from a given type of lights in the scene.
1346
1347
Refer to the \l CustomMaterial documentation for details on functions such as \c
1348
DIRECTIONAL_LIGHT, \c POINT_LIGHT, \c SPOT_LIGHT, \c AMBIENT_LIGHT, and \c SPECULAR_LIGHT.
1349
1350
\section2 Unshaded custom materials
1351
1352
There is another type of \l CustomMaterial: \c unshaded custom materials. All the example
1353
so far used \c shaded custom materials, with the
1354
\l{CustomMaterial::shadingMode}{shadingMode} property left at its default
1355
CustomMaterial.Shaded value.
1356
1357
What happens if we switch this property to CustomMaterial.Unshaded?
1358
1359
First of all, keywords like \c BASE_COLOR, \c EMISSIVE_COLOR, \c METALNESS, etc. no longer
1360
have the desired effect. This is because an unshaded material, as the name suggests, does
1361
not automatically get amended with much of the standard shading code, thus ignoring
1362
lights, image based lighting, shadows, and ambient occlusion in the scene. Rather, an
1363
unshaded material gives full control to the shader via the \c FRAGCOLOR keyword. This is
1364
similar to gl_FragColor: the color assigned to \c FRAGCOLOR is the result and the final
1365
color of the fragment, without any further adjustments by Qt Quick 3D.
1366
1367
\table
1368
\header
1369
\li main.qml, material.frag, material2.frag
1370
\li Result
1371
\row \li \qml
1372
import QtQuick
1373
import QtQuick3D
1374
Item {
1375
View3D {
1376
anchors.fill: parent
1377
environment: SceneEnvironment {
1378
backgroundMode: SceneEnvironment.Color
1379
clearColor: "black"
1380
}
1381
PerspectiveCamera { z: 600 }
1382
DirectionalLight { }
1383
Model {
1384
source: "#Cylinder"
1385
x: -100
1386
eulerRotation.x: 30
1387
materials: CustomMaterial {
1388
fragmentShader: "material.frag"
1389
}
1390
}
1391
Model {
1392
source: "#Cylinder"
1393
x: 100
1394
eulerRotation.x: 30
1395
materials: CustomMaterial {
1396
shadingMode: CustomMaterial.Unshaded
1397
fragmentShader: "material2.frag"
1398
}
1399
}
1400
}
1401
}
1402
\endqml
1403
\badcode
1404
void MAIN()
1405
{
1406
BASE_COLOR = vec4(1.0);
1407
}
1408
\endcode
1409
\badcode
1410
void MAIN()
1411
{
1412
FRAGCOLOR = vec4(1.0);
1413
}
1414
\endcode
1415
\li \image quick3d-custom-unshaded1.jpg
1416
{Cube and cylinder with unshaded custom material}
1417
\endtable
1418
1419
Notice how the right cylinder ignores the DirectionalLight in the scene. Its shading knows
1420
nothing about scene lighting, the final fragment color is all white.
1421
1422
The vertex shader in an unshaded material still has the typical inputs available: \c
1423
VERTEX, \c NORMAL, \c MODELVIEWPROJECTION_MATRIX, etc. and can write to \c POSITION. The
1424
fragment shader no longer has the similar conveniences available, however: \c NORMAL, \c
1425
UV0, or \c VAR_WORLD_POSITION are not available in an unshaded material's fragment
1426
shader. Rather, it is now up to the shader code to calculate and pass on using \c VARYING
1427
everything it needs to determine the final fragment color.
1428
1429
Let's look at an example that has both a vertex and fragment shader. The altered vertex
1430
position is passed on to the fragment shader, with an interpolated value made available to
1431
every fragment.
1432
1433
\table
1434
\header
1435
\li main.qml, material.vert, material.frag
1436
\row \li \qml
1437
import QtQuick
1438
import QtQuick3D
1439
Item {
1440
View3D {
1441
anchors.fill: parent
1442
environment: SceneEnvironment {
1443
backgroundMode: SceneEnvironment.Color
1444
clearColor: "black"
1445
}
1446
PerspectiveCamera { z: 600 }
1447
Model {
1448
source: "#Sphere"
1449
scale: Qt.vector3d(3, 3, 3)
1450
materials: CustomMaterial {
1451
property real time: 0.0
1452
NumberAnimation on time { from: 0; to: 100; duration: 20000; loops: -1 }
1453
property real amplitude: 10.0
1454
shadingMode: CustomMaterial.Unshaded
1455
vertexShader: "material.vert"
1456
fragmentShader: "material.frag"
1457
}
1458
}
1459
}
1460
}
1461
\endqml
1462
\badcode
1463
VARYING vec3 pos;
1464
void MAIN()
1465
{
1466
pos = VERTEX;
1467
pos.x += sin(time * 4.0 + pos.y) * amplitude;
1468
POSITION = MODELVIEWPROJECTION_MATRIX * vec4(pos, 1.0);
1469
}
1470
\endcode
1471
\badcode
1472
VARYING vec3 pos;
1473
void MAIN()
1474
{
1475
FRAGCOLOR = vec4(vec3(pos.x * 0.02, pos.y * 0.02, pos.z * 0.02), 1.0);
1476
}
1477
\endcode
1478
\endtable
1479
1480
\image quick3d-custom-unshaded-anim.gif
1481
{Animation showing lighting toggle between shaded and unshaded}
1482
1483
Unshaded materials are useful when interacting with scene lighting is not necessary or
1484
desired, and the material needs full control on the final fragment color. Notice how the
1485
example above has neither a DirectionalLight nor any other lights, but the sphere with the
1486
custom material shows up as expected.
1487
1488
\note An unshaded material that only has a vertex shader snippet, but does not specify the
1489
fragmentShader property, will still be functional but the results are as if the
1490
shadingMode was set to Shaded. Therefore it makes little sense to switch shadingMode for
1491
materials that only have a vertex shader.
1492
1493
\section1 Programmability for Effects
1494
1495
Post-processing effects apply one or more fragment shaders to the result of a \l
1496
View3D. The output from these fragment shaders is then displayed instead of the original
1497
rendering results. This is conceptually very similar to Qt Quick's \l ShaderEffect and \l
1498
ShaderEffectSource.
1499
1500
\note Post-processing effects are only available when the
1501
\l{View3D::renderMode}{renderMode} for the View3D is set to View3D.Offscreen.
1502
1503
Custom vertex shader snippets can also be specified for an effect, but they have limited
1504
usefulness and therefore are expected to be used relatively rarely. The vertex input for a
1505
post-processing effect is a quad (either two triangles or a triangle strip), transforming
1506
or displacing the vertices of that is often not helpful. It can however make sense to have
1507
a vertex shader in order to calculate and pass on data to the fragment shader using the \c
1508
VARYING keyword. As usual, the fragment shader will then receive an interpolated value
1509
based on the current fragment coordinate.
1510
1511
The syntax of the shader snippets associated with a \l Effect is identical to the shaders
1512
for an unshaded \l CustomMaterial. When it comes to the built-in special keywords, \c
1513
VARYING, \c MAIN, \c FRAGCOLOR (fragment shader only), \c POSITION (vertex shader only), \c
1514
VERTEX (vertex shader only), and \c MODELVIEWPROJECTION_MATRIX work identically to \l
1515
CustomMaterial.
1516
1517
The most important special keywords for \l Effect fragment shaders are the following:
1518
1519
\table
1520
\header
1521
\li Name
1522
\li Type
1523
\li Description
1524
\row
1525
\li INPUT
1526
\li sampler2D or sampler2DArray
1527
\li The sampler for the input texture. An effect will typically sample this using \c INPUT_UV.
1528
\row
1529
\li INPUT_UV
1530
\li vec2
1531
\li UV coordinates for sampling \c INPUT.
1532
\row
1533
\li INPUT_SIZE
1534
\li vec2
1535
\li The size of the \c INPUT texture, in pixels. This is a convenient alternative to calling textureSize().
1536
\row
1537
\li OUTPUT_SIZE
1538
\li vec2
1539
\li The size of the output texture, in pixels. Equal to \c INPUT_SIZE in many cases, but a multi-pass effect
1540
may have passes that output to intermediate textures with different sizes.
1541
\row
1542
\li DEPTH_TEXTURE
1543
\li sampler2D
1544
\li Depth texture with the depth buffer contents with the opaque objects in the scene. Like with CustomMaterial,
1545
the presence of this keyword in the shader triggers generating the depth texture automatically.
1546
\endtable
1547
1548
\note When multiview rendering is enabled, the input texture is a 2D texture
1549
array. GLSL functions such as texture() and textureSize() take/return a
1550
vec3/ivec3, respectively, then. Use \c VIEW_INDEX for the layer. In VR/AR
1551
applications that wish to function both with and without multiview rendering, the
1552
portable approach is to write the shader code like this:
1553
\badcode
1554
#if QSHADER_VIEW_COUNT >= 2
1555
vec4 c = texture(INPUT, vec3(INPUT_UV, VIEW_INDEX));
1556
#else
1557
vec4 c = texture(INPUT, INPUT_UV);
1558
#endif
1559
\endcode
1560
1561
\section2 A post-processing effect
1562
1563
Let's start with a simple scene, this time using a few more objects, including a textured
1564
rectangle that uses a checkerboard texture as its base color map.
1565
1566
\table
1567
\header
1568
\li main.qml
1569
\li Result
1570
\row \li \qml
1571
import QtQuick
1572
import QtQuick3D
1573
Item {
1574
View3D {
1575
anchors.fill: parent
1576
environment: SceneEnvironment {
1577
backgroundMode: SceneEnvironment.Color
1578
clearColor: "black"
1579
}
1580
1581
PerspectiveCamera { z: 400 }
1582
1583
DirectionalLight { }
1584
1585
Texture {
1586
id: checkerboard
1587
source: "checkerboard.png"
1588
scaleU: 20
1589
scaleV: 20
1590
tilingModeHorizontal: Texture.Repeat
1591
tilingModeVertical: Texture.Repeat
1592
}
1593
1594
Model {
1595
source: "#Rectangle"
1596
scale: Qt.vector3d(10, 10, 1)
1597
eulerRotation.x: -45
1598
materials: PrincipledMaterial {
1599
baseColorMap: checkerboard
1600
}
1601
}
1602
1603
Model {
1604
source: "#Cone"
1605
position: Qt.vector3d(100, -50, 100)
1606
materials: PrincipledMaterial { }
1607
}
1608
1609
Model {
1610
source: "#Cube"
1611
position.y: 100
1612
eulerRotation.y: 20
1613
materials: PrincipledMaterial { }
1614
}
1615
1616
Model {
1617
source: "#Sphere"
1618
position: Qt.vector3d(-150, 200, -100)
1619
materials: PrincipledMaterial { }
1620
}
1621
}
1622
}
1623
\endqml
1624
\li \image quick3d-custom-effect-section-scene.jpg
1625
{Reference scene with sphere, cone, and cube}
1626
\endtable
1627
1628
Now let's apply an affect to the entire scene. More precisely, to the View3D. When there
1629
are multiple View3D items in the scene, each has its own SceneEnvironment and therefore
1630
have their own post-processing effect chain. In the example there is one single View3D
1631
covering the entire window.
1632
1633
\table
1634
\header
1635
\li Change in main.qml
1636
\li effect.frag
1637
\row \li \qml
1638
environment: SceneEnvironment {
1639
backgroundMode: SceneEnvironment.Color
1640
clearColor: "black"
1641
effects: redEffect
1642
}
1643
1644
Effect {
1645
id: redEffect
1646
property real uRed: 1.0
1647
NumberAnimation on uRed { from: 1; to: 0; duration: 5000; loops: -1 }
1648
passes: Pass {
1649
shaders: Shader {
1650
stage: Shader.Fragment
1651
shader: "effect.frag"
1652
}
1653
}
1654
}
1655
\endqml
1656
\li \badcode
1657
void MAIN()
1658
{
1659
vec4 c = texture(INPUT, INPUT_UV);
1660
c.r = uRed;
1661
FRAGCOLOR = c;
1662
}
1663
\endcode
1664
\endtable
1665
1666
This simple effect alters the red color channel value. Exposing QML properties as uniforms
1667
works the same way with effects as with custom materials. The shader starts with a line
1668
that is going to be very common when writing fragment shaders fro effects: sampling \c
1669
INPUT at the UV coordinates \c INPUT_UV. It then performs its desired calculations, and
1670
assigns the final fragment color to \c FRAGCOLOR.
1671
1672
\image quick3d-custom-first-effect-anim.gif
1673
{Animation showing color inversion post-processing effect}
1674
1675
Many properties set in the example are in plural (effects, passes, shaders). While the
1676
list \c{[ ]} syntax can be omitted when having a single element only, all these properties
1677
are lists, and can hold more than one element. Why is this?
1678
1679
\list
1680
1681
\li \l{SceneEnvironment::effects}{effects} is a list, because View3D allows chaining
1682
multiple effects together. The effects are applied in the order in which they are added to
1683
the list. This allows easily applying two or more effects together to the View3D, and is
1684
similar to what one can achieve in Qt Quick by nesting \l ShaderEffect items. The \c INPUT
1685
texture of the next effect is always a texture that contains the previous effect's
1686
output. The output of the last effect in what gets used as the final output of the View3D.
1687
1688
\li \l{Effect::passes}{passes} is a list, because unlike ShaderEffect, Effect has built-in
1689
support for multiple passes. A multi-pass effect is more powerful than chaining together
1690
multiple, independent effects in \l{SceneEnvironment::effects}{effects}: a pass can output
1691
to a temporary, intermediate texture, which can then be used as input to subsequent
1692
passes, in addition to the original input texture of the effect. This allows creating
1693
complex effects that calculate, render, and blend together multiple textures in order to
1694
get to the final fragment color. This advanced use case is not going to be covered
1695
here. Refer to the \l Effect documentation page for details.
1696
1697
\li \l{Pass::shaders}{shaders} is a list, because an effect may have both a vertex and a
1698
fragment shader associated.
1699
1700
\endlist
1701
1702
\section2 Chaining multiple effects
1703
1704
Let's look at an example where the effect from the previous example gets complemented by
1705
another effect similar to the built-in \l DistortionSpiral effect.
1706
1707
\table
1708
\header
1709
\li Change in main.qml
1710
\li effect2.frag
1711
\row \li \qml
1712
environment: SceneEnvironment {
1713
backgroundMode: SceneEnvironment.Color
1714
clearColor: "black"
1715
effects: [redEffect, distortEffect]
1716
}
1717
1718
Effect {
1719
id: redEffect
1720
property real uRed: 1.0
1721
NumberAnimation on uRed { from: 1; to: 0; duration: 5000; loops: -1 }
1722
passes: Pass {
1723
shaders: Shader {
1724
stage: Shader.Fragment
1725
shader: "effect.frag"
1726
}
1727
}
1728
}
1729
1730
Effect {
1731
id: distortEffect
1732
property real uRadius: 0.1
1733
NumberAnimation on uRadius { from: 0.1; to: 1.0; duration: 5000; loops: -1 }
1734
passes: Pass {
1735
shaders: Shader {
1736
stage: Shader.Fragment
1737
shader: "effect2.frag"
1738
}
1739
}
1740
}
1741
\endqml
1742
\li \badcode
1743
void MAIN()
1744
{
1745
vec2 center_vec = INPUT_UV - vec2(0.5, 0.5);
1746
center_vec.y *= INPUT_SIZE.y / INPUT_SIZE.x;
1747
float dist_to_center = length(center_vec) / uRadius;
1748
vec2 texcoord = INPUT_UV;
1749
if (dist_to_center <= 1.0) {
1750
float rotation_amount = (1.0 - dist_to_center) * (1.0 - dist_to_center);
1751
float r = radians(360.0) * rotation_amount / 4.0 * FRAMEBUFFER_Y_UP;
1752
float cos_r = cos(r);
1753
float sin_r = sin(r);
1754
mat2 rotation = mat2(cos_r, sin_r, -sin_r, cos_r);
1755
texcoord = vec2(0.5, 0.5) + rotation * (INPUT_UV - vec2(0.5, 0.5));
1756
}
1757
vec4 c = texture(INPUT, texcoord);
1758
FRAGCOLOR = c;
1759
}
1760
\endcode
1761
\endtable
1762
1763
\image quick3d-custom-chained-effect-anim.gif
1764
{Animation showing combined blur and color inversion effects}
1765
1766
Now the perhaps surprising question: why is this a bad example?
1767
1768
More precisely, it is not bad, but rather shows a pattern that can often be beneficial to
1769
avoid.
1770
1771
Chaining effects this way can be useful, but it is important to keep in mind the
1772
performance implications: doing two render passes (one to generate a texture with the
1773
adjusted red color channel, and then another one two calculate the distortion) is quite
1774
wasteful when one would be enough. If the fragment shader snippets were combined, the same
1775
result could have been achieved with one single effect.
1776
1777
\section1 Defining Mesh and Texture Data from C++
1778
1779
Procedurally generating mesh and texture image data both follow similar steps:
1780
1781
\list
1782
\li Subclass \l QQuick3DGeometry or \l QQuick3DTextureData
1783
\li Set the desired vertex or image data upon construction by calling the protected member functions
1784
from the base class
1785
\li If dynamic changes are needed afterwards at some point, set the new data and call update()
1786
\li Once the implementation is done, the class needs to be registered to make it visible in QML
1787
\li \l Model and \l Texture objects in QML can now use the custom vertex or image data provider by
1788
setting the \l{Model::geometry} or \l{Texture::textureData} property
1789
\endlist
1790
1791
\section2 Custom vertex data
1792
1793
Vertex data refers to the sequence of (typically \c float) values that make up a
1794
mesh. Instead of loading \c{.mesh} files, a custom geometry provider is responsible for
1795
providing the same data. The vertex data consist of \c attributes, such as position,
1796
texture (UV) coordinates, or normals. The specification of attributes describes what kind
1797
of attributes are present, the component type (for example, a 3 component float vector for
1798
vertex position consisting of x, y, z values), which offset they start at in the provided
1799
data, and what the stride (the increment that needs to be added to the offset to point to
1800
the next element for the same attribute) is.
1801
1802
This may seem familiar if one has worked with graphics APIs, such as OpenGL or Vulkan
1803
directly, because the way vertex input is specified with those APIs maps loosely to what a
1804
\c{.mesh} file or a \l QQuick3DGeometry instance defines.
1805
1806
In addition, the mesh topology (primitive type) must be specified too. For indexed
1807
drawing, the data for an index buffer must be provided as well.
1808
1809
There is one built-in custom geometry implementation: the QtQuick3D.Helpers module
1810
includes a \l GridGeometry type. This allows rendering a grid in the scene with line
1811
primitives, without having to implement a custom \l QQuick3DGeometry subclass.
1812
1813
One other common use cases is rendering points. This is fairly simple to do since the
1814
attribute specification is going to be minimal: we provide three floats (x, y, z) for each
1815
vertex, nothing else. A QQuick3DGeometry subclass could implement a geometry consisting of
1816
2000 points similarly to the following:
1817
1818
\badcode
1819
clear();
1820
const int N = 2000;
1821
const int stride = 3 * sizeof(float);
1822
QByteArray v;
1823
v.resize(N * stride);
1824
float *p = reinterpret_cast<float *>(v.data());
1825
QRandomGenerator *rg = QRandomGenerator::global();
1826
for (int i = 0; i < N; ++i) {
1827
const float x = float(rg->bounded(200.0f) - 100.0f) / 20.0f;
1828
const float y = float(rg->bounded(200.0f) - 100.0f) / 20.0f;
1829
*p++ = x;
1830
*p++ = y;
1831
*p++ = 0.0f;
1832
}
1833
setVertexData(v);
1834
setStride(stride);
1835
setPrimitiveType(QQuick3DGeometry::PrimitiveType::Points);
1836
addAttribute(QQuick3DGeometry::Attribute::PositionSemantic, 0, QQuick3DGeometry::Attribute::F32Type);
1837
\endcode
1838
1839
Combined with a material of
1840
1841
\qml
1842
DefaultMaterial {
1843
lighting: DefaultMaterial.NoLighting
1844
cullMode: DefaultMaterial.NoCulling
1845
diffuseColor: "yellow"
1846
pointSize: 4
1847
}
1848
\endqml
1849
1850
the end result is similar to this (here viewed from an altered camera angle, with the help
1851
of \l WasdController):
1852
1853
\image quick3d-custom-points.jpg
1854
{Point cloud geometry rendered as individual points}
1855
1856
\note Be aware that point sizes and line widths other than 1 may not be supported at run
1857
time, depending on the underlying graphics API. This is not something Qt has control
1858
over. Therefore, it can become necessary to implement alternative techniques instead of
1859
relying on point and line drawing.
1860
1861
\section2 Custom texture data
1862
1863
With textures, the data that needs to be provided is a lot simpler structurally: it is the
1864
raw pixel data, with a varying number of bytes per pixel, depending on the texture
1865
format. For example, an \c RGBA texture expects four bytes per pixel, whereas \c RGBA16F
1866
is four half-floats per pixel. This is similar to what a \l QImage stores
1867
internally. However, Qt Quick 3D textures can have formats the data for which cannot be
1868
represented by a QImage. For example, floating point HDR textures, or compressed
1869
textures. Therefore the data for \l QQuick3DTextureData is always provided as a raw
1870
sequence of bytes. This may seem familiar if one has worked with graphics APIs, such as
1871
OpenGL or Vulkan directly.
1872
1873
For details, refer to the \l QQuick3DGeometry and \l QQuick3DTextureData documentation pages.
1874
1875
\sa CustomMaterial, Effect, QQuick3DGeometry, QQuick3DTextureData, {Qt Quick 3D - Custom
1876
Effect Example}, {Qt Quick 3D - Custom Shaders Example}, {Qt Quick 3D - Custom Materials
1877
Example}, {Qt Quick 3D - Custom Geometry Example}, {Qt Quick 3D - Procedural Texture
1878
Example}
1879
1880
*/
qtquick3d
src
quick3d
doc
src
qtquick3d-custom.qdoc
Generated on
for Qt by
1.18.0