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
qquick3dquadtextureprovider.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include <QtQuick3DRuntimeRender/private/qssgshadermaterialadapter_p.h>
8
9#include <ssg/qssgrenderextensions.h>
10#include <ssg/qssgrenderhelpers.h>
11#include <ssg/qssgrendercontextcore.h>
12#include <ssg/qquick3dextensionhelpers.h>
13
14
15/*!
16 \qmltype QuadTextureProvider
17 \nativetype QQuick3DQuadTextureProvider
18 \inqmlmodule QtQuick3D.Helpers
19 \inherits TextureProviderExtension
20 \since 6.12
21 \brief Used to render a quad texture using a custom fragment shader.
22
23 This type is used to render quad textures using custom shader code, enabling a convenient way
24 to get programmable textures. By providing a fragment shader and wanted properties, a pass is created
25 and a shader pipeline is built based on the provided data, passing the properties in as uniform values
26 to the fragment shader.
27
28 Built-ins provided:
29
30 \table
31 \header
32 \li Keyword
33 \li Type
34 \li Description
35 \row
36 \li MAIN
37 \li
38 \li void MAIN() is the entry point. This function must always be present in the fragment shader provided.
39 \row
40 \li INPUT_UV
41 \li vec2
42 \li UV coordinates for current fragment. Top-right: [1, 1] and bottom-left: [0, 0].
43 \row
44 \li OUTPUT_SIZE
45 \li vec2
46 \li Size of the output texture.
47 \row
48 \endtable
49
50 Custom properties gets mapped to uniforms. Any time the values change, the updated
51 value will become visible in the shader. This concept may already be familiar from \l ShaderEffect.
52
53 The name of the QML property and the GLSL variable must match. There is no separate
54 declaration in the shader code for the individual uniforms. Rather, the QML property name
55 can be used as-is.
56
57 The following table lists how the types are mapped:
58
59 \table
60 \header
61 \li QML Type
62 \li Shader Type
63 \li Notes
64 \row
65 \li real, int, bool
66 \li float, int, bool
67 \li
68 \row
69 \li color
70 \li vec4
71 \li sRGB to linear conversion is performed implicitly
72 \row
73 \li vector2d
74 \li vec2
75 \li
76 \row
77 \li vector3d
78 \li vec3
79 \li
80 \row
81 \li vector4d
82 \li vec4
83 \li
84 \row
85 \li matrix4x4
86 \li mat4
87 \li
88 \row
89 \li quaternion
90 \li vec4
91 \li scalar value is \c w
92 \row
93 \li rect
94 \li vec4
95 \li
96 \row
97 \li point, size
98 \li vec2
99 \li
100 \row
101 \li TextureInput
102 \li sampler2D
103 \li
104 \endtable
105
106 An example of outputting a simple red texture could be done the following way:
107 \badcode
108 Texture {
109 textureProvider: QuadTextureProvider {
110 width: 128
111 height: 128
112 fragmentShaderCode: `
113 void MAIN() {
114 FRAGCOLOR = vec4(1.0, 0.0, 0.0, 1.0);
115 }
116 `
117 }
118 }
119 \endcode
120
121 Another example sampling from a \l Texture property and mixing with UV colors:
122 \badcode
123 Texture {
124 textureProvider: QuadTextureProvider {
125 fragmentShaderCode: `
126 void MAIN() {
127 vec2 uv = INPUT_UV;
128 vec4 c = texture(checkers, uv);
129 FRAGCOLOR = mix(c, vec4(uv, 1, 1), 0.5);
130 }`
131
132 property Texture checkers : Texture {
133 source: "../shared/maps/checkers2.png"
134 }
135 }
136 }
137 \endcode
138
139 The result is the following:
140 \image quadtextureprovider_checkers.webp
141 {2x2 grid of gradient-filled cells in teal, white, blue, and
142 magenta}
143
144 \note Providing a vertex shader is not supported, only a fragment shader.
145
146 \note If \l Texture properties are provided it will not render until the dependent textures are available.
147
148 \note There is currently no support for adding / removing properties at runtime, just modifying the original ones.
149
150 \sa ShaderEffect
151 */
152
153/*!
154 \qmlproperty url QuadTextureProvider::fragmentShader
155 \since 6.12
156
157 Specifies the file with the snippet of custom fragment shader code.
158
159 The value is a URL and must either be a local file or use the qrc scheme to
160 access files embedded via the Qt resource system. Relative file paths
161 (without a scheme) are also accepted, in which case the file is treated as
162 relative to the component (the \c{.qml} file).
163
164 \warning Shader snippets are assumed to be trusted content. Application
165 developers are advised to carefully consider the potential implications
166 before allowing the loading of user-provided content that is not part of the
167 application.
168
169 \note If set, fragmentShaderCode will take precedence over fragmentShader.
170
171 \sa fragmentShaderCode
172*/
173
174/*!
175 \qmlproperty string QuadTextureProvider::fragmentShaderCode
176 \since 6.12
177
178 Specifies a snippet of custom fragment shader code.
179
180 Used as a way to inline shader code as a string instead of providing a file.
181
182 \note If set, this property will take precedence over \l fragmentShader.
183
184 \sa fragmentShader
185*/
186
187/*!
188 \qmlproperty int QuadTextureProvider::width
189 \since 6.12
190 \default 128
191
192 Specifies the width in pixels of the output texture.
193
194 \sa height
195*/
196
197/*!
198 \qmlproperty int QuadTextureProvider::height
199 \since 6.12
200 \default 128
201
202 Specifies the height in pixels of the output texture.
203
204 \sa width
205*/
206
207/*!
208 \qmlproperty enumeration QuadTextureProvider::format
209 \since 6.12
210 \default TexureData.RGBA16F
211
212 This property holds the format of the output texture.
213
214 \value TexureData.RGBA8 The color format is considered as 8-bit integer in R, G, B and alpha channels.
215 \value TexureData.RGBA16F The color format is considered as 16-bit float in R,G,B and alpha channels.
216 \value TexureData.RGBA32F The color format is considered as 32-bit float in R, G, B and alpha channels.
217 \value TexureData.RGBE8 The color format is considered as 8-bit mantissa in the R, G, and B channels and 8-bit shared exponent.
218 \value TexureData.R8 The color format is considered as 8-bit integer in R channel.
219 \value TexureData.R16 The color format is considered as 16-bit integer in R channel.
220 \value TexureData.R16F The color format is considered as 16-bit float in R channel.
221 \value TexureData.R32F The color format is considered as 32-bit float R channel.
222
223 \note With the exception of \c TexureData.RGBA8, not every format is supported at runtime as this
224 depends on which backend is being used as well which hardware is being used.
225*/
226
228
229static constexpr float g_vertexData[] = { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
230 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f };
231
232static constexpr uint16_t g_indexData[] = { 0, 1, 2, 0, 2, 3 };
233
235void main()
236{
237 qt_inputUV = attr_uv;
238 gl_Position = vec4(attr_pos, 0.0, 1.0);
239}
240)";
241
243void main()
244{
245 qt_inputUV = attr_uv;
246 qt_inputUV.y = 1.0 - qt_inputUV.y;
247 gl_Position = vec4(attr_pos, 0.0, 1.0);
248}
249)";
250
252void main()
253{
254 qt_customMain();
255}
256)";
257
259void MAIN()
260{
261 FRAGCOLOR = vec4(1.0, 0.0, 1.0, 1.0);
262}
263)";
264
265static inline void insertVertexMainArgs(QByteArray &snippet)
266{
267 static const char *argKey = "/*%QT_ARGS_MAIN%*/";
268 const int argKeyLen = int(strlen(argKey));
269 const int argKeyPos = snippet.indexOf(argKey);
270 if (argKeyPos >= 0)
271 snippet = snippet.left(argKeyPos) + QByteArrayLiteral("inout vec3 VERTEX") + snippet.mid(argKeyPos + argKeyLen);
272}
273
274namespace {
275
276QRhiTexture::Format rhiTextureFormatFromTextureDataFormat(QQuick3DTextureData::Format format)
277{
278 switch (format) {
279 case QQuick3DTextureData::RGBA8:
280 return QRhiTexture::Format::RGBA8;
281 case QQuick3DTextureData::RGBA16F:
282 return QRhiTexture::Format::RGBA16F;
283 case QQuick3DTextureData::RGBA32F:
284 return QRhiTexture::Format::RGBA32F;
285 case QQuick3DTextureData::RGBE8:
286 return QRhiTexture::Format::RGBA8;
287 case QQuick3DTextureData::R8:
288 return QRhiTexture::Format::R8;
289 case QQuick3DTextureData::R16:
290 return QRhiTexture::Format::R16;
291 case QQuick3DTextureData::R16F:
292 return QRhiTexture::Format::R16F;
293 case QQuick3DTextureData::R32F:
294 return QRhiTexture::Format::R32F;
295 default:
296 return QRhiTexture::Format::RGBA8;
297 }
298 Q_UNREACHABLE_RETURN(QRhiTexture::Format::RGBA8);
299}
300
301QByteArray generateFinalVertexShaderCode(QRhi *rhi,
302 QSSGShaderCustomMaterialAdapter::StringPairList uniforms,
303 QSSGShaderCustomMaterialAdapter::StringPairList varyings)
304{
305 // Handle d3d flipped textures
306 const bool doFlip = rhi->isYUpInNDC() && !rhi->isYUpInFramebuffer();
307 QByteArray vertexShader = doFlip ? mainVertexSnippetFlipped : mainVertexSnippet;
308
309 QByteArrayList metadata;
310 QSSGShaderCustomMaterialAdapter::ShaderCodeAndMetaData result;
311 QByteArray buf;
312 QSSGShaderCustomMaterialAdapter::CustomShaderPrepWorkData scratch;
313 QSSGShaderCustomMaterialAdapter::beginPrepareCustomShader(&scratch, &result, vertexShader, QSSGShaderCache::ShaderType::Vertex, false);
314 QSSGShaderCustomMaterialAdapter::finishPrepareCustomShader(&buf,
315 scratch,
316 result,
317 QSSGShaderCache::ShaderType::Vertex,
318 false,
319 uniforms,
320 metadata,
321 { },
322 varyings,
323 { },
324 { });
325 insertVertexMainArgs(result.first);
326 return result.first + buf;
327}
328
329QByteArray generateFinalFragmentShaderCode(const QByteArray &baseFragmentShaderCode,
330 QSSGShaderCustomMaterialAdapter::StringPairList uniforms,
331 QSSGShaderCustomMaterialAdapter::StringPairList varyings)
332{
333 QSSGShaderCustomMaterialAdapter::ShaderCodeAndMetaData result;
334 QByteArray buf;
335 QByteArrayList metadata;
336 QSSGShaderCustomMaterialAdapter::CustomShaderPrepWorkData scratch;
337 QSSGShaderCustomMaterialAdapter::beginPrepareCustomShader(&scratch, &result, baseFragmentShaderCode, QSSGShaderCache::ShaderType::Fragment, false);
338 QSSGShaderCustomMaterialAdapter::finishPrepareCustomShader(&buf,
339 scratch,
340 result,
341 QSSGShaderCache::ShaderType::Fragment,
342 false,
343 uniforms,
344 metadata,
345 varyings,
346 { },
347 { },
348 { });
349 return result.first + buf;
350}
351
352QSSGRhiShaderPipelinePtr compileShader(QSSGRenderContextInterface *sgContext,
353 const QByteArray &shaderPathKey,
354 const QByteArray &vertexShader,
355 const QByteArray &fragmentShader)
356{
357 QSSGProgramGenerator *generator = sgContext->shaderProgramGenerator().get();
358 QSSGShaderLibraryManager *shaderLib = sgContext->shaderLibraryManager().get();
359 QSSGShaderCache *shaderCache = sgContext->shaderCache().get();
360
361 generator->beginProgram();
362 auto vertex = generator->getStage(QSSGShaderGeneratorStage::Vertex);
363 vertex->addIncoming("attr_pos", "vec2");
364 vertex->addIncoming("attr_uv", "vec2");
365 vertex->append(vertexShader);
366
367 generator->getStage(QSSGShaderGeneratorStage::Fragment)->append(fragmentShader);
368
369 QSSGShaderFeatures features;
370 const QByteArray key = shaderPathKey + ':'
371 + QCryptographicHash::hash(QByteArray(vertexShader + fragmentShader), QCryptographicHash::Algorithm::Sha1)
372 .toHex();
373 return generator->compileGeneratedRhiShader(key, features, *shaderLib, *shaderCache, QSSGRhiShaderPipeline::UsedWithoutIa, { }, 1, false);
374}
375
376} // namespace
377
379{
380public:
383 bool prepareData(QSSGFrameData &data) override;
384 void prepareRender(QSSGFrameData &data) override;
385 void render(QSSGFrameData &data) override;
387
389
393 int width = 128;
394 int height = 128;
395
396 QByteArray shaderPathKey = "quad texture provider --";
397
398private:
399 QPointer<QQuick3DQuadTextureProvider> m_ext;
400
401 QSSGRhiShaderResourceBindingList m_srbBindings;
402 QSSGRhiShaderPipelinePtr m_shaderPipeline;
403
404 std::unique_ptr<QRhiBuffer> m_vertexBuffer;
405 std::unique_ptr<QRhiBuffer> m_indexBuffer;
406
407 std::unique_ptr<QRhiTexture> m_outputTexture;
408 std::unique_ptr<QRhiTexture> m_outputTextureOld;
409 std::unique_ptr<QRhiTextureRenderTarget> m_renderTarget;
410 std::unique_ptr<QRhiRenderPassDescriptor> m_renderPassDesc;
411
412 std::unique_ptr<QRhiGraphicsPipeline> m_graphicsPipeline;
413 QRhiShaderResourceBindings* m_srb = nullptr; // not owned
414};
415
417
419
420bool QSSGQuadTextureProvider::prepareData(QSSGFrameData &data)
421{
422 QSSGRenderContextInterface *ctxIfx = data.contextInterface();
423 auto bufferManager = ctxIfx->bufferManager().get();
424 QSSGRhiContext *rhiCtx = ctxIfx->rhiContext().get();
425 if (!rhiCtx)
426 return false;
427
428 QSSGExtensionId extensionId = m_ext ? QQuick3DExtensionHelpers::getExtensionId(*m_ext) : QSSGExtensionId { };
429 if (QQuick3DExtensionHelpers::isNull(extensionId))
430 return false;
431
432 // TODO: should know if new properties are added or removed
433 bool needsRebuild = false;
434 if (dirtyFlag & QQuick3DQuadTextureProvider::Dirty::Dimensions)
435 needsRebuild = true;
436 if (dirtyFlag & QQuick3DQuadTextureProvider::Dirty::Format)
437 needsRebuild = true;
438 if (dirtyFlag & QQuick3DQuadTextureProvider::Dirty::FragmentShader)
439 needsRebuild = true;
440 if (m_shaderPipeline && !needsRebuild)
441 return dirtyFlag & QQuick3DQuadTextureProvider::Dirty::TrackedProperty;
442
443 if (!m_shaderPipeline || dirtyFlag & QQuick3DQuadTextureProvider::Dirty::FragmentShader) {
444 // Run through all inputs and if any texture is not created yet wait until next frame.
445 // The problem with textures not created yet is that they are assumed to be sampler2DArray in glsl but
446 // that could cause shader compilation failures so we need to know the actual type before trying to compile.
447 for (const auto &u : std::as_const(propertyUniforms)) {
448 if (u.shaderDataType == QSSGRenderShaderValue::Texture) {
449 QSSGRenderImage *image = u.value.value<QSSGRenderImage *>();
450 const QSSGRenderImageTexture texture = image ? bufferManager->loadRenderImage(image) : QSSGRenderImageTexture { };
451 if (!image || !texture.m_texture) {
452 return false;
453 }
454 }
455 }
456
457 QByteArray fragmentShaderCode = (!fragmentShaderSource.isEmpty() ? fragmentShaderSource : fallbackFragmentShaderStr)
458 + mainFragmentSnippet;
459
460 QSSGShaderCustomMaterialAdapter::StringPairList baseUniforms;
461 for (const auto &u : std::as_const(propertyUniforms))
462 baseUniforms.append({ u.typeName, u.name });
463
464 baseUniforms.append({ "vec2", "qt_outputSize" });
465
466 QSSGShaderCustomMaterialAdapter::StringPairList baseInputOutputs;
467 baseInputOutputs.append({ "vec2", "qt_inputUV" });
468
469 QByteArray vertexShader = generateFinalVertexShaderCode(rhiCtx->rhi(), baseUniforms, baseInputOutputs);
470 QByteArray fragmentShader = generateFinalFragmentShaderCode(fragmentShaderCode, baseUniforms, baseInputOutputs);
471
472 QSSGRenderContextInterface *sgContext = data.contextInterface();
473
474 m_shaderPipeline = compileShader(sgContext, shaderPathKey, vertexShader, fragmentShader);
475 // If there's an issue compiling try using the fallback fragment shader. Might be something wrong with the
476 // provided fragment shader, e.g. syntax error. This avoids asserting at runtime.
477 if (!m_shaderPipeline) {
478 fragmentShaderCode = fallbackFragmentShaderStr + mainFragmentSnippet;
479 fragmentShader = generateFinalFragmentShaderCode(fragmentShaderCode, baseUniforms, baseInputOutputs);
480 m_shaderPipeline = compileShader(sgContext, shaderPathKey, vertexShader, fragmentShader);
481 }
482 }
483
484 QRhi *rhi = rhiCtx->rhi();
485
486 if (!m_outputTexture || dirtyFlag & QQuick3DQuadTextureProvider::Dirty::Dimensions
487 || dirtyFlag & QQuick3DQuadTextureProvider::Dirty::Format) {
488 // Workaround: Preserve the previous texture until the end of the frame.
489 //
490 // QuadTextureProviders are rendered sequentially. If recreating the output
491 // texture destroys the old QRhiTexture immediately, consumers that have not
492 // rendered yet may still hold a pointer to the previous texture, resulting in
493 // a dangling reference during the current frame.
494 //
495 // By the next frame, surfaceChanged() will have propagated and consumers are
496 // expected to have updated to the new texture. The old texture is then released
497 // in resetForFrame().
498 if (m_outputTexture)
499 m_outputTextureOld = std::move(m_outputTexture);
500 m_outputTexture.reset(rhi->newTexture(rhiTextureFormatFromTextureDataFormat(format), QSize(width, height), 1, QRhiTexture::RenderTarget));
501 m_outputTexture->create();
502
503 m_renderTarget.reset(rhi->newTextureRenderTarget({ m_outputTexture.get() }));
504 m_renderPassDesc.reset(m_renderTarget->newCompatibleRenderPassDescriptor());
505 m_renderTarget->setRenderPassDescriptor(m_renderPassDesc.get());
506 m_renderTarget->create();
507
508 QSSGRenderExtensionHelpers::registerRenderResult(data, extensionId, m_outputTexture.get());
509
510 m_graphicsPipeline.reset();
511 }
512
513 return true;
514}
515
516void QSSGQuadTextureProvider::prepareRender(QSSGFrameData &data)
517{
518 QSSGRenderContextInterface *ctxIfx = data.contextInterface();
519 QSSGRhiContext *rhiCtx = ctxIfx->rhiContext().get();
520 if (!rhiCtx || !m_shaderPipeline)
521 return;
522
523 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
524 QRhi *rhi = rhiCtx->rhi();
525
526 QSSGRhiDrawCallData *dcd = &rhiCtxD->drawCallData({ (void *)this, nullptr, nullptr, nullptr, 0 });
527 if (!dcd->ubuf) {
528 const int uniformStride = rhiCtx->rhi()->ubufAligned(m_shaderPipeline->ub0Size());
529 dcd->ubuf = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, uniformStride);
530 dcd->ubuf->create();
531 }
532
533 const bool trackedPropertyDirty = dirtyFlag & QQuick3DQuadTextureProvider::Dirty::TrackedProperty;
534 const bool dimensionsDirty = dirtyFlag & QQuick3DQuadTextureProvider::Dirty::Dimensions;
535 const bool pipelineDirty = !m_graphicsPipeline || (dirtyFlag & QQuick3DQuadTextureProvider::Dirty::Format)
536 || (dirtyFlag & QQuick3DQuadTextureProvider::Dirty::FragmentShader);
537 // SRB only needs rebuild when texture bindings may have changed
538 const bool srbDirty = pipelineDirty || trackedPropertyDirty || !m_srb;
539
540 // Update uniforms / textures
541 if (trackedPropertyDirty || dimensionsDirty) {
542
543 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
544
545 if (trackedPropertyDirty) {
546 // rebuild transient texture list
547 m_shaderPipeline->resetExtraTextures();
548
549 QSSGBufferManager *bufferManager = ctxIfx->bufferManager().get();
550
551 for (const auto &u : std::as_const(propertyUniforms)) {
552 m_shaderPipeline->setShaderResources(ubufData, *bufferManager, u.name, u.value, u.shaderDataType);
553 }
554 }
555
556 if (dimensionsDirty) {
557 m_shaderPipeline->setUniformValue(ubufData, "qt_outputSize", QVector2D(width, height), QSSGRenderShaderValue::Vec2);
558 }
559 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
560 }
561
562 // Static geometry (create once)
563 if (!m_vertexBuffer && !m_indexBuffer) {
564 // 1 quad (2 trianges), pos + uv. 4 vertices, 5 values each (x, y, z, u, v)
565 m_vertexBuffer.reset(rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, 5 * 4 * sizeof(float)));
566 m_vertexBuffer->create();
567
568 // 6 indexes (2 triangles)
569 m_indexBuffer.reset(rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::IndexBuffer, 6 * sizeof(uint16_t)));
570 m_indexBuffer->create();
571 QRhiResourceUpdateBatch *updates = rhi->nextResourceUpdateBatch();
572 updates->uploadStaticBuffer(m_vertexBuffer.get(), g_vertexData);
573 updates->uploadStaticBuffer(m_indexBuffer.get(), g_indexData);
574 rhiCtx->commandBuffer()->resourceUpdate(updates);
575 }
576
577 // SRB rebuild
578 if (srbDirty) {
579 rhiCtxD->releaseCachedSrb(m_srbBindings);
580 m_srbBindings = QSSGRhiShaderResourceBindingList();
581 m_srbBindings.addUniformBuffer(0, QRhiShaderResourceBinding::FragmentStage, dcd->ubuf);
582
583 // Add textures (mostly copy pasta from addOpaqueDepthPrePassBindings())
584 int maxSamplerBinding = -1;
585 QVector<QShaderDescription::InOutVariable> samplerVars = m_shaderPipeline->fragmentStage()->shader().description().combinedImageSamplers();
586 for (const QShaderDescription::InOutVariable &var :
587 m_shaderPipeline->vertexStage()->shader().description().combinedImageSamplers()) {
588 auto it = std::find_if(samplerVars.cbegin(), samplerVars.cend(), [&var](const QShaderDescription::InOutVariable &v) {
589 return var.binding == v.binding;
590 });
591 if (it == samplerVars.cend())
592 samplerVars.append(var);
593 }
594 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars))
595 maxSamplerBinding = qMax(maxSamplerBinding, var.binding);
596
597 if (maxSamplerBinding >= 0) {
598 // custom property textures
599 int customTexCount = m_shaderPipeline->extraTextureCount();
600 for (int i = 0; i < customTexCount; ++i) {
601 const QSSGRhiTexture &t(m_shaderPipeline->extraTextureAt(i));
602 const int samplerBinding = m_shaderPipeline->bindingForTexture(t.name);
603 if (samplerBinding >= 0) {
604 QRhiSampler *sampler = rhiCtx->sampler(t.samplerDesc);
605 m_srbBindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, t.texture, sampler);
606 }
607 }
608 }
609
610 m_srb = rhiCtxD->srb(m_srbBindings);
611 }
612
613 // Graphics pipeline rebuild
614 if (pipelineDirty) {
615
616 m_graphicsPipeline.reset(rhi->newGraphicsPipeline());
617 m_graphicsPipeline->setShaderStages({ *m_shaderPipeline->vertexStage(), *m_shaderPipeline->fragmentStage() });
618
619 // 2 Attributes, Position (vec3) + UV (vec2)
620 QRhiVertexInputLayout inputLayout;
621 inputLayout.setBindings({ { 5 * sizeof(float) } });
622 inputLayout.setAttributes({ { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
623 { 0, 1, QRhiVertexInputAttribute::Float2, 3 * sizeof(float) } });
624 m_graphicsPipeline->setVertexInputLayout(inputLayout);
625 m_graphicsPipeline->setShaderResourceBindings(m_srb);
626 m_graphicsPipeline->setRenderPassDescriptor(m_renderPassDesc.get());
627
628 m_graphicsPipeline->create();
629 }
630
631 dirtyFlag = 0;
632}
633
634void QSSGQuadTextureProvider::render(QSSGFrameData &data)
635{
636 const auto &ctxIfx = data.contextInterface();
637 const auto &rhiCtx = ctxIfx->rhiContext();
638 if (!rhiCtx)
639 return;
640
641 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
642 cb->debugMarkBegin(QByteArrayLiteral("Quick3D Quad Texture Provider"));
643
644 cb->beginPass(m_renderTarget.get(), Qt::transparent, { 1.0f, 0 }, nullptr, rhiCtx->commonPassFlags());
645 cb->setViewport(QRhiViewport(0, 0, width, height));
646 cb->setScissor(QRhiScissor(0, 0, width, height));
647
648 cb->setGraphicsPipeline(m_graphicsPipeline.get());
649
650 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx.get());
651 auto srb = rhiCtxD->srb(m_srbBindings);
652 cb->setShaderResources(srb);
653
654 QRhiCommandBuffer::VertexInput vb(m_vertexBuffer.get(), 0);
655 cb->setVertexInput(0, 1, &vb, m_indexBuffer.get(), QRhiCommandBuffer::IndexFormat::IndexUInt16);
656 cb->drawIndexed(6);
657 cb->endPass();
658
659 cb->debugMarkEnd();
660
661}
662
664 m_outputTextureOld.reset();
665}
666
667QQuick3DQuadTextureProvider::QQuick3DQuadTextureProvider(QQuick3DObject *parent)
668 : QQuick3DTextureProviderExtension(parent)
669 , QQuick3DPropertyChangedTracker(this, QQuick3DSuperClassInfo<QQuick3DQuadTextureProvider>())
670{
671}
672
673QQuick3DQuadTextureProvider::~QQuick3DQuadTextureProvider() { }
674
675QSSGRenderGraphObject *QQuick3DQuadTextureProvider::updateSpatialNode(QSSGRenderGraphObject *node)
676{
677 auto n = static_cast<QSSGQuadTextureProvider *>(node);
678
679 if (!n) {
680 n = new QSSGQuadTextureProvider(this);
681 }
682
683 if (m_dirtyFlag & Dirty::Dimensions) {
684 n->width = m_width;
685 n->height = m_height;
686 }
687
688 if (m_dirtyFlag & Dirty::Format)
689 n->format = m_format;
690
691 if (m_dirtyFlag & Dirty::FragmentShader) {
692 const QQmlContext *context = qmlContext(this);
693 n->fragmentShaderSource = !m_fragmentShaderCode.isEmpty() ? m_fragmentShaderCode.toUtf8()
694 : !m_fragmentShader.isEmpty() ? QSSGShaderUtils::resolveShader(m_fragmentShader, context, n->shaderPathKey)
695 : QByteArray();
696 }
697
698 if (m_dirtyFlag & Dirty::TrackedProperty) {
699 n->propertyUniforms = extractProperties();
700 }
701
702 if (m_dirtyFlag != 0)
703 emit surfaceChanged();
704
705 n->dirtyFlag = m_dirtyFlag;
706 m_dirtyFlag = 0;
707
708 return n;
709}
710
711void QQuick3DQuadTextureProvider::itemChange(ItemChange change, const ItemChangeData &value)
712{
713 QQuick3DTextureProviderExtension::itemChange(change, value);
714 if (change == ItemSceneChange)
715 updateTrackedSceneManager(value.sceneManager);
716}
717
718void QQuick3DQuadTextureProvider::markTrackedPropertyDirty(QMetaProperty property, DirtyPropertyHint hint)
719{
720 Q_UNUSED(property);
721 Q_UNUSED(hint);
722 markDirty(Dirty::TrackedProperty);
723}
724
725void QQuick3DQuadTextureProvider::markDirty(Dirty v)
726{
727 m_dirtyFlag |= v;
728 update();
729}
730
731QUrl QQuick3DQuadTextureProvider::fragmentShader() const
732{
733 return m_fragmentShader;
734}
735
736void QQuick3DQuadTextureProvider::setFragmentShader(const QUrl &newFragmentShader)
737{
738 if (m_fragmentShader == newFragmentShader)
739 return;
740 m_fragmentShader = newFragmentShader;
741 emit fragmentShaderChanged();
742 markDirty(Dirty::FragmentShader);
743}
744
745QString QQuick3DQuadTextureProvider::fragmentShaderCode() const
746{
747 return m_fragmentShaderCode;
748}
749
750void QQuick3DQuadTextureProvider::setFragmentShaderCode(const QString &newFragmentShaderCode)
751{
752 if (m_fragmentShaderCode == newFragmentShaderCode)
753 return;
754 m_fragmentShaderCode = newFragmentShaderCode;
755 emit fragmentShaderCodeChanged();
756 markDirty(Dirty::FragmentShader);
757}
758
759
760int QQuick3DQuadTextureProvider::width() const
761{
762 return m_width;
763}
764
765void QQuick3DQuadTextureProvider::setWidth(int newWidth)
766{
767 newWidth = qMax(1, newWidth);
768 if (m_width == newWidth)
769 return;
770 m_width = newWidth;
771 emit widthChanged();
772 markDirty(Dirty::Dimensions);
773}
774
775int QQuick3DQuadTextureProvider::height() const
776{
777 return m_height;
778}
779
780void QQuick3DQuadTextureProvider::setHeight(int newHeight)
781{
782 newHeight = qMax(1, newHeight);
783 if (m_height == newHeight)
784 return;
785 m_height = newHeight;
786 emit heightChanged();
787 markDirty(Dirty::Dimensions);
788}
789
790QQuick3DTextureData::Format QQuick3DQuadTextureProvider::format() const
791{
792 return m_format;
793}
794
795void QQuick3DQuadTextureProvider::setFormat(QQuick3DTextureData::Format newFormat)
796{
797 if (m_format == newFormat)
798 return;
799 m_format = newFormat;
800 emit formatChanged();
801 markDirty(Dirty::Format);
802}
803
804QT_END_NAMESPACE
QSSGQuadTextureProvider(QQuick3DQuadTextureProvider *ext)
void render(QSSGFrameData &data) override
Record the render pass.
QList< QSSGBaseTypeProperty > propertyUniforms
QQuick3DQuadTextureProvider::DirtyT dirtyFlag
void prepareRender(QSSGFrameData &data) override
Prepare data for rendering.
void resetForFrame() override
Called each time a new frame starts.
bool prepareData(QSSGFrameData &data) override
Called after scene data is collected, but before any render data or rendering in the current frame ha...
QQuick3DTextureData::Format format
Combined button and popup list for selecting options.
static const QByteArray mainVertexSnippet
static const QByteArray mainFragmentSnippet
static const QByteArray fallbackFragmentShaderStr
static constexpr uint16_t g_indexData[]
static QT_BEGIN_NAMESPACE constexpr float g_vertexData[]
\qmltype QuadTextureProvider \nativetype QQuick3DQuadTextureProvider \inqmlmodule QtQuick3D....
static void insertVertexMainArgs(QByteArray &snippet)
static const QByteArray mainVertexSnippetFlipped