Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquick3dcustommaterial.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
7#include <QtQuick3DRuntimeRender/private/qssgrenderbuffer_p.h>
8#include <QtQuick3DRuntimeRender/private/qssgrendercustommaterial_p.h>
9#include <ssg/qssgrendercontextcore.h>
10#include <QtQuick3DRuntimeRender/private/qssgshadermaterialadapter_p.h>
11#include <QtQuick/QQuickWindow>
12
13#include <QtQuick3D/QQuick3DTextureProviderExtension>
14
18
20
21/*!
22 \qmltype CustomMaterial
23 \inherits Material
24 \inqmlmodule QtQuick3D
25 \brief Base component for creating custom materials used to shade models.
26
27 The custom material allows using custom shader code for a material, enabling
28 programmability on graphics shader level. A vertex, fragment, or both
29 shaders can be provided. The \l vertexShader and \l fragmentShader
30 properties are URLs, referencing files containing shader snippets, and work
31 very similarly to ShaderEffect or \l{Image::source}{Image.source}. Only the
32 \c file and \c qrc schemes are supported with custom materials. It is also
33 possible to omit the \c file scheme, allowing to specify a relative path in
34 a convenient way. Such a path is resolved relative to the component's (the
35 \c{.qml} file's) location.
36
37 For a getting started guide to custom materials, see the page \l{Programmable
38 Materials, Effects, Geometry, and Texture data}.
39
40 \section1 Introduction
41
42 Consider the following versions of the same scene. On the left, the cylinder
43 is using a built-in, non-programmable material. Such materials are
44 configurable through a wide range of properties, but there is no further
45 control given over the shaders that are generated under the hood. On the
46 right, the same cylinder is now associated with a CustomMaterial referencing
47 application-provided vertex and fragment shader snippets. This allows
48 inserting custom, application-specific logic into the vertex shader to
49 transform the geometry, and to determine certain color properties in a
50 custom manner in the fragment shader. As this is a
51 \l{shadingMode}{shaded} custom material, the cylinder still
52 participates in the scene lighting normally.
53
54 \table 70%
55 \row
56 \li \qml
57 View3D {
58 anchors.fill: parent
59 PerspectiveCamera {
60 id: camera
61 position: Qt.vector3d(0, 0, 600)
62 }
63 camera: camera
64 DirectionalLight {
65 position: Qt.vector3d(-500, 500, -100)
66 color: Qt.rgba(0.2, 0.2, 0.2, 1.0)
67 ambientColor: Qt.rgba(0.1, 0.1, 0.1, 1.0)
68 }
69 Model {
70 source: "#Cylinder"
71 eulerRotation: Qt.vector3d(30, 30, 0)
72 scale: Qt.vector3d(1.5, 1.5, 1.5)
73 materials: [
74 DefaultMaterial {
75 diffuseColor: Qt.rgba(0, 1, 0, 1)
76 }
77 ]
78 }
79 }
80 \endqml
81 \li \qml
82 View3D {
83 anchors.fill: parent
84 PerspectiveCamera {
85 id: camera
86 position: Qt.vector3d(0, 0, 600)
87 }
88 camera: camera
89 DirectionalLight {
90 position: Qt.vector3d(-500, 500, -100)
91 color: Qt.rgba(0.2, 0.2, 0.2, 1.0)
92 ambientColor: Qt.rgba(0.1, 0.1, 0.1, 1.0)
93 }
94 Model {
95 source: "#Cylinder"
96 eulerRotation: Qt.vector3d(30, 30, 0)
97 scale: Qt.vector3d(1.5, 1.5, 1.5)
98 materials: [
99 CustomMaterial {
100 vertexShader: "material.vert"
101 fragmentShader: "material.frag"
102 property real uTime
103 property real uAmplitude: 50
104 NumberAnimation on uTime { from: 0; to: 100; duration: 10000; loops: -1 }
105 }
106 ]
107 }
108 }
109 \endqml
110 \endtable
111
112 Let's assume that the shader snippets in \c{material.vert} and \c{material.frag} are
113 the following:
114
115 \table 70%
116 \row
117 \li \badcode
118 void MAIN()
119 {
120 VERTEX.x += sin(uTime + VERTEX.y) * uAmplitude;
121 }
122 \endcode
123 \li \badcode
124 void MAIN()
125 {
126 BASE_COLOR = vec4(0.0, 1.0, 0.0, 1.0);
127 }
128 \endcode
129 \endtable
130
131 Notice how \c uTime and \c uAmplitude are properties of the CustomMaterial
132 element. They can change values and get animated normally, the values will
133 be exposed to the shaders automatically without any further action from the
134 developer.
135
136 The result is a cylinder that animates its vertices:
137
138 \image custommaterial_cylinder.png
139 {Bent cylinder with custom vertex shader}
140
141 \section1 Two flavors of custom materials
142
143 There are two main types of custom materials. This is specified by the \l
144 shadingMode property. In \l{CustomMaterial::shadingMode}{unshaded} custom
145 materials the fragment shader outputs a single \c vec4 color, ignoring
146 lights, light probes, shadowing in the scene. In
147 \l{CustomMaterial::shadingMode}{shaded} materials the shader is expected to
148 implement certain functions and work with built-in variables to take
149 lighting and shadow contribution into account.
150
151 The default choice is typically a shaded material, this is reflected in the
152 default value of the \l shadingMode property. This fits materials that needs
153 to transform vertices or other incoming data from the geometry, or determine
154 values like \c BASE_COLOR or \c EMISSIVE_COLOR in a custom manner, perhaps
155 by sampling \c SCREEN_TEXTURE or \c DEPTH_TEXTURE, while still reciving
156 light and shadow contributions from the scene. Additionally, such materials
157 can also override and reimplement the equations used to calculate the
158 contributions from directional, point, and other lights. The
159 application-provided shader snippets are heavily amended by the Qt Quick 3D
160 engine under the hood, in order to provide the features, such as lighting,
161 the standard materials have.
162
163 Unshaded materials are useful when the object's appearance is determined
164 completely by the custom shader code. The shaders for such materials
165 receive minimal additions by the engine, and therefore it is completely up
166 to the shader to determine the final fragment color. This gives more
167 freedom, but also limits possiblities to integrate with other elements of
168 the scene, such as lights.
169
170 \note Shader code is always provided using Vulkan-style GLSL, regardless of
171 the graphics API used by Qt at run time.
172
173 \note The vertex and fragment shader code provided by the material are not
174 full, complete GLSL shaders on their own. Rather, they provide a set of
175 functions, which are then amended with further shader code by the engine.
176
177 \section1 Exposing data to the shaders
178
179 The dynamic properties of the CustomMaterial can be changed and animated
180 using QML and Qt Quick facilities, and the values are exposed to the
181 shaders automatically. This in practice is very similar ShaderEffect. The
182 following list shows how properties are mapped:
183
184 \list
185 \li bool, int, real -> bool, int, float
186 \li QColor, \l{QtQml::Qt::rgba()}{color} -> vec4, and the color gets
187 converted to linear, assuming sRGB space for the color value specified in
188 QML. The built-in Qt colors, such as \c{"green"} are in sRGB color space as
189 well, and the same conversion is performed for all color properties of
190 DefaultMaterial and PrincipledMaterial, so this behavior of CustomMaterial
191 matches those. Unlike Qt Quick, for Qt Quick 3D linearizing is essential as
192 there will typically be tonemapping performed on the 3D scene.
193 \li QRect, QRectF, \l{QtQml::Qt::rect()}{rect} -> vec4
194 \li QPoint, QPointF, \l{QtQml::Qt::point()}{point}, QSize, QSizeF, \l{QtQml::Qt::size()}{size} -> vec2
195 \li QVector2D, \l{QtQml::Qt::vector2d()}{vector2d} -> vec2
196 \li QVector3D, \l{QtQml::Qt::vector3d()}{vector3d} -> vec3
197 \li QVector4D, \l{QtQml::Qt::vector4d()}{vector4d} -> vec4
198 \li QMatrix4x4, \l{QtQml::Qt::matrix4x4()}{matrix4x4} -> mat4
199 \li QQuaternion, \l{QtQml::Qt::quaternion()}{quaternion} -> vec4, scalar value is \c w
200
201 \li \l Texture -> a sampler whose type follows the texture: samplerCube
202 for a \l CubeMapTexture, sampler3D when the texture data has a depth,
203 and sampler2D otherwise. For a texture with a
204 \l{Texture::textureProvider}{textureProvider}, the provider's
205 \l{TextureProviderExtension::samplerHint}{samplerHint} decides the type
206 instead, which also allows sampler2DArray, samplerCubeArray, and
207 samplerBuffer. Properties of the \l Texture type are supported since
208 Qt 6.13; earlier versions require a \l TextureInput.
209
210 A null property has no texture to take the sampler type from, so the
211 declared type of the property is used: a property declared as
212 \l CubeMapTexture is a samplerCube while it is null, and any other is a
213 sampler2D. Declare a property that will hold a cube map as
214 \l CubeMapTexture, so that the shader code sampling it stays valid before
215 the texture is assigned. A null property exposes a dummy texture of the
216 declared type to the shader, meaning the shaders are still functional
217 but will sample a texture with opaque black image content.
218
219 When it comes to the \l Texture properties, the source, tiling, and
220 filtering related ones are the only ones that are taken into account
221 implicitly with custom materials, as the rest (such as, UV
222 transformations) is up to the custom shaders to implement as they see
223 fit.
224
225 \li TextureInput -> the same as for the \l Texture it references. This is
226 deprecated, and supported for compatibility. Setting its
227 \l{TextureInput::enabled}{enabled} property to false has the same effect
228 as a null texture.
229
230 \li \l ShaderImage -> a GLSL image (such as \c image2D or
231 \c uimage3D), declared in the shader with the \c SHADER_IMAGE macro.
232 Unlike \l Texture, a \l ShaderImage is meant to be read and/or
233 written directly with \c imageLoad()/imageStore() rather than sampled.
234
235 \li \l ShaderStorageBuffer -> a shader storage buffer, declared in
236 the shader with the \c STORAGE_BUFFER macro, exposing the referenced
237 \l ShaderStorageBuffer's content as a GLSL buffer block.
238
239 \endlist
240
241 \section1 Reading and writing images and buffers
242
243 In addition to sampling textures via \l Texture properties, a
244 CustomMaterial's shaders can read and/or write a \l ShaderImage or a
245 \l ShaderStorageBuffer directly, using the same
246 \c{SHADER_IMAGE}/\c{STORAGE_BUFFER} mechanism available to a
247 \l ComputePass:
248
249 \qml
250 CustomMaterial {
251 property ShaderImage myImage: sharedImage
252 property ShaderStorageBuffer myBuffer: sharedBuffer
253 fragmentShader: "material.frag"
254 }
255 \endqml
256
257 \badcode
258 SHADER_IMAGE(rgba8, myImage, image2D, readonly);
259 STORAGE_BUFFER(myBuffer, readonly) {
260 vec4 values[];
261 }
262
263 void MAIN()
264 {
265 BASE_COLOR = imageLoad(myImage, ivec2(0, 0)) * values[0];
266 }
267 \endcode
268
269 A writable \c SHADER_IMAGE (one declared without the \c readonly
270 memory qualifier) is bound the same way as for a
271 \l ComputePass, so a material's fragment shader can also write to a
272 \l ShaderImage, for example to accumulate per-fragment data for a later
273 pass to consume. The same applies to a writable \c STORAGE_BUFFER.
274 Unlike a ComputePass, which runs a fixed number of invocations known
275 ahead of time, how many times a material's shaders run per frame
276 depends on how much geometry is actually rasterized.
277
278 \note Writing to a \c SHADER_IMAGE or a \c STORAGE_BUFFER from a
279 material's shaders requires the graphics API to support storage access
280 in the graphics pipeline stages, which is not universally available.
281 Direct3D 11 only allows it in fragment shaders, and OpenGL ES 3.1
282 implementations are not required to support it in vertex or fragment
283 shaders at all. For portable code, do the writing in a \l ComputePass
284 and declare the resources \c readonly in the material.
285
286 \note When a uniform referenced in the shader code does not have a
287 corresponding property, it will cause a shader compilation error when
288 processing the material at run time. There are some exceptions to this,
289 such as, sampler uniforms, that get a dummy texture bound when no
290 corresponding QML property is present, but as a general rule, all uniforms
291 and samplers must have a corresponding property declared in the
292 CustomMaterial object.
293
294 \section1 Unshaded custom materials
295
296 The following is an example of an \l{CustomMaterial::shadingMode}{unshaded}
297 custom material.
298
299 \qml
300 CustomMaterial {
301 // These properties are automatically exposed to the shaders
302 property real time: 0.0
303 property real amplitude: 5.0
304 property real alpha: 1.0
305 property Texture tex: Texture { source: "image.png" }
306
307 shadingMode: CustomMaterial.Unshaded
308 sourceBlend: alpha < 1.0 ? CustomMaterial.SrcAlpha : CustomMaterial.NoBlend
309 destinationBlend: alpha < 1.0 ? CustomMaterial.OneMinusSrcAlpha : CustomMaterial.NoBlend
310 cullMode: CustomMaterial.BackFaceCulling
311
312 vertexShader: "customshader.vert"
313 fragmentShader: "customshader.frag"
314 }
315 \endqml
316
317 With the above example, the \l{CustomMaterial::shadingMode}{unshaded} vertex
318 and fragment shaders snippets could look like the following. Note how the
319 shaders do not, and must not, declare uniforms or vertex inputs as that is
320 taken care of by Qt when assembling the final shader code.
321
322 \badcode
323 VARYING vec3 pos;
324 VARYING vec2 texcoord;
325
326 void MAIN()
327 {
328 pos = VERTEX;
329 pos.x += sin(time * 4.0 + pos.y) * amplitude;
330 texcoord = UV0;
331 POSITION = MODELVIEWPROJECTION_MATRIX * vec4(pos, 1.0);
332 }
333 \endcode
334
335 \badcode
336 VARYING vec3 pos;
337 VARYING vec2 texcoord;
338
339 void MAIN()
340 {
341 vec4 c = texture(tex, texcoord);
342 FRAGCOLOR = vec4(pos.x * 0.02, pos.y * 0.02, pos.z * 0.02, alpha) * c;
343 }
344 \endcode
345
346 The following special, uppercase keywords are available:
347
348 \list
349
350 \li MAIN -> the name of the entry point in the vertex or fragment shader
351 snippet must always be \c MAIN. Providing this function is mandatory in
352 shader snippets for unshaded custom materials.
353
354 \li VARYING -> declares an output from the vertex shader or an input to the
355 fragment shader
356
357 \li POSITION -> vec4, the output from the vertex shader
358
359 \li FRAGCOLOR -> vec4, the output from the fragment shader. Available only
360 for unshaded custom materials.
361
362 \li VERTEX -> vec3, the vertex position in the vertex shader.
363
364 \li NORMAL -> vec3, the vertex normal in the vertex shader. When the mesh
365 for the associated model does not provide normals, the value is vec3(0.0).
366
367 \li UV0 -> vec2, the first set of texture coordinates in the vertex shader.
368 When the mesh for the associated model does not provide texture
369 coordinates, the value is vec2(0.0).
370
371 \li UV1 -> vec2, the second set of texture coordinates in the vertex
372 shader. When the mesh for the associated model does not provide a second
373 set of texture coordinates, the value is vec2(0.0).
374
375 \li COLOR -> vec4, the vertex color in the vertex shader. When the mesh for
376 the associated model does not provide per-vertex colors, the value is
377 vec4(1.0).
378
379 \li TANGENT -> vec3, tangent in the vertex shader. When the mesh for the
380 associated model does not provide tangent data, the value is vec3(0.0).
381
382 \li BINORMAL -> vec3, binormal in the vertex shader. When the mesh for the
383 associated model does not provide binormal data, the value is vec3(0.0).
384
385 \li JOINTS -> ivec4, joint indexes in the vertex shader. When the mesh for
386 the associated model does not provide joint indexes data, the value is
387 ivec4(0).
388
389 \li WEIGHTS -> vec4, joint weights in the vertex shader. When the mesh for
390 the associated model does not provide joint weights data, the value is
391 vec4(0.0).
392
393 \li MORPH_POSITION(\e{n}) -> vec3, the \e{n+1}th morph target position in the vertex
394 shader. The associated model should provide proper data.
395
396 \li MORPH_NORMAL(\e{n}) -> vec3, the \e{n+1}th morph target normal in the vertex
397 shader. The associated model should provide proper data.
398
399 \li MORPH_TANGENT(\e{n}) -> vec3, the \e{n+1}th morph target tangent in the vertex
400 shader. The associated model should provide proper data.
401
402 \li MORPH_BINORMAL(\e{n}) -> vec3, the \e{n+1}th morph target binormal in the vertex
403 shader. The associated model should provide proper data.
404
405 \li MODELVIEWPROJECTION_MATRIX -> mat4, the model-view-projection matrix.
406 Projection matrices always follow OpenGL conventions, with a baked-in
407 transformation for the Y axis direction and clip depth, depending on the
408 graphics API used at run time.
409
410 \li VIEWPROJECTION_MATRIX -> mat4, the view-projection matrix
411
412 \li PROJECTION_MATRIX -> mat4, the projection matrix
413
414 \li INVERSE_PROJECTION_MATRIX -> mat4, the inverse projection matrix
415
416 \li VIEW_MATRIX -> mat4, the view (camera) matrix
417
418 \li MODEL_MATRIX -> mat4, the model (world) matrix
419
420 \li NORMAL_MATRIX -> mat3, the normal matrix (the transpose of the inverse
421 of the top-left 3x3 part of the model matrix)
422
423 \li BONE_TRANSFORMS -> mat4[], the array of the model's bone matrixes
424
425 \li BONE_NORMAL_TRANSFORMS -> mat3[], the array of the model's bone normal
426 matrixes (the transpose of the inverse of the top-left 3x3 part of the each
427 bone matrixes)
428
429 \li MORPH_WEIGHTS -> float[], the array of the morph weights. The associated model
430 should provide proper data. For safety, \b {QT_MORPH_MAX_COUNT} is defined to the
431 size of this array.
432
433 \li CAMERA_POSITION -> vec3, the camera position in world space
434
435 \li CAMERA_DIRECTION -> vec3, the camera direction vector
436
437 \li CAMERA_PROPERTIES -> vec2, the near and far clip values for the camera
438
439 \li POINT_SIZE -> float, writable in the vertex shader only. When rendering
440 geometry with a topology of points, the custom vertex shader must set this
441 to either 1.0 or another value, both in shaded and unshaded custom
442 materials. See \l{PrincipledMaterial::pointSize} for further notes on
443 support for sizes other than 1.
444
445 \endlist
446
447 \section1 Shaded custom materials
448
449 A \l{CustomMaterial::shadingMode}{shaded} material \c augments the shader code
450 that would be generated by a PrincipledMaterial. Unlike unshaded materials,
451 that provide almost all logic for the vertex and fragment shader main
452 functions on their own, preventing adding generated code for lighting,
453 shadowing, global illumination, etc., shaded materials let shader
454 generation happen normally, as if the CustomMaterial was a
455 PrincipledMaterial. The vertex and fragment shader snippets are expected to
456 provide optional functions that are then invoked at certain points, giving
457 them the possibility to customize the colors and other values that are then
458 used for calculating lighting and the final fragment color.
459
460 Rather than implementing just a \c MAIN function, the fragment shader for a
461 shaded custom material can implement multiple functions. All functions,
462 including \c MAIN, are optional to implement in shaded custom materials. An
463 empty shader snippet, or, even, not specifying the
464 \l{CustomMaterial::vertexShader}{vertexShader} or
465 \l{CustomMaterial::fragmentShader}{fragmentShader} properties at all can be
466 perfectly valid too.
467
468 \section2 Vertex shader snippets in a shaded custom material
469
470 The following functions can be implemented in a vertex shader snippet:
471
472 \list
473
474 \li \c{void MAIN()} When present, this function is called in order to set
475 the value of \c POSITION, the vec4 output from the vertex shader, and,
476 optionally, to modify the values of \c VERTEX, \c COLOR, \c NORMAL, \c UV0,
477 \c UV1, \c TANGENT, \c BINORMAL, \c JOINTS, and \c WEIGHTS. Unlike in
478 unshaded materials, writing to these makes sense because the modified values
479 are then taken into account in the rest of the generated shader code
480 (whereas for unshaded materials there is no additional shader code
481 generated). For example, if the custom vertex shader displaces the vertices
482 or the normals, it will want to store the modified values to \c VERTEX or
483 \c NORMAL, to achieve correct lighting calculations afterwards.
484 Additionally, the function can write to variables defined with \c VARYING in
485 order to pass interpolated data to the fragment shader. When this function
486 or a redefinition of \c POSITION is not present, \c POSITION is calculated
487 based on \c VERTEX and \c MODELVIEWPROJECTION_MATRIX, just like a
488 PrincipledMaterial would do.
489
490 Example, with relying both on QML properties exposed as uniforms, and also
491 passing data to the fragment shader:
492 \badcode
493 VARYING vec3 vNormal;
494 VARYING vec3 vViewVec;
495
496 void MAIN()
497 {
498 VERTEX.x += sin(uTime * 4.0 + VERTEX.y) * uAmplitude;
499 vNormal = normalize(NORMAL_MATRIX * NORMAL);
500 vViewVec = CAMERA_POSITION - (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
501 POSITION = MODELVIEWPROJECTION_MATRIX * vec4(VERTEX, 1.0);
502 }
503 \endcode
504
505 \note In the above example, assigning a value to \c POSITION is optional as
506 the usage in this case is identical to the default behavior.
507
508 \endlist
509
510 \note To pass data without interpolation from the vertex to the fragment
511 stage, add the \c flat keyword before the type in the \c VARYING
512 declarations.
513
514 \section2 Fragment shader snippets in a shaded custom material
515
516 The following functions can be implemented in a fragment shader snippet:
517
518 \list
519
520 \li \c{void MAIN()} When present, this function is called to set the values
521 of the special writable variables \c BASE_COLOR, \c METALNESS, \c ROUGHNESS, \c
522 SPECULAR_AMOUNT, NORMAL, CLEARCOAT_FRESNEL_POWER, CLEARCOAT_FRESNEL_SCALE,
523 CLEARCOAT_FRESNEL_BIAS, CLEARCOAT_AMOUNT, CLEARCOAT_ROUGHNESS, CLEARCOAT_NORMAL,
524 SHEEN_COLOR, SHEEN_ROUGHNESS, ANISOTROPY_STRENGTH, ANISOTROPY_ROTATION,
525 IRIDESCENCE_FACTOR, IRIDESCENCE_IOR, IRIDESCENCE_THICKNESS, DISPERSION,
526 FRESNEL_BIAS, FRESNEL_SCALE, FRESNEL_POWER, IOR, \c TRANSMISSION_FACTOR,
527 THICKNESS_FACTOR, ATTENUATION_COLOR, ATTENUATION_DISTANCE and \c OCCLUSION_AMOUNT.
528
529 One common use case is to set the value of \c BASE_COLOR based on sampling
530 a texture, be it a base color map, \c SCREEN_TEXTURE, or some other kind of
531 source. This can be relevant and convenient especially when no custom light
532 processor functions are implemented. Setting \c{BASE_COLOR.a} to something
533 other than the default 1.0 allows affecting the final alpha value of the
534 fragment. (note that this will often require also enabling alpha blending
535 in \l sourceBlend and \l destinationBlend)
536
537 Another scenario is when there is no custom \c SPECULAR_LIGHT function
538 provided, or when there is a light probe set in the SceneEnvironment. The
539 metalness, roughness, and other values that affect the specular
540 contribution calculation can be set in \c MAIN to their desired custom
541 values.
542
543 The function can write to the following special variables. The values
544 written to these will typically be either hardcoded or be calculated based
545 on QML properties mapped to uniforms. The semantics are identical to
546 PrincipledMaterial.
547
548 \list
549
550 \li vec4 \c BASE_COLOR - The base color and material alpha value.
551 Corresponds to the \l{PrincipledMaterial::baseColor}{built-in materials'
552 color property}. When light processor functions are not implemented, it can
553 be convenient to set a custom base color in \c MAIN because that is then
554 taken into account in the default lighting calculations. The default value
555 is \c{vec4(1.0)}, meaning white with an alpha of 1.0. The alpha value
556 effects the final alpha of the fragment. The final alpha value is the
557 object (model) opacity multiplied by the base color alpha. When specifying
558 the value directly in shader code, not relying on uniform values exposed
559 from \b color properties in QML, be aware that it is up to the shader to
560 perform the sRGB to linear conversion, if needed. For example, assuming
561 a \c{vec3 color} and \c{float alpha} this can be achieved like the following:
562 \badcode
563 float C1 = 0.305306011;
564 vec3 C2 = vec3(0.682171111, 0.682171111, 0.682171111);
565 vec3 C3 = vec3(0.012522878, 0.012522878, 0.012522878);
566 BASE_COLOR = vec4(rgb * (rgb * (rgb * C1 + C2) + C3), alpha);
567 \endcode
568
569 \li vec3 \c EMISSIVE_COLOR - The color of self-illumination. Corresponds to
570 the built-in materials' emissive color which is combined by
571 \l {PrincipledMaterial::emissiveFactor}{built-in materials's emissiveFactor property}
572 and \l {PrincipledMaterial::emissiveMap}{built-in materials's emissiveMap property}.
573 The default value is \c{vec3(0.0)}. When specifying the value
574 directly in shader code, not relying on uniform values exposed from \b color
575 properties in QML, be aware that it is up to the shader to perform the sRGB
576 to linear conversion, if needed.
577
578 \li float \c IOR Specifies the index of refraction of the material. A typical value,
579 and also the default, is \c{1.5} as that is what a PrincipledMaterial would use.
580
581 \li float \c TRANSMISSION_FACTOR Specifies the amount of the translucency. A typical value,
582 would be \c{1.0} and also the default, is \c{0.0} as that is what a PrincipledMaterial would use.
583
584 \li float \c THICKNESS_FACTOR Specifies the amount of the translucent material thickness. A typical value,
585 would be \c{10.0} and also the default, is \c{0.0} as that is what a PrincipledMaterial would use.
586
587 \li vec3 \c ATTENUATION_COLOR Specifies the color shift of the translucent material by distance. A typical value,
588 would be \c{vec3(1.0, 0.0, 0.0)} and also the default, is \c{vec3(1.0)} as that is what a PrincipledMaterial would use.
589
590 \li float \c ATTENUATION_DISTANCE Specifies the distance attenuation of color shift of the translucent material. A typical value,
591 would be \c{100.0} and also the default, is \c{0.0} as that is what a PrincipledMaterial would use.
592
593 \li float \c METALNESS Metalness amount in range 0.0 - 1.0. The default
594 value is 0. Must be set to a non-zero value to have effect.
595
596 \li float \c ROUGHNESS Roughness value in range 0.0 - 1.0. The default value is 0.
597
598 \li float \c CLEARCOAT_FRESNEL_POWER Specifies the fresnel power of the clearcoat layer. A typical value,
599 and also the default, is \c{5.0} as that is what a PrincipledMaterial would use.
600
601 \li float \c CLEARCOAT_FRESNEL_SCALE Specifies the fresnel scale of the clearcoat layer. A typical value,
602 and also the default, is \c{1.0} as that is what a PrincipledMaterial would use.
603
604 \li float \c CLEARCOAT_FRESNEL_BIAS Specifies the fresnel bias of the clearcoat layer. A typical value,
605 and also the default, is \c{0.0} as that is what a PrincipledMaterial would use.
606
607 \li float \c CLEARCOAT_AMOUNT Specifies the amount of the clearcoat layer on top of the material. A typical value,
608 would be \c{1.0} and also the default, is \c{0.0} as that is what a PrincipledMaterial would use.
609
610 \li float \c CLEARCOAT_ROUGHNESS Specifies the roughness of the clearcoat layer. A typical value,
611 would be \c{1.0} for fully blurred clearcoat layer and also the default, is \c{0.0} as that is
612 what a PrincipledMaterial would use.
613
614 \li vec3 \c CLEARCOAT_NORMAL - The clearcoat layer normal that comes from the vertex shader in world
615 space. While this property has the same initial value as \c VAR_WORLD_NORMAL,
616 only changing the value of \c CLEARCOAT_NORMAL will have an effect on clearcoat layer normal.
617
618 \li vec3 \c SHEEN_COLOR Specifies the color of the sheen layer, which also acts as its
619 strength: the default \c{vec3(0.0)} leaves the sheen layer disabled, as that is what a
620 PrincipledMaterial with the default sheenColor would do.
621 \note Available since Qt 6.13.
622
623 \li float \c SHEEN_ROUGHNESS Specifies the roughness of the sheen layer, where higher
624 values spread the highlight further from the silhouette. A typical value, and also the
625 default, is \c{0.0} as that is what a PrincipledMaterial would use.
626 \note Available since Qt 6.13.
627
628 \li float \c ANISOTROPY_STRENGTH Specifies how strongly the specular highlight is
629 stretched along the anisotropy direction. A typical value, and also the default, is
630 \c{0.0} as that is what a PrincipledMaterial would use, which leaves the highlight
631 round.
632 \note Available since Qt 6.13.
633
634 \li float \c ANISOTROPY_ROTATION Specifies the rotation of the anisotropy direction
635 within the tangent plane, in radians. Note that unlike the PrincipledMaterial property
636 of the same name this is in radians, since shader code works in radians throughout. The
637 default is \c{0.0}.
638 \note Available since Qt 6.13.
639
640 \li float \c IRIDESCENCE_FACTOR Specifies the strength of the thin film that produces
641 iridescence. A typical value, and also the default, is \c{0.0} as that is what a
642 PrincipledMaterial would use, which disables the effect.
643 \note Available since Qt 6.13.
644
645 \li float \c IRIDESCENCE_IOR Specifies the index of refraction of the thin film, which
646 together with its thickness decides the colors produced. The default is \c{1.3}, roughly
647 that of a soap film.
648 \note Available since Qt 6.13.
649
650 \li float \c IRIDESCENCE_THICKNESS Specifies the thickness of the thin film in
651 nanometers. Note that this is the final thickness rather than the minimum and maximum
652 pair a PrincipledMaterial interpolates between, since a custom shader can compute it
653 directly. The default is \c{400.0}.
654 \note Available since Qt 6.13.
655
656 \li float \c DISPERSION Specifies how much the index of refraction varies across
657 wavelengths, splitting refracted light into color fringes. Only has an effect together
658 with \c TRANSMISSION_FACTOR. A typical value, and also the default, is \c{0.0} as that
659 is what a PrincipledMaterial would use.
660 \note Available since Qt 6.13.
661
662 \li float \c FRESNEL_POWER Specifies the fresnel power. A typical value,
663 and also the default, is \c{5.0} as that is what a PrincipledMaterial would use.
664
665 \li float \c FRESNEL_SCALE Specifies the fresnel scale. A typical value,
666 and also the default, is \c{1.0} as that is what a PrincipledMaterial would use.
667
668 \li float \c FRESNEL_BIAS Specifies the fresnel bias. A typical value,
669 and also the default, is \c{0.0} as that is what a PrincipledMaterial would use.
670
671 \li float \c SPECULAR_AMOUNT Specular amount in range 0.0 - 1.0. The
672 default value is \c{0.5}, matching \l{PrincipledMaterial::specularAmount}. Must
673 be set to a non-zero value to have effect.
674
675 \li float \c OCCLUSION_AMOUNT Specifies the AO factor. A typical value,
676 and also the default, is \c{1.0} as that is what a PrincipledMaterial would use.
677
678 \li vec3 \c NORMAL - The normal that comes from the vertex shader in world
679 space. While this property has the same initial value as \c VAR_WORLD_NORMAL,
680 only changing the value of \c NORMAL will have an effect on lighting.
681
682 \li vec3 \c TANGENT - The tanget that comes from the vertex shader in world
683 space. This value is potentially adjusted for double-sidedness.
684
685 \li vec3 \c BINORMAL - The binormal that comes from the vertex shader in
686 world space. This value is potentially adjusted for double-sidedness.
687
688 \li vec2 \c UV0 - The first set of texture coordinates from the vertex shader.
689 This property is readonly in the fragment shader.
690
691 \li vec2 \c UV1 - The second set of texture coordinates from the vertex shader.
692 This property is readonly in the fragment shader.
693
694 \endlist
695
696 \note Unlike with unshaded materials, the fragment \c MAIN for a shaded
697 material has no direct control over \c FRAGCOLOR. Rather, it is the \c
698 DIFFUSE and \c SPECULAR values written in the light processor functions
699 that decide what the final fragment color is. When a light processor
700 function is not implemented, the relevant default shading calculations are
701 performed as with a PrincipledMaterial, taking \c BASE_COLOR and other
702 values from the list above into account.
703
704 An example of a simple, metallic custom material shader could be the following:
705 \badcode
706 void MAIN()
707 {
708 METALNESS = 1.0;
709 ROUGHNESS = 0.5;
710 FRESNEL_POWER = 5.0;
711 }
712 \endcode
713
714 Another example, where the base color and alpha are set by sampling a texture:
715 \badcode
716 VARYING vec2 texcoord;
717 void MAIN()
718 {
719 BASE_COLOR = texture(uColorMap, texcoord);
720 }
721 \endcode
722
723 \li \c{void AMBIENT_LIGHT()} When present, this function is called once for
724 each fragment. The task of the function is to add the total ambient
725 contribution to a writable special variable \c DIFFUSE. It can of course
726 choose to calculate a different value, or not touch \c DIFFUSE at all (to
727 ignore ambient lighting completely). When this function is not present at
728 all, the ambient contribution is calculated normally, like a
729 PrincipledMaterial would do.
730
731 The function can write to the following special variables:
732
733 \list
734
735 \li vec3 \c DIFFUSE Accumulates the diffuse light contributions, per
736 fragment. The light processor functions will typically add (\c{+=}) to it,
737 since overwriting the value would lose the contribution from other lights.
738
739 \endlist
740
741 The function can read the following special variables, in addition to the
742 matrix (such as, \c MODEL_MATRIX) and vector (such as, \c CAMERA_POSITION)
743 uniforms from the table above:
744
745 \list
746 \li vec3 \c TOTAL_AMBIENT_COLOR The total ambient contribution in the scene.
747 \endlist
748
749 Example:
750 \badcode
751 void AMBIENT_LIGHT()
752 {
753 DIFFUSE += TOTAL_AMBIENT_COLOR;
754 }
755 \endcode
756
757 \li \c{void DIRECTIONAL_LIGHT()} When present, this function is called for
758 each active directional light in the scene for each fragment. The task of
759 the function is to add the diffuse contribution to a writable special
760 variable \c DIFFUSE. The function can also choose to do nothing, in which
761 case diffuse contributions from directional lights are ignored. When the
762 function is not present at all, the diffuse contributions from directional
763 lights are accumulated normally, like a PrincipledMaterial would do.
764
765 The function can write to the following special variables:
766
767 \list
768
769 \li vec3 \c DIFFUSE Accumulates the diffuse light contributions, per
770 fragment. The light processor functions will typically add (\c{+=}) to it,
771 since overwriting the value would lose the contribution from other lights.
772
773 \endlist
774
775 The function can read the following special variables, in addition to the
776 matrix (such as, \c MODEL_MATRIX) and vector (such as, \c CAMERA_POSITION)
777 uniforms from the table above:
778
779 \list
780
781 \li vec3 \c LIGHT_COLOR Diffuse light color.
782 \li float \c SHADOW_CONTRIB Shadow contribution, or 1.0 if not shadowed at all or not reciving shadows.
783 \li vec3 \c TO_LIGHT_DIR Vector pointing towards the light source.
784 \li vec3 \c NORMAL The normal vector in world space.
785 \li vec4 \c BASE_COLOR The base color and material alpha value.
786 \li float \c METALNESS The Metalness amount.
787 \li float \c ROUGHNESS The Roughness amount.
788
789 \endlist
790
791 Example:
792 \badcode
793 void DIRECTIONAL_LIGHT()
794 {
795 DIFFUSE += LIGHT_COLOR * SHADOW_CONTRIB * vec3(max(0.0, dot(normalize(VAR_WORLD_NORMAL), TO_LIGHT_DIR)));
796 }
797 \endcode
798
799 \li \c{void POINT_LIGHT()} When present, this function is called for
800 each active point light in the scene for each fragment. The task of
801 the function is to add the diffuse contribution to a writable special
802 variable \c DIFFUSE. The function can also choose to do nothing, in which
803 case diffuse contributions from point lights are ignored. When the
804 function is not present at all, the diffuse contributions from point
805 lights are accumulated normally, like a PrincipledMaterial would do.
806
807 The function can write to the following special variables:
808
809 \list
810 \li vec3 \c DIFFUSE Accumulates the diffuse light contributions, per fragment.
811 \endlist
812
813 The function can read the following special variables, in addition to the
814 matrix (such as, \c MODEL_MATRIX) and vector (such as, \c CAMERA_POSITION)
815 uniforms from the table above:
816
817 \list
818 \li vec3 \c LIGHT_COLOR Diffuse light color.
819 \li float \c LIGHT_ATTENUATION Light attenuation.
820 \li float \c SHADOW_CONTRIB Shadow contribution, or 1.0 if not shadowed at all or not reciving shadows.
821 \li vec3 \c TO_LIGHT_DIR Vector pointing towards the light source.
822 \li vec3 \c NORMAL The normal vector in world space.
823 \li vec4 \c BASE_COLOR The base color and material alpha value.
824 \li float \c METALNESS The Metalness amount.
825 \li float \c ROUGHNESS The Roughness amount.
826 \endlist
827
828 Example:
829 \badcode
830 void POINT_LIGHT()
831 {
832 DIFFUSE += LIGHT_COLOR * LIGHT_ATTENUATION * SHADOW_CONTRIB * vec3(max(0.0, dot(normalize(VAR_WORLD_NORMAL), TO_LIGHT_DIR)));
833 }
834 \endcode
835
836 \li \c{void SPOT_LIGHT()} When present, this function is called for
837 each active spot light in the scene for each fragment. The task of
838 the function is to add the diffuse contribution to a writable special
839 variable \c DIFFUSE. The function can also choose to do nothing, in which
840 case diffuse contributions from spot lights are ignored. When the
841 function is not present at all, the diffuse contributions from spot
842 lights are accumulated normally, like a PrincipledMaterial would do.
843
844 The function can write to the following special variables:
845
846 \list
847 \li vec3 \c DIFFUSE Accumulates the diffuse light contributions, per fragment.
848 \endlist
849
850 The function can read the following special variables, in addition to the
851 matrix (such as, \c MODEL_MATRIX) and vector (such as, \c CAMERA_POSITION)
852 uniforms from the table above:
853
854 \list
855 \li vec3 \c LIGHT_COLOR Diffuse light color.
856 \li float \c LIGHT_ATTENUATION Light attenuation.
857 \li float \c SHADOW_CONTRIB Shadow contribution, or 1.0 if not shadowed at all or not reciving shadows.
858 \li vec3 \c TO_LIGHT_DIR Vector pointing towards the light source.
859 \li float \c SPOT_FACTOR Spot light factor.
860 \li vec3 \c NORMAL The normal vector in world space.
861 \li vec4 \c BASE_COLOR The base color and material alpha value.
862 \li float \c METALNESS The Metalness amount.
863 \li float \c ROUGHNESS The Roughness amount.
864 \endlist
865
866 Example:
867 \badcode
868 void SPOT_LIGHT()
869 {
870 DIFFUSE += LIGHT_COLOR * LIGHT_ATTENUATION * SPOT_FACTOR * SHADOW_CONTRIB * vec3(max(0.0, dot(normalize(VAR_WORLD_NORMAL), TO_LIGHT_DIR)));
871 }
872 \endcode
873
874 \li \c{void SPECULAR_LIGHT()} When present, this function is called for
875 each active light in the scene for each fragment. The task of the function
876 is to add the specular contribution to a writable special variable \c
877 SPECULAR. The function can also choose to do nothing, in which case
878 specular contributions from lights are ignored. When the function is not
879 present at all, the specular contributions from lights are accumulated
880 normally, like a PrincipledMaterial would do.
881
882 The function can write to the following special variables:
883
884 \list
885
886 \li vec3 \c SPECULAR Accumulates the specular light contributions, per
887 frament. The light processor functions will typically add (\c{+=}) to it,
888 since overwriting the value would lose the contribution from other lights.
889
890 \endlist
891
892 The function can read the following special variables, in addition to the
893 matrix (such as, \c MODEL_MATRIX) and vector (such as, \c CAMERA_POSITION)
894 uniforms from the table above:
895
896 \list
897 \li vec3 \c LIGHT_COLOR Specular light color.
898 \li float \c LIGHT_ATTENUATION Light attenuation. For directional lights the value is 1.0. For spot lights the value is the same as \c {LIGHT_ATTENUATION * SPOT_FACTOR} of \c {void SPOT_LIGHT()}.
899 \li float \c SHADOW_CONTRIB Shadow contribution, or 1.0 if not shadowed at all or not reciving shadows.
900 \li vec3 \c FRESNEL_CONTRIB Fresnel contribution from built in Fresnel calculation.
901 \li vec3 \c TO_LIGHT_DIR Vector pointing towards the light source.
902 \li vec3 \c NORMAL The normal vector in world space.
903 \li vec4 \c BASE_COLOR The base color and material alpha value.
904 \li float \c METALNESS The Metalness amount.
905 \li float \c ROUGHNESS The Roughness amount.
906 \li float \c SPECULAR_AMOUNT The specular amount. This value will be between
907 0.0 and 1.0 will be the same value set in the custom \c MAIN function. This
908 value will useful for calculating Fresnel contributions when not using the
909 built-in Fresnel contribution provided by \c FRESNEL_CONTRIB.
910 \endlist
911
912 \badcode
913 void SPECULAR_LIGHT()
914 {
915 vec3 H = normalize(VIEW_VECTOR + TO_LIGHT_DIR);
916 float cosAlpha = max(0.0, dot(H, normalize(NORMAL)));
917 float shine = pow(cosAlpha, exp2(15.0 * (1.0 - ROUGHNESS) + 1.0) * 0.25);
918 SPECULAR += shine * LIGHT_COLOR * FRESNEL_CONTRIB * SHADOW_CONTRIB * LIGHT_ATTENUATION;
919 }
920 \endcode
921
922 \li \c{void POST_PROCESS()} When present, this function is called at the
923 end of the fragment pipeline. The task of the function is to finalize
924 \c COLOR_SUM with final diffuse, specular and emissive terms. Unlike
925 \c FRAGCOLOR for a unshaded material, \c COLOR_SUM will be automatically
926 tonemapped before written to the framebuffer. For debugging purposes it is
927 sometimes useful to output a value that should not be treated as a color.
928 To avoid the tonemapping distorting this value it can be disabled by
929 setting the \l {SceneEnvironment::tonemapMode}{tonemapMode} property
930 to \c TonemapModeNone
931
932 The function can write to the following special variables:
933
934 \list
935 \li vec4 \c COLOR_SUM the output from the fragment shader. The default value
936 is vec4(DIFFUSE.rgb + SPECULAR + EMISSIVE, DIFFUSE.a)
937 \endlist
938
939 The function can read the following special variables.
940
941 \list
942 \li vec4 \c DIFFUSE The final diffuse term of the fragment pipeline.
943 \li vec3 \c SPECULAR The final specular term of the fragment pipeline.
944 \li vec3 \c EMISSIVE The final emissive term of the fragment pipeline.
945 \li vec2 \c UV0 - The first set of texture coordinates from the vertex shader.
946 \li vec2 \c UV1 - The second set of texture coordinates from the vertex shader.
947 \endlist
948
949 \badcode
950 void POST_PROCESS()
951 {
952 float center_x = textureSize(SCREEN_TEXTURE, 0).x * 0.5;
953 if (gl_FragCoord.x > center_x)
954 COLOR_SUM = DIFFUSE;
955 else
956 COLOR_SUM = vec4(EMISSIVE, DIFFUSE.a);
957 }
958 \endcode
959
960 \li \c{void IBL_PROBE()} When present, this function is called for IBL
961 (Image-Based Lighting).
962 The task of the function is to add both the diffuse and the specular
963 contributions of IBL to writable special variables \c DIFFUSE and
964 \c SPECULAR.
965
966 The function can write to the following special variables:
967
968 \list
969 \li vec3 \c DIFFUSE Accumulates the diffuse light contributions, per fragment.
970 \li vec3 \c SPECULAR Accumulates the specular light contributions, per
971 frament.
972 \endlist
973
974 The function can read the following special variables.
975
976 \list
977 \li vec4 \c BASE_COLOR The base color and material alpha value.
978 \li float \c AO_FACTOR The screen space occlusion factor.
979 \li float \c SPECULAR_AMOUNT The specular amount.
980 \li float \c ROUGHNESS The final emissive term of the fragment pipeline.
981 \li vec3 \c NORMAL The normal vector in world space.
982 \li vec3 \c VIEW_VECTOR Points towards the camera.
983 \li mat3 \c IBL_ORIENTATION The orientation of the light probe. It comes
984 from \l {SceneEnvironment::probeOrientation}.
985 \endlist
986
987 \badcode
988 void IBL_PROBE()
989 {
990 vec3 smpDir = IBL_ORIENTATION * NORMAL;
991 DIFFUSE += AO_FACTOR * BASE_COLOR.rgb * textureLod(IBL_TEXTURE, smpDir, IBL_MAXMIPMAP).rgb;
992 }
993 \endcode
994
995 \endlist
996
997 \sa SceneEnvironment::tonemapMode, {Using Image-Based Lighting}
998
999 \section2 Custom variables between functions
1000
1001 Additional variables can be delivered from the MAIN function to the others.
1002 The \c SHARED_VARS keyword can be used for defining new custom variables.
1003 These user-defined variables can be accessed with SHARED.<variable name>.
1004
1005 For example, a shaded custom material can fetch a shared value in the MAIN
1006 and use it in other functions.
1007
1008 \badcode
1009 SHARED_VARS {
1010 vec3 colorThreshold;
1011 };
1012 void MAIN()
1013 {
1014 BASE_COLOR = texture(baseColorMap, UV0);
1015 SHARED.colorThreshold = texture(thresholdMap, UV0).rgb;
1016 }
1017 void DIRECTIONAL_LIGHT()
1018 {
1019 if (DIFFUSE >= SHARED.colorThreshold) {
1020 DIFFUSE = SHARED.colorThreshold;
1021 return;
1022 }
1023 DIFFUSE += LIGHT_COLOR * SHADOW_CONTRIB;
1024 }
1025 \endcode
1026
1027 \note SHARED can be written on all the functions without POST_PROCESS but it
1028 is safe to write it on MAIN and read on the other functions.
1029
1030 \note A recommended use case to write SHARED on LIGHT functions is
1031 reseting it on MAIN first and then accumulating it on each LIGHT functions.
1032
1033 \badcode
1034 SHARED_VARS {
1035 float sheenIntensity;
1036 float sheenRoughness;
1037 vec3 sheenColor;
1038 vec3 outSheenColor;
1039 };
1040 void MAIN()
1041 {
1042 ...
1043 vec4 tex = texture(uSheenMap, UV0);
1044 SHARED.sheenColor = tex.rgb;
1045 SHARED.sheenIntensity = tex.a;
1046 SHARED.sheenRoughness = uSheenRoughness;
1047 SHARED.outSheenColor = vec3(0.0);
1048 }
1049 void SPECULAR_LIGHT()
1050 {
1051 SHARED.outSheenColor += ...;
1052 }
1053 void POST_PROCESS()
1054 {
1055 COLOR_SUM = DIFFUSE + SPECULAR + EMISSIVE + SHARED.outSheenColor;
1056 }
1057 \endcode
1058
1059 \note MAIN is called before others, and POST_PROCESS after all others,
1060 but that there is no guarantee for any other ordering for light processors.
1061
1062 \section2 Additional special keywords
1063
1064 The custom fragment shader code can freely access uniforms (such as, \c
1065 CAMERA_DIRECTION or \c CAMERA_POSITION), and varyings passed on from the
1066 custom vertex shader. Additionally, there are a number of built-in varyings
1067 available as special keywords. Some of these are optional in the sense that
1068 a vertex \c MAIN could calculate and pass on these on its own, but to
1069 reduce duplicated data fragment shaders can also rely on these built-ins
1070 instead. These built-ins are available in light processor functions and in
1071 the fragment MAIN.
1072
1073 \list
1074
1075 \li vec3 \c VAR_WORLD_NORMAL - Interpolated normal transformed by \c
1076 NORMAL_MATRIX.
1077
1078 \li vec3 \c VAR_WORLD_TANGENT - Interpolated tangent transformed by \c
1079 MODEL_MATRIX.
1080
1081 \li vec3 \c VAR_WORLD_BINORMAL - Interpolated binormal transformed by \c
1082 MODEL_MATRIX
1083
1084 \li vec3 \c NORMAL - Unlike \c VAR_WORLD_NORMAL, which is the
1085 interpolated normal as-is, this value is potentially adjusted for
1086 double-sidedness: when rendering with culling disabled, the normal will get
1087 inverted as necessary. Therefore lighting and other calculations are
1088 recommended to use \c NORMAL instead of \c VAR_WORLD_NORMAL in order
1089 behave correctly with all culling modes.
1090
1091 \li vec3 \c TANGENT - Like \c NORMAL, this value is potentially adjusted for
1092 double-sidedness: when rendering with culling disabled, the tangent will get
1093 inverted as necessary.
1094
1095 \li vec3 \c BINORMAL - Like \c NORMAL, this value is potentially adjusted for
1096 double-sidedness: when rendering with culling disabled, the binormal will get
1097 inverted as necessary.
1098
1099 \li vec3 \c VAR_WORLD_POSITION - Interpolated world space vertex position
1100 (\c{(MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz})
1101
1102 \li vec4 \c VAR_COLOR - The interpolated vertex color when colors are
1103 provided in the mesh. \c{vec4(1.0)} otherwise.
1104
1105 \li vec3 \c VIEW_VECTOR - Points towards the camera. This is
1106 effectively the \c{CAMERA_POSITION - VAR_WORLD_POSITION} vector normalized.
1107
1108 \li vec4 \c FRAGCOORD - Contains the View3D-relative coordinates of the
1109 current fragment.
1110
1111 \li float \c FRAMEBUFFER_Y_UP - The value is \c 1 when the Y axis points up
1112 in the coordinate system for framebuffers (textures), meaning \c{(0, 0)} is
1113 the bottom-left corner. The value is \c{-1} when the Y axis points down,
1114 \c{(0, 0)} being the top-left corner. Such differences in the underlying
1115 graphics APIs do not concern most custom materials. One notable exception
1116 is sampling \c SCREEN_TEXTURE with texture coordinates \b not based on
1117 \c FRAGCOORD. As the orientation of \c SCREEN_TEXTURE is tied to the
1118 underlying graphics API by nature, using texture coordinates from a mesh
1119 may need appropriate adjustments to the Y coordinate.
1120
1121 For example, the following fragment shader, suitable for Rectangle or Cube
1122 meshes, will display the opaque objects from the scene on the model:
1123
1124 \badcode
1125 VARYING vec2 texcoord;
1126 void MAIN()
1127 {
1128 vec2 screencoord = texcoord;
1129 if (FRAMEBUFFER_Y_UP < 0.0) // effectively: if not OpenGL
1130 screencoord.y = 1.0 - screencoord.y;
1131 BASE_COLOR = texture(SCREEN_TEXTURE, screencoord);
1132 }
1133 \endcode
1134
1135 When sampling textures other than \c SCREEN_TEXTURE, and \c DEPTH_TEXTURE,
1136 or when \c FRAGCOORD is used to calculate the texture coordinate (which
1137 would be the typical use case for accessing the screen and depth textures),
1138 such an adjustment is not necessary.
1139
1140 \li float \c NDC_Y_UP - The value is \c 1 when the Y axis points up in
1141 normalized device coordinate space, and \c{-1} when the Y axis points down.
1142 Y pointing down is the case when rendering happens with Vulkan. Most
1143 materials do not need to be concerned by this, but being able to branch
1144 based on this can become useful in certain advanced use cases.
1145
1146 \li float \c NEAR_CLIP_VALUE - The value is \c -1 for when the clipping plane
1147 range's starts at \c -1 and goes to \c 1. This is true when using OpenGL for
1148 rendering. For other rendering backends the value of this property will be
1149 \c 0 meaning the clipping plane range is \c 0 to \c 1. This value is useful
1150 with certain techniques involving the \c DEPTH_TEXTURE
1151
1152 For example, the following fragment shader demonstrates a technique for
1153 reconstructing the position of a value from the depth buffer to determine
1154 the distance from the current position being rendered. When used in
1155 combination with \c INVERSE_PROJECTION_MATRIX the value of depth needs
1156 to be in normalized device coordinates so it is important to make sure that
1157 the range of depth value reflects that. When the \c NEAR_CLIP_VALUE is
1158 \c -1 then the depth value gets scaled to be between \c -1 and \c 1.
1159
1160 \badcode
1161 void MAIN() {
1162 vec2 screen_uv = FRAGCOORD.xy / vec2(textureSize(SCREEN_TEXTURE, 0));
1163 float depth = texture(DEPTH_TEXTURE, screen_uv).r;
1164
1165 if (NEAR_CLIP_VALUE < 0.0) // effectively: if opengl
1166 depth = depth * 2.0 - 1.0;
1167
1168 vec4 unproject = INVERSE_PROJECTION_MATRIX * vec4(screen_uv, depth, 1.0);
1169 depth = (unproject.xyz / unproject.w).z;
1170 float viewVectorZ = (VIEW_MATRIX * vec4(VAR_WORLD_POSITION, 1.0)).z;
1171 depth = viewVectorZ - depth;
1172
1173 BASE_COLOR = vec4(depth, depth, depth, 1.0);
1174 }
1175 \endcode
1176
1177 \li float \c IBL_EXPOSE - The amount of light emitted by the light probe.
1178 It comes from \l {SceneEnvironment::probeExposure}.
1179 \badcode
1180 DIFFUSE += AO_FACTOR * IBL_EXPOSE * BASE_COLOR.rgb * textureLod(IBL_TEXTURE, NORMAL, IBL_MAXMIPMAP).rgb;
1181 \endcode
1182
1183 \li float \c IBL_HORIZON - The horizontal cut-off value of reflections from
1184 the lower half environment. It comes from \l {SceneEnvironment::probeHorizon}
1185 {Horizon Cut-Off} but remapped to [-1, 0).
1186 \badcode
1187 vec3 diffuse += AO_FACTOR * IBL_EXPOSE * BASE_COLOR.rgb * textureLod(IBL_TEXTURE, NORMAL, IBL_MAXMIPMAP).rgb;
1188 if (IBL_HORIZON > -1.0) {
1189 float ctr = 0.5 + 0.5 * IBL_HORIZON;
1190 float vertWt = smoothstep(ctr * 0.25, ctr + 0.25, NORMAL.y);
1191 float wtScaled = mix(1.0, vertWt, IBL_HORIZON + 1.0);
1192 diffuse *= wtScaled;
1193 }
1194 \endcode
1195
1196 \li float \c IBL_MAXMIPMAP - The maximum mipmap level of IBL_TEXTURE.
1197
1198 \endlist
1199
1200 \section2 Instancing
1201
1202 When doing instanced rendering, some of the keywords above do not apply.
1203 The following keywords are only available with instancing:
1204
1205 \list
1206 \li \c INSTANCE_MODEL_MATRIX -> mat4, replacement for \c MODEL_MATRIX, including the instancing transformation.
1207 \li \c INSTANCE_MODELVIEWPROJECTION_MATRIX -> mat4, replacement for \c MODELVIEWPROJECTION_MATRIX, including the instancing transformation.
1208 \li \c INSTANCE_NORMAL_MATRIX -> mat3, replacement for \c NORMAL_MATRIX, including the instancing transformation.
1209 \li \c INSTANCE_COLOR -> vec4, the instance color: to be combined with \c {COLOR}.
1210 \li \c INSTANCE_DATA -> vec4, instance custom data.
1211 \li \c INSTANCE_INDEX -> int, the index of the instance in the instancing table.
1212 \endlist
1213
1214 With instancing, \c MODEL_MATRIX and \c NORMAL_MATRIX only contain the
1215 part of the model transform that is applied before the instance transform.
1216 \c MODELVIEWPROJECTION_MATRIX is not available with an instance table. With
1217 \l ShaderInstancing, it contains the part applied after the instance
1218 transform.
1219
1220 With \l ShaderInstancing there is no instance table, and these keywords
1221 are not available, except \c INSTANCE_INDEX. Instead, the vertex shader
1222 of a shaded material sets the transform of each instance:
1223
1224 \list
1225 \li \c INSTANCE_TRANSFORM -> mat4, the instance transform, applied in
1226 the same way as an instance table's. It starts out as the identity.
1227 \endlist
1228
1229 \note In an unshaded material, setting \c INSTANCE_TRANSFORM has no
1230 effect. The vertex shader must apply the instance transform itself when
1231 calculating \c POSITION.
1232
1233 \section1 Screen, depth, and other textures
1234
1235 The rendering pipeline can expose a number of textures to the custom
1236 material shaders with content from special render passes. This applies both
1237 to shaded and unshaded custom materials.
1238
1239 For example, a shader may want access to a depth texture that contains the
1240 depth buffer contents for the opaque objects in the scene. This is achieved
1241 by sampling \c DEPTH_TEXTURE. Such a texture is not normally generated,
1242 unless there is a real need for it. Therefore, the presence of the
1243 following keywords in the vertex or fragment shader also acts as a toggle
1244 for opting in to the - potentially expensive - passes for generating the
1245 texture in question. (of course, it could be that some of these become
1246 already enabled due to other settings, such as the ambient occlusion
1247 parameters in SceneEnvironment or due to a post-processing effect relying
1248 on the depth texture, in which case the textures in question are generated
1249 regardless of the custom material and so sampling these special textures in
1250 the material comes at no extra cost apart from the texture access itself)
1251
1252 \list
1253
1254 \li \c SCREEN_TEXTURE - When present, a texture (\c sampler2D or \c
1255 sampler2DArray) with the color buffer from a rendering pass containing the
1256 contents of the scene excluding any transparent materials or any materials
1257 also using the SCREEN_TEXTURE is exposed to the shader under this name. The
1258 texture can be used for techniques that require the contents of the
1259 framebuffer they are being rendered to. The SCREEN_TEXTURE texture uses the
1260 same clear mode as the View3D. The size of these textures matches the size
1261 of the View3D in pixels. For example, a fragment shader could contain the
1262 following:
1263 \badcode
1264 vec2 uv = FRAGCOORD.xy / vec2(textureSize(SCREEN_TEXTURE, 0));
1265 vec2 displace = vec2(0.1);
1266 vec4 c = texture(SCREEN_TEXTURE, uv + displace);
1267 \endcode
1268
1269 Be aware that using \c SCREEN_TEXTURE requires appropriate, conscious
1270 design of the scene. Objects using such materials have to be positioned
1271 carefully, typically above all other objects that are expected to be
1272 visible in the texture. Objects that employ semi-transparency in some form
1273 are never part of the \c SCREEN_TEXTURE. Often \c SCREEN_TEXTURE will be
1274 used in combination with \c BASE_COLOR in \c MAIN. For example, the
1275 following custom fragment shader applies an emboss effect, while keeping
1276 fragments not touched by opaque objects transparent. This assumes that the
1277 object with the material is placed in the front, and that it has blending
1278 enabled. \badcode
1279 void MAIN()
1280 {
1281 vec2 size = vec2(textureSize(SCREEN_TEXTURE, 0));
1282 vec2 uv = FRAGCOORD.xy / size;
1283
1284 // basic emboss effect
1285 vec2 d = vec2(1.0 / size.x, 1.0 / size.y);
1286 vec4 diff = texture(SCREEN_TEXTURE, uv + d) - texture(SCREEN_TEXTURE, uv - d);
1287 float c = (diff.x + diff.y + diff.z) + 0.5;
1288
1289 float alpha = texture(SCREEN_TEXTURE, uv).a;
1290 BASE_COLOR = vec4(vec3(c), alpha);
1291 }
1292 \endcode
1293 With \l{Multiview Rendering}{multiview rendering}, \c SCREEN_TEXTURE is a \c
1294 sampler2DArray. Use \c VIEW_INDEX to select the layer to use. For VR/AR
1295 applications that wish to support both types of rendering, the portable
1296 approach is the following:
1297 \badcode
1298 #if QSHADER_VIEW_COUNT >= 2
1299 vec4 c = texture(SCREEN_TEXTURE, vec3(uv, VIEW_INDEX));
1300 #else
1301 vec4 c = texture(SCREEN_TEXTURE, uv);
1302 #endif
1303 \endcode
1304
1305 \li \c SCREEN_MIP_TEXTURE - Identical to \c SCREEN_TEXTURE in most ways,
1306 the difference being that this texture has mipmaps generated. This can be
1307 an expensive feature performance-wise, depending on the screen size, and
1308 due to having to generate the mipmaps every time the scene is rendered.
1309 Therefore, prefer using \c SCREEN_TEXTURE always, unless a technique
1310 relying on the texture mip levels (e.g. using \c textureLod in the shader)
1311 is implemented by the custom material.
1312
1313 \li \c DEPTH_TEXTURE - When present, a texture (\c sampler2D or \c
1314 sampler2DArray) with the (non-linearized) depth buffer contents is exposed
1315 to the shader under this name. Only opaque objects are included.
1316 For example, a fragment shader could contain the following: \badcode
1317 ivec2 dtSize = textureSize(DEPTH_TEXTURE, 0);
1318 vec2 dtUV = (FRAGCOORD.xy) / vec2(dtSize);
1319 vec4 depthSample = texture(DEPTH_TEXTURE, dtUV);
1320 float zNear = CAMERA_PROPERTIES.x;
1321 float zFar = CAMERA_PROPERTIES.y;
1322 float zRange = zFar - zNear;
1323 float z_n = 2.0 * depthSample.r - 1.0;
1324 float d = 2.0 * zNear * zFar / (zFar + zNear - z_n * zRange);
1325 d /= zFar;
1326 \endcode
1327 With \l{Multiview Rendering}{multiview rendering}, \c DEPTH_TEXTURE is a \c
1328 sampler2DArray. Use \c VIEW_INDEX to select the layer to use. For VR/AR
1329 applications that wish to support both types of rendering, the portable
1330 approach is the following:
1331 \badcode
1332 #if QSHADER_VIEW_COUNT >= 2
1333 vec4 depthSample = texture(DEPTH_TEXTURE, vec3(uv, VIEW_INDEX));
1334 #else
1335 vec4 depthSample = texture(DEPTH_TEXTURE, uv);
1336 #endif
1337 \endcode
1338
1339 \li \c NORMAL_ROUGHNESS_TEXTURE - When present, a texture (\c sampler2D)
1340 with the world-space normals and the material roughness is exposed to the
1341 shader under this name. Only opaque objects are included. The roughness is
1342 stored in the alpha channel.
1343 For example, a fragment shader could contain the following: \badcode
1344 vec3 N = normalize(texture(NORMAL_ROUGHNESS_TEXTURE, uv).rgb);
1345 \endcode
1346
1347 \li \c AO_TEXTURE - When present and screen space ambient occlusion is
1348 enabled (meaning when the AO strength and distance are both non-zero) in
1349 SceneEnvironment, the SSAO texture (\c sampler2D or \c sampler2DArray) is
1350 exposed to the shader under this name. Sampling this texture can be useful
1351 in unshaded materials. Shaded materials have ambient occlusion support built
1352 in. This means that the ambient occlusion factor is taken into account
1353 automatically. Whereas in a fragment shader for an unshaded material one
1354 could write the following to achieve the same: \badcode
1355 ivec2 aoSize = textureSize(AO_TEXTURE, 0);
1356 vec2 aoUV = (FRAGCOORD.xy) / vec2(aoSize);
1357 float aoFactor = texture(AO_TEXTURE, aoUV).x;
1358 \endcode
1359 With \l{Multiview Rendering}{multiview rendering}, \c AO_TEXTURE is a \c
1360 sampler2DArray. Use \c VIEW_INDEX to select the layer to use. For VR/AR
1361 applications that wish to support both types of rendering, the portable
1362 approach is the following:
1363 \badcode
1364 #if QSHADER_VIEW_COUNT >= 2
1365 ivec2 aoSize = textureSize(AO_TEXTURE, 0).xy;
1366 vec2 aoUV = (FRAGCOORD.xy) / vec2(aoSize);
1367 float aoFactor = texture(AO_TEXTURE, vec3(aoUV, VIEW_INDEX)).x;
1368 #else
1369 ivec2 aoSize = textureSize(AO_TEXTURE, 0);
1370 vec2 aoUV = (FRAGCOORD.xy) / vec2(aoSize);
1371 float aoFactor = texture(AO_TEXTURE, aoUV).x;
1372 #endif
1373 \endcode
1374
1375 \li \c IBL_TEXTURE - It will not enable any special rendering pass, but it can
1376 be used when the material has \l {Material::lightProbe} or the model is in the scope of
1377 \l {SceneEnvironment::lightProbe}.
1378
1379 \badcode
1380 void IBL_PROBE()
1381 {
1382 DIFFUSE += AO_FACTOR * BASE_COLOR.rgb * textureLod(IBL_TEXTURE, NORMAL, IBL_MAXMIPMAP).rgb;
1383 }
1384 \endcode
1385
1386 \li \c MOTION_VECTOR_TEXTURE — Enables a dedicated rendering pass that computes per-object
1387 motion vectors for the scene.
1388 The output is a four-channel texture: the R and G components contain the scaled motion vectors
1389 of the models, while the B and A components store the unscaled motion vectors.
1390
1391 \li \c VIEW_INDEX - When used in the custom shader code, this is a
1392 (non-interpolated) uint variable. When \l{Multiview Rendering}{multiview
1393 rendering} is not used, the value is always 0. With multiview rendering, the
1394 value is the current view index (e.g., gl_ViewIndex). Useful in particular
1395 in combination with \c DEPTH_TEXTURE and similar when multiview rendering is
1396 enabled.
1397
1398 \endlist
1399
1400 \sa {Qt Quick 3D - Custom Shaders Example}, {Qt Quick 3D - Custom Materials Example}, {Programmable Materials, Effects, Geometry, and Texture data}
1401*/
1402
1403/*!
1404 \qmlproperty url CustomMaterial::vertexShader
1405
1406 Specfies the file with the snippet of custom vertex shader code.
1407
1408 The value is a URL and must either be a local file or use the qrc scheme to
1409 access files embedded via the Qt resource system. Relative file paths
1410 (without a scheme) are also accepted, in which case the file is treated as
1411 relative to the component (the \c{.qml} file).
1412
1413 \warning Shader snippets are assumed to be trusted content. Application
1414 developers are advised to carefully consider the potential implications
1415 before allowing the loading of user-provided content that is not part of the
1416 application.
1417
1418 \sa fragmentShader
1419*/
1420
1421/*!
1422 \qmlproperty url CustomMaterial::fragmentShader
1423
1424 Specfies the file with the snippet of custom fragment shader code.
1425
1426 The value is a URL and must either be a local file or use the qrc scheme to
1427 access files embedded via the Qt resource system. Relative file paths
1428 (without a scheme) are also accepted, in which case the file is treated as
1429 relative to the component (the \c{.qml} file).
1430
1431 \warning Shader snippets are assumed to be trusted content. Application
1432 developers are advised to carefully consider the potential implications
1433 before allowing the loading of user-provided content that is not part of the
1434 application.
1435
1436 \sa vertexShader
1437*/
1438
1439/*!
1440 \qmlproperty enumeration CustomMaterial::shadingMode
1441 Specifies the type of the material. The default value is Shaded.
1442
1443 \value CustomMaterial.Unshaded
1444 \value CustomMaterial.Shaded
1445*/
1446
1447/*!
1448 \qmlproperty bool CustomMaterial::alwaysDirty
1449 Specifies that the material state is always dirty, which indicates that the material needs
1450 to be refreshed every time it is used by the QtQuick3D.
1451*/
1452
1453/*!
1454 \qmlproperty enumeration CustomMaterial::sourceBlend
1455
1456 Specifies the source blend factor. The default value is \c
1457 CustomMaterial.NoBlend.
1458
1459 \value CustomMaterial.NoBlend
1460 \value CustomMaterial.Zero
1461 \value CustomMaterial.One
1462 \value CustomMaterial.SrcColor
1463 \value CustomMaterial.OneMinusSrcColor
1464 \value CustomMaterial.DstColor
1465 \value CustomMaterial.OneMinusDstColor
1466 \value CustomMaterial.SrcAlpha
1467 \value CustomMaterial.OneMinusSrcAlpha
1468 \value CustomMaterial.DstAlpha
1469 \value CustomMaterial.OneMinusDstAlpha
1470 \value CustomMaterial.ConstantColor
1471 \value CustomMaterial.OneMinusConstantColor
1472 \value CustomMaterial.ConstantAlpha
1473 \value CustomMaterial.OneMinusConstantAlpha
1474 \value CustomMaterial.SrcAlphaSaturate
1475
1476 \note Both \l sourceBlend and \l destinationBlend needs to be set to a non-default
1477 value before blending is enabled.
1478
1479 \sa destinationBlend
1480*/
1481
1482/*!
1483 \qmlproperty enumeration CustomMaterial::destinationBlend
1484
1485 Specifies the destination blend factor. The default value is \c
1486 CustomMaterial.NoBlend.
1487
1488 \value CustomMaterial.NoBlend
1489 \value CustomMaterial.Zero
1490 \value CustomMaterial.One
1491 \value CustomMaterial.SrcColor
1492 \value CustomMaterial.OneMinusSrcColor
1493 \value CustomMaterial.DstColor
1494 \value CustomMaterial.OneMinusDstColor
1495 \value CustomMaterial.SrcAlpha
1496 \value CustomMaterial.OneMinusSrcAlpha
1497 \value CustomMaterial.DstAlpha
1498 \value CustomMaterial.OneMinusDstAlpha
1499 \value CustomMaterial.ConstantColor
1500 \value CustomMaterial.OneMinusConstantColor
1501 \value CustomMaterial.ConstantAlpha
1502 \value CustomMaterial.OneMinusConstantAlpha
1503 \value CustomMaterial.SrcAlphaSaturate
1504
1505 \note Both \l sourceBlend and \l destinationBlend needs to be set to a non-default
1506 value before blending is enabled.
1507
1508 \sa sourceBlend
1509*/
1510
1511/*!
1512 \qmlproperty real CustomMaterial::lineWidth
1513
1514 This property determines the width of the lines rendered, when the geometry
1515 is using a primitive type of lines or line strips. The default value is
1516 1.0. This property is not relevant when rendering other types of geometry,
1517 such as, triangle meshes.
1518
1519 \warning Line widths other than 1 may not be suported at run time,
1520 depending on the underlying graphics API. When that is the case, the
1521 request to change the width is ignored. For example, none of the following
1522 can be expected to support wide lines: Direct3D, Metal, OpenGL with core
1523 profile contexts.
1524
1525 \note Unlike the line width, the value of which is part of the graphics
1526 pipeline object, the point size for geometries with a topology of points is
1527 controlled by the vertex shader (when supported), and has therefore no
1528 corresponding QML property.
1529*/
1530
1531/*!
1532 \qmlproperty enumeration CustomMaterial::sourceAlphaBlend
1533 \since 6.7
1534
1535 Specifies the source alpha blend factor. The default value is \c
1536 CustomMaterial.NoBlend. This value is only actively used if \l sourceBlend and
1537 \l destinationBlend is set to a non-default value.
1538
1539 \value CustomMaterial.NoBlend
1540 \value CustomMaterial.Zero
1541 \value CustomMaterial.One
1542 \value CustomMaterial.SrcColor
1543 \value CustomMaterial.OneMinusSrcColor
1544 \value CustomMaterial.DstColor
1545 \value CustomMaterial.OneMinusDstColor
1546 \value CustomMaterial.SrcAlpha
1547 \value CustomMaterial.OneMinusSrcAlpha
1548 \value CustomMaterial.DstAlpha
1549 \value CustomMaterial.OneMinusDstAlpha
1550 \value CustomMaterial.ConstantColor
1551 \value CustomMaterial.OneMinusConstantColor
1552 \value CustomMaterial.ConstantAlpha
1553 \value CustomMaterial.OneMinusConstantAlpha
1554 \value CustomMaterial.SrcAlphaSaturate
1555
1556 \note For backwards compatibility purposes, when left to its default value,
1557 will be assigned the same value as \l sourceBlend when \l sourceBlend and
1558 \l destinationBlend is set to non-default values.
1559
1560 \sa sourceBlend
1561*/
1562
1563/*!
1564 \qmlproperty enumeration CustomMaterial::destinationAlphaBlend
1565 \since 6.7
1566
1567 Specifies the destination alpha blend factor. The default value is \c
1568 CustomMaterial.NoBlend. This value is only actively used if \l sourceBlend and
1569 \l destinationBlend is set to a non-default value.
1570
1571 \value CustomMaterial.NoBlend
1572 \value CustomMaterial.Zero
1573 \value CustomMaterial.One
1574 \value CustomMaterial.SrcColor
1575 \value CustomMaterial.OneMinusSrcColor
1576 \value CustomMaterial.DstColor
1577 \value CustomMaterial.OneMinusDstColor
1578 \value CustomMaterial.SrcAlpha
1579 \value CustomMaterial.OneMinusSrcAlpha
1580 \value CustomMaterial.DstAlpha
1581 \value CustomMaterial.OneMinusDstAlpha
1582 \value CustomMaterial.ConstantColor
1583 \value CustomMaterial.OneMinusConstantColor
1584 \value CustomMaterial.ConstantAlpha
1585 \value CustomMaterial.OneMinusConstantAlpha
1586 \value CustomMaterial.SrcAlphaSaturate
1587
1588 \note For backwards compatibility purposes, when left to its default value,
1589 will be assigned the same value as \l destinationBlend when \l sourceBlend and
1590 \l destinationBlend is set to non-default values.
1591
1592 \sa destinationBlend
1593*/
1594
1595static inline QRhiGraphicsPipeline::BlendFactor toRhiBlendFactor(QQuick3DCustomMaterial::BlendMode mode)
1596{
1597 switch (mode) {
1598 case QQuick3DCustomMaterial::BlendMode::Zero:
1599 return QRhiGraphicsPipeline::Zero;
1600 case QQuick3DCustomMaterial::BlendMode::One:
1601 return QRhiGraphicsPipeline::One;
1602 case QQuick3DCustomMaterial::BlendMode::SrcColor:
1603 return QRhiGraphicsPipeline::SrcColor;
1604 case QQuick3DCustomMaterial::BlendMode::OneMinusSrcColor:
1605 return QRhiGraphicsPipeline::OneMinusSrcColor;
1606 case QQuick3DCustomMaterial::BlendMode::DstColor:
1607 return QRhiGraphicsPipeline::DstColor;
1608 case QQuick3DCustomMaterial::BlendMode::OneMinusDstColor:
1609 return QRhiGraphicsPipeline::OneMinusDstColor;
1610 case QQuick3DCustomMaterial::BlendMode::SrcAlpha:
1611 return QRhiGraphicsPipeline::SrcAlpha;
1612 case QQuick3DCustomMaterial::BlendMode::OneMinusSrcAlpha:
1613 return QRhiGraphicsPipeline::OneMinusSrcAlpha;
1614 case QQuick3DCustomMaterial::BlendMode::DstAlpha:
1615 return QRhiGraphicsPipeline::DstAlpha;
1616 case QQuick3DCustomMaterial::BlendMode::OneMinusDstAlpha:
1617 return QRhiGraphicsPipeline::OneMinusDstAlpha;
1618 case QQuick3DCustomMaterial::BlendMode::ConstantColor:
1619 return QRhiGraphicsPipeline::ConstantColor;
1620 case QQuick3DCustomMaterial::BlendMode::OneMinusConstantColor:
1621 return QRhiGraphicsPipeline::OneMinusConstantColor;
1622 case QQuick3DCustomMaterial::BlendMode::ConstantAlpha:
1623 return QRhiGraphicsPipeline::ConstantAlpha;
1624 case QQuick3DCustomMaterial::BlendMode::OneMinusConstantAlpha:
1625 return QRhiGraphicsPipeline::OneMinusConstantAlpha;
1626 case QQuick3DCustomMaterial::BlendMode::SrcAlphaSaturate:
1627 return QRhiGraphicsPipeline::SrcAlphaSaturate;
1628 default:
1629 return QRhiGraphicsPipeline::One;
1630 }
1631}
1632
1633QQuick3DCustomMaterial::QQuick3DCustomMaterial(QQuick3DObject *parent)
1634 : QQuick3DMaterial(*(new QQuick3DObjectPrivate(QQuick3DObjectPrivate::Type::CustomMaterial, QQuick3DObjectPrivate::Flags::RequiresSecondaryUpdate)), parent)
1635 , QQuick3DPropertyChangedTracker(this, QQuick3DSuperClassInfo<QQuick3DCustomMaterial>())
1636{
1637}
1638
1639QQuick3DCustomMaterial::~QQuick3DCustomMaterial() {}
1640
1641QQuick3DCustomMaterial::BlendMode QQuick3DCustomMaterial::srcBlend() const
1642{
1643 return m_srcBlend;
1644}
1645
1646void QQuick3DCustomMaterial::setSrcBlend(BlendMode mode)
1647{
1648 if (m_srcBlend == mode)
1649 return;
1650
1651 m_srcBlend = mode;
1652 update();
1653 emit srcBlendChanged();
1654}
1655
1656QQuick3DCustomMaterial::BlendMode QQuick3DCustomMaterial::dstBlend() const
1657{
1658 return m_dstBlend;
1659}
1660
1661void QQuick3DCustomMaterial::setDstBlend(BlendMode mode)
1662{
1663 if (m_dstBlend == mode)
1664 return;
1665
1666 m_dstBlend = mode;
1667 update();
1668 emit dstBlendChanged();
1669}
1670
1671QQuick3DCustomMaterial::BlendMode QQuick3DCustomMaterial::srcAlphaBlend() const
1672{
1673 return m_srcAlphaBlend;
1674}
1675
1676void QQuick3DCustomMaterial::setSrcAlphaBlend(QQuick3DCustomMaterial::BlendMode mode)
1677{
1678 if (m_srcAlphaBlend == mode)
1679 return;
1680
1681 m_srcAlphaBlend = mode;
1682 update();
1683 emit srcAlphaBlendChanged();
1684}
1685
1686QQuick3DCustomMaterial::BlendMode QQuick3DCustomMaterial::dstAlphaBlend() const
1687{
1688 return m_dstAlphaBlend;
1689}
1690
1691void QQuick3DCustomMaterial::setDstAlphaBlend(QQuick3DCustomMaterial::BlendMode mode)
1692{
1693 if (m_dstAlphaBlend == mode)
1694 return;
1695
1696 m_dstAlphaBlend = mode;
1697 update();
1698 emit dstAlphaBlendChanged();
1699}
1700
1701QQuick3DCustomMaterial::ShadingMode QQuick3DCustomMaterial::shadingMode() const
1702{
1703 return m_shadingMode;
1704}
1705
1706void QQuick3DCustomMaterial::setShadingMode(ShadingMode mode)
1707{
1708 if (m_shadingMode == mode)
1709 return;
1710
1711 m_shadingMode = mode;
1712 markDirty(*this, Dirty::ShaderSettingsDirty);
1713 emit shadingModeChanged();
1714}
1715
1716QUrl QQuick3DCustomMaterial::vertexShader() const
1717{
1718 return m_vertexShader;
1719}
1720
1721void QQuick3DCustomMaterial::setVertexShader(const QUrl &url)
1722{
1723 if (m_vertexShader == url)
1724 return;
1725
1726 m_vertexShader = url;
1727 markDirty(*this, Dirty::ShaderSettingsDirty);
1728 emit vertexShaderChanged();
1729}
1730
1731QUrl QQuick3DCustomMaterial::fragmentShader() const
1732{
1733 return m_fragmentShader;
1734}
1735
1736void QQuick3DCustomMaterial::setFragmentShader(const QUrl &url)
1737{
1738 if (m_fragmentShader == url)
1739 return;
1740
1741 m_fragmentShader = url;
1742 markDirty(*this, Dirty::ShaderSettingsDirty);
1743 emit fragmentShaderChanged();
1744}
1745
1746
1747QString QQuick3DCustomMaterial::vertexShaderCode() const
1748{
1749 return m_vertexShaderCode;
1750}
1751
1752void QQuick3DCustomMaterial::setVertexShaderCode(const QString &code)
1753{
1754 if (m_vertexShaderCode == code)
1755 return;
1756
1757 m_vertexShaderCode = code;
1758 markDirty(*this, Dirty::ShaderSettingsDirty);
1759 emit vertexShaderCodeChanged();
1760}
1761
1762QString QQuick3DCustomMaterial::fragmentShaderCode() const
1763{
1764 return m_fragmentShaderCode;
1765}
1766
1767void QQuick3DCustomMaterial::setFragmentShaderCode(const QString &code)
1768{
1769 if (m_fragmentShaderCode == code)
1770 return;
1771
1772 m_fragmentShaderCode = code;
1773 markDirty(*this, Dirty::ShaderSettingsDirty);
1774 emit fragmentShaderCodeChanged();
1775}
1776
1777float QQuick3DCustomMaterial::lineWidth() const
1778{
1779 return m_lineWidth;
1780}
1781
1782void QQuick3DCustomMaterial::setLineWidth(float width)
1783{
1784 if (qFuzzyCompare(m_lineWidth, width))
1785 return;
1786 m_lineWidth = width;
1787 update();
1788 emit lineWidthChanged();
1789}
1790
1791void QQuick3DCustomMaterial::markAllDirty()
1792{
1793 m_dirtyAttributes |= Dirty::AllDirty;
1794 QQuick3DMaterial::markAllDirty();
1795}
1796
1797void QQuick3DCustomMaterial::markTrackedPropertyDirty(QMetaProperty, DirtyPropertyHint hint)
1798{
1799 if (hint == DirtyPropertyHint::Reference)
1800 markDirty(*this, Dirty::TextureDirty);
1801 else
1802 markDirty(*this, Dirty::PropertyDirty);
1803}
1804
1805void QQuick3DCustomMaterial::markDirty(QQuick3DCustomMaterial &that, Dirty type)
1806{
1807 if (!(that.m_dirtyAttributes & quint32(type))) {
1808 that.m_dirtyAttributes |= quint32(type);
1809 that.update();
1810 }
1811}
1812
1813bool QQuick3DCustomMaterial::alwaysDirty() const
1814{
1815 return m_alwaysDirty;
1816}
1817
1818void QQuick3DCustomMaterial::setAlwaysDirty(bool alwaysDirty)
1819{
1820 if (m_alwaysDirty == alwaysDirty)
1821 return;
1822
1823 m_alwaysDirty = alwaysDirty;
1824 update();
1825 emit alwaysDirtyChanged();
1826}
1827
1828static void setCustomMaterialFlagsFromShader(QSSGRenderCustomMaterial *material, const QSSGCustomShaderMetaData &meta)
1829{
1830 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesScreenTexture))
1831 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenTexture, true);
1832 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesScreenMipTexture))
1833 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenMipTexture, true);
1834 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesDepthTexture))
1835 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::DepthTexture, true);
1836 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesNormalTexture))
1837 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::NormalTexture, true);
1838 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesAoTexture))
1839 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::AoTexture, true);
1840 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesProjectionMatrix))
1841 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::ProjectionMatrix, true);
1842 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesInverseProjectionMatrix))
1843 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::InverseProjectionMatrix, true);
1844 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesVarColor))
1845 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::VarColor, true);
1846 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesIblOrientation))
1847 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::IblOrientation, true);
1848 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesLightmap))
1849 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Lightmap, true);
1850 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesSkinning))
1851 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Skinning, true);
1852 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesMorphing))
1853 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Morphing, true);
1854 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesViewIndex))
1855 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::ViewIndex, true);
1856 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesClearcoat))
1857 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Clearcoat, true);
1858 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesSheen))
1859 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Sheen, true);
1860 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesAnisotropy))
1861 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Anisotropy, true);
1862 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesIridescence))
1863 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Iridescence, true);
1864 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesDispersion))
1865 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Dispersion, true);
1866 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesInstanceIndex))
1867 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::InstanceIndex, true);
1868 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesClearcoatFresnelScaleBias))
1869 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::ClearcoatFresnelScaleBias, true);
1870 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesFresnelScaleBias))
1871 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::FresnelScaleBias, true);
1872 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesMotionVectorTexture))
1873 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::MotionVectorTexture, true);
1874 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesTransmission)) {
1875 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Transmission, true);
1876 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenTexture, true);
1877 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenMipTexture, true);
1878 }
1879 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesFragcoord))
1880 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Fragcoord, true);
1881
1882 // vertex only
1883 if (meta.flags.testFlag(QSSGCustomShaderMetaData::OverridesPosition))
1884 material->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::OverridesPosition, true);
1885
1886 // fragment only
1887 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesSharedVars))
1888 material->m_usesSharedVariables = true;
1889}
1890
1891static QByteArray prepareCustomShader(QSSGRenderCustomMaterial *customMaterial,
1892 const QSSGShaderCustomMaterialAdapter::StringPairList &uniforms,
1893 const QByteArray &snippet,
1894 QSSGShaderCache::ShaderType shaderType,
1895 QSSGCustomShaderMetaData &meta,
1896 bool multiViewCompatible)
1897{
1898 if (snippet.isEmpty())
1899 return QByteArray();
1900
1901 QByteArray sourceCode = snippet;
1902 QByteArray buf;
1903 const auto imgBufs = meta.imageBufferMetadata;
1904
1905 QSSGShaderCustomMaterialAdapter::ShaderCodeAndMetaData result;
1906 QSSGShaderCustomMaterialAdapter::CustomShaderPrepWorkData scratch;
1907 QSSGShaderCustomMaterialAdapter::beginPrepareCustomShader(&scratch, &result, sourceCode, shaderType, multiViewCompatible);
1908 QSSGShaderCustomMaterialAdapter::finishPrepareCustomShader(&buf, scratch, result, shaderType, multiViewCompatible, uniforms, imgBufs, {}, {}, {}, {});
1909
1910 sourceCode = result.first;
1911 sourceCode.append(buf);
1912 meta = result.second;
1913 meta.imageBufferMetadata = imgBufs;
1914 setCustomMaterialFlagsFromShader(customMaterial, meta);
1915 return sourceCode;
1916}
1917
1918QSSGRenderGraphObject *QQuick3DCustomMaterial::updateSpatialNode(QSSGRenderGraphObject *node)
1919{
1920 using namespace QSSGShaderUtils;
1921
1922 const auto &renderContext = QQuick3DObjectPrivate::get(this)->sceneManager->wattached->rci();
1923 if (!renderContext) {
1924 qWarning("QQuick3DCustomMaterial: No render context interface?");
1925 return nullptr;
1926 }
1927
1928 QSSGShaderCustomMaterialAdapter::StringPairList uniforms;
1929 QSSGRenderCustomMaterial *customMaterial = static_cast<QSSGRenderCustomMaterial *>(node);
1930 bool newBackendNode = false;
1931 bool shadersMayChange = false;
1932 bool needsSecondaryUpdate = false;
1933 if (!customMaterial) {
1934 customMaterial = new QSSGRenderCustomMaterial;
1935 newBackendNode = true;
1936 } else if (m_dirtyAttributes & ShaderSettingsDirty) {
1937 shadersMayChange = true;
1938 }
1939
1940 if (!newBackendNode && (m_dirtyAttributes & Dirty::TextureDirty)) {
1941 const auto previousProperties = m_propertyList;
1942 const auto properties = extractProperties();
1943 // Texture bindings can change without affecting the shader, but a different
1944 // sampler type requires rebuilding the uniform declarations as well.
1945 if (!std::equal(previousProperties.cbegin(), previousProperties.cend(), properties.cbegin(), properties.cend(),
1946 [](const auto &a, const auto &b) { return a.pid == b.pid && a.typeName == b.typeName; })) {
1947 shadersMayChange = true;
1948 }
1949 }
1950
1951 // A tracked texture property is either a plain Texture or, for compatibility, a
1952 // TextureInput. Resolves both to the TextureInput (if any) and the texture currently
1953 // referred to.
1954 struct ResolvedTexture
1955 {
1956 QQuick3DShaderUtilsTextureInput *texInput = nullptr;
1957 QQuick3DTexture *texture = nullptr;
1958 };
1959 const auto resolveTexture = [this](int pid) {
1960 ResolvedTexture resolved;
1961 const QVariant value = metaObject()->property(pid).read(this);
1962 resolved.texInput = value.value<QQuick3DShaderUtilsTextureInput *>();
1963 resolved.texture = resolved.texInput ? resolved.texInput->texture() : QSSGShaderUtils::textureFromValue(value);
1964 return resolved;
1965 };
1966
1967 if (newBackendNode || shadersMayChange) {
1968 markAllDirty();
1969
1970 customMaterial->m_properties.clear();
1971 customMaterial->m_textureProperties.clear();
1972
1973 customMaterial->m_shadingMode = QSSGRenderCustomMaterial::ShadingMode(int(m_shadingMode));
1974
1975 // Registers a sampler uniform. The render image, the filter and tiling settings and
1976 // the connections to the texture are filled in by the TextureDirty pass further
1977 // down, which always follows a rebuild (markAllDirty()).
1978 const auto addTextureProperty = [&](const QByteArray &name, const QByteArray &samplerType,
1979 QQuick3DShaderUtilsTextureInput *texInput, int pid) {
1980 if (texInput)
1981 texInput->name = name;
1982 QSSGRenderCustomMaterial::TextureProperty textureData;
1983 textureData.texInput = texInput;
1984 textureData.name = name;
1985 textureData.shaderDataType = QSSGRenderShaderValue::Texture;
1986 textureData.pid = pid;
1987 uniforms.append({ samplerType, name });
1988 customMaterial->m_textureProperties.push_back(textureData);
1989 };
1990
1991 // Dynamic properties are not covered by the tracker, so changes to those
1992 // TextureInputs have to be watched here.
1993 const auto addDynamicTextureInput = [&](const QByteArray &name, QQuick3DShaderUtilsTextureInput *texInput) {
1994 addTextureProperty(name, samplerTypeName(texInput->texture()), texInput, -1);
1995 if (newBackendNode) {
1996 connect(texInput, &QQuick3DShaderUtilsTextureInput::enabledChanged,
1997 this, &QQuick3DCustomMaterial::onTextureDirty);
1998 connect(texInput, &QQuick3DShaderUtilsTextureInput::textureChanged,
1999 this, &QQuick3DCustomMaterial::onTextureDirty);
2000 } // else already connected
2001 };
2002
2003 // The ShaderImage and ShaderStorageBuffer properties are watched by
2004 // m_shaderResources rather than by the tracker, and extractProperties() only
2005 // re-reads dirty properties, so have it re-read them on every rebuild to pick up
2006 // one that gained or lost its object.
2007 for (int pid : m_shaderResources.resourceProperties())
2008 addDirtyProperty(pid);
2009
2010 // The tracker discovers all user-declared properties and watches them, including
2011 // the textures (and TextureInputs) they refer to. The sampler type was determined
2012 // by the tracker from the texture.
2013 QByteArrayList metadata;
2014 for (const auto &prop : extractProperties()) {
2015 switch (prop.shaderDataType) {
2016 case QSSGRenderShaderValue::Texture:
2017 addTextureProperty(prop.name, prop.typeName, resolveTexture(prop.pid).texInput, prop.pid);
2018 break;
2019 case QSSGRenderShaderValue::StorageBuffer: {
2020 const QVariant value = metaObject()->property(prop.pid).read(this);
2021 needsSecondaryUpdate |= !handleBufferProperty(value.value<QQuick3DShaderStorageBuffer *>(), prop.name,
2022 prop.pid, metadata, customMaterial->m_properties);
2023 break;
2024 }
2025 case QSSGRenderShaderValue::Image: {
2026 const QVariant value = metaObject()->property(prop.pid).read(this);
2027 needsSecondaryUpdate |= !handleImageProperty(value.value<QQuick3DShaderImage *>(), prop.name,
2028 prop.pid, metadata, customMaterial->m_properties);
2029 break;
2030 }
2031 default:
2032 uniforms.append({ prop.typeName, prop.name });
2033 customMaterial->m_properties.push_back(prop);
2034 break;
2035 }
2036 }
2037
2038 static const QMetaMethod onResourceDirty = staticMetaObject.method(staticMetaObject.indexOfSlot("onShaderResourceDirty()"));
2039 m_shaderResources.trackProperties(staticMetaObject.propertyCount(), onResourceDirty);
2040
2041 if (customMaterial->incompleteBuildTimeObject || (m_dirtyAttributes & DynamicPropertiesDirty)) { // This object came from the shadergen tool
2042 const auto names = dynamicPropertyNames();
2043 for (const auto &name : names) {
2044 QVariant propValue = property(name.constData());
2045 QMetaType propType = propValue.metaType();
2046 if (propType == QMetaType(QMetaType::QVariant))
2047 propType = propValue.metaType();
2048
2049 if (propType.id() >= QMetaType::User) {
2050 if (propType.id() == qMetaTypeId<QQuick3DShaderUtilsTextureInput *>()) {
2051 if (auto *texInput = propValue.value<QQuick3DShaderUtilsTextureInput *>())
2052 addDynamicTextureInput(name, texInput);
2053 }
2054 } else if (propType.id() == QMetaType::QObjectStar) {
2055 if (auto *texInput = qobject_cast<QQuick3DShaderUtilsTextureInput *>(propValue.value<QObject *>()))
2056 addDynamicTextureInput(name, texInput);
2057 } else {
2058 const auto type = uniformType(propType);
2059 if (type != QSSGRenderShaderValue::Unknown) {
2060 uniforms.append({ uniformTypeName(propType), name });
2061 customMaterial->m_properties.push_back({ name, uniformTypeName(propType), propValue,
2062 uniformType(propType), -1 /* aka. dynamic property */});
2063 } else {
2064 qWarning("No known uniform conversion found for custom material property %s. Skipping", name.constData());
2065 }
2066 }
2067 }
2068 }
2069
2070 const QQmlContext *context = qmlContext(this);
2071 QByteArray vertex;
2072 QByteArray fragment;
2073 QByteArray vertexProcessed[2];
2074 QSSGCustomShaderMetaData vertexMeta;
2075 QByteArray fragmentProcessed[2];
2076 QSSGCustomShaderMetaData fragmentMeta;
2077 QByteArray shaderPathKey("custom material --");
2078
2079 customMaterial->m_renderFlags = {};
2080
2081 if (!m_vertexShader.isEmpty())
2082 vertex = QSSGShaderUtils::resolveShader(m_vertexShader, context, shaderPathKey);
2083 else if (!m_vertexShaderCode.isEmpty())
2084 vertex = m_vertexShaderCode.toLatin1();
2085
2086 if (!m_fragmentShader.isEmpty())
2087 fragment = QSSGShaderUtils::resolveShader(m_fragmentShader, context, shaderPathKey);
2088 else if (!m_fragmentShaderCode.isEmpty())
2089 fragment = m_fragmentShaderCode.toLatin1();
2090
2091 if (!vertex.isEmpty()) {
2092 if (!processMetadata(customMaterial->m_properties, metadata, vertexMeta.imageBufferMetadata, vertex)) {
2093 qWarning("CustomMaterial: Shader Image and/or Buffer processing failed in vertex shader.");
2094 // Leave nothing pending, so that the next change triggers an update again.
2095 m_dirtyAttributes = 0;
2096 return customMaterial;
2097 }
2098 }
2099 if (!fragment.isEmpty()) {
2100 if (!processMetadata(customMaterial->m_properties, metadata, fragmentMeta.imageBufferMetadata, fragment)) {
2101 qWarning("CustomMaterial: Shader Image and/or Buffer processing failed in fragment shader.");
2102 // Leave nothing pending, so that the next change triggers an update again.
2103 m_dirtyAttributes = 0;
2104 return customMaterial;
2105 }
2106 }
2107
2108 // Multiview is a problem, because we will get a dedicated snippet after
2109 // preparation (the one that has [qt_viewIndex] added where it matters).
2110 // But at least the view count plays no role here on this level. So one
2111 // normal and one multiview "variant" is good enough.
2112
2113 vertexProcessed[QSSGRenderCustomMaterial::RegularShaderPathKeyIndex] =
2114 prepareCustomShader(customMaterial, uniforms, vertex, QSSGShaderCache::ShaderType::Vertex, vertexMeta, false);
2115 fragmentProcessed[QSSGRenderCustomMaterial::RegularShaderPathKeyIndex] =
2116 prepareCustomShader(customMaterial, uniforms, fragment, QSSGShaderCache::ShaderType::Fragment, fragmentMeta, false);
2117
2118 vertexProcessed[QSSGRenderCustomMaterial::MultiViewShaderPathKeyIndex] =
2119 prepareCustomShader(customMaterial, uniforms, vertex, QSSGShaderCache::ShaderType::Vertex, vertexMeta, true);
2120 fragmentProcessed[QSSGRenderCustomMaterial::MultiViewShaderPathKeyIndex] =
2121 prepareCustomShader(customMaterial, uniforms, fragment, QSSGShaderCache::ShaderType::Fragment, fragmentMeta, true);
2122
2123 // At this point we have snippets that look like this:
2124 // - the original code, with VARYING ... lines removed
2125 // - followed by QQ3D_SHADER_META block for uniforms
2126 // - followed by QQ3D_SHADER_META block for inputs/outputs
2127
2128 customMaterial->m_customShaderPresence = {};
2129 for (int i : { QSSGRenderCustomMaterial::RegularShaderPathKeyIndex, QSSGRenderCustomMaterial::MultiViewShaderPathKeyIndex }) {
2130 if (vertexProcessed[i].isEmpty() && fragmentProcessed[i].isEmpty())
2131 continue;
2132
2133 const QByteArray key = shaderPathKey + ':' + QCryptographicHash::hash(QByteArray(vertexProcessed[i] + fragmentProcessed[i]), QCryptographicHash::Algorithm::Sha1).toHex();
2134 // the processed snippet code is different for regular and multiview, so 'key' reflects that already
2135 customMaterial->m_shaderPathKey[i] = key;
2136 if (!vertexProcessed[i].isEmpty()) {
2137 customMaterial->m_customShaderPresence.setFlag(QSSGRenderCustomMaterial::CustomShaderPresenceFlag::Vertex);
2138 renderContext->shaderLibraryManager()->setShaderSource(key, QSSGShaderCache::ShaderType::Vertex, vertexProcessed[i], vertexMeta);
2139 }
2140 if (!fragmentProcessed[i].isEmpty()) {
2141 customMaterial->m_customShaderPresence.setFlag(QSSGRenderCustomMaterial::CustomShaderPresenceFlag::Fragment);
2142 renderContext->shaderLibraryManager()->setShaderSource(key, QSSGShaderCache::ShaderType::Fragment, fragmentProcessed[i], fragmentMeta);
2143 }
2144 }
2145 }
2146
2147 customMaterial->setAlwaysDirty(m_alwaysDirty);
2148 if (m_srcBlend != BlendMode::NoBlend && m_dstBlend != BlendMode::NoBlend) { // both must be set to something other than NoBlend
2149 customMaterial->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Blending, true);
2150 customMaterial->m_srcBlend = toRhiBlendFactor(m_srcBlend);
2151 customMaterial->m_dstBlend = toRhiBlendFactor(m_dstBlend);
2152 // alpha blending is only active if rgb blending is
2153 if (m_srcAlphaBlend != BlendMode::NoBlend && m_dstAlphaBlend != BlendMode::NoBlend) {
2154 customMaterial->m_srcAlphaBlend = toRhiBlendFactor(m_srcAlphaBlend);
2155 customMaterial->m_dstAlphaBlend = toRhiBlendFactor(m_dstAlphaBlend);
2156 } else {
2157 customMaterial->m_srcAlphaBlend = customMaterial->m_srcBlend;
2158 customMaterial->m_dstAlphaBlend = customMaterial->m_dstBlend;
2159 }
2160 } else {
2161 customMaterial->m_renderFlags.setFlag(QSSGRenderCustomMaterial::RenderFlag::Blending, false);
2162 }
2163 customMaterial->m_lineWidth = m_lineWidth;
2164
2165 QQuick3DMaterial::updateSpatialNode(customMaterial);
2166
2167 if (m_dirtyAttributes & Dirty::PropertyDirty) {
2168 // Refresh the values of the tracked properties in place. Dynamic properties
2169 // (pid -1) are not tracked and keep the values recorded when they were added.
2170 const auto props = extractProperties();
2171 for (auto &prop : customMaterial->m_properties) {
2172 if (prop.pid < 0)
2173 continue;
2174 // The value of an image or buffer property is the render side object, not the
2175 // tracker's value. A rebuild has just resolved it.
2176 if (prop.shaderDataType == QSSGRenderShaderValue::StorageBuffer
2177 || prop.shaderDataType == QSSGRenderShaderValue::Image) {
2178 if (newBackendNode || shadersMayChange)
2179 continue;
2180 const QVariant value = metaObject()->property(prop.pid).read(this);
2181 if (prop.shaderDataType == QSSGRenderShaderValue::StorageBuffer)
2182 updateBufferProperty(value.value<QQuick3DShaderStorageBuffer *>(), prop);
2183 else
2184 updateImageProperty(value.value<QQuick3DShaderImage *>(), prop);
2185 continue;
2186 }
2187 const auto it = std::lower_bound(props.cbegin(), props.cend(), prop.pid,
2188 [](const QSSGBaseTypeProperty &p, int pid) { return p.pid < pid; });
2189 if (it != props.cend() && it->pid == prop.pid)
2190 prop.value = it->value;
2191 }
2192 // A swapped-in object may not have been referenced into the scene yet.
2193 if (!newBackendNode && !shadersMayChange)
2194 needsSecondaryUpdate |= !m_shaderResources.updateResources();
2195 }
2196
2197 if (m_dirtyAttributes & Dirty::TextureDirty) {
2198 // Let the tracker process the pending reference changes first, so that its watchers
2199 // (e.g. for the creation of the texture backend node) follow a replaced texture.
2200 extractProperties();
2201
2202 for (QSSGRenderCustomMaterial::TextureProperty &prop : customMaterial->m_textureProperties) {
2203 // Tracked properties are re-read, since both the TextureInput and the texture may
2204 // have been replaced. Dynamic properties always go through their TextureInput.
2205 QQuick3DTexture *tex = nullptr;
2206 if (prop.pid >= 0) {
2207 const ResolvedTexture resolved = resolveTexture(prop.pid);
2208 prop.texInput = resolved.texInput;
2209 tex = resolved.texture;
2210 } else if (prop.texInput) {
2211 tex = prop.texInput->texture();
2212 }
2213 const bool enabled = !prop.texInput || prop.texInput->enabled;
2214
2215 if (tex) {
2216 prop.texImage = enabled ? tex->getRenderImage() : nullptr;
2217 prop.minFilterType = tex->minFilter() == QQuick3DTexture::Nearest ? QSSGRenderTextureFilterOp::Nearest
2218 : QSSGRenderTextureFilterOp::Linear;
2219 prop.magFilterType = tex->magFilter() == QQuick3DTexture::Nearest ? QSSGRenderTextureFilterOp::Nearest
2220 : QSSGRenderTextureFilterOp::Linear;
2221 prop.mipFilterType = tex->generateMipmaps() ? (tex->mipFilter() == QQuick3DTexture::Nearest ? QSSGRenderTextureFilterOp::Nearest
2222 : QSSGRenderTextureFilterOp::Linear)
2223 : QSSGRenderTextureFilterOp::None;
2224 prop.horizontalClampType = tex->horizontalTiling() == QQuick3DTexture::Repeat ? QSSGRenderTextureCoordOp::Repeat
2225 : (tex->horizontalTiling() == QQuick3DTexture::ClampToEdge) ? QSSGRenderTextureCoordOp::ClampToEdge
2226 : QSSGRenderTextureCoordOp::MirroredRepeat;
2227 prop.verticalClampType = tex->verticalTiling() == QQuick3DTexture::Repeat ? QSSGRenderTextureCoordOp::Repeat
2228 : (tex->verticalTiling() == QQuick3DTexture::ClampToEdge) ? QSSGRenderTextureCoordOp::ClampToEdge
2229 : QSSGRenderTextureCoordOp::MirroredRepeat;
2230 prop.zClampType = tex->depthTiling() == QQuick3DTexture::Repeat ? QSSGRenderTextureCoordOp::Repeat
2231 : (tex->depthTiling() == QQuick3DTexture::ClampToEdge) ? QSSGRenderTextureCoordOp::ClampToEdge
2232 : QSSGRenderTextureCoordOp::MirroredRepeat;
2233 } else {
2234 prop.texImage = nullptr;
2235 }
2236
2237 if (tex != prop.lastConnectedTexture) {
2238 prop.lastConnectedTexture = tex;
2239 disconnect(prop.minFilterChangedConn);
2240 disconnect(prop.magFilterChangedConn);
2241 disconnect(prop.mipFilterChangedConn);
2242 disconnect(prop.horizontalTilingChangedConn);
2243 disconnect(prop.verticalTilingChangedConn);
2244 disconnect(prop.depthTilingChangedConn);
2245 if (tex) {
2246 prop.minFilterChangedConn = connect(tex, &QQuick3DTexture::minFilterChanged, this, &QQuick3DCustomMaterial::onTextureDirty);
2247 prop.magFilterChangedConn = connect(tex, &QQuick3DTexture::magFilterChanged, this, &QQuick3DCustomMaterial::onTextureDirty);
2248 prop.mipFilterChangedConn = connect(tex, &QQuick3DTexture::mipFilterChanged, this, &QQuick3DCustomMaterial::onTextureDirty);
2249 prop.horizontalTilingChangedConn = connect(tex, &QQuick3DTexture::horizontalTilingChanged, this, &QQuick3DCustomMaterial::onTextureDirty);
2250 prop.verticalTilingChangedConn = connect(tex, &QQuick3DTexture::verticalTilingChanged, this, &QQuick3DCustomMaterial::onTextureDirty);
2251 prop.depthTilingChangedConn = connect(tex, &QQuick3DTexture::depthTilingChanged, this, &QQuick3DCustomMaterial::onTextureDirty);
2252 }
2253 }
2254 }
2255 }
2256
2257 m_dirtyAttributes = 0;
2258 if (needsSecondaryUpdate) {
2259 markDirty(*this, Dirty::ShaderSettingsDirty);
2260 QQuick3DObjectPrivate::get(this)->requestSecondaryUpdate();
2261 }
2262
2263 return customMaterial;
2264}
2265
2266void QQuick3DCustomMaterial::itemChange(QQuick3DObject::ItemChange change, const QQuick3DObject::ItemChangeData &value)
2267{
2268 QQuick3DMaterial::itemChange(change, value);
2269 if (change == QQuick3DObject::ItemSceneChange) {
2270 updateTrackedSceneManager(value.sceneManager);
2271 if (auto sceneManager = value.sceneManager) {
2272 for (const auto &it : std::as_const(m_dynamicTextureMaps)) {
2273 if (auto tex = it->texture())
2274 QQuick3DObjectPrivate::refSceneManager(tex, *sceneManager);
2275 }
2276 } else {
2277 for (const auto &it : std::as_const(m_dynamicTextureMaps)) {
2278 if (auto tex = it->texture())
2279 QQuick3DObjectPrivate::derefSceneManager(tex);
2280 }
2281 }
2282 m_shaderResources.updateSceneManager(value.sceneManager);
2283 }
2284}
2285
2286void QQuick3DCustomMaterial::onTextureDirty()
2287{
2288 markDirty(*this, Dirty::TextureDirty);
2289 update();
2290}
2291
2292void QQuick3DCustomMaterial::onShaderResourceDirty()
2293{
2294 // Swapping one object for another only changes the binding, but a property
2295 // gaining or losing its object, or an image of another format, changes the
2296 // generated shader.
2297 markDirty(*this, m_shaderResources.hasResourceLayoutChanged() ? Dirty::ShaderSettingsDirty : Dirty::PropertyDirty);
2298}
2299
2300void QQuick3DCustomMaterial::setDynamicTextureMap(QQuick3DShaderUtilsTextureInput *textureMap)
2301{
2302 // There can only be one texture input per property, as the texture input is a combination
2303 // of the texture used and the uniform name!
2304 auto it = m_dynamicTextureMaps.constFind(textureMap);
2305
2306 if (it == m_dynamicTextureMaps.constEnd()) {
2307 // Track the object, if it's destroyed we need to remove it from our table.
2308 connect(textureMap, &QQuick3DShaderUtilsTextureInput::destroyed, this, [this, textureMap]() {
2309 auto it = m_dynamicTextureMaps.constFind(textureMap);
2310 if (it != m_dynamicTextureMaps.constEnd())
2311 m_dynamicTextureMaps.erase(it);
2312 });
2313 m_dynamicTextureMaps.insert(textureMap);
2314
2315 update();
2316 }
2317}
2318
2319QT_END_NAMESPACE
Combined button and popup list for selecting options.
static QByteArray prepareCustomShader(QSSGRenderCustomMaterial *customMaterial, const QSSGShaderCustomMaterialAdapter::StringPairList &uniforms, const QByteArray &snippet, QSSGShaderCache::ShaderType shaderType, QSSGCustomShaderMetaData &meta, bool multiViewCompatible)
static QT_BEGIN_NAMESPACE QRhiGraphicsPipeline::BlendFactor toRhiBlendFactor(QQuick3DCustomMaterial::BlendMode mode)
\qmlproperty url CustomMaterial::vertexShader
static void setCustomMaterialFlagsFromShader(QSSGRenderCustomMaterial *material, const QSSGCustomShaderMetaData &meta)