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
qssgrhicustommaterialsystem.cpp
Go to the documentation of this file.
1// Copyright (C) 2008-2012 NVIDIA Corporation.
2// Copyright (C) 2019 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6
8
9#include <QtQuick3DUtils/private/qssgutils_p.h>
10
12#include <QtQuick3DRuntimeRender/private/qssgrenderbuffermanager_p.h>
13#include <QtQuick3DRuntimeRender/private/qssgrendermesh_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgrendercamera_p.h>
15#include <QtQuick3DRuntimeRender/private/qssgrenderlight_p.h>
16#include <QtQuick3DRuntimeRender/private/qssgrenderlayer_p.h>
17#include <QtQuick3DRuntimeRender/private/qssgrenderableimage_p.h>
18#include <QtQuick3DRuntimeRender/private/qssgvertexpipelineimpl_p.h>
19#include <QtQuick3DRuntimeRender/private/qssglayerrenderdata_p.h>
20#include <QtQuick3DRuntimeRender/private/qssgrendermodel_p.h>
21#include <QtQuick3DRuntimeRender/private/qssgruntimerenderlogging_p.h>
22#include <QtQuick3DRuntimeRender/private/qssgrhiparticles_p.h>
23#include <QtQuick3DRuntimeRender/private/qssgrenderhelpers_p.h>
24#include <QtQuick3DRuntimeRender/private/qssgrenderbuffer_p.h>
25#include <qtquick3d_tracepoints_p.h>
26
27#include <QtCore/qbitarray.h>
28
30
31Q_TRACE_POINT(qtquick3d, QSSG_generateShader_entry)
32Q_TRACE_POINT(qtquick3d, QSSG_generateShader_exit)
33
34QSSGCustomMaterialSystem::QSSGCustomMaterialSystem() = default;
35
36QSSGCustomMaterialSystem::~QSSGCustomMaterialSystem()
37{
38}
39
40bool QSSGCustomMaterialSystem::prepareForRender(const QSSGRenderModel &,
41 const QSSGRenderSubset &,
42 QSSGRenderCustomMaterial &inMaterial)
43{
44 return inMaterial.isDirty();
45}
46
47void QSSGCustomMaterialSystem::setRenderContextInterface(QSSGRenderContextInterface *inContext)
48{
49 context = inContext;
50}
51
52void QSSGCustomMaterialSystem::releaseCachedResources()
53{
54 shaderMap.clear();
55}
56
57QSSGRhiShaderPipelinePtr QSSGCustomMaterialSystem::shadersForCustomMaterial(QSSGRhiGraphicsPipelineState *ps,
58 const QSSGRenderCustomMaterial &material,
59 QSSGSubsetRenderable &renderable,
60 const QSSGShaderDefaultMaterialKeyProperties &defaultMaterialShaderKeyProperties,
61 const QSSGShaderFeatures &featureSet,
62 const QSSGUserShaderAugmentation &shaderAugmentation)
63{
64 QElapsedTimer timer;
65 timer.start();
66
67 QSSGRhiShaderPipelinePtr shaderPipeline;
68
69 const bool multiView = featureSet.isSet(QSSGShaderFeatures::Feature::DisableMultiView)
70 ? false
71 : defaultMaterialShaderKeyProperties.m_viewCount.getValue(renderable.shaderDescription) >= 2;
72 const QByteArray &baseShaderPathKey = material.m_shaderPathKey[multiView ? QSSGRenderCustomMaterial::MultiViewShaderPathKeyIndex
73 : QSSGRenderCustomMaterial::RegularShaderPathKeyIndex];
74 const QByteArray shaderPathKey = shaderAugmentation.hasUserAugmentation()
75 ? baseShaderPathKey + ':' + shaderAugmentation.hash
76 : baseShaderPathKey;
77
78 // This just references inFeatureSet and inRenderable.shaderDescription -
79 // cheap to construct and is good enough for the find(). This is the first
80 // level, fast lookup. (equivalent to what
81 // QSSGRenderer::getShaderPipelineForDefaultMaterial does for the
82 // default/principled material)
83 QSSGShaderMapKey skey = QSSGShaderMapKey(shaderPathKey,
84 featureSet,
85 renderable.shaderDescription);
86 auto it = shaderMap.find(skey);
87 if (it == shaderMap.end()) {
88 // This is also passed to generateMaterialRhiShader() so that newly
89 // generated shaders get stored in the caches under the same key.
90 QByteArray shaderString = shaderPathKey;
91 QSSGShaderDefaultMaterialKey matKey(renderable.shaderDescription);
92 matKey.toString(shaderString, defaultMaterialShaderKeyProperties);
93 for (const auto &def : shaderAugmentation.defines)
94 shaderString.append(def.name).append(';').append(def.value).append(';');
95
96 // Try the persistent (disk-based) cache.
97 const QByteArray qsbcKey = QQsbCollection::EntryDesc::generateSha(shaderString, QQsbCollection::toFeatureSet(featureSet));
98 shaderPipeline = context->shaderCache()->tryNewPipelineFromPersistentCache(qsbcKey, shaderString, featureSet);
99
100 if (!shaderPipeline) {
101 // Have to generate the shaders and send it all through the shader conditioning pipeline.
102 Q_TRACE_SCOPE(QSSG_generateShader);
103 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DGenerateShader);
104 QSSGMaterialVertexPipeline vertexPipeline(*context->shaderProgramGenerator(),
105 defaultMaterialShaderKeyProperties,
106 material.adapter);
107
108 shaderPipeline = QSSGMaterialShaderGenerator::generateMaterialRhiShader(shaderPathKey,
109 shaderString,
110 vertexPipeline,
111 renderable.shaderDescription,
112 defaultMaterialShaderKeyProperties,
113 featureSet,
114 material,
115 *context->shaderLibraryManager(),
116 *context->shaderCache(),
117 shaderAugmentation);
118 Q_QUICK3D_PROFILE_END_WITH_ID(QQuick3DProfiler::Quick3DGenerateShader, 0, material.profilingId);
119 }
120
121 // make skey useable as a key for the QHash (makes a copy of the materialKey, instead of just referencing)
122 skey.detach();
123 // insert it no matter what, no point in trying over and over again
124 shaderMap.insert(skey, shaderPipeline);
125 } else {
126 shaderPipeline = it.value();
127 }
128
129 if (shaderPipeline) {
130 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(*ps, shaderPipeline.get());
131 shaderPipeline->resetExtraTextures();
132 }
133
134 QSSGRhiContextStats::get(*context->rhiContext()).registerMaterialShaderGenerationTime(timer.elapsed());
135
136 return shaderPipeline;
137}
138
139void QSSGCustomMaterialSystem::updateUniformsForCustomMaterial(QSSGRhiShaderPipeline &shaderPipeline,
140 QSSGRhiContext *rhiCtx,
141 const QSSGLayerRenderData &inData,
142 char *ubufData,
143 QSSGRhiGraphicsPipelineState *ps,
144 const QSSGRenderCustomMaterial &material,
145 QSSGSubsetRenderable &renderable,
146 const QSSGRenderCameraList &cameras,
147 const QVector2D *depthAdjust,
148 const QMatrix4x4 *alteredModelViewProjection)
149{
150 QSSGRenderMvpArray alteredMvpList;
151 if (alteredModelViewProjection)
152 alteredMvpList[0] = *alteredModelViewProjection;
153
154 const QMatrix4x4 clipSpaceCorrMatrix = rhiCtx->rhi()->clipSpaceCorrMatrix();
155 QRhiTexture *lightmapTexture = inData.getLightmapTexture(renderable.modelContext);
156
157 const auto &modelNode = renderable.modelContext.model;
158 const auto &[localInstanceTransform, globalInstanceTransform] = inData.getInstanceTransforms(modelNode);
159
160 const auto &defaultMaterialShaderKeyProperties = inData.getDefaultMaterialPropertyTable();
161
162 const QMatrix4x4 &modelMatrix(modelNode.usesBoneTexture() ? QMatrix4x4() : renderable.modelContext.globalTransform);
163
164 QSSGMaterialShaderGenerator::setRhiMaterialProperties(*context,
165 shaderPipeline,
166 ubufData,
167 ps,
168 material,
169 renderable.shaderDescription,
170 defaultMaterialShaderKeyProperties,
171 cameras,
172 alteredModelViewProjection ? alteredMvpList : renderable.modelContext.modelViewProjections,
173 renderable.modelContext.normalMatrix,
174 modelMatrix,
175 clipSpaceCorrMatrix,
176 localInstanceTransform,
177 globalInstanceTransform,
178 toDataView(modelNode.morphWeights),
179 renderable.firstImage,
180 renderable.opacity,
181 inData,
182 renderable.lights,
183 renderable.reflectionProbe,
184 true,
185 renderable.renderableFlags.receivesReflections(),
186 depthAdjust,
187 lightmapTexture);
188}
189
191 QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
192
193void QSSGCustomMaterialSystem::rhiPrepareRenderable(QSSGRhiGraphicsPipelineState *ps,
194 QSSGPassKey passKey,
195 QSSGSubsetRenderable &renderable,
196 const QSSGShaderFeatures &featureSet,
197 const QSSGRenderCustomMaterial &material,
198 const QSSGLayerRenderData &layerData,
199 QRhiRenderPassDescriptor *renderPassDescriptor,
200 int samples,
201 int viewCount,
202 bool screenMapPass,
203 QSSGRenderCamera *alteredCamera,
204 QSSGRenderTextureCubeFace cubeFace,
205 QMatrix4x4 *alteredModelViewProjection,
206 QSSGReflectionMapEntry *entry,
207 bool oit)
208{
209 QSSGRhiContext *rhiCtx = context->rhiContext().get();
210
211 QRhiGraphicsPipeline::TargetBlend blend; // no blending by default
212 if (material.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Blending)) {
213 blend.enable = true;
214 blend.srcColor = material.m_srcBlend;
215 blend.srcAlpha = material.m_srcAlphaBlend;
216 blend.dstColor = material.m_dstBlend;
217 blend.dstAlpha = material.m_dstAlphaBlend;
218 }
219
220 const QSSGCullFaceMode cullMode = material.m_cullMode;
221
222 const auto &defaultMaterialShaderKeyProperties = layerData.getDefaultMaterialPropertyTable();
223
224 const bool blendParticles = defaultMaterialShaderKeyProperties.m_blendParticles.getValue(renderable.shaderDescription);
225
226 const auto &shaderPipeline = shadersForCustomMaterial(ps, material, renderable, defaultMaterialShaderKeyProperties, featureSet);
227
228 if (shaderPipeline) {
229 QSSGRhiShaderResourceBindingList bindings;
230 const auto &modelNode = renderable.modelContext.model;
231
232 // NOTE:
233 // - entryIdx should 0 for QSSGRenderTextureCubeFaceNone (and a null entry).
234 // In all other cases the entryIdx is a combination of the cubeface idx and the subset
235 // offset, where the lower bits are the cubeface idx. The per-probe reflection map
236 // entry, if any, goes in the key's mapEntry slot. The key's resource must be the
237 // material itself, and nothing but the material, since
238 // cleanupDrawCallDataForResource() releases the entries for a to-be-destroyed
239 // material by matching on the resource.
240 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
241 const quintptr entryIdx = quintptr(cubeFace != QSSGRenderTextureCubeFaceNone)
242 * (cubeFaceIdx + (quintptr(renderable.subset.offset) << 3));
243
244 // cleanupDrawCallDataForResource() is handed a QSSGRenderGraphObject pointer, so
245 // that is the identity the key has to carry.
246 const auto *materialResource = static_cast<const QSSGRenderGraphObject *>(&material);
247 QSSGRhiDrawCallData &dcd = QSSGRhiContextPrivate::get(rhiCtx)->drawCallData({ passKey, &modelNode,
248 materialResource, entry,
249 entryIdx });
250
251 shaderPipeline->ensureCombinedUniformBuffer(&dcd.ubuf);
252 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
253 if (!alteredCamera) {
254 updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, layerData, ubufData, ps, material, renderable, layerData.renderedCameras, nullptr, nullptr);
255 } else {
256 QSSGRenderCameraList cameras({ alteredCamera });
257 updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, layerData, ubufData, ps, material, renderable, cameras, nullptr, alteredModelViewProjection);
258 }
259 if (blendParticles)
260 QSSGParticleRenderer::updateUniformsForParticleModel(*shaderPipeline, ubufData, &renderable.modelContext.model, renderable.subset.offset);
261 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
262
263 if (blendParticles)
264 QSSGParticleRenderer::prepareParticlesForModel(*shaderPipeline, rhiCtx, bindings, &renderable.modelContext.model);
265 bool instancing = false;
266 // instancingLodMin/Max limit the instances to a range of distances in every pass. With the
267 // automatic per-instance LOD, the levels are then selected among the instances in the range.
268 if (!alteredCamera) {
269 const QSSGRenderCameraDataList &cameraDatas(*layerData.renderedCameraData);
270 instancing = QSSGLayerRenderData::prepareInstancing(rhiCtx, &renderable, cameraDatas[0].direction, cameraDatas[0].position,
271 renderable.instancingLodMin, renderable.instancingLodMax, layerData);
272 if (instancing && renderable.usesAutoLod)
273 QSSGLayerRenderData::prepareAutoLodInstancing(rhiCtx, &renderable, layerData);
274 } else {
275 // Reflection probes draw the whole table at the original level, see rhiRenderRenderable().
276 const auto &altCamTransform = layerData.getGlobalTransform(*alteredCamera);
277 instancing = QSSGLayerRenderData::prepareInstancing(rhiCtx, &renderable, QSSGRenderNode::getScalingCorrectDirection(altCamTransform), QSSGRenderNode::getGlobalPos(altCamTransform),
278 renderable.instancingLodMin, renderable.instancingLodMax, layerData);
279 }
280
281 ps->samples = samples;
282 ps->viewCount = viewCount;
283
284 ps->cullMode = QSSGRhiHelpers::toCullMode(cullMode);
285
286 if (!oit)
287 ps->targetBlend[0] = blend;
288
289 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
290
291 ia = renderable.subset.rhi.ia;
292
293 //### Copied code from default materials
294
295 // -1, not 0: 0 is a valid binding when the geometry contributes none.
296 int instanceBufferBinding = -1;
297 if (instancing) {
298 // Need to setup new bindings for instanced buffers
299 const quint32 stride = renderable.modelContext.model.instanceTable->stride();
300 QVarLengthArray<QRhiVertexInputBinding, 8> bindings;
301 std::copy(ia.inputLayout.cbeginBindings(),
302 ia.inputLayout.cendBindings(),
303 std::back_inserter(bindings));
304 bindings.append({ stride, QRhiVertexInputBinding::PerInstance });
305 instanceBufferBinding = bindings.size() - 1;
306 const bool usesInstanceIndex = shaderPipeline->instanceBufferLocations().index >= 0;
307 if (usesInstanceIndex)
308 bindings.append({ quint32(sizeof(qint32)), QRhiVertexInputBinding::PerInstance });
309 ia.inputLayout.setBindings(bindings.cbegin(), bindings.cend());
310 }
311
312 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
313
314 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
315 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
316 QRhiTexture *dummyTextureArray = rhiCtx->dummyTexture({}, resourceUpdates, QSize(64, 64), Qt::black, qMax(2, viewCount));
317 QRhiTexture *dummyTexture3D = rhiCtx->dummyTexture(QRhiTexture::ThreeDimensional, resourceUpdates);
318 QRhiTexture *dummyCubeTexture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
319 QRhiTexture *dummyCubeTextureArray = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates, QSize(64, 64), Qt::black, qMax(2, viewCount));
320
321 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
322
323 bindings.addUniformBuffer(0, CUSTOM_MATERIAL_VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline->ub0Size());
324 bindings.addUniformBuffer(1, CUSTOM_MATERIAL_VISIBILITY_ALL, dcd.ubuf, shaderPipeline->ub0LightDataOffset(), sizeof(QSSGShaderLightsUniformData));
325 bindings.addUniformBuffer(2, CUSTOM_MATERIAL_VISIBILITY_ALL, dcd.ubuf, shaderPipeline->ub0DirectionalLightDataOffset(), sizeof(QSSGShaderDirectionalLightsUniformData));
326
327 QVector<QShaderDescription::InOutVariable> samplerVars =
328 shaderPipeline->fragmentStage()->shader().description().combinedImageSamplers();
329 const auto combinedSamplers = shaderPipeline->vertexStage()->shader().description().combinedImageSamplers();
330 for (const QShaderDescription::InOutVariable &var : combinedSamplers) {
331 auto it = std::find_if(samplerVars.cbegin(), samplerVars.cend(),
332 [&var](const QShaderDescription::InOutVariable &v) { return var.binding == v.binding; });
333 if (it == samplerVars.cend())
334 samplerVars.append(var);
335 }
336
337 int maxSamplerBinding = -1;
338 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars))
339 maxSamplerBinding = qMax(maxSamplerBinding, var.binding);
340
341 // Will need to set unused image-samplers to something dummy
342 // because the shader code contains all custom property textures,
343 // and not providing a binding for all of them is invalid with some
344 // graphics APIs (and will need a real texture because setting a
345 // null handle or similar is not permitted with some of them so the
346 // srb does not accept null QRhiTextures either; but first let's
347 // figure out what bindings are unused in this frame)
348 QBitArray samplerBindingsSpecified(maxSamplerBinding + 1);
349
350 if (blendParticles)
351 samplerBindingsSpecified.setBit(shaderPipeline->bindingForTexture("qt_particleTexture"));
352
353 // Skinning
354 if (QRhiTexture *boneTexture = layerData.getBonemapTexture(renderable.modelContext)) {
355 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
356 if (binding >= 0) {
357 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
358 QRhiSampler::Nearest,
359 QRhiSampler::None,
360 QRhiSampler::ClampToEdge,
361 QRhiSampler::ClampToEdge,
362 QRhiSampler::Repeat
363 });
364 bindings.addTexture(binding,
365 QRhiShaderResourceBinding::VertexStage,
366 boneTexture,
367 boneSampler);
368 samplerBindingsSpecified.setBit(binding);
369 }
370 }
371
372 // Morphing
373 auto *targetsTexture = renderable.subset.rhi.targetsTexture;
374 if (targetsTexture) {
375 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
376 if (binding >= 0) {
377 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
378 QRhiSampler::Nearest,
379 QRhiSampler::None,
380 QRhiSampler::ClampToEdge,
381 QRhiSampler::ClampToEdge,
382 QRhiSampler::ClampToEdge
383 });
384 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, renderable.subset.rhi.targetsTexture, targetsSampler);
385 samplerBindingsSpecified.setBit(binding);
386 }
387 }
388
389 // Prioritize reflection texture over Light Probe texture because
390 // reflection texture also contains the irradiance and pre filtered
391 // values for the light probe.
392 if (featureSet.isSet(QSSGShaderFeatures::Feature::ReflectionProbe)) {
393 int reflectionSampler = shaderPipeline->bindingForTexture("qt_reflectionMap");
394 QRhiTexture* reflectionTexture = layerData.getReflectionMapManager()->reflectionMapEntry(renderable.reflectionProbeIndex)->m_rhiPrefilteredCube;
395 const auto mipMapFilter = reflectionTexture && reflectionTexture->flags().testFlag(QRhiTexture::Flag::MipMapped)
396 ? QRhiSampler::Linear
397 : QRhiSampler::None;
398 QRhiSampler *sampler = rhiCtx->sampler(
399 { QRhiSampler::Linear, QRhiSampler::Linear, mipMapFilter, QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
400 if (reflectionSampler >= 0 && reflectionTexture) {
401 bindings.addTexture(reflectionSampler, QRhiShaderResourceBinding::FragmentStage, reflectionTexture, sampler);
402 samplerBindingsSpecified.setBit(reflectionSampler);
403 }
404 }
405
406 if (int binding = shaderPipeline->bindingForTexture("qt_lightProbe", int(QSSGRhiSamplerBindingHints::LightProbe));
407 binding >= 0) {
408 auto texture = shaderPipeline->lightProbeTexture();
409 if (!texture)
410 texture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
411 Q_ASSERT(texture);
412
413 samplerBindingsSpecified.setBit(binding);
414 QPair<QSSGRenderTextureCoordOp, QSSGRenderTextureCoordOp> tiling = shaderPipeline->lightProbeTiling();
415 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
416 QRhiSampler::Linear,
417 QRhiSampler::Linear, // enables mipmapping
418 QSSGRhiHelpers::toRhi(tiling.first),
419 QSSGRhiHelpers::toRhi(tiling.second),
420 QRhiSampler::Repeat });
421 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
422 }
423
424 if (shaderPipeline->screenTexture()) {
425 const int screenTextureBinding = shaderPipeline->bindingForTexture("qt_screenTexture", int(QSSGRhiSamplerBindingHints::ScreenTexture));
426 const int screenTextureArrayBinding = shaderPipeline->bindingForTexture("qt_screenTextureArray", int(QSSGRhiSamplerBindingHints::ScreenTextureArray));
427 if (screenTextureBinding >= 0 || screenTextureArrayBinding >= 0) {
428 QRhiTexture *screenTexture = shaderPipeline->screenTexture();
429 // If we're called as part of the screen map pass there's obviously no screen texture available, but the shader may still expect it, so bind a dummy texture.
430 if (screenMapPass) {
431 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
432 // Just mirror what is set up by the ScreenMap pass.
433 const QRhiTexture::Flags flags = screenTexture->flags();
434 // and set the dummy texture so there's something for the shader to sample.
435 screenTexture = rhiCtx->dummyTexture(flags, resourceUpdates, QSize(64, 64), Qt::black, screenTexture->arraySize());
436 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
437 }
438 // linear min/mag, mipmap filtering depends on the
439 // texture, with SCREEN_TEXTURE there are no mipmaps, but
440 // once SCREEN_MIP_TEXTURE is seen the texture (the same
441 // one) has mipmaps generated.
442 QRhiSampler::Filter mipFilter = shaderPipeline->screenTexture()->flags().testFlag(QRhiTexture::MipMapped)
443 ? QRhiSampler::Linear : QRhiSampler::None;
444 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, mipFilter,
445 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
446 if (screenTextureBinding >= 0) {
447 samplerBindingsSpecified.setBit(screenTextureBinding);
448 bindings.addTexture(screenTextureBinding,
449 QRhiShaderResourceBinding::FragmentStage,
450 screenTexture, sampler);
451 }
452 if (screenTextureArrayBinding >= 0) {
453 samplerBindingsSpecified.setBit(screenTextureArrayBinding);
454 bindings.addTexture(screenTextureArrayBinding,
455 QRhiShaderResourceBinding::FragmentStage,
456 screenTexture, sampler);
457 }
458 } // else ignore, not an error
459 }
460
461 if (shaderPipeline->depthTexture()) {
462 const int depthTextureBinding = shaderPipeline->bindingForTexture("qt_depthTexture", int(QSSGRhiSamplerBindingHints::DepthTexture));
463 const int depthTextureArrayBinding = shaderPipeline->bindingForTexture("qt_depthTextureArray", int(QSSGRhiSamplerBindingHints::DepthTextureArray));
464 if (depthTextureBinding >= 0 || depthTextureArrayBinding >= 0) {
465 // nearest min/mag, no mipmap
466 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
467 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
468 if (depthTextureBinding >= 0) {
469 samplerBindingsSpecified.setBit(depthTextureBinding);
470 bindings.addTexture(depthTextureBinding,
471 CUSTOM_MATERIAL_VISIBILITY_ALL,
472 shaderPipeline->depthTexture(), sampler);
473 }
474 if (depthTextureArrayBinding >= 0) {
475 samplerBindingsSpecified.setBit(depthTextureArrayBinding);
476 bindings.addTexture(depthTextureArrayBinding,
477 CUSTOM_MATERIAL_VISIBILITY_ALL,
478 shaderPipeline->depthTexture(), sampler);
479 }
480 } // else ignore, not an error
481 }
482
483 if (shaderPipeline->normalTexture()) {
484 const int normalTextureBinding = shaderPipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
485 if (normalTextureBinding >= 0) {
486 // nearest min/mag, no mipmap
487 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
488 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
489 samplerBindingsSpecified.setBit(normalTextureBinding);
490 bindings.addTexture(normalTextureBinding, CUSTOM_MATERIAL_VISIBILITY_ALL, shaderPipeline->normalTexture(), sampler);
491 } // else ignore, not an error
492 }
493
494 if (shaderPipeline->ssaoTexture()) {
495 const int ssaoTextureBinding = shaderPipeline->bindingForTexture("qt_aoTexture", int(QSSGRhiSamplerBindingHints::AoTexture));
496 const int ssaoTextureArrayBinding = shaderPipeline->bindingForTexture("qt_aoTextureArray", int(QSSGRhiSamplerBindingHints::AoTextureArray));
497 if (ssaoTextureBinding >= 0 || ssaoTextureArrayBinding >= 0) {
498 // linear min/mag, no mipmap
499 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
500 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
501 if (ssaoTextureBinding >= 0) {
502 samplerBindingsSpecified.setBit(ssaoTextureBinding);
503 bindings.addTexture(ssaoTextureBinding,
504 QRhiShaderResourceBinding::FragmentStage,
505 shaderPipeline->ssaoTexture(), sampler);
506 }
507 if (ssaoTextureArrayBinding >= 0) {
508 samplerBindingsSpecified.setBit(ssaoTextureArrayBinding);
509 bindings.addTexture(ssaoTextureArrayBinding,
510 QRhiShaderResourceBinding::FragmentStage,
511 shaderPipeline->ssaoTexture(), sampler);
512 }
513 } // else ignore, not an error
514 }
515
516 if (shaderPipeline->lightmapTexture()) {
517 int binding = shaderPipeline->bindingForTexture("qt_lightmap", int(QSSGRhiSamplerBindingHints::LightmapTexture));
518 if (binding >= 0) {
519 samplerBindingsSpecified.setBit(binding);
520 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
521 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
522 bindings.addTexture(binding,
523 QRhiShaderResourceBinding::FragmentStage,
524 shaderPipeline->lightmapTexture(), sampler);
525 } // else ignore, not an error
526 }
527
528 if (shaderPipeline->MotionVectorTexture()) {
529 int binding = shaderPipeline->bindingForTexture("qt_motionVectorTexture", int(QSSGRhiSamplerBindingHints::MotionVectorTexture));
530 if (binding >= 0) {
531 samplerBindingsSpecified.setBit(binding);
532 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
533 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
534 bindings.addTexture(binding,
535 QRhiShaderResourceBinding::FragmentStage,
536 shaderPipeline->MotionVectorTexture(), sampler);
537
538 }
539 }
540
541 // Shadow map atlas
542 auto shadowMapAtlas = shaderPipeline->shadowMapAtlasTexture();
543 if (shadowMapAtlas) {
544 int binding = shaderPipeline->bindingForTexture("qt_shadowmap_texture");
545 if (binding >= 0) {
546 samplerBindingsSpecified.setBit(binding);
547 QRhiTexture *texture = shadowMapAtlas;
548 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
549 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
550 Q_ASSERT(texture && sampler);
551 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
552 }
553 }
554
555 // Shadow map blue noise
556 if (auto shadowMapBlueNoise = shaderPipeline->shadowMapBlueNoiseTexture()) {
557 int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture");
558 if (binding >= 0) {
559 samplerBindingsSpecified.setBit(binding);
560 QRhiTexture *texture = shadowMapBlueNoise;
561 QRhiSampler *sampler = rhiCtx->sampler(
562 { QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None, QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
563 Q_ASSERT(texture && sampler);
564 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
565 }
566 }
567
568 QSSGRenderableImage *renderableImage = renderable.firstImage;
569 while (renderableImage) {
570 const char *samplerName = QSSGMaterialShaderGenerator::getSamplerName(renderableImage->m_mapType);
571 const int samplerHint = int(renderableImage->m_mapType);
572 int samplerBinding = shaderPipeline->bindingForTexture(samplerName, samplerHint);
573 if (samplerBinding >= 0) {
574 QRhiTexture *texture = renderableImage->m_texture.m_texture;
575 if (samplerBinding >= 0 && texture) {
576 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
577 QSSGRhiSamplerDescription samplerDesc = {
578 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
579 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
580 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
581 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
582 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
583 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
584 };
585 rhiCtx->checkAndAdjustForNPoT(texture, &samplerDesc);
586 QRhiSampler *sampler = rhiCtx->sampler(samplerDesc);
587 samplerBindingsSpecified.setBit(samplerBinding);
588 bindings.addTexture(samplerBinding,
589 CUSTOM_MATERIAL_VISIBILITY_ALL,
590 texture, sampler);
591 }
592 } // else this is not necessarily an error, e.g. having metalness/roughness maps with metalness disabled
593 renderableImage = renderableImage->m_nextImage;
594 }
595
596 if (maxSamplerBinding >= 0) {
597 // custom property textures
598 int customTexCount = shaderPipeline->extraTextureCount();
599 for (int i = 0; i < customTexCount; ++i) {
600 QSSGRhiTexture &t(shaderPipeline->extraTextureAt(i));
601 const int samplerBinding = shaderPipeline->bindingForTexture(t.name);
602 if (samplerBinding >= 0) {
603 samplerBindingsSpecified.setBit(samplerBinding);
604 rhiCtx->checkAndAdjustForNPoT(t.texture, &t.samplerDesc);
605 QRhiSampler *sampler = rhiCtx->sampler(t.samplerDesc);
606 bindings.addTexture(samplerBinding,
607 CUSTOM_MATERIAL_VISIBILITY_ALL,
608 t.texture,
609 sampler);
610 }
611 }
612
613 // use a dummy texture for the unused samplers in the shader
614 QRhiSampler *dummySampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
615 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
616
617 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars)) {
618 if (!samplerBindingsSpecified.testBit(var.binding)) {
619 QRhiTexture *t = nullptr;
620 if (var.type == QShaderDescription::SamplerCube)
621 t = dummyCubeTexture;
622 else if (var.type == QShaderDescription::Sampler3D)
623 t = dummyTexture3D;
624 else if (var.type == QShaderDescription::Sampler2DArray)
625 t = dummyTextureArray;
626 else if (var.type == QShaderDescription::SamplerCubeArray)
627 t = dummyCubeTextureArray;
628 else
629 t = dummyTexture;
630 bindings.addTexture(var.binding, CUSTOM_MATERIAL_VISIBILITY_ALL, t, dummySampler);
631 }
632 }
633 }
634 shaderPipeline->applyAndClearStorageBindings(CUSTOM_MATERIAL_VISIBILITY_ALL, bindings);
635
636 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
637
638 if (oit && layerData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
639 RenderHelpers::addAccumulatorImageBindings(shaderPipeline.get(), bindings);
640
641 // do the same srb lookup acceleration as default materials
642 QRhiShaderResourceBindings *&srb = dcd.srb;
643 bool srbChanged = false;
644 if (!srb || bindings != dcd.bindings) {
645 srb = rhiCtxD->srb(bindings);
646 rhiCtxD->releaseCachedSrb(dcd.bindings);
647 dcd.bindings = bindings;
648 srbChanged = true;
649 }
650
651 if (cubeFace == QSSGRenderTextureCubeFaceNone)
652 renderable.rhiRenderData.mainPass.srb = srb;
653 else
654 renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
655
656 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
657 if (dcd.pipeline
658 && !srbChanged
659 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
660 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
661 && dcd.ps == *ps)
662 {
663 if (cubeFace == QSSGRenderTextureCubeFaceNone)
664 renderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
665 else
666 renderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
667 } else {
668 if (cubeFace == QSSGRenderTextureCubeFaceNone) {
669 renderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
670 renderPassDescriptor,
671 srb);
672 dcd.pipeline = renderable.rhiRenderData.mainPass.pipeline;
673 } else {
674 renderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
675 renderPassDescriptor,
676 srb);
677 dcd.pipeline = renderable.rhiRenderData.reflectionPass.pipeline;
678 }
679
680 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
681 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
682 dcd.ps = *ps;
683 }
684 }
685}
686
687void QSSGCustomMaterialSystem::setShaderResources(char *ubufData,
688 const QSSGRenderCustomMaterial &inMaterial,
689 const QByteArray &inPropertyName,
690 const QVariant &propertyValue,
691 QSSGRenderShaderValue::Type inPropertyType,
692 QSSGRhiShaderPipeline &shaderPipeline)
693{
694 Q_UNUSED(inMaterial);
695
696 if (inPropertyType == QSSGRenderShaderValue::Texture) {
697 QSSGRenderCustomMaterial::TextureProperty *textureProperty =
698 reinterpret_cast<QSSGRenderCustomMaterial::TextureProperty *>(propertyValue.value<void *>());
699 QSSGRenderImage *image = textureProperty->texImage;
700 if (image) {
701 const auto &theBufferManager(context->bufferManager());
702 const QSSGRenderImageTexture texture = theBufferManager->loadRenderImage(image);
703 if (texture.m_texture) {
704 const QSSGRhiTexture t = {
705 inPropertyName,
706 texture.m_texture,
707 { QSSGRhiHelpers::toRhi(textureProperty->minFilterType),
708 QSSGRhiHelpers::toRhi(textureProperty->magFilterType),
709 textureProperty->mipFilterType != QSSGRenderTextureFilterOp::None ? QSSGRhiHelpers::toRhi(textureProperty->mipFilterType) : QRhiSampler::None,
710 QSSGRhiHelpers::toRhi(textureProperty->horizontalClampType),
711 QSSGRhiHelpers::toRhi(textureProperty->verticalClampType),
712 QSSGRhiHelpers::toRhi(textureProperty->zClampType)
713 }
714 };
715 shaderPipeline.addExtraTexture(t);
716 }
717 }
718 } else if (inPropertyType == QSSGRenderShaderValue::StorageBuffer
719 || inPropertyType == QSSGRenderShaderValue::Image) {
720 shaderPipeline.setShaderResources(ubufData, *context->bufferManager(), inPropertyName, propertyValue, inPropertyType);
721 } else {
722 shaderPipeline.setUniformValue(ubufData, inPropertyName, propertyValue, inPropertyType);
723 }
724}
725
726void QSSGCustomMaterialSystem::applyRhiShaderPropertyValues(char *ubufData,
727 const QSSGRenderCustomMaterial &material,
728 QSSGRhiShaderPipeline &shaderPipeline)
729{
730 const auto &properties = material.m_properties;
731 for (const auto &prop : properties)
732 setShaderResources(ubufData, material, prop.name, prop.value, prop.shaderDataType, shaderPipeline);
733
734 const auto textProps = material.m_textureProperties;
735 for (const auto &prop : textProps)
736 setShaderResources(ubufData, material, prop.name, QVariant::fromValue((void *)&prop), prop.shaderDataType, shaderPipeline);
737}
738
739void QSSGCustomMaterialSystem::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
740 QSSGSubsetRenderable &renderable,
741 bool *needsSetViewport,
742 QSSGRenderTextureCubeFace cubeFace,
743 const QSSGRhiGraphicsPipelineState &state,
744 qsizetype userPassIndex)
745{
746 QRhiGraphicsPipeline *ps = (userPassIndex >= 0) ? renderable.rhiRenderData.userPassData[userPassIndex].pipeline : renderable.rhiRenderData.mainPass.pipeline;
747 QRhiShaderResourceBindings *srb = (userPassIndex >= 0) ? renderable.rhiRenderData.userPassData[userPassIndex].srb : renderable.rhiRenderData.mainPass.srb;
748
749 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
750 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
751 ps = renderable.rhiRenderData.reflectionPass.pipeline;
752 srb = renderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
753 }
754
755 if (!ps || !srb)
756 return;
757
758 // As in RenderHelpers::rhiRenderRenderable(), reflection cube map faces draw the full
759 // instance buffer at the original level.
760 const bool autoLod = renderable.usesAutoLod && renderable.subset.rhi.indexBuffer && cubeFace == QSSGRenderTextureCubeFaceNone;
761 if (autoLod && !RenderHelpers::anyAutoLodInstances(renderable))
762 return;
763
764 QRhiBuffer *indexBuffer = renderable.subset.rhi.indexBuffer ? renderable.subset.rhi.indexBuffer->buffer() : nullptr;
765
766 QRhiCommandBuffer::VertexInput vertexBuffers[3];
767 int vertexBufferCount = 0;
768 quint32 instances = 1;
769 if (!RenderHelpers::setupDrawInputs(rhiCtx, ps, renderable,
770 autoLod ? renderable.autoLodInstanceIndexBuffer : renderable.instanceIndexBuffer,
771 vertexBuffers, vertexBufferCount, instances))
772 return;
773
774 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
775
776 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
777 cb->setGraphicsPipeline(ps);
778 cb->setShaderResources(srb);
779
780 if (*needsSetViewport) {
781 cb->setViewport(state.viewport);
782 if (state.flags & QSSGRhiGraphicsPipelineState::Flag::UsesScissor)
783 cb->setScissor(state.scissor);
784 *needsSetViewport = false;
785 }
786
787 if (autoLod) {
788 RenderHelpers::rhiDrawAutoLodInstanced(rhiCtx, cb, vertexBuffers, vertexBufferCount, indexBuffer, renderable);
789 } else if (indexBuffer) {
790 cb->setVertexInput(0, vertexBufferCount, vertexBuffers, indexBuffer, 0, renderable.subset.rhi.indexBuffer->indexFormat());
791 cb->drawIndexed(renderable.subset.lodCount(renderable.subsetLevelOfDetail), instances, renderable.subset.lodOffset(renderable.subsetLevelOfDetail));
792 QSSGRHICTX_STAT(rhiCtx, drawIndexed(renderable.subset.lodCount(renderable.subsetLevelOfDetail), instances));
793 } else {
794 cb->setVertexInput(0, vertexBufferCount, vertexBuffers);
795 RenderHelpers::rhiDrawNonIndexed(rhiCtx, cb, renderable, instances);
796 }
797 Q_QUICK3D_PROFILE_END_WITH_IDS(QQuick3DProfiler::Quick3DRenderCall, (renderable.subset.count | quint64(instances) << 32),
798 QVector<int>({renderable.modelContext.model.profilingId,
799 renderable.material.profilingId}));
800}
801
802QT_END_NAMESPACE
Combined button and popup list for selecting options.
static const QRhiShaderResourceBinding::StageFlags CUSTOM_MATERIAL_VISIBILITY_ALL