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
qssgrenderhelpers.cpp
Go to the documentation of this file.
1// Copyright (C) 2023 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
8#include <QtQuick3DRuntimeRender/private/qssgrhiresourcehandle_p.h>
9
10#include "qssgrenderer_p.h"
12#include <QtQuick3DRuntimeRender/private/qssgrenderskymaterial_p.h>
15#include "../qssgrendercontextcore.h"
16#include "../qssgrhicustommaterialsystem_p.h"
17#include "../resourcemanager/qssgrenderbuffermanager_p.h"
18#include "../qssgrenderdefaultmaterialshadergenerator_p.h"
19#include "rendererimpl/qssgshadowmaphelpers_p.h"
20#include <QtQuick3DUtils/private/qssgassert_p.h>
21
22#include <QtGui/qquaternion.h>
23
24#include <QtCore/qbitarray.h>
25
26#include <cmath>
27
29
30static constexpr float QSSG_PI = float(M_PI);
31static constexpr float QSSG_HALFPI = float(M_PI_2);
32
34 QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
35
36static QSSGRhiShaderPipelinePtr shadersForDefaultMaterial(QSSGRhiGraphicsPipelineState *ps,
37 QSSGSubsetRenderable &subsetRenderable,
38 const QSSGShaderFeatures &featureSet,
39 const QSSGUserShaderAugmentation &shaderAugmentation = {})
40{
41 auto &renderer(subsetRenderable.renderer);
42 const auto &shaderPipeline = QSSGRendererPrivate::getShaderPipelineForDefaultMaterial(*renderer, subsetRenderable, featureSet, shaderAugmentation);
43 if (shaderPipeline) {
44 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(*ps, shaderPipeline.get());
45 // NOTE: It's not just custom materials that can have custom property textures,
46 // augmented default materials can have them too.
47 shaderPipeline->resetExtraTextures();
48 }
49 return shaderPipeline;
50}
51
52static QSSGRhiShaderPipelinePtr shadersForParticleMaterial(QSSGRhiGraphicsPipelineState *ps,
53 QSSGParticlesRenderable &particleRenderable,
54 const QSSGShaderFeatures &featureSet)
55{
56 auto &renderer(particleRenderable.renderer);
57 const auto &shaderPipeline = QSSGParticleRenderer::getShaderPipelineParticles(*renderer, particleRenderable, featureSet);
58 if (shaderPipeline)
59 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(*ps, shaderPipeline.get());
60 return shaderPipeline;
61}
62
63static void updateUniformsForDefaultMaterial(QSSGRhiShaderPipeline &shaderPipeline,
64 QSSGRhiContext *rhiCtx,
65 const QSSGLayerRenderData &inData,
66 char *ubufData,
67 QSSGRhiGraphicsPipelineState *ps,
68 QSSGSubsetRenderable &subsetRenderable,
69 const QSSGRenderCameraList &cameras,
70 const QVector2D *depthAdjust,
71 const QMatrix4x4 *alteredModelViewProjection,
72 const QSSGRenderGraphObject *materialOverride = nullptr)
73{
74 const auto &renderer(subsetRenderable.renderer);
75 const QMatrix4x4 clipSpaceCorrMatrix = rhiCtx->rhi()->clipSpaceCorrMatrix();
76 QSSGRenderMvpArray alteredMvpList;
77 if (alteredModelViewProjection)
78 alteredMvpList[0] = *alteredModelViewProjection;
79
80 const auto &modelNode = subsetRenderable.modelContext.model;
81 QRhiTexture *lightmapTexture = inData.getLightmapTexture(subsetRenderable.modelContext);
82
83 const auto &[localInstanceTransform, globalInstanceTransform] = inData.getInstanceTransforms(modelNode);
84 const QMatrix4x4 &modelMatrix(modelNode.usesBoneTexture() ? QMatrix4x4() : inData.getGlobalTransform(modelNode));
85
86 QSSGMaterialShaderGenerator::setRhiMaterialProperties(*renderer->contextInterface(),
87 shaderPipeline,
88 ubufData,
89 ps,
90 materialOverride ? *materialOverride : subsetRenderable.material,
91 subsetRenderable.shaderDescription,
92 inData.getDefaultMaterialPropertyTable(),
93 cameras,
94 alteredModelViewProjection ? alteredMvpList : subsetRenderable.modelContext.modelViewProjections,
95 subsetRenderable.modelContext.normalMatrix,
96 modelMatrix,
97 clipSpaceCorrMatrix,
98 localInstanceTransform,
99 globalInstanceTransform,
100 toDataView(modelNode.morphWeights),
101 subsetRenderable.firstImage,
102 subsetRenderable.opacity,
103 inData,
104 subsetRenderable.lights,
105 subsetRenderable.reflectionProbe,
106 subsetRenderable.renderableFlags.receivesShadows(),
107 subsetRenderable.renderableFlags.receivesReflections(),
108 depthAdjust,
109 lightmapTexture);
110}
111
112static QSSGBoxPoints computeFrustumBounds(const QMatrix4x4 &projection)
113{
114 bool invertible = false;
115 QMatrix4x4 inv = projection.inverted(&invertible);
116 Q_ASSERT(invertible);
117
118 // The frustum points will be in this orientation
119 //
120 // bottom top
121 // 4__________5 7__________6
122 // \ / \ /
123 // \ / \ /
124 // \____/ \____/
125 // 0 1 3 2
126 return { inv.map(QVector3D(-1, -1, -1)), inv.map(QVector3D(+1, -1, -1)), inv.map(QVector3D(+1, +1, -1)),
127 inv.map(QVector3D(-1, +1, -1)), inv.map(QVector3D(-1, -1, +1)), inv.map(QVector3D(+1, -1, +1)),
128 inv.map(QVector3D(+1, +1, +1)), inv.map(QVector3D(-1, +1, +1)) };
129}
130
131static QSSGBoxPoints sliceFrustum(const QSSGBoxPoints &frustumPoints, float t0, float t1)
132{
133 QSSGBoxPoints pts;
134 for (int i = 0; i < 4; ++i) {
135 const QVector3D forward = frustumPoints[i + 4] - frustumPoints[i];
136 pts[i] = frustumPoints[i] + forward * t0;
137 pts[i + 4] = frustumPoints[i] + forward * t1;
138 }
139 return pts;
140}
141
142static std::unique_ptr<QSSGRenderCamera> computeShadowCameraFromFrustum(const QMatrix4x4 &lightMatrix,
143 const QMatrix4x4 &lightMatrixInverted,
144 const QVector3D &lightPivot,
145 const QVector3D &lightForward,
146 const QVector3D &lightUp,
147 const float shadowMapResolution,
148 const float pcfRadius,
149 const QSSGBoxPoints &frustumPoints,
150 float frustumStartT,
151 float frustumEndT,
152 float frustumRadius,
153 bool lockShadowmapTexels,
154 const QSSGBounds3 &castingBox,
155 const QSSGBounds3 &receivingBox,
156 QSSGDebugDrawSystem *debugDrawSystem,
157 const bool drawCascades,
158 const bool drawSceneCascadeIntersection)
159{
160 if (!castingBox.isFinite() || castingBox.isEmpty() || !receivingBox.isFinite() || receivingBox.isEmpty())
161 return nullptr; // Return early, no casting or receiving objects means no shadows
162
163 Q_ASSERT(frustumStartT <= frustumEndT);
164 Q_ASSERT(frustumStartT >= 0.f);
165 Q_ASSERT(frustumEndT <= 1.0f);
166
167 auto transformPoints = [&](const QSSGBoxPoints &points) {
168 QSSGBoxPoints result;
169 for (int i = 0; i < int(points.size()); ++i) {
170 result[i] = lightMatrix.map(points[i]);
171 }
172 return result;
173 };
174
175 QSSGBoxPoints frustumPointsSliced = sliceFrustum(frustumPoints, frustumStartT, frustumEndT);
176 if (drawCascades)
177 ShadowmapHelpers::addDebugFrustum(frustumPointsSliced, QColorConstants::Black, debugDrawSystem);
178
179 const QList<QVector3D> receivingSliced = ShadowmapHelpers::intersectBoxByFrustum(frustumPointsSliced,
180 receivingBox.toQSSGBoxPoints(),
181 drawSceneCascadeIntersection ? debugDrawSystem : nullptr,
182 QColorConstants::DarkGray);
183 if (receivingSliced.isEmpty())
184 return nullptr;
185
186 QSSGBounds3 receivingFrustumSlicedLightSpace;
187 for (const QVector3D &point : receivingSliced)
188 receivingFrustumSlicedLightSpace.include(lightMatrix.map(point));
189
190 // Slice casting box by frustumBounds' left, right, up, down planes
191 const QList<QVector3D> castingPointsLightSpace = ShadowmapHelpers::intersectBoxByBox(receivingFrustumSlicedLightSpace,
192 transformPoints(castingBox.toQSSGBoxPointsNoEmptyCheck()));
193 if (castingPointsLightSpace.isEmpty())
194 return nullptr;
195
196 // Create box containing casting and receiving from light space:
197 QSSGBounds3 castReceiveBounds;
198 for (const QVector3D &p : castingPointsLightSpace) {
199 castReceiveBounds.include(p);
200 }
201
202 for (const QVector3D &p : receivingFrustumSlicedLightSpace.toQSSGBoxPointsNoEmptyCheck()) {
203 float zMax = qMax(p.z(), castReceiveBounds.maximum.z());
204 float zMin = qMin(p.z(), castReceiveBounds.minimum.z());
205 castReceiveBounds.maximum.setZ(zMax);
206 castReceiveBounds.minimum.setZ(zMin);
207 }
208
209 // Expand to fit pcf radius
210 castReceiveBounds.fatten(pcfRadius);
211
212 QVector3D boundsCenterWorld = lightMatrixInverted.map(castReceiveBounds.center());
213 QVector3D boundsDims = castReceiveBounds.dimensions();
214 boundsDims.setZ(boundsDims.z() * 1.01f); // Expand slightly in z direction to avoid pancaking precision errors
215
216 if (lockShadowmapTexels) {
217 // Calculate center position aligned to texel size to avoid shimmering
218 const float diam = (pcfRadius + frustumRadius) * 2.0f;
219 const float texelsPerUnit = diam / shadowMapResolution;
220 QVector3D centerLight = lightMatrix.map(boundsCenterWorld);
221 float x = centerLight.x();
222 float y = centerLight.y();
223 float z = centerLight.z();
224 centerLight = QVector3D(int(x / texelsPerUnit), int(y / texelsPerUnit), int(z / texelsPerUnit)) * texelsPerUnit;
225 boundsCenterWorld = lightMatrixInverted.map(centerLight);
226 boundsDims.setX(diam);
227 boundsDims.setY(diam);
228 } else {
229 // We expand the shadowmap to cover the bounds with one extra texel on all sides
230 const float texelExpandFactor = shadowMapResolution / (shadowMapResolution - 2);
231 boundsDims.setX(boundsDims.x() * texelExpandFactor);
232 boundsDims.setY(boundsDims.y() * texelExpandFactor);
233 }
234
235 QRectF theViewport(0.0f, 0.0f, boundsDims.x(), boundsDims.y());
236
237 auto camera = std::make_unique<QSSGRenderCamera>(QSSGRenderGraphObject::Type::OrthographicCamera);
238 camera->clipPlanes = QSSGRenderCamera::ClipPlanes{-0.5f * boundsDims.z(), 0.5f * boundsDims.z()};
239 camera->fov = QSSGRenderCamera::FieldOfView::fromDegrees(90.f);
240 camera->parent = nullptr;
241 camera->localTransform = QSSGRenderNode::calculateTransformMatrix(boundsCenterWorld,
242 QSSGRenderNode::initScale,
243 lightPivot,
244 QQuaternion::fromDirection(lightForward, lightUp));
245 QSSGRenderCamera::calculateProjectionInternal(*camera, theViewport);
246
247 return camera;
248}
249
251 const QSSGRenderCamera &inCamera,
252 const QSSGRenderLight *inLight,
253 const int shadowMapResolution,
254 const float pcfRadius,
255 const float clipNear,
256 const float clipFar,
257 const QSSGBounds3 &castingObjectsBox,
258 const QSSGBounds3 &receivingObjectsBox,
259 bool lockShadowmapTexels,
260 QSSGDebugDrawSystem *debugDrawSystem,
261 bool drawCascades,
262 bool drawSceneCascadeIntersection)
263{
264 Q_ASSERT(inLight->type == QSSGRenderLight::Type::DirectionalLight);
265 QVarLengthArray<std::unique_ptr<QSSGRenderCamera>, 4> result;
266
267 if (clipNear >= clipFar || qFuzzyCompare(clipNear, clipFar))
268 return result;
269
270 const QMatrix4x4 lightGlobalTransform = data.getGlobalTransform(*inLight);
271 const QVector3D lightDir = inLight->getDirection(lightGlobalTransform);
272 const QVector3D lightPivot = inLight->pivot;
273
274 const QVector3D forward = lightDir.normalized();
275 const QVector3D right = qFuzzyCompare(qAbs(forward.y()), 1.0f)
276 ? QVector3D::crossProduct(forward, QVector3D(1, 0, 0)).normalized()
277 : QVector3D::crossProduct(forward, QVector3D(0, 1, 0)).normalized();
278 const QVector3D up = QVector3D::crossProduct(right, forward).normalized();
279
280 QMatrix4x4 lightMatrix;
281 lightMatrix.setRow(0, QVector4D(right, 0.0f));
282 lightMatrix.setRow(1, QVector4D(up, 0.0f));
283 lightMatrix.setRow(2, QVector4D(forward, 0.0f));
284 lightMatrix.setRow(3, QVector4D(0.0f, 0.0f, 0.0f, 1.0f));
285 QMatrix4x4 lightMatrixInverted = lightMatrix.inverted();
286
287 const float farScale = (clipFar - clipNear) / (inCamera.clipPlanes.clipFar() - inCamera.clipPlanes.clipNear());
288
289 const QMatrix4x4 cameraGlobalTransform = data.getGlobalTransform(inCamera);
290 QMatrix4x4 viewProjection(Qt::Uninitialized);
291 inCamera.calculateViewProjectionMatrix(cameraGlobalTransform, viewProjection);
292 const QSSGBoxPoints frustum = computeFrustumBounds(viewProjection);
293 const QSSGBoxPoints frustumUntransformed = lockShadowmapTexels ? computeFrustumBounds(inCamera.projection) : QSSGBoxPoints();
294
295 // We calculate the radius of the cascade without rotation or translation so we always get
296 // the same floating point value.
297 const auto calcFrustumRadius = [&](float t0, float t1) -> float {
298 const QSSGBoxPoints pts = sliceFrustum(frustumUntransformed, t0 * farScale, t1 * farScale);
299
300 QVector3D center = QVector3D(0.f, 0.f, 0.f);
301 for (QVector3D point : pts) {
302 center += point;
303 }
304 center = center * 0.125f;
305
306 float radiusSquared = 0;
307 for (QVector3D point : pts) {
308 radiusSquared = qMax(radiusSquared, (point - center).lengthSquared());
309 }
310
311 return std::sqrt(radiusSquared);
312 };
313
314 const auto computeSplitRanges = [inLight](const QVarLengthArray<float, 3> &splits) -> QVarLengthArray<QPair<float, float>, 4> {
315 QVarLengthArray<QPair<float, float>, 4> ranges;
316 const float csmBlendRatio = inLight->m_csmBlendRatio;
317 float t0 = 0.f;
318 for (qsizetype i = 0; i < splits.length(); i++) {
319 const float tI = qBound(qMin(t0 + 0.01f, 1.0f), splits[i], 1.0f);
320 ranges.emplace_back(t0, qMin(1.0f, tI + csmBlendRatio));
321 t0 = tI;
322 }
323 ranges.emplace_back(t0, 1.0f);
324 return ranges;
325 };
326
327 const auto computeFrustums = [&](const QVarLengthArray<float, 3> &splits) {
328 for (const auto &range : computeSplitRanges(splits)) {
329 const float frustumRadius = lockShadowmapTexels ? calcFrustumRadius(range.first, range.second) : 0.0f;
330 auto camera = computeShadowCameraFromFrustum(lightMatrix,
331 lightMatrixInverted,
332 lightPivot,
333 forward,
334 up,
335 shadowMapResolution,
336 pcfRadius,
337 frustum,
338 range.first * farScale,
339 range.second * farScale,
340 frustumRadius,
341 lockShadowmapTexels,
342 castingObjectsBox,
343 receivingObjectsBox,
344 debugDrawSystem,
345 drawCascades,
346 drawSceneCascadeIntersection);
347 result.emplace_back(std::move(camera));
348 }
349 };
350
351 switch (inLight->m_csmNumSplits) {
352 case 0: {
353 computeFrustums({});
354 break;
355 }
356 case 1: {
357 computeFrustums({ inLight->m_csmSplit1 });
358 break;
359 }
360 case 2: {
361 computeFrustums({ inLight->m_csmSplit1, inLight->m_csmSplit2 });
362 break;
363 }
364 case 3: {
365 computeFrustums({ inLight->m_csmSplit1, inLight->m_csmSplit2, inLight->m_csmSplit3 });
366 break;
367 }
368 default:
369 Q_UNREACHABLE();
370 break;
371 }
372
373 return result;
374}
375
376static void setupCubeReflectionCameras(const QSSGLayerRenderData &inData, const QSSGRenderReflectionProbe *inProbe, QSSGRenderCamera inCameras[6])
377{
378 Q_ASSERT(inProbe != nullptr);
379
380 // setup light matrix
381 quint32 mapRes = 1 << inProbe->reflectionMapRes;
382 QRectF theViewport(0.0f, 0.0f, (float)mapRes, (float)mapRes);
383 static const QQuaternion rotOfs[6] {
384 QQuaternion::fromEulerAngles(0.f, qRadiansToDegrees(-QSSG_HALFPI), qRadiansToDegrees(QSSG_PI)),
385 QQuaternion::fromEulerAngles(0.f, qRadiansToDegrees(QSSG_HALFPI), qRadiansToDegrees(QSSG_PI)),
386 QQuaternion::fromEulerAngles(qRadiansToDegrees(QSSG_HALFPI), 0.f, 0.f),
387 QQuaternion::fromEulerAngles(qRadiansToDegrees(-QSSG_HALFPI), 0.f, 0.f),
388 QQuaternion::fromEulerAngles(0.f, qRadiansToDegrees(QSSG_PI), qRadiansToDegrees(-QSSG_PI)),
389 QQuaternion::fromEulerAngles(0.f, 0.f, qRadiansToDegrees(QSSG_PI)),
390 };
391
392 auto inProbeGlobalTranform = inData.getGlobalTransform(*inProbe);
393 const QVector3D inProbePos = QSSGRenderNode::getGlobalPos(inProbeGlobalTranform);
394 const QVector3D inProbePivot = inProbe->pivot;
395
396 for (int i = 0; i < 6; ++i) {
397 inCameras[i].parent = nullptr;
398 inCameras[i].clipPlanes = {1.0f, qMax<float>(2.0f, 10000.0f)};
399 inCameras[i].fov = QSSGRenderCamera::FieldOfView::fromDegrees(90.f);
400
401 inCameras[i].localTransform = QSSGRenderNode::calculateTransformMatrix(inProbePos, QSSGRenderNode::initScale, inProbePivot, rotOfs[i]);
402 QSSGRenderCamera::calculateProjectionInternal(inCameras[i], theViewport);
403 }
404}
405
406static void addOpaqueDepthPrePassBindings(QSSGRhiContext *rhiCtx,
407 QSSGRhiShaderPipeline *shaderPipeline,
408 QSSGRenderableImage *renderableImage,
409 QSSGRhiShaderResourceBindingList &bindings,
410 bool isCustomMaterialMeshSubset = false)
411{
412 static const auto imageAffectsAlpha = [](QSSGRenderableImage::Type mapType) {
413 return mapType == QSSGRenderableImage::Type::BaseColor ||
414 mapType == QSSGRenderableImage::Type::Diffuse ||
415 mapType == QSSGRenderableImage::Type::Translucency ||
416 mapType == QSSGRenderableImage::Type::Opacity;
417 };
418
419 while (renderableImage) {
420 const auto mapType = renderableImage->m_mapType;
421 if (imageAffectsAlpha(mapType)) {
422 const char *samplerName = QSSGMaterialShaderGenerator::getSamplerName(mapType);
423 const int samplerHint = int(mapType);
424 int samplerBinding = shaderPipeline->bindingForTexture(samplerName, samplerHint);
425 if (samplerBinding >= 0) {
426 QRhiTexture *texture = renderableImage->m_texture.m_texture;
427 if (samplerBinding >= 0 && texture) {
428 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
429 QRhiSampler *sampler = rhiCtx->sampler({ QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
430 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
431 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
432 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
433 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
434 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
435 });
436 bindings.addTexture(samplerBinding, RENDERER_VISIBILITY_ALL, texture, sampler);
437 }
438 } // else this is not necessarily an error, e.g. having metalness/roughness maps with metalness disabled
439 }
440 renderableImage = renderableImage->m_nextImage;
441 }
442 // For custom Materials we can't know which maps affect alpha, so map all
443 if (isCustomMaterialMeshSubset) {
444 QVector<QShaderDescription::InOutVariable> samplerVars =
445 shaderPipeline->fragmentStage()->shader().description().combinedImageSamplers();
446 const auto combinedSamplers = shaderPipeline->vertexStage()->shader().description().combinedImageSamplers();
447 for (const QShaderDescription::InOutVariable &var : combinedSamplers) {
448 auto it = std::find_if(samplerVars.cbegin(), samplerVars.cend(),
449 [&var](const QShaderDescription::InOutVariable &v) { return var.binding == v.binding; });
450 if (it == samplerVars.cend())
451 samplerVars.append(var);
452 }
453
454 int maxSamplerBinding = -1;
455 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars))
456 maxSamplerBinding = qMax(maxSamplerBinding, var.binding);
457
458 // Will need to set unused image-samplers to something dummy
459 // because the shader code contains all custom property textures,
460 // and not providing a binding for all of them is invalid with some
461 // graphics APIs (and will need a real texture because setting a
462 // null handle or similar is not permitted with some of them so the
463 // srb does not accept null QRhiTextures either; but first let's
464 // figure out what bindings are unused in this frame)
465 QBitArray samplerBindingsSpecified(maxSamplerBinding + 1);
466
467 if (maxSamplerBinding >= 0) {
468 // custom property textures
469 int customTexCount = shaderPipeline->extraTextureCount();
470 for (int i = 0; i < customTexCount; ++i) {
471 const QSSGRhiTexture &t(shaderPipeline->extraTextureAt(i));
472 const int samplerBinding = shaderPipeline->bindingForTexture(t.name);
473 if (samplerBinding >= 0) {
474 samplerBindingsSpecified.setBit(samplerBinding);
475 QRhiSampler *sampler = rhiCtx->sampler(t.samplerDesc);
476 bindings.addTexture(samplerBinding,
477 RENDERER_VISIBILITY_ALL,
478 t.texture,
479 sampler);
480 }
481 }
482 }
483
484 // use a dummy texture for the unused samplers in the shader
485 QRhiSampler *dummySampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
486 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
487 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
488 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
489 QRhiTexture *dummyCubeTexture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
490 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
491
492 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars)) {
493 if (!samplerBindingsSpecified.testBit(var.binding)) {
494 QRhiTexture *t = var.type == QShaderDescription::SamplerCube ? dummyCubeTexture : dummyTexture;
495 bindings.addTexture(var.binding, RENDERER_VISIBILITY_ALL, t, dummySampler);
496 }
497 }
498 }
499}
500
502 const QSSGRenderLight *inLight,
503 float shadowMapFar,
504 QSSGRenderCamera inCameras[6])
505{
506 Q_ASSERT(inLight != nullptr);
507 Q_ASSERT(inLight->type != QSSGRenderLight::Type::DirectionalLight);
508
509 // setup light matrix
510 quint32 mapRes = inLight->m_shadowMapRes;
511 QRectF theViewport(0.0f, 0.0f, (float)mapRes, (float)mapRes);
512 static const QQuaternion rotOfs[6] {
513 QQuaternion::fromEulerAngles(0.f, qRadiansToDegrees(-QSSG_HALFPI), qRadiansToDegrees(QSSG_PI)),
514 QQuaternion::fromEulerAngles(0.f, qRadiansToDegrees(QSSG_HALFPI), qRadiansToDegrees(QSSG_PI)),
515 QQuaternion::fromEulerAngles(qRadiansToDegrees(QSSG_HALFPI), 0.f, 0.f),
516 QQuaternion::fromEulerAngles(qRadiansToDegrees(-QSSG_HALFPI), 0.f, 0.f),
517 QQuaternion::fromEulerAngles(0.f, qRadiansToDegrees(QSSG_PI), qRadiansToDegrees(-QSSG_PI)),
518 QQuaternion::fromEulerAngles(0.f, 0.f, qRadiansToDegrees(QSSG_PI)),
519 };
520
521 const auto gt = inData.getGlobalTransform(*inLight);
522 const QVector3D inLightPos = QSSGRenderNode::getGlobalPos(gt);
523 constexpr QVector3D lightPivot = QVector3D(0, 0, 0);
524
525 for (int i = 0; i < 6; ++i) {
526 inCameras[i].parent = nullptr;
527 inCameras[i].clipPlanes = {1.0f, shadowMapFar};
528 inCameras[i].fov = QSSGRenderCamera::FieldOfView::fromDegrees(90.f);
529 inCameras[i].localTransform = QSSGRenderNode::calculateTransformMatrix(inLightPos, QSSGRenderNode::initScale, lightPivot, rotOfs[i]);
530 QSSGRenderCamera::calculateProjectionInternal(inCameras[i], theViewport);
531 }
532
533 /*
534 if ( inLight->type == RenderLightTypes::Point ) return;
535
536 QVector3D viewDirs[6];
537 QVector3D viewUp[6];
538 QMatrix3x3 theDirMatrix( inLight->m_GlobalTransform.getUpper3x3() );
539
540 viewDirs[0] = theDirMatrix.transform( QVector3D( 1.f, 0.f, 0.f ) );
541 viewDirs[2] = theDirMatrix.transform( QVector3D( 0.f, -1.f, 0.f ) );
542 viewDirs[4] = theDirMatrix.transform( QVector3D( 0.f, 0.f, 1.f ) );
543 viewDirs[0].normalize(); viewDirs[2].normalize(); viewDirs[4].normalize();
544 viewDirs[1] = -viewDirs[0];
545 viewDirs[3] = -viewDirs[2];
546 viewDirs[5] = -viewDirs[4];
547
548 viewUp[0] = viewDirs[2];
549 viewUp[1] = viewDirs[2];
550 viewUp[2] = viewDirs[5];
551 viewUp[3] = viewDirs[4];
552 viewUp[4] = viewDirs[2];
553 viewUp[5] = viewDirs[2];
554
555 for (int i = 0; i < 6; ++i)
556 {
557 inCameras[i].LookAt( inLightPos, viewUp[i], inLightPos + viewDirs[i] );
558 inCameras[i].CalculateGlobalVariables( theViewport, QVector2D( theViewport.m_Width,
559 theViewport.m_Height ) );
560 }
561 */
562}
563
564bool RenderHelpers::anyAutoLodInstances(const QSSGSubsetRenderable &renderable)
565{
566 for (int lod = 0; lod < renderable.autoLodLevelCount; ++lod) {
567 if (renderable.autoLodInstanceCounts[lod] > 0)
568 return true;
569 }
570 return false;
571}
572
573// The instance buffer is expected in the binding after the vertex buffer, and the rows for
574// INSTANCE_INDEX, when the pipeline has them, in the one after that, see bindInstanceIndices().
575void RenderHelpers::rhiDrawAutoLodInstanced(QSSGRhiContext *rhiCtx,
576 QRhiCommandBuffer *cb,
577 QRhiCommandBuffer::VertexInput *vertexBuffers,
578 int vertexBufferCount,
579 QRhiBuffer *indexBuffer,
580 const QSSGSubsetRenderable &renderable)
581{
582 const auto indexFormat = renderable.subset.rhi.indexBuffer->indexFormat();
583 // bindInstanceIndices() bound the rows when the pipeline reads them, or the draw was skipped.
584 const bool usesInstanceIndex = vertexBufferCount > 2;
585 const int levelCount = renderable.autoLodLevelCount;
586 // The levels are one after the other in the buffer.
587 std::array<quint32, QSSGSubsetRenderable::MaxAutoLodLevels> firstInstance {};
588 for (int lod = 1; lod < levelCount; ++lod)
589 firstInstance[lod] = firstInstance[lod - 1] + quint32(renderable.autoLodInstanceCounts[lod - 1]);
590 // Opaque instances are drawn from the nearest level to the farthest, so that the depth test
591 // rejects more of what is behind them, and semi-transparent ones the other way around, which
592 // is closer to back to front. Depth sorted tables do not get the automatic level, see
593 // usesAutoInstanceLod().
594 const bool farthestFirst = renderable.renderableFlags.hasTransparency();
595 for (int i = 0; i < levelCount; ++i) {
596 const int lod = farthestFirst ? levelCount - 1 - i : i;
597 const int cnt = renderable.autoLodInstanceCounts[lod];
598 if (cnt == 0)
599 continue;
600 const quint32 offset = firstInstance[lod] * quint32(sizeof(QSSGRenderInstanceTableEntry));
601 vertexBuffers[1] = QRhiCommandBuffer::VertexInput(renderable.autoLodBuffer, offset);
602 if (usesInstanceIndex)
603 vertexBuffers[2] = QRhiCommandBuffer::VertexInput(renderable.autoLodInstanceIndexBuffer, firstInstance[lod] * quint32(sizeof(qint32)));
604 cb->setVertexInput(0, vertexBufferCount, vertexBuffers, indexBuffer, 0, indexFormat);
605 cb->drawIndexed(renderable.subset.lodCount(lod), cnt, renderable.subset.lodOffset(lod));
606 QSSGRHICTX_STAT(rhiCtx, drawIndexed(renderable.subset.lodCount(lod), cnt));
607 }
608}
609
610// Binds a model's vertex buffers and works out the instance count, returning
611// false if nothing should be drawn. Call before Q_QUICK3D_PROFILE_START, which
612// must be matched by an end. vertexBuffers needs room for three. instanceIndexBuffer
613// is passed on to bindInstanceIndices().
614bool RenderHelpers::setupDrawInputs(QSSGRhiContext *rhiCtx,
615 QRhiGraphicsPipeline *ps,
616 const QSSGSubsetRenderable &renderable,
617 QRhiBuffer *instanceIndexBuffer,
618 QRhiCommandBuffer::VertexInput *vertexBuffers,
619 int &vertexBufferCount,
620 quint32 &instances)
621{
622 const QSSGRenderModel &model = renderable.modelContext.model;
623 instances = 1;
624 vertexBufferCount = 0;
625
626 // A ShaderGeometry has no vertex buffer; QRhi accepts binding none.
627 if (const auto &vertexBuffer = renderable.subset.rhi.vertexBuffer)
628 vertexBuffers[vertexBufferCount++] = QRhiCommandBuffer::VertexInput(vertexBuffer->buffer(), 0);
629
630 // An IndirectShaderGeometry's vertex and instance counts are on the GPU,
631 // so there is nothing to check them against here.
632 if (model.geometry && model.geometry->indirectDraw().enabled) {
633 if (model.usesInstanceBuffer()) {
634 vertexBuffers[vertexBufferCount++] = QRhiCommandBuffer::VertexInput(renderable.instanceBuffer, 0);
635 if (!bindInstanceIndices(ps, instanceIndexBuffer, vertexBuffers, &vertexBufferCount))
636 return false;
637 }
638 return renderable.indirectBuffer != nullptr;
639 }
640
641 if (!model.instancing())
642 return true;
643
644 // A zero-instance draw is invalid on Metal and likely elsewhere. A model
645 // particle system, an empty instance list, or bufferless instancing with a
646 // count of zero all arrive here.
647 const int count = model.instanceCount();
648 if (count <= 0)
649 return false;
650
651 if (!model.usesInstanceBuffer()) {
652 // Without hardware instancing the draw would collapse to one instance
653 // and gl_InstanceIndex would be unavailable, so the shader could not
654 // tell the instances apart at all.
655 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing))
656 return true;
657 } else {
658 vertexBuffers[vertexBufferCount++] = QRhiCommandBuffer::VertexInput(renderable.instanceBuffer, 0);
659 if (!bindInstanceIndices(ps, instanceIndexBuffer, vertexBuffers, &vertexBufferCount))
660 return false;
661 }
662
663 instances = quint32(count);
664 return true;
665}
666
667// Issues the draw for a subset without an index buffer, after setVertexInput().
668void RenderHelpers::rhiDrawNonIndexed(QSSGRhiContext *rhiCtx,
669 QRhiCommandBuffer *cb,
670 const QSSGSubsetRenderable &renderable,
671 quint32 instances)
672{
673 if (renderable.indirectBuffer) {
674 cb->drawIndirect(renderable.indirectBuffer, renderable.indirectOffset,
675 renderable.indirectDrawCount, renderable.indirectStride);
676 // The real counts are only known on the GPU.
677 QSSGRHICTX_STAT(rhiCtx, draw(renderable.subset.count, renderable.indirectDrawCount));
678 } else {
679 cb->draw(renderable.subset.count, instances, renderable.subset.offset);
680 QSSGRHICTX_STAT(rhiCtx, draw(renderable.subset.count, instances));
681 }
682}
683
684// Which instances a pass draws with the automatic per-instance LOD.
685enum class InstanceLevels {
686 // The levels of the instances, selected for the camera of the layer: the main render pass
687 // and the depth, normal and user passes that share its camera.
689 // The whole instance buffer at the level of the model: the shadow map, reflection probe and
690 // motion vector passes.
692};
693
694static int setupInstancing(QSSGSubsetRenderable *renderable, QSSGRhiGraphicsPipelineState *ps, QSSGRhiContext *rhiCtx,
695 const QSSGLayerRenderData &inData, const QVector3D &cameraDirection, const QVector3D &cameraPosition,
696 InstanceLevels instanceLevels, const QSSGRhiShaderPipeline &shaders)
697{
698 // TODO: non-static so it can be used from QSSGCustomMaterialSystem::rhiPrepareRenderable()?
699 // instancingLodMin/Max limit the instances to a range of distances in every pass. With the
700 // automatic per-instance LOD, the levels are then selected among the instances in the range.
701 const bool instancing = QSSGLayerRenderData::prepareInstancing(rhiCtx, renderable, cameraDirection, cameraPosition,
702 renderable->instancingLodMin, renderable->instancingLodMax,
703 inData);
704
705 if (instancing && renderable->usesAutoLod && instanceLevels == InstanceLevels::PerInstance)
706 QSSGLayerRenderData::prepareAutoLodInstancing(rhiCtx, renderable, inData);
707
708 // -1, not 0: with no vertex bindings the instance binding lands at 0.
709 int instanceBufferBinding = -1;
710 if (instancing) {
711 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
712 // set up new bindings for instanced buffers
713 const quint32 stride = renderable->modelContext.model.instanceTable->stride();
714 QVarLengthArray<QRhiVertexInputBinding, 8> bindings;
715 std::copy(ia.inputLayout.cbeginBindings(), ia.inputLayout.cendBindings(), std::back_inserter(bindings));
716 bindings.append({ stride, QRhiVertexInputBinding::PerInstance });
717 instanceBufferBinding = bindings.size() - 1;
718 const bool usesInstanceIndex = shaders.instanceBufferLocations().index >= 0;
719 if (usesInstanceIndex)
720 bindings.append({ quint32(sizeof(qint32)), QRhiVertexInputBinding::PerInstance });
721 ia.inputLayout.setBindings(bindings.cbegin(), bindings.cend());
722 }
723 return instanceBufferBinding;
724}
725
727 QSSGPassKey passKey,
728 const QSSGLayerRenderData &inData,
730 QSSGRhiGraphicsPipelineState *ps,
731 const QSSGRenderableObjectList &sortedOpaqueObjects,
732 QSSGRenderCamera &inCamera,
733 QSSGRenderer &renderer,
734 QSSGRenderTextureCubeFace cubeFace)
735{
736 using namespace RenderHelpers;
737
738 QSSGRhiContext *rhiCtx = context.rhiContext().get();
739
740 if ((inData.layer.background == QSSGRenderLayer::Background::SkyBox && (inData.layer.lightProbe || inData.layer.skyMaterial))
741 || inData.layer.background == QSSGRenderLayer::Background::SkyBoxCubeMap
742 || (inData.layer.background == QSSGRenderLayer::Background::SkyMaterial && inData.layer.skyMaterial))
743 rhiPrepareSkyBoxForReflectionMap(context, passKey, inData.layer, inCamera, renderer, pEntry, cubeFace);
744
745 QSSGShaderFeatures features = inData.getShaderFeatures();
746 // because of alteredCamera/alteredMvp below
747 features.set(QSSGShaderFeatures::Feature::DisableMultiView, true);
748 features.set(QSSGShaderFeatures::Feature::Ssao, false);
749
750 const auto &defaultMaterialShaderKeyProperties = inData.getDefaultMaterialPropertyTable();
751
752 for (const auto &handle : sortedOpaqueObjects) {
753 QSSGRenderableObject &inObject = *handle.obj;
754
755 QMatrix4x4 modelViewProjection;
756 if (inObject.type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || inObject.type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
757 QSSGSubsetRenderable &renderable(static_cast<QSSGSubsetRenderable &>(inObject));
758 const bool hasSkinning = defaultMaterialShaderKeyProperties.m_boneCount.getValue(renderable.shaderDescription) > 0;
759 const QMatrix4x4 &globalTransform = renderable.modelContext.globalTransform;
760 modelViewProjection = hasSkinning ? pEntry->m_viewProjection
761 : pEntry->m_viewProjection * globalTransform;
762 }
763
764 // here we pass on our own alteredCamera and alteredModelViewProjection
765 rhiPrepareRenderable(rhiCtx, passKey, inData, inObject, pEntry->m_rhiRenderPassDesc, ps, features, 1, 1,
766 &inCamera, &modelViewProjection, cubeFace, pEntry);
767 }
768}
769
770static inline void addDepthTextureBindings(QSSGRhiContext *rhiCtx,
771 QSSGRhiShaderPipeline *shaderPipeline,
772 QSSGRhiShaderResourceBindingList &bindings,
773 QBitArray *specifiedBindings = nullptr)
774{
775 const auto markSpecifiedBinding = [specifiedBindings](int binding) {
776 if (specifiedBindings)
777 specifiedBindings->setBit(binding);
778 };
779
780 if (shaderPipeline->depthTexture()) {
781 const int depthTextureBinding = shaderPipeline->bindingForTexture("qt_depthTexture", int(QSSGRhiSamplerBindingHints::DepthTexture));
782 const int depthTextureArrayBinding = shaderPipeline->bindingForTexture("qt_depthTextureArray", int(QSSGRhiSamplerBindingHints::DepthTextureArray));
783 if (depthTextureBinding >= 0 || depthTextureArrayBinding >= 0) {
784 // nearest min/mag, no mipmap
785 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
786 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
787 if (depthTextureBinding >= 0) {
788 markSpecifiedBinding(depthTextureBinding);
789 bindings.addTexture(depthTextureBinding, RENDERER_VISIBILITY_ALL, shaderPipeline->depthTexture(), sampler);
790 }
791 if (depthTextureArrayBinding >= 0) {
792 markSpecifiedBinding(depthTextureArrayBinding);
793 bindings.addTexture(depthTextureArrayBinding, RENDERER_VISIBILITY_ALL, shaderPipeline->depthTexture(), sampler);
794 }
795 } // else ignore, not an error
796 }
797
798 // SSAO texture
799 if (shaderPipeline->ssaoTexture()) {
800 const int ssaoTextureBinding = shaderPipeline->bindingForTexture("qt_aoTexture", int(QSSGRhiSamplerBindingHints::AoTexture));
801 const int ssaoTextureArrayBinding = shaderPipeline->bindingForTexture("qt_aoTextureArray", int(QSSGRhiSamplerBindingHints::AoTextureArray));
802 if (ssaoTextureBinding >= 0 || ssaoTextureArrayBinding >= 0) {
803 // linear min/mag, no mipmap
804 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
805 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
806 if (ssaoTextureBinding >= 0) {
807 markSpecifiedBinding(ssaoTextureBinding);
808 bindings.addTexture(ssaoTextureBinding,
809 QRhiShaderResourceBinding::FragmentStage,
810 shaderPipeline->ssaoTexture(), sampler);
811 }
812 if (ssaoTextureArrayBinding >= 0) {
813 markSpecifiedBinding(ssaoTextureArrayBinding);
814 bindings.addTexture(ssaoTextureArrayBinding,
815 QRhiShaderResourceBinding::FragmentStage,
816 shaderPipeline->ssaoTexture(), sampler);
817 }
818 } // else ignore, not an error
819 }
820}
821
822static inline void addNormalTextureBindings(QSSGRhiContext *rhiCtx,
823 QSSGRhiShaderPipeline *shaderPipeline,
824 QSSGRhiShaderResourceBindingList &bindings)
825{
826 if (shaderPipeline->normalTexture()) {
827 const int normalTextureBinding = shaderPipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
828 if (normalTextureBinding >= 0) {
829 // nearest min/mag, no mipmap
830 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
831 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
832 bindings.addTexture(normalTextureBinding, RENDERER_VISIBILITY_ALL, shaderPipeline->normalTexture(), sampler);
833 } // else ignore, not an error
834 }
835}
836
837void RenderHelpers::addAccumulatorImageBindings(QSSGRhiShaderPipeline *shaderPipeline,
838 QSSGRhiShaderResourceBindingList &bindings)
839{
840 const auto images = shaderPipeline->oitImages();
841 if (!images[0])
842 return;
843
844#ifdef QSSG_OIT_USE_BUFFERS
845 bindings.addStorageBufferStore(3, QRhiShaderResourceBinding::FragmentStage, (QRhiBuffer*)images[0]);
846 bindings.addStorageBufferLoadStore(4, QRhiShaderResourceBinding::FragmentStage, (QRhiBuffer*)images[1]);
847 bindings.addStorageBufferLoadStore(5, QRhiShaderResourceBinding::FragmentStage, (QRhiBuffer*)images[2]);
848#else
849 int abuf = shaderPipeline->bindingForStorageImage("qt_imgAbuffer");
850 int aux = shaderPipeline->bindingForStorageImage("qt_imgAux");
851 int counter = shaderPipeline->bindingForStorageImage("qt_imgCounter");
852 if (abuf == -1 || aux == -1 || counter == -1) {
853 qWarning()<<"Shader is missing image binding points;";
854 return;
855 }
856 bindings.addImageStore(abuf, QRhiShaderResourceBinding::FragmentStage, images[0], 0);
857 // atomic operations require loadstore
858 bindings.addImageLoadStore(aux, QRhiShaderResourceBinding::FragmentStage, images[1], 0);
859 bindings.addImageLoadStore(counter, QRhiShaderResourceBinding::FragmentStage, images[2], 0);
860#endif
861}
862
863// Returns the srb for the bindings and records it in the draw call data, releasing the
864// previously recorded srb if the bindings changed. The bindings refer to the draw call
865// data's uniform buffer, so the srb must be owned by the draw call data; otherwise
866// releaseDrawCallData() cannot purge it and the cache keeps an srb referencing a
867// deleted buffer.
868static QRhiShaderResourceBindings *drawCallDataSrb(QSSGRhiContextPrivate *rhiCtxD,
869 QSSGRhiDrawCallData &dcd,
870 const QSSGRhiShaderResourceBindingList &bindings)
871{
872 if (!dcd.srb || bindings != dcd.bindings) {
873 dcd.srb = rhiCtxD->srb(bindings);
874 rhiCtxD->releaseCachedSrb(dcd.bindings);
875 dcd.bindings = bindings;
876 }
877 return dcd.srb;
878}
879
880static void rhiPrepareResourcesForShadowMap(QSSGRhiContext *rhiCtx,
881 const QSSGLayerRenderData &inData,
882 QSSGPassKey passKey,
883 QSSGShadowMapEntry *pEntry,
884 QSSGRhiGraphicsPipelineState *ps,
885 const QVector2D *depthAdjust,
886 const QSSGRenderableObjectList &sortedOpaqueObjects,
887 QSSGRenderCamera &inCamera,
888 bool orthographic,
889 QSSGRenderTextureCubeFace cubeFace,
890 quint32 cascadeIndex)
891{
892 QSSGShaderFeatures featureSet;
893 if (orthographic)
894 featureSet.set(QSSGShaderFeatures::Feature::OrthoShadowPass, true);
895 else
896 featureSet.set(QSSGShaderFeatures::Feature::PerspectiveShadowPass, true);
897
898 // Do note how updateUniformsForDefaultMaterial() get a single camera and a
899 // custom mvp; make sure multiview is disabled in the shader generator using
900 // the common flag, instead of it having to write logic for checking for
901 // OrthoShadowPoss || CubeShadowPass.
902 featureSet.set(QSSGShaderFeatures::Feature::DisableMultiView, true);
903
904 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
905 const auto &defaultMaterialShaderKeyProperties = inData.getDefaultMaterialPropertyTable();
906 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
907
908 for (const auto &handle : sortedOpaqueObjects) {
909 QSSGRenderableObject *theObject = handle.obj;
910 QSSG_ASSERT(theObject->renderableFlags.castsShadows(), continue);
911
912 QSSGShaderFeatures objectFeatureSet = featureSet;
913 const bool isOpaqueDepthPrePass = theObject->depthWriteMode == QSSGDepthDrawMode::OpaquePrePass;
914 if (isOpaqueDepthPrePass)
915 objectFeatureSet.set(QSSGShaderFeatures::Feature::OpaqueDepthPrePass, true);
916
917 QSSGRhiDrawCallData *dcd = nullptr;
918 QMatrix4x4 modelViewProjection;
919 QSSGSubsetRenderable &renderable(static_cast<QSSGSubsetRenderable &>(*theObject));
920 if (theObject->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || theObject->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
921 const bool hasSkinning = defaultMaterialShaderKeyProperties.m_boneCount.getValue(renderable.shaderDescription) > 0;
922 modelViewProjection = hasSkinning ? pEntry->m_lightViewProjection[cascadeIndex]
923 : pEntry->m_lightViewProjection[cascadeIndex] * renderable.modelContext.globalTransform;
924 // cascadeIndex is 0..3 for directional light and 0 for the pointlight & spotlight
925 // cubeFaceIdx is 0 for directional & spotlight and 0..5 for the pointlight
926 // pEntry is unique per light and a light can only be one of directional, point, or spotlight.
927 // NOTE: The material is deliberately not part of the key here. The draw call data belongs to
928 // the shadow map entry, so swapping the material reuses it instead of creating a new one.
929 const quintptr entryIdx = cascadeIndex + cubeFaceIdx + (quintptr(renderable.subset.offset) << 3);
930 dcd = &rhiCtxD->drawCallData({ passKey, &renderable.modelContext.model, nullptr, pEntry, entryIdx });
931 }
932
933 QSSGRhiShaderResourceBindingList bindings;
934 QSSGRhiShaderPipelinePtr shaderPipeline;
935 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*theObject));
936 if (theObject->type == QSSGSubsetRenderable::Type::DefaultMaterialMeshSubset) {
937 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(subsetRenderable.getMaterial());
938 ps->cullMode = QSSGRhiHelpers::toCullMode(material.cullMode);
939 const bool blendParticles = defaultMaterialShaderKeyProperties.m_blendParticles.getValue(subsetRenderable.shaderDescription);
940
941 shaderPipeline = shadersForDefaultMaterial(ps, subsetRenderable, objectFeatureSet);
942 if (!shaderPipeline)
943 continue;
944 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
945 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
946 // calls updateUni with an alteredCamera and alteredModelViewProjection
947 QSSGRenderCameraList cameras({ &inCamera });
948 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, ps, subsetRenderable, cameras, depthAdjust, &modelViewProjection);
949 if (blendParticles)
950 QSSGParticleRenderer::updateUniformsForParticleModel(*shaderPipeline, ubufData, &subsetRenderable.modelContext.model, subsetRenderable.subset.offset);
951 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
952 if (blendParticles)
953 QSSGParticleRenderer::prepareParticlesForModel(*shaderPipeline, rhiCtx, bindings, &subsetRenderable.modelContext.model);
954 } else if (theObject->type == QSSGSubsetRenderable::Type::CustomMaterialMeshSubset) {
955 const auto &material = static_cast<const QSSGRenderCustomMaterial &>(subsetRenderable.getMaterial());
956 ps->cullMode = QSSGRhiHelpers::toCullMode(material.m_cullMode);
957
958 QSSGCustomMaterialSystem &customMaterialSystem(*subsetRenderable.renderer->contextInterface()->customMaterialSystem().get());
959 shaderPipeline = customMaterialSystem.shadersForCustomMaterial(ps, material, subsetRenderable, inData.getDefaultMaterialPropertyTable(), objectFeatureSet);
960 if (!shaderPipeline)
961 continue;
962 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
963 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
964 // inCamera is the shadow camera, not the same as inData.renderedCameras
965 QSSGRenderCameraList cameras({ &inCamera });
966 customMaterialSystem.updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, inData, ubufData, ps, material, subsetRenderable,
967 cameras, depthAdjust, &modelViewProjection);
968 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
969 }
970
971 if (theObject->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || theObject->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
972
973 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(*ps, shaderPipeline.get());
974 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
975 ia = subsetRenderable.subset.rhi.ia;
976 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
977 int instanceBufferBinding = setupInstancing(&subsetRenderable, ps, rhiCtx, inData, cameraDatas[0].direction, cameraDatas[0].position,
978 InstanceLevels::ModelWide, *shaderPipeline);
979 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
980
981
982 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd->ubuf);
983
984 // Depth and SSAO textures, in case a custom material's shader code does something with them.
985 addDepthTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
986 // and the normal texture, if there is one.
987 addNormalTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
988
989 if (isOpaqueDepthPrePass) {
990 addOpaqueDepthPrePassBindings(rhiCtx,
991 shaderPipeline.get(),
992 subsetRenderable.firstImage,
993 bindings,
994 (theObject->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset));
995 }
996
997 // There is no screen texture at this stage. But the shader from a
998 // custom material may rely on it, and an object with that material
999 // can end up in the shadow map's object list. So bind a dummy
1000 // texture then due to the lack of other options.
1001 const int screenTextureBinding = shaderPipeline->bindingForTexture("qt_screenTexture", int(QSSGRhiSamplerBindingHints::ScreenTexture));
1002 const int screenTextureArrayBinding = shaderPipeline->bindingForTexture("qt_screenTextureArray", int(QSSGRhiSamplerBindingHints::ScreenTextureArray));
1003 if (screenTextureBinding >= 0 || screenTextureArrayBinding >= 0) {
1004 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
1005 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
1006 if (screenTextureBinding >= 0) {
1007 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
1008 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
1009 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
1010 bindings.addTexture(screenTextureBinding,
1011 QRhiShaderResourceBinding::FragmentStage,
1012 dummyTexture, sampler);
1013 }
1014 if (screenTextureArrayBinding >= 0) {
1015 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
1016 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates, QSize(64, 64), Qt::black, inData.layer.viewCount);
1017 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
1018 bindings.addTexture(screenTextureArrayBinding,
1019 QRhiShaderResourceBinding::FragmentStage,
1020 dummyTexture, sampler);
1021 }
1022 }
1023
1024 // Skinning
1025 if (QRhiTexture *boneTexture = inData.getBonemapTexture(subsetRenderable.modelContext)) {
1026 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
1027 if (binding >= 0) {
1028 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
1029 QRhiSampler::Nearest,
1030 QRhiSampler::None,
1031 QRhiSampler::ClampToEdge,
1032 QRhiSampler::ClampToEdge,
1033 QRhiSampler::Repeat
1034 });
1035 bindings.addTexture(binding,
1036 QRhiShaderResourceBinding::VertexStage,
1037 boneTexture,
1038 boneSampler);
1039 }
1040 }
1041
1042 // Morphing
1043 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
1044 if (targetsTexture) {
1045 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
1046 if (binding >= 0) {
1047 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
1048 QRhiSampler::Nearest,
1049 QRhiSampler::None,
1050 QRhiSampler::ClampToEdge,
1051 QRhiSampler::ClampToEdge,
1052 QRhiSampler::ClampToEdge
1053 });
1054 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
1055 }
1056 }
1057
1058 shaderPipeline->applyAndClearStorageBindings(RENDERER_VISIBILITY_ALL, bindings);
1059 QRhiShaderResourceBindings *srb = drawCallDataSrb(rhiCtxD, *dcd, bindings);
1060
1061 subsetRenderable.rhiRenderData.shadowPass.pipeline = rhiCtxD->pipeline(*ps, pEntry->m_rhiRenderPassDesc[cascadeIndex], srb);
1062 subsetRenderable.rhiRenderData.shadowPass.srb[cubeFaceIdx] = srb;
1063 }
1064 }
1065}
1066
1067static void fillTargetBlend(QRhiGraphicsPipeline::TargetBlend *targetBlend, QSSGRenderDefaultMaterial::MaterialBlendMode materialBlend)
1068{
1069 // Assuming default values in the other TargetBlend fields
1070 switch (materialBlend) {
1071 case QSSGRenderDefaultMaterial::MaterialBlendMode::Screen:
1072 targetBlend->srcColor = QRhiGraphicsPipeline::SrcAlpha;
1073 targetBlend->dstColor = QRhiGraphicsPipeline::One;
1074 targetBlend->srcAlpha = QRhiGraphicsPipeline::One;
1075 targetBlend->dstAlpha = QRhiGraphicsPipeline::One;
1076 break;
1077 case QSSGRenderDefaultMaterial::MaterialBlendMode::Multiply:
1078 targetBlend->srcColor = QRhiGraphicsPipeline::DstColor;
1079 targetBlend->dstColor = QRhiGraphicsPipeline::Zero;
1080 targetBlend->srcAlpha = QRhiGraphicsPipeline::One;
1081 targetBlend->dstAlpha = QRhiGraphicsPipeline::One;
1082 break;
1083 default:
1084 // Use SourceOver for everything else
1085 targetBlend->srcColor = QRhiGraphicsPipeline::SrcAlpha;
1086 targetBlend->dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
1087 targetBlend->srcAlpha = QRhiGraphicsPipeline::One;
1088 targetBlend->dstAlpha = QRhiGraphicsPipeline::OneMinusSrcAlpha;
1089 break;
1090 }
1091}
1092
1093void rhiPrepareRenderableImp(QSSGRhiContext *rhiCtx,
1094 QSSGPassKey passKey,
1095 const QSSGLayerRenderData &inData,
1096 QSSGRenderableObject &inObject,
1097 QRhiRenderPassDescriptor *renderPassDescriptor,
1098 QSSGRhiGraphicsPipelineState *ps,
1099 QSSGShaderFeatures featureSet,
1100 int samples,
1101 int viewCount,
1102 bool screenMapPass,
1103 QSSGRenderCamera *alteredCamera,
1104 QMatrix4x4 *alteredModelViewProjection,
1105 QSSGRenderTextureCubeFace cubeFace,
1107 bool oit)
1108{
1109 const auto &defaultMaterialShaderKeyProperties = inData.getDefaultMaterialPropertyTable();
1110
1111 switch (inObject.type) {
1112 case QSSGRenderableObject::Type::DefaultMaterialMeshSubset:
1113 {
1114 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(inObject));
1115
1116 if ((cubeFace == QSSGRenderTextureCubeFaceNone) && subsetRenderable.reflectionProbeIndex >= 0 && subsetRenderable.renderableFlags.testFlag(QSSGRenderableObjectFlag::ReceivesReflections))
1117 featureSet.set(QSSGShaderFeatures::Feature::ReflectionProbe, true);
1118
1119 if ((cubeFace != QSSGRenderTextureCubeFaceNone)) {
1120 // Disable tonemapping for the reflection pass
1121 featureSet.disableTonemapping();
1122 }
1123
1124 if (subsetRenderable.renderableFlags.rendersWithLightmap())
1125 featureSet.set(QSSGShaderFeatures::Feature::Lightmap, true);
1126
1127 const auto &shaderPipeline = shadersForDefaultMaterial(ps, subsetRenderable, featureSet);
1128 if (shaderPipeline) {
1129 // Unlike the subsetRenderable (which is allocated per frame so is
1130 // not persistent in any way), the model reference is persistent in
1131 // the sense that it references the model node in the scene graph.
1132 // Combined with the layer node (multiple View3Ds may share the
1133 // same scene!), this is suitable as a key to get the uniform
1134 // buffers that were used with the rendering of the same model in
1135 // the previous frame.
1136 QSSGRhiShaderResourceBindingList bindings;
1137 const auto &modelNode = subsetRenderable.modelContext.model;
1138 const bool blendParticles = defaultMaterialShaderKeyProperties.m_blendParticles.getValue(subsetRenderable.shaderDescription);
1139
1140
1141 // NOTE:
1142 // - entryIdx should 0 for QSSGRenderTextureCubeFaceNone (and a null entry).
1143 // In all other cases the entryIdx is a combination of the cubeface idx and the subset
1144 // offset, where the lower bits are the cubeface idx. The per-probe reflection map
1145 // entry, if any, goes in the key's mapEntry slot. The key's resource must be the
1146 // material itself, and nothing but the material, since
1147 // cleanupDrawCallDataForResource() releases the entries for a to-be-destroyed
1148 // material by matching on the resource.
1149 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1150 const quintptr entryIdx = quintptr(cubeFace != QSSGRenderTextureCubeFaceNone)
1151 * (cubeFaceIdx + (quintptr(subsetRenderable.subset.offset) << 3));
1152
1153 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
1154 QSSGRhiDrawCallData &dcd = rhiCtxD->drawCallData({ passKey, &modelNode, &subsetRenderable.material, entry,
1155 entryIdx });
1156
1157 shaderPipeline->ensureCombinedUniformBuffer(&dcd.ubuf);
1158 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
1159 if (alteredCamera) {
1160 Q_ASSERT(alteredModelViewProjection);
1161 QSSGRenderCameraList cameras({ alteredCamera });
1162 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, ps, subsetRenderable, cameras, nullptr, alteredModelViewProjection);
1163 } else {
1164 Q_ASSERT(!alteredModelViewProjection);
1165 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, ps, subsetRenderable, inData.renderedCameras, nullptr, nullptr);
1166 }
1167
1168 if (blendParticles)
1169 QSSGParticleRenderer::updateUniformsForParticleModel(*shaderPipeline, ubufData, &subsetRenderable.modelContext.model, subsetRenderable.subset.offset);
1170 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
1171
1172 if (blendParticles)
1173 QSSGParticleRenderer::prepareParticlesForModel(*shaderPipeline, rhiCtx, bindings, &subsetRenderable.modelContext.model);
1174
1175 // Skinning
1176 if (QRhiTexture *boneTexture = inData.getBonemapTexture(subsetRenderable.modelContext)) {
1177 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
1178 if (binding >= 0) {
1179 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
1180 QRhiSampler::Nearest,
1181 QRhiSampler::None,
1182 QRhiSampler::ClampToEdge,
1183 QRhiSampler::ClampToEdge,
1184 QRhiSampler::Repeat
1185 });
1186 bindings.addTexture(binding,
1187 QRhiShaderResourceBinding::VertexStage,
1188 boneTexture,
1189 boneSampler);
1190 }
1191 }
1192 // Morphing
1193 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
1194 if (targetsTexture) {
1195 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
1196 if (binding >= 0) {
1197 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
1198 QRhiSampler::Nearest,
1199 QRhiSampler::None,
1200 QRhiSampler::ClampToEdge,
1201 QRhiSampler::ClampToEdge,
1202 QRhiSampler::ClampToEdge
1203 });
1204 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
1205 }
1206 }
1207
1208 ps->samples = samples;
1209 ps->viewCount = viewCount;
1210
1211 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(subsetRenderable.getMaterial());
1212 ps->cullMode = QSSGRhiHelpers::toCullMode(material.cullMode);
1213 if (!oit || (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::None))
1214 fillTargetBlend(&ps->targetBlend[0], material.blendMode);
1215
1216 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
1217
1218 ia = subsetRenderable.subset.rhi.ia;
1219 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
1220 QVector3D cameraDirection = cameraDatas[0].direction;
1221 QVector3D cameraPosition = cameraDatas[0].position;
1222 if (alteredCamera) {
1223 const QMatrix4x4 camGlobalTranform = inData.getGlobalTransform(*alteredCamera);
1224 cameraDirection = QSSGRenderNode::getScalingCorrectDirection(camGlobalTranform);
1225 cameraPosition = QSSGRenderNode::getGlobalPos(camGlobalTranform);
1226 }
1227 // Do not set up per-LOD distributions for altered-camera passes (reflection probes):
1228 // they prepare all 6 faces before rendering any, so buffers would reflect only
1229 // the last face's camera position. The render path falls back to the full buffer.
1230 int instanceBufferBinding = setupInstancing(&subsetRenderable, ps, rhiCtx, inData, cameraDirection, cameraPosition,
1231 alteredCamera ? InstanceLevels::ModelWide : InstanceLevels::PerInstance, *shaderPipeline);
1232 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
1233
1234 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd.ubuf, 0, shaderPipeline->ub0Size());
1235
1236 if (shaderPipeline->isLightingEnabled()) {
1237 bindings.addUniformBuffer(1, RENDERER_VISIBILITY_ALL, dcd.ubuf,
1238 shaderPipeline->ub0LightDataOffset(),
1239 sizeof(QSSGShaderLightsUniformData));
1240 bindings.addUniformBuffer(2, RENDERER_VISIBILITY_ALL, dcd.ubuf,
1241 shaderPipeline->ub0DirectionalLightDataOffset(),
1242 sizeof(QSSGShaderDirectionalLightsUniformData));
1243
1244 }
1245
1246 // Texture maps
1247 QSSGRenderableImage *renderableImage = subsetRenderable.firstImage;
1248 while (renderableImage) {
1249 const char *samplerName = QSSGMaterialShaderGenerator::getSamplerName(renderableImage->m_mapType);
1250 const int samplerHint = int(renderableImage->m_mapType);
1251 int samplerBinding = shaderPipeline->bindingForTexture(samplerName, samplerHint);
1252 if (samplerBinding >= 0) {
1253 QRhiTexture *texture = renderableImage->m_texture.m_texture;
1254 if (samplerBinding >= 0 && texture) {
1255 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
1256 QSSGRhiSamplerDescription samplerDesc = {
1257 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
1258 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
1259 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
1260 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
1261 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
1262 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
1263 };
1264 rhiCtx->checkAndAdjustForNPoT(texture, &samplerDesc);
1265 QRhiSampler *sampler = rhiCtx->sampler(samplerDesc);
1266 bindings.addTexture(samplerBinding, RENDERER_VISIBILITY_ALL, texture, sampler);
1267 }
1268 } // else this is not necessarily an error, e.g. having metalness/roughness maps with metalness disabled
1269 renderableImage = renderableImage->m_nextImage;
1270 }
1271
1272 if (shaderPipeline->isLightingEnabled()) {
1273 // Shadow map atlas
1274 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_texture"); binding >= 0) {
1275 QRhiTexture *texture = shaderPipeline->shadowMapAtlasTexture();
1276
1277 if (!texture) {
1278 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
1279 texture = rhiCtx->dummyTexture({ }, resourceUpdates, QSize(1, 1), Qt::black, 2);
1280 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
1281 }
1282
1283 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
1284 QRhiSampler::Linear,
1285 QRhiSampler::None,
1286 QRhiSampler::ClampToEdge,
1287 QRhiSampler::ClampToEdge,
1288 QRhiSampler::Repeat });
1289
1290 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
1291 }
1292
1293 // Shadow map blue noise
1294 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture"); binding >= 0) {
1295 if (auto shadowMapBlueNoise = shaderPipeline->shadowMapBlueNoiseTexture()) {
1296 int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture");
1297 if (binding >= 0) {
1298 QRhiTexture *texture = shadowMapBlueNoise;
1299 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
1300 QRhiSampler::Linear,
1301 QRhiSampler::None,
1302 QRhiSampler::Repeat,
1303 QRhiSampler::Repeat,
1304 QRhiSampler::Repeat });
1305 Q_ASSERT(texture && sampler);
1306 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
1307 }
1308 } else {
1309 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
1310 QRhiTexture *texture = rhiCtx->dummyTexture({}, resourceUpdates);
1311 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
1312 QRhiSampler::Linear,
1313 QRhiSampler::None,
1314 QRhiSampler::Repeat,
1315 QRhiSampler::Repeat,
1316 QRhiSampler::Repeat });
1317 Q_ASSERT(texture && sampler);
1318 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
1319 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
1320 }
1321 }
1322
1323 // Prioritize reflection texture over Light Probe texture because
1324 // reflection texture also contains the irradiance and pre filtered
1325 // values for the light probe.
1326 if (featureSet.isSet(QSSGShaderFeatures::Feature::ReflectionProbe)) {
1327 int reflectionSampler = shaderPipeline->bindingForTexture("qt_reflectionMap");
1328 QRhiTexture* reflectionTexture = inData.getReflectionMapManager()->reflectionMapEntry(subsetRenderable.reflectionProbeIndex)->m_rhiPrefilteredCube;
1329 const auto mipMapFilter = reflectionTexture && reflectionTexture->flags().testFlag(QRhiTexture::Flag::MipMapped)
1330 ? QRhiSampler::Linear
1331 : QRhiSampler::None;
1332 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
1333 QRhiSampler::Linear,
1334 mipMapFilter,
1335 QRhiSampler::ClampToEdge,
1336 QRhiSampler::ClampToEdge,
1337 QRhiSampler::Repeat });
1338 if (reflectionSampler >= 0) {
1339 // The shader samples the map even when the probe has no usable
1340 // texture, for example one in a format the GPU does not support
1341 if (!reflectionTexture) {
1342 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
1343 reflectionTexture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
1344 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
1345 }
1346 bindings.addTexture(reflectionSampler, QRhiShaderResourceBinding::FragmentStage, reflectionTexture, sampler);
1347 }
1348 }
1349
1350 if (int binding = shaderPipeline->bindingForTexture("qt_lightProbe", int(QSSGRhiSamplerBindingHints::LightProbe));
1351 binding >= 0) {
1352 auto texture = shaderPipeline->lightProbeTexture();
1353 if (!texture) {
1354 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
1355 texture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
1356 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
1357 }
1358 Q_ASSERT(texture);
1359
1360 QPair<QSSGRenderTextureCoordOp, QSSGRenderTextureCoordOp> tiling = shaderPipeline->lightProbeTiling();
1361 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
1362 QRhiSampler::Linear,
1363 QRhiSampler::Linear, // enables mipmapping
1364 QSSGRhiHelpers::toRhi(tiling.first),
1365 QSSGRhiHelpers::toRhi(tiling.second),
1366 QRhiSampler::Repeat });
1367 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
1368 }
1369
1370 // Screen Texture
1371 if (shaderPipeline->screenTexture()) {
1372 const int screenTextureBinding = shaderPipeline->bindingForTexture("qt_screenTexture", int(QSSGRhiSamplerBindingHints::ScreenTexture));
1373 const int screenTextureArrayBinding = shaderPipeline->bindingForTexture("qt_screenTextureArray", int(QSSGRhiSamplerBindingHints::ScreenTextureArray));
1374 if (screenTextureBinding >= 0 || screenTextureArrayBinding >= 0) {
1375 QRhiTexture *screenTexture = shaderPipeline->screenTexture();
1376 // If we're called as part of the screen map pass there's obviosly no screen texture available, but the shader may still expect it, so bind a dummy texture.
1377 if (screenMapPass) {
1378 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
1379 // Just mirror what is set up by the ScreenMap pass.
1380 const QRhiTexture::Flags flags = screenTexture->flags();
1381 // and set the dummy texture so there's something for the shader to sample.
1382 screenTexture = rhiCtx->dummyTexture(flags, resourceUpdates, QSize(64, 64), Qt::black, screenTexture->arraySize());
1383 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
1384 }
1385
1386 // linear min/mag, mipmap filtering depends on the
1387 // texture, with SCREEN_TEXTURE there are no mipmaps, but
1388 // once SCREEN_MIP_TEXTURE is seen the texture (the same
1389 // one) has mipmaps generated.
1390 QRhiSampler::Filter mipFilter = shaderPipeline->screenTexture()->flags().testFlag(QRhiTexture::MipMapped)
1391 ? QRhiSampler::Linear : QRhiSampler::None;
1392 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, mipFilter,
1393 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
1394 if (screenTextureBinding >= 0) {
1395 bindings.addTexture(screenTextureBinding,
1396 QRhiShaderResourceBinding::FragmentStage,
1397 screenTexture, sampler);
1398 }
1399 if (screenTextureArrayBinding >= 0) {
1400 bindings.addTexture(screenTextureArrayBinding,
1401 QRhiShaderResourceBinding::FragmentStage,
1402 screenTexture, sampler);
1403 }
1404 } // else ignore, not an error
1405 }
1406
1407 if (shaderPipeline->lightmapTexture()) {
1408 int binding = shaderPipeline->bindingForTexture("qt_lightmap", int(QSSGRhiSamplerBindingHints::LightmapTexture));
1409 if (binding >= 0) {
1410 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
1411 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
1412 bindings.addTexture(binding,
1413 QRhiShaderResourceBinding::FragmentStage,
1414 shaderPipeline->lightmapTexture(), sampler);
1415 } // else ignore, not an error
1416 }
1417 }
1418
1419 // Depth and SSAO textures
1420 addDepthTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
1421
1422 // Normal texture
1423 addNormalTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
1424
1425 if (oit && inData.layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
1426 RenderHelpers::addAccumulatorImageBindings(shaderPipeline.get(), bindings);
1427
1428 // Instead of always doing a QHash find in srb(), store the binding
1429 // list and the srb object in the per-model+material
1430 // QSSGRhiUniformBufferSet. While this still needs comparing the
1431 // binding list, to see if something has changed, it results in
1432 // significant gains with lots of models in the scene (because the
1433 // srb hash table becomes large then, so avoiding the lookup as
1434 // much as possible is helpful)
1435 QRhiShaderResourceBindings *&srb = dcd.srb;
1436 bool srbChanged = false;
1437 if (!srb || bindings != dcd.bindings) {
1438 srb = rhiCtxD->srb(bindings);
1439 rhiCtxD->releaseCachedSrb(dcd.bindings);
1440 dcd.bindings = bindings;
1441 srbChanged = true;
1442 }
1443
1444 if (cubeFace != QSSGRenderTextureCubeFaceNone)
1445 subsetRenderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx] = srb;
1446 else
1447 subsetRenderable.rhiRenderData.mainPass.srb = srb;
1448
1449 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
1450 if (dcd.pipeline
1451 && !srbChanged
1452 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash // we have the hash code anyway, use it to early out upon mismatch
1453 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
1454 && dcd.ps == *ps)
1455 {
1456 if (cubeFace != QSSGRenderTextureCubeFaceNone)
1457 subsetRenderable.rhiRenderData.reflectionPass.pipeline = dcd.pipeline;
1458 else
1459 subsetRenderable.rhiRenderData.mainPass.pipeline = dcd.pipeline;
1460 } else {
1461 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1462 subsetRenderable.rhiRenderData.reflectionPass.pipeline = rhiCtxD->pipeline(pipelineKey,
1463 renderPassDescriptor,
1464 srb);
1465 dcd.pipeline = subsetRenderable.rhiRenderData.reflectionPass.pipeline;
1466 } else {
1467 subsetRenderable.rhiRenderData.mainPass.pipeline = rhiCtxD->pipeline(pipelineKey,
1468 renderPassDescriptor,
1469 srb);
1470 dcd.pipeline = subsetRenderable.rhiRenderData.mainPass.pipeline;
1471 }
1472 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
1473 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
1474 dcd.ps = *ps;
1475 }
1476 }
1477 break;
1478 }
1479 case QSSGRenderableObject::Type::CustomMaterialMeshSubset:
1480 {
1481 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(inObject));
1482 const QSSGRenderCustomMaterial &material = static_cast<const QSSGRenderCustomMaterial &>(subsetRenderable.getMaterial());
1483 QSSGCustomMaterialSystem &customMaterialSystem(*subsetRenderable.renderer->contextInterface()->customMaterialSystem().get());
1484
1485 featureSet.set(QSSGShaderFeatures::Feature::LightProbe, inData.layer.lightProbe || material.m_iblProbe);
1486
1487 if ((cubeFace == QSSGRenderTextureCubeFaceNone) && subsetRenderable.reflectionProbeIndex >= 0 && subsetRenderable.renderableFlags.testFlag(QSSGRenderableObjectFlag::ReceivesReflections))
1488 featureSet.set(QSSGShaderFeatures::Feature::ReflectionProbe, true);
1489
1490 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1491 // Disable tonemapping for the reflection pass
1492 featureSet.disableTonemapping();
1493 }
1494
1495 if (subsetRenderable.renderableFlags.rendersWithLightmap())
1496 featureSet.set(QSSGShaderFeatures::Feature::Lightmap, true);
1497
1498 customMaterialSystem.rhiPrepareRenderable(ps, passKey, subsetRenderable, featureSet,
1499 material, inData, renderPassDescriptor, samples, viewCount, screenMapPass,
1500 alteredCamera, cubeFace, alteredModelViewProjection, entry, oit);
1501 break;
1502 }
1503 case QSSGRenderableObject::Type::Particles:
1504 {
1505 QSSGParticlesRenderable &particleRenderable(static_cast<QSSGParticlesRenderable &>(inObject));
1506 const auto &shaderPipeline = shadersForParticleMaterial(ps, particleRenderable, featureSet);
1507 if (shaderPipeline) {
1508 QSSGParticleRenderer::rhiPrepareRenderable(*shaderPipeline, passKey, rhiCtx, ps, particleRenderable, inData, renderPassDescriptor, samples, viewCount,
1509 alteredCamera, cubeFace, entry, oit);
1510 }
1511 break;
1512 }
1513 }
1514}
1515
1516void RenderHelpers::rhiPrepareRenderable(QSSGRhiContext *rhiCtx,
1517 QSSGPassKey passKey,
1518 const QSSGLayerRenderData &inData,
1519 QSSGRenderableObject &inObject,
1520 QRhiRenderPassDescriptor *renderPassDescriptor,
1521 QSSGRhiGraphicsPipelineState *ps,
1522 QSSGShaderFeatures featureSet,
1523 int samples,
1524 int viewCount,
1525 QSSGRenderCamera *alteredCamera,
1526 QMatrix4x4 *alteredModelViewProjection,
1527 QSSGRenderTextureCubeFace cubeFace,
1529 bool oit)
1530{
1531 rhiPrepareRenderableImp(rhiCtx, passKey, inData, inObject, renderPassDescriptor, ps, featureSet, samples, viewCount,
1532 false, alteredCamera, alteredModelViewProjection, cubeFace, entry, oit);
1533}
1534
1535void RenderHelpers::rhiPrepareRenderableForScreenMapPass(QSSGRhiContext *rhiCtx,
1536 QSSGPassKey passKey,
1537 const QSSGLayerRenderData &inData,
1538 QSSGRenderableObject &inObject,
1539 QRhiRenderPassDescriptor *renderPassDescriptor,
1540 QSSGRhiGraphicsPipelineState *ps,
1541 QSSGShaderFeatures featureSet,
1542 int samples,
1543 int viewCount,
1544 QSSGRenderCamera *alteredCamera,
1545 QMatrix4x4 *alteredModelViewProjection,
1546 QSSGRenderTextureCubeFace cubeFace,
1548 bool oit)
1549{
1550 rhiPrepareRenderableImp(rhiCtx, passKey, inData, inObject, renderPassDescriptor, ps, featureSet, samples, viewCount,
1551 true, alteredCamera, alteredModelViewProjection, cubeFace, entry, oit);
1552}
1553
1554// Binds the rows of the instances for INSTANCE_INDEX in the binding after the instance buffer,
1555// the last one in vertexBuffers, when the pipeline has that binding, see
1556// bakeVertexInputLocations(). The pipeline decides, as the draw call has to match it. Returns false when it has the binding but there is
1557// no buffer for it, as when the buffer could not be created: the draw call must then be skipped.
1558// instanceIndexBuffer is that of the renderable, or its autoLodInstanceIndexBuffer when it is
1559// drawn level by level, which rhiDrawAutoLodInstanced() binds from the first instance of each
1560// level.
1561bool RenderHelpers::bindInstanceIndices(QRhiGraphicsPipeline *ps, QRhiBuffer *instanceIndexBuffer,
1562 QRhiCommandBuffer::VertexInput *vertexBuffers, int *vertexBufferCount)
1563{
1564 if (ps->vertexInputLayout().bindingCount() <= *vertexBufferCount)
1565 return true;
1566 if (!instanceIndexBuffer)
1567 return false;
1568 vertexBuffers[(*vertexBufferCount)++] = QRhiCommandBuffer::VertexInput(instanceIndexBuffer, 0);
1569 return true;
1570}
1571
1572void RenderHelpers::rhiRenderRenderable(QSSGRhiContext *rhiCtx,
1573 const QSSGRhiGraphicsPipelineState &state,
1574 QSSGRenderableObject &object,
1575 bool *needsSetViewport,
1576 QSSGRenderTextureCubeFace cubeFace,
1577 qsizetype userPassIndex)
1578{
1579 switch (object.type) {
1580 case QSSGRenderableObject::Type::DefaultMaterialMeshSubset:
1581 {
1582 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(object));
1583
1584 QSSG_ASSERT(QSSGUserRenderPassManager::maxUserPassSlots() == std::size(subsetRenderable.rhiRenderData.userPassData), return);
1585
1586 QRhiGraphicsPipeline *ps = (userPassIndex >= 0 && size_t(userPassIndex) < QSSGUserRenderPassManager::maxUserPassSlots())
1587 ? subsetRenderable.rhiRenderData.userPassData[userPassIndex].pipeline : subsetRenderable.rhiRenderData.mainPass.pipeline;
1588 QRhiShaderResourceBindings *srb = (userPassIndex >= 0 && size_t(userPassIndex) < QSSGUserRenderPassManager::maxUserPassSlots())
1589 ? subsetRenderable.rhiRenderData.userPassData[userPassIndex].srb : subsetRenderable.rhiRenderData.mainPass.srb;
1590
1591 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
1592 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
1593 ps = subsetRenderable.rhiRenderData.reflectionPass.pipeline;
1594 srb = subsetRenderable.rhiRenderData.reflectionPass.srb[cubeFaceIdx];
1595 }
1596
1597 if (!ps || !srb)
1598 return;
1599
1600 QRhiBuffer *indexBuffer = subsetRenderable.subset.rhi.indexBuffer ? subsetRenderable.subset.rhi.indexBuffer->buffer() : nullptr;
1601
1602 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1603 // QRhi optimizes out unnecessary binding of the same pipline
1604 cb->setGraphicsPipeline(ps);
1605 cb->setShaderResources(srb);
1606
1607 if (*needsSetViewport) {
1608 cb->setViewport(state.viewport);
1609 if (state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::UsesScissor))
1610 cb->setScissor(state.scissor);
1611 *needsSetViewport = false;
1612 }
1613
1614 QRhiCommandBuffer::VertexInput vertexBuffers[3];
1615 int vertexBufferCount = 0;
1616 quint32 instances = 1;
1617 // The faces of a reflection cube map draw the full instance buffer at the original level
1618 // instead of the instances grouped by level: they are all prepared before any is
1619 // rendered, so the levels would only fit the camera of the last face.
1620 const bool autoLod = subsetRenderable.usesAutoLod && indexBuffer && cubeFace == QSSGRenderTextureCubeFaceNone;
1621 if (autoLod && !RenderHelpers::anyAutoLodInstances(subsetRenderable))
1622 return;
1623
1624 if (!setupDrawInputs(rhiCtx, ps, subsetRenderable,
1625 autoLod ? subsetRenderable.autoLodInstanceIndexBuffer : subsetRenderable.instanceIndexBuffer,
1626 vertexBuffers, vertexBufferCount, instances))
1627 return;
1628 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1629 if (state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::UsesStencilRef))
1630 cb->setStencilRef(state.stencilRef);
1631 if (autoLod) {
1632 RenderHelpers::rhiDrawAutoLodInstanced(rhiCtx, cb, vertexBuffers, vertexBufferCount, indexBuffer, subsetRenderable);
1633 } else if (indexBuffer) {
1634 cb->setVertexInput(0, vertexBufferCount, vertexBuffers, indexBuffer, 0, subsetRenderable.subset.rhi.indexBuffer->indexFormat());
1635 cb->drawIndexed(subsetRenderable.subset.lodCount(subsetRenderable.subsetLevelOfDetail), instances, subsetRenderable.subset.lodOffset(subsetRenderable.subsetLevelOfDetail));
1636 QSSGRHICTX_STAT(rhiCtx, drawIndexed(subsetRenderable.subset.lodCount(subsetRenderable.subsetLevelOfDetail), instances));
1637 } else {
1638 cb->setVertexInput(0, vertexBufferCount, vertexBuffers);
1639 rhiDrawNonIndexed(rhiCtx, cb, subsetRenderable, instances);
1640 }
1641 Q_QUICK3D_PROFILE_END_WITH_IDS(QQuick3DProfiler::Quick3DRenderCall, (subsetRenderable.subset.count | quint64(instances) << 32),
1642 QVector<int>({subsetRenderable.modelContext.model.profilingId,
1643 subsetRenderable.material.profilingId}));
1644 break;
1645 }
1646 case QSSGRenderableObject::Type::CustomMaterialMeshSubset:
1647 {
1648 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(object));
1649 QSSGCustomMaterialSystem &customMaterialSystem(*subsetRenderable.renderer->contextInterface()->customMaterialSystem().get());
1650 customMaterialSystem.rhiRenderRenderable(rhiCtx, subsetRenderable, needsSetViewport, cubeFace, state, userPassIndex);
1651 break;
1652 }
1653 case QSSGRenderableObject::Type::Particles:
1654 {
1655 QSSGParticlesRenderable &renderable(static_cast<QSSGParticlesRenderable &>(object));
1656 QSSGParticleRenderer::rhiRenderRenderable(rhiCtx, renderable, needsSetViewport, cubeFace, state);
1657 break;
1658 }
1659 }
1660}
1661
1662static QRhiViewport calculateAtlasViewport(QSize atlasPixelSize, const QSSGShadowMapEntry::AtlasEntry &atlasEntry, bool yIsUp) {
1663 // Convert normalized offsets/scales to actual pixel values
1664 float x = atlasEntry.uOffset * atlasPixelSize.width();
1665 float w = atlasEntry.uvScale * atlasPixelSize.width();
1666 float h = atlasEntry.uvScale * atlasPixelSize.height();
1667
1668 // Y in atlasEntry is top-based, whereas QRhiViewport is bottom-based
1669 // topY in pixel = atlasEntry.vOffset * atlasPixelSize.height()
1670 // so bottom-left Y = totalHeight - topY - h
1671 float y;
1672 if (!yIsUp)
1673 y = atlasPixelSize.height() - (atlasEntry.vOffset * atlasPixelSize.height()) - h;
1674 else
1675 y = atlasEntry.vOffset * atlasPixelSize.height();
1676
1677 return QRhiViewport(x, y, w, h);
1678}
1679
1680void RenderHelpers::rhiRenderShadowMap(QSSGRhiContext *rhiCtx,
1681 QSSGPassKey passKey,
1682 QSSGRhiGraphicsPipelineState &ps,
1683 QSSGRenderShadowMap &shadowMapManager,
1684 const QSSGRenderCamera &camera,
1685 QSSGRenderCamera *debugCamera,
1686 const QSSGShaderLightList &globalLights,
1687 const QSSGRenderableObjectList &sortedOpaqueObjects,
1688 QSSGRenderer &renderer,
1689 const QSSGBounds3 &castingObjectsBox,
1690 const QSSGBounds3 &receivingObjectsBox)
1691{
1692 const QSSGLayerRenderData &layerData = *QSSGLayerRenderData::getCurrent(renderer);
1693 QSSGDebugDrawSystem *debugDrawSystem = renderer.contextInterface()->debugDrawSystem().get();
1694 const bool drawDirectionalLightShadowBoxes = layerData.layer.drawDirectionalLightShadowBoxes;
1695 const bool drawPointLightShadowBoxes = layerData.layer.drawPointLightShadowBoxes;
1696 const bool drawShadowCastingBounds = layerData.layer.drawShadowCastingBounds;
1697 const bool drawShadowReceivingBounds = layerData.layer.drawShadowReceivingBounds;
1698 const bool drawCascades = layerData.layer.drawCascades;
1699 const bool drawSceneCascadeIntersection = layerData.layer.drawSceneCascadeIntersection;
1700 const bool disableShadowCameraUpdate = layerData.layer.disableShadowCameraUpdate;
1701 const bool drawCulledObjects = layerData.layer.drawCulledObjects;
1702 QVector<bool> debugIsObjectCulled = drawCulledObjects ? QVector<bool>(sortedOpaqueObjects.size(), true) : QVector<bool>();
1703
1704 static const auto rhiRenderOneShadowMap = [](QSSGRhiContext *rhiCtx,
1705 QSSGRhiGraphicsPipelineState *ps,
1706 const QSSGRenderableObjectList &sortedOpaqueObjects,
1707 int cubeFace,
1708 const QSSGBounds3 cameraBounds,
1709 QVector<bool> &debugIsObjectCulled,
1710 bool drawCulledObjects) {
1711 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1712 bool needsSetViewport = true;
1713
1714 for (int i = 0, n = sortedOpaqueObjects.size(); i < n; ++i) {
1715 const QSSGRenderableObjectHandle &handle = sortedOpaqueObjects[i];
1716 QSSGRenderableObject *theObject = handle.obj;
1717
1718 // Only attempt to cull models if both of its bounds are valid
1719 if (theObject->globalBoundsInstancing.isFinite() && theObject->globalBounds.isFinite()) {
1720 const QSSGBounds3 &globalBounds = !theObject->globalBoundsInstancing.isEmpty() ? theObject->globalBoundsInstancing
1721 : theObject->globalBounds;
1722 if (!globalBounds.isEmpty() && !cameraBounds.intersects(globalBounds)) {
1723 continue;
1724 }
1725 }
1726
1727 if (Q_UNLIKELY(drawCulledObjects))
1728 debugIsObjectCulled[i] = false;
1729
1730 QSSG_ASSERT(theObject->renderableFlags.castsShadows(), continue);
1731 if (theObject->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || theObject->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
1732 QSSGSubsetRenderable *renderable(static_cast<QSSGSubsetRenderable *>(theObject));
1733
1734 QRhiBuffer *indexBuffer = renderable->subset.rhi.indexBuffer
1735 ? renderable->subset.rhi.indexBuffer->buffer()
1736 : nullptr;
1737
1738 // Ideally we shouldn't need to deal with this, as only "valid" objects should be processed at this point.
1739 if (!renderable->rhiRenderData.shadowPass.pipeline)
1740 continue;
1741
1742 // With the automatic per-instance LOD, the shadow maps are drawn with the full
1743 // instance buffer at the original level (subsetLevelOfDetail is 0).
1744 QRhiCommandBuffer::VertexInput vertexBuffers[3];
1745 int vertexBufferCount = 0;
1746 quint32 instances = 1;
1747 if (!setupDrawInputs(rhiCtx, renderable->rhiRenderData.shadowPass.pipeline, *renderable, renderable->instanceIndexBuffer,
1748 vertexBuffers, vertexBufferCount, instances))
1749 continue;
1750
1751 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
1752
1753 cb->setGraphicsPipeline(renderable->rhiRenderData.shadowPass.pipeline);
1754
1755 QRhiShaderResourceBindings *srb = renderable->rhiRenderData.shadowPass.srb[cubeFace];
1756 cb->setShaderResources(srb);
1757
1758 if (needsSetViewport) {
1759 cb->setViewport(ps->viewport);
1760 needsSetViewport = false;
1761 }
1762
1763 if (indexBuffer) {
1764 cb->setVertexInput(0, vertexBufferCount, vertexBuffers, indexBuffer, 0, renderable->subset.rhi.indexBuffer->indexFormat());
1765 cb->drawIndexed(renderable->subset.lodCount(renderable->subsetLevelOfDetail), instances, renderable->subset.lodOffset(renderable->subsetLevelOfDetail));
1766 QSSGRHICTX_STAT(rhiCtx, drawIndexed(renderable->subset.lodCount(renderable->subsetLevelOfDetail), instances));
1767 } else {
1768 cb->setVertexInput(0, vertexBufferCount, vertexBuffers);
1769 rhiDrawNonIndexed(rhiCtx, cb, *renderable, instances);
1770 }
1771 Q_QUICK3D_PROFILE_END_WITH_IDS(QQuick3DProfiler::Quick3DRenderCall, (renderable->subset.count | quint64(instances) << 32),
1772 QVector<int>({renderable->modelContext.model.profilingId,
1773 renderable->material.profilingId}));
1774 }
1775 }
1776 };
1777
1778 static const auto rhiClearShadowMap = [](QSSGRenderer &renderer, QSSGRenderShadowMap &shadowMapManager, QSSGRhiContext *rhiCtx, QSSGRhiGraphicsPipelineState *ps, QRhiRenderPassDescriptor *renderPassDesc) {
1779 auto clearShadowMapShaderPipeline = renderer.contextInterface()->shaderCache()->getBuiltInRhiShaders().getRhiClearShadowMapShader();
1780 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(*ps, clearShadowMapShaderPipeline.get());
1781
1782 // Disable Depth Test and Depth Write
1783 ps->flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled, false);
1784 ps->flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled, false);
1785 renderer.rhiQuadRenderer()->recordRenderQuad(rhiCtx, ps, shadowMapManager.shadowClearSrb(), renderPassDesc, {});
1786 // Reset
1787 ps->flags |= { QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled, QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled };
1788 };
1789
1790 QRhi *rhi = rhiCtx->rhi();
1791 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
1792
1793 // We need to deal with a clip depth range of [0, 1] or
1794 // [-1, 1], depending on the graphics API underneath.
1795 QVector2D depthAdjust; // (d + depthAdjust[0]) * depthAdjust[1] = d mapped to [0, 1]
1796 if (rhi->isClipDepthZeroToOne()) {
1797 // d is [0, 1] so no need for any mapping
1798 depthAdjust[0] = 0.0f;
1799 depthAdjust[1] = 1.0f;
1800 } else {
1801 // d is [-1, 1]
1802 depthAdjust[0] = 1.0f;
1803 depthAdjust[1] = 0.5f;
1804 }
1805
1806 if (drawShadowCastingBounds)
1807 ShadowmapHelpers::addDebugBox(castingObjectsBox.toQSSGBoxPointsNoEmptyCheck(), QColorConstants::Red, debugDrawSystem);
1808 if (drawShadowReceivingBounds)
1809 ShadowmapHelpers::addDebugBox(receivingObjectsBox.toQSSGBoxPointsNoEmptyCheck(), QColorConstants::Green, debugDrawSystem);
1810
1811 // Create shadow map for each light in the scene
1812 const QSize atlasTextureSize = shadowMapManager.shadowMapAtlasTexture()->pixelSize();
1813 // Make sure quad renderer is ready
1814 renderer.rhiQuadRenderer()->prepareQuad(rhiCtx, nullptr);
1815 for (int i = 0, ie = globalLights.size(); i != ie; ++i) {
1816 if (!globalLights[i].shadows || globalLights[i].light->m_fullyBaked)
1817 continue;
1818
1819 QSSGShadowMapEntry *pEntry = shadowMapManager.shadowMapEntry(i);
1820 if (!pEntry)
1821 continue;
1822
1823 const auto &light = globalLights[i].light;
1824
1825 if (!shadowMapManager.shadowMapAtlasTexture())
1826 break;
1827
1828 if (light->type == QSSGRenderLight::Type::DirectionalLight || light->type == QSSGRenderLight::Type::SpotLight) {
1829 const QSize size = atlasTextureSize * pEntry->m_atlasInfo[0].uvScale;
1830
1831 // This is just a way to store the old camera so we can use it for debug
1832 // drawing. There are probably cleaner ways to do this
1833 if (!disableShadowCameraUpdate && debugCamera) {
1834 debugCamera->clipPlanes = camera.clipPlanes;
1835 debugCamera->projection = camera.projection;
1836 // NOTE: Since the debug camera is an internally injected camera, there will only be
1837 // the local transform. Anywhere the global transform is looked up for the debug camera
1838 // it will return the local transform.
1839 debugCamera->localTransform = layerData.getGlobalTransform(camera);
1840 }
1841
1842 QVarLengthArray<std::unique_ptr<QSSGRenderCamera>, 4> cascades;
1843 if (light->type == QSSGRenderLight::Type::DirectionalLight) {
1844 const float pcfRadius = light->m_softShadowQuality == QSSGRenderLight::SoftShadowQuality::Hard ? 0.f : light->m_pcfFactor;
1845 const float clipNear = camera.clipPlanes.clipNear();
1846 const float clipFar = qMin(light->m_shadowMapFar, camera.clipPlanes.clipFar());
1847 const float clipRange = clipFar - clipNear;
1848 cascades = setupCascadingCamerasForShadowMap(layerData,
1849 disableShadowCameraUpdate ? *debugCamera : camera,
1850 light,
1851 size.width(),
1852 pcfRadius,
1853 clipNear,
1854 clipFar,
1855 castingObjectsBox,
1856 receivingObjectsBox,
1857 light->m_lockShadowmapTexels,
1858 debugDrawSystem,
1859 drawCascades,
1860 drawSceneCascadeIntersection);
1861
1862 // Write the split distances from value 0 in the z-axis of the eye view-space
1863 pEntry->m_csmSplits[0] = clipNear + clipRange * (light->m_csmNumSplits > 0 ? light->m_csmSplit1 : 1.0f);
1864 pEntry->m_csmSplits[1] = clipNear + clipRange * (light->m_csmNumSplits > 1 ? light->m_csmSplit2 : 1.0f);
1865 pEntry->m_csmSplits[2] = clipNear + clipRange * (light->m_csmNumSplits > 2 ? light->m_csmSplit3 : 1.0f);
1866 pEntry->m_csmSplits[3] = clipNear + clipRange * 1.0f;
1867 pEntry->m_shadowMapFar = clipFar;
1868 } else if (light->type == QSSGRenderLight::Type::SpotLight) {
1869 auto spotlightCamera = std::make_unique<QSSGRenderCamera>(QSSGRenderCamera::Type::PerspectiveCamera);
1870 spotlightCamera->fov = QSSGRenderCamera::FieldOfView::fromDegrees(light->m_coneAngle * 2.0f);
1871 spotlightCamera->clipPlanes = { 1.0f, light->m_shadowMapFar };
1872 const QMatrix4x4 lightGlobalTransform = layerData.getGlobalTransform(*light);
1873 const QVector3D lightDir = QSSGRenderNode::getDirection(lightGlobalTransform);
1874 const QVector3D lightPos = QSSGRenderNode::getGlobalPos(lightGlobalTransform) - lightDir * spotlightCamera->clipPlanes.clipNear();
1875 const QVector3D lightPivot = light->pivot;
1876 const QVector3D forward = lightDir.normalized();
1877 const QVector3D right = qFuzzyCompare(qAbs(forward.y()), 1.0f)
1878 ? QVector3D::crossProduct(forward, QVector3D(1, 0, 0)).normalized()
1879 : QVector3D::crossProduct(forward, QVector3D(0, 1, 0)).normalized();
1880 const QVector3D up = QVector3D::crossProduct(right, forward).normalized();
1881 spotlightCamera->localTransform = QSSGRenderNode::calculateTransformMatrix(lightPos,
1882 QSSGRenderNode::initScale,
1883 lightPivot,
1884 QQuaternion::fromDirection(forward, up));
1885 QRectF theViewport(0.0f, 0.0f, (float)light->m_shadowMapRes, (float)light->m_shadowMapRes);
1886 QSSGRenderCamera::calculateProjectionInternal(*spotlightCamera, theViewport);
1887 cascades.push_back(std::move(spotlightCamera));
1888 pEntry->m_shadowMapFar = light->m_shadowMapFar;
1889 } else {
1890 Q_UNREACHABLE();
1891 }
1892
1893 memset(pEntry->m_csmActive, 0, sizeof(pEntry->m_csmActive));
1894
1895 QMatrix4x4 cascadeCameraGlobalTransforms(Qt::Uninitialized);
1896 const QMatrix4x4 bias = { 0.5, 0.0, 0.0, 0.5,
1897 0.0, 0.5, 0.0, 0.5,
1898 0.0, 0.0, 0.5, 0.5,
1899 0.0, 0.0, 0.0, 1.0 };
1900
1901 for (int cascadeIndex = 0; cascadeIndex < cascades.length(); cascadeIndex++) {
1902 const auto &cascadeCamera = cascades[cascadeIndex];
1903 if (!cascadeCamera)
1904 continue;
1905
1906 cascadeCameraGlobalTransforms = layerData.getGlobalTransform(*cascadeCamera);
1907 pEntry->m_csmActive[cascadeIndex] = 1.f;
1908 QMatrix4x4 &viewProjection = pEntry->m_lightViewProjection[cascadeIndex];
1909 cascadeCamera->calculateViewProjectionMatrix(cascadeCameraGlobalTransforms, viewProjection);
1910 pEntry->m_lightViewProjection[cascadeIndex] = viewProjection;
1911 pEntry->m_fixedScaleBiasMatrix[cascadeIndex] = bias * viewProjection;
1912 const QMatrix4x4 inverted = viewProjection.inverted();
1913 const float x = 0.5f / (inverted * QVector4D(1, 0, 0, 0)).length();
1914 const float y = 0.5f / (inverted * QVector4D(0, 1, 0, 0)).length();
1915 const float z = 0.5f / (inverted * QVector4D(0, 0, 1, 0)).length();
1916 const QSSGBoxPoints frustumPoints = computeFrustumBounds(viewProjection);
1917 const QSSGBounds3 bounds = QSSGBounds3(frustumPoints);
1918 pEntry->m_dimensionsInverted[cascadeIndex] = QVector4D(x, y, z, 0.0f);
1919 pEntry->m_lightView = cascadeCameraGlobalTransforms.inverted(); // pre-calculate this for the material
1920 const bool isOrtho = cascadeCamera->type == QSSGRenderGraphObject::Type::OrthographicCamera;
1921 ps.viewport = calculateAtlasViewport(atlasTextureSize, pEntry->m_atlasInfo[cascadeIndex], rhi->isYUpInFramebuffer());
1922 rhiPrepareResourcesForShadowMap(rhiCtx, layerData, passKey, pEntry, &ps, &depthAdjust, sortedOpaqueObjects, *cascadeCamera, isOrtho, QSSGRenderTextureCubeFaceNone, cascadeIndex);
1923 // Render into the 2D texture pEntry->m_rhiDepthMap, using
1924 // pEntry->m_rhiDepthStencil as the (throwaway) depth/stencil buffer.
1925 QRhiTextureRenderTarget *rt = pEntry->m_rhiRenderTargets[cascadeIndex];
1926 cb->beginPass(rt, Qt::white, { 1.0f, 0 }, nullptr, rhiCtx->commonPassFlags());
1927 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
1928 QSSGRHICTX_STAT(rhiCtx, beginRenderPass(rt));
1929 rhiClearShadowMap(renderer, shadowMapManager, rhiCtx, &ps, rt->renderPassDescriptor());
1930 rhiRenderOneShadowMap(rhiCtx, &ps, sortedOpaqueObjects, 0, bounds, debugIsObjectCulled, drawCulledObjects);
1931 cb->endPass();
1932 QSSGRHICTX_STAT(rhiCtx, endRenderPass());
1933
1934 if (drawDirectionalLightShadowBoxes) {
1935 ShadowmapHelpers::addDirectionalLightDebugBox(frustumPoints, debugDrawSystem);
1936 }
1937 }
1938 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QByteArrayLiteral("shadow_map"));
1939 } else { // Point Light
1940 const QSize size = atlasTextureSize * pEntry->m_atlasInfo[0].uvScale;
1941 ps.viewport = QRhiViewport(0, 0, float(size.width()), float(size.height()));
1942
1943 QSSGRenderCamera theCameras[6] { QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
1944 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
1945 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
1946 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
1947 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
1948 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera} };
1949 const float shadowMapFar = qMax<float>(2.0f, light->m_shadowMapFar);
1950 setupCubeShadowCameras(layerData, light, shadowMapFar, theCameras);
1951 pEntry->m_lightView = QMatrix4x4();
1952 pEntry->m_shadowMapFar = shadowMapFar;
1953
1954 const bool swapYFaces = !rhi->isYUpInFramebuffer();
1955 QMatrix4x4 cameraGlobalTransform(Qt::Uninitialized);
1956 for (const auto face : QSSGRenderTextureCubeFaces) {
1957 cameraGlobalTransform = layerData.getGlobalTransform(theCameras[quint8(face)]);
1958 theCameras[quint8(face)].calculateViewProjectionMatrix(cameraGlobalTransform, pEntry->m_lightViewProjection[0]);
1959 pEntry->m_lightCubeView[quint8(face)] = cameraGlobalTransform.inverted(); // pre-calculate this for the material
1960
1961 rhiPrepareResourcesForShadowMap(rhiCtx,
1962 layerData,
1963 passKey,
1964 pEntry,
1965 &ps,
1966 &depthAdjust,
1967 sortedOpaqueObjects,
1968 theCameras[quint8(face)],
1969 false,
1970 face,
1971 0);
1972 }
1973
1974 // The bounds should be the same for all view projections of the cube
1975 const QVector3D center = QSSGRenderNode::getGlobalPos(layerData.getGlobalTransform(*light));
1976 const QSSGBounds3 bounds = QSSGBounds3(center - QVector3D(shadowMapFar, shadowMapFar, shadowMapFar),
1977 center + QVector3D(shadowMapFar, shadowMapFar, shadowMapFar));
1978
1979 for (const auto face : QSSGRenderTextureCubeFaces) {
1980 // Render into one face of the cubemap texture pEntry->m_rhiDephCube, using
1981 // pEntry->m_rhiDepthStencil as the (throwaway) depth/stencil buffer.
1982
1983 QSSGRenderTextureCubeFace outFace = face;
1984 // FACE S T GL
1985 // +x -z, -y right
1986 // -x +z, -y left
1987 // +y +x, +z top
1988 // -y +x, -z bottom
1989 // +z +x, -y front
1990 // -z -x, -y back
1991 // FACE S T D3D
1992 // +x -z, +y right
1993 // -x +z, +y left
1994 // +y +x, -z bottom
1995 // -y +x, +z top
1996 // +z +x, +y front
1997 // -z -x, +y back
1998 if (swapYFaces) {
1999 // +Y and -Y faces get swapped (D3D, Vulkan, Metal).
2000 // See shadowMapping.glsllib. This is complemented there by reversing T as well.
2001 if (outFace == QSSGRenderTextureCubeFace::PosY)
2002 outFace = QSSGRenderTextureCubeFace::NegY;
2003 else if (outFace == QSSGRenderTextureCubeFace::NegY)
2004 outFace = QSSGRenderTextureCubeFace::PosY;
2005 }
2006 QRhiTextureRenderTarget *rt = pEntry->m_rhiRenderTargetCube[quint8(outFace)];
2007 cb->beginPass(rt, Qt::white, { 1.0f, 0 }, nullptr, rhiCtx->commonPassFlags());
2008 QSSGRHICTX_STAT(rhiCtx, beginRenderPass(rt));
2009 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
2010 rhiRenderOneShadowMap(rhiCtx, &ps, sortedOpaqueObjects, quint8(face), bounds, debugIsObjectCulled, drawCulledObjects);
2011 cb->endPass();
2012 QSSGRHICTX_STAT(rhiCtx, endRenderPass());
2013 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QSSG_RENDERPASS_NAME("shadow_cube", 0, outFace));
2014 }
2015
2016 // Render the CubeMap into the shadowMapAtlasTexture
2017 // NOTE: These passes don't require a manual clear because we will always write every pixel in that atlas space
2018
2019 // Render the front hemisphere of the cube map into the shadow map atlas
2020 QRhiTextureRenderTarget *rtFront = pEntry->m_rhiRenderTargets[0]; // A layer in the Atlas
2021 QRhiRenderPassDescriptor *frontDesc = pEntry->m_rhiRenderPassDesc[0];
2022 auto atlasShaderPipeline = renderer.contextInterface()->shaderCache()->getBuiltInRhiShaders().getRhiCubeMapToAtlasShader();
2023 ps.viewport = calculateAtlasViewport(atlasTextureSize, pEntry->m_atlasInfo[0], rhi->isYUpInFramebuffer());
2024 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(ps, atlasShaderPipeline.get());
2025 QRhiShaderResourceBindings *srb = pEntry->m_cubeToAtlasFrontSrb;
2026 cb->beginPass(rtFront, Qt::white, { 1.0f, 0 }, nullptr, rhiCtx->commonPassFlags());
2027 QSSGRHICTX_STAT(rhiCtx, beginRenderPass(rtFront));
2028 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
2029
2030 renderer.rhiQuadRenderer()->recordRenderQuad(rhiCtx, &ps, srb, frontDesc, QSSGRhiQuadRenderer::UvCoords);
2031
2032 cb->endPass();
2033 QSSGRHICTX_STAT(rhiCtx, endRenderPass());
2034 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QSSG_RENDERPASS_NAME("shadow_atlas", 6, 0));
2035
2036 // Render the back hemisphere of the cube map into the shadow map atlas
2037 QRhiTextureRenderTarget *rtBack = pEntry->m_rhiRenderTargets[1]; // A layer in the Atlas
2038 QRhiRenderPassDescriptor *backDesc = pEntry->m_rhiRenderPassDesc[1];
2039 srb = pEntry->m_cubeToAtlasBackSrb;
2040 ps.viewport = calculateAtlasViewport(atlasTextureSize, pEntry->m_atlasInfo[1], rhi->isYUpInFramebuffer());
2041 cb->beginPass(rtBack, Qt::white, { 1.0f, 0 }, nullptr, rhiCtx->commonPassFlags());
2042 QSSGRHICTX_STAT(rhiCtx, beginRenderPass(rtBack));
2043 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
2044
2045 renderer.rhiQuadRenderer()->recordRenderQuad(rhiCtx, &ps, srb, backDesc, QSSGRhiQuadRenderer::UvCoords);
2046
2047 cb->endPass();
2048 QSSGRHICTX_STAT(rhiCtx, endRenderPass());
2049 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QSSG_RENDERPASS_NAME("shadow_atlas", 7, 0));
2050
2051
2052 // reset pipeline (This part is necessary, but not ideal)
2053 ps = layerData.getPipelineState();
2054 ps.flags |= { QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled, QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled };
2055 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::UsesScissor, false);
2056 ps.depthBias = 2;
2057 ps.slopeScaledDepthBias = 1.5f;
2058
2059 if (drawPointLightShadowBoxes) {
2060 ShadowmapHelpers::addDebugBox(bounds.toQSSGBoxPoints(), QColorConstants::Yellow, debugDrawSystem);
2061 }
2062 }
2063 }
2064
2065 if (Q_UNLIKELY(drawCulledObjects)) {
2066 for (int i = 0, n = sortedOpaqueObjects.size(); i < n; ++i) {
2067 QSSGRenderableObject *theObject = sortedOpaqueObjects[i].obj;
2068 const QSSGBounds3 &globalBounds = !theObject->globalBoundsInstancing.isEmpty() ? theObject->globalBoundsInstancing
2069 : theObject->globalBounds;
2070 const QColor color = debugIsObjectCulled[i] ? QColorConstants::Red : QColorConstants::Green;
2071 ShadowmapHelpers::addDebugBox(globalBounds.toQSSGBoxPointsNoEmptyCheck(), color, debugDrawSystem);
2072 }
2073 }
2074}
2075
2077 QSSGPassKey passKey,
2078 const QSSGLayerRenderData &inData,
2079 QSSGRhiGraphicsPipelineState *ps,
2080 QSSGRenderReflectionMap &reflectionMapManager,
2081 const std::vector<QSSGRenderReflectionProbe *> &reflectionProbes,
2082 const QSSGRenderableObjectList &reflectionPassObjects,
2083 QSSGRenderer &renderer)
2084{
2085 QSSGRhiContext *rhiCtx = context.rhiContext().get();
2086 QRhi *rhi = rhiCtx->rhi();
2087 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
2088
2089 const bool renderSkybox = (inData.layer.background == QSSGRenderLayer::Background::SkyBox
2090 || inData.layer.background == QSSGRenderLayer::Background::SkyBoxCubeMap
2091 || inData.layer.background == QSSGRenderLayer::Background::SkyMaterial)
2092 && rhiCtx->rhi()->isFeatureSupported(QRhi::TexelFetch);
2093
2094 for (size_t i = 0, ie = reflectionProbes.size(); i != ie; ++i) {
2095 QSSGReflectionMapEntry *pEntry = reflectionMapManager.reflectionMapEntry(int(i));
2096 if (!pEntry)
2097 continue;
2098
2099 if (!pEntry->m_needsRender)
2100 continue;
2101
2102 if (reflectionProbes[i]->refreshMode == QSSGRenderReflectionProbe::ReflectionRefreshMode::FirstFrame && pEntry->m_rendered)
2103 continue;
2104
2105 if (reflectionProbes[i]->texture)
2106 continue;
2107
2108 Q_ASSERT(pEntry->m_rhiDepthStencil);
2109 Q_ASSERT(pEntry->m_rhiCube);
2110
2111 const QSize size = pEntry->m_rhiCube->pixelSize();
2112 ps->viewport = QRhiViewport(0, 0, float(size.width()), float(size.height()));
2113
2114 QSSGRenderCamera theCameras[6] { QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
2115 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
2116 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
2117 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
2118 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera},
2119 QSSGRenderCamera{QSSGRenderCamera::Type::PerspectiveCamera} };
2120 setupCubeReflectionCameras(inData, reflectionProbes[i], theCameras);
2121 const bool swapYFaces = !rhi->isYUpInFramebuffer();
2122 QMatrix4x4 cameraGlobalTransform(Qt::Uninitialized);
2123 for (const auto face : QSSGRenderTextureCubeFaces) {
2124 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(face);
2125 cameraGlobalTransform = inData.getGlobalTransform(theCameras[cubeFaceIdx]);
2126 theCameras[cubeFaceIdx].calculateViewProjectionMatrix(cameraGlobalTransform, pEntry->m_viewProjection);
2127
2128 rhiPrepareResourcesForReflectionMap(context, passKey, inData, pEntry, ps, reflectionPassObjects, theCameras[cubeFaceIdx], renderer, face);
2129 }
2130 QRhiRenderPassDescriptor *renderPassDesc = nullptr;
2131 for (auto face : QSSGRenderTextureCubeFaces) {
2132 if (pEntry->m_timeSlicing == QSSGRenderReflectionProbe::ReflectionTimeSlicing::IndividualFaces)
2133 face = pEntry->m_timeSliceFace;
2134
2135 QSSGRenderTextureCubeFace outFace = face;
2136 // Faces are swapped similarly to shadow maps due to differences in backends
2137 // Prefilter step handles correcting orientation differences in the final render
2138 if (swapYFaces) {
2139 if (outFace == QSSGRenderTextureCubeFace::PosY)
2140 outFace = QSSGRenderTextureCubeFace::NegY;
2141 else if (outFace == QSSGRenderTextureCubeFace::NegY)
2142 outFace = QSSGRenderTextureCubeFace::PosY;
2143 }
2144 QRhiTextureRenderTarget *rt = pEntry->m_rhiRenderTargets[quint8(outFace)];
2145 cb->beginPass(rt, reflectionProbes[i]->clearColor, { 1.0f, 0 }, nullptr, rhiCtx->commonPassFlags());
2146 QSSGRHICTX_STAT(rhiCtx, beginRenderPass(rt));
2147 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderPass);
2148
2149 if (renderSkybox && pEntry->m_skyBoxSrbs[quint8(face)]) {
2150 const auto &shaderCache = renderer.contextInterface()->shaderCache();
2151 const bool useSkyBoxQuad = inData.layer.background == QSSGRenderLayer::Background::SkyBox
2152 || inData.layer.background == QSSGRenderLayer::Background::SkyMaterial;
2153 const auto &shaderPipeline = useSkyBoxQuad
2154 ? shaderCache->getBuiltInRhiShaders().getRhiSkyBoxShader(QSSGRenderLayer::TonemapMode::None,
2155 inData.layer.skyBoxIsRgbe8,
2156 1)
2157 : shaderCache->getBuiltInRhiShaders().getRhiSkyBoxCubeShader(QSSGRenderLayer::TonemapMode::None,
2158 !inData.layer.skyBoxIsSrgb,
2159 1);
2160 Q_ASSERT(shaderPipeline);
2161 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(*ps, shaderPipeline.get());
2162 QRhiShaderResourceBindings *srb = pEntry->m_skyBoxSrbs[quint8(face)];
2163 if (!renderPassDesc)
2164 renderPassDesc = rt->newCompatibleRenderPassDescriptor();
2165 rt->setRenderPassDescriptor(renderPassDesc);
2166 useSkyBoxQuad ? renderer.rhiQuadRenderer()->recordRenderQuad(rhiCtx, ps, srb, renderPassDesc, {})
2167 : renderer.rhiCubeRenderer()->recordRenderCube(rhiCtx, ps, srb, renderPassDesc, {});
2168 }
2169
2170 bool needsSetViewport = true;
2171 for (const auto &handle : reflectionPassObjects)
2172 rhiRenderRenderable(rhiCtx, *ps, *handle.obj, &needsSetViewport, face);
2173
2174 cb->endPass();
2175 QSSGRHICTX_STAT(rhiCtx, endRenderPass());
2176 Q_QUICK3D_PROFILE_END_WITH_STRING(QQuick3DProfiler::Quick3DRenderPass, 0, QSSG_RENDERPASS_NAME("reflection_cube", 0, outFace));
2177
2178 if (pEntry->m_timeSlicing == QSSGRenderReflectionProbe::ReflectionTimeSlicing::IndividualFaces)
2179 break;
2180 }
2181 if (renderPassDesc)
2182 renderPassDesc->deleteLater();
2183
2184 pEntry->renderMips(rhiCtx);
2185
2186 if (pEntry->m_timeSlicing == QSSGRenderReflectionProbe::ReflectionTimeSlicing::IndividualFaces)
2187 pEntry->m_timeSliceFace = QSSGBaseTypeHelpers::next(pEntry->m_timeSliceFace); // Wraps
2188
2189 if (reflectionProbes[i]->refreshMode == QSSGRenderReflectionProbe::ReflectionRefreshMode::FirstFrame)
2190 pEntry->m_rendered = true;
2191
2192 reflectionProbes[i]->hasScheduledUpdate = false;
2193 pEntry->m_needsRender = false;
2194 }
2195}
2196
2197bool RenderHelpers::rhiPrepareAoTexture(QSSGRhiContext *rhiCtx,
2198 const QSize &size,
2199 QSSGRhiRenderableTexture *renderableTex,
2200 quint8 viewCount)
2201{
2202 QRhi *rhi = rhiCtx->rhi();
2203 QSSGRhiResourceRegistry &registry = QSSGRhiContextPrivate::get(rhiCtx)->resourceRegistry();
2204 bool needsBuild = false;
2205
2206 if (!renderableTex->texture) {
2207 QRhiTexture::Flags flags = QRhiTexture::RenderTarget;
2208 // the ambient occlusion texture is always non-msaa, even if multisampling is used in the main pass
2209 if (viewCount <= 1)
2210 renderableTex->texture = rhi->newTexture(QRhiTexture::RGBA8, size, 1, flags);
2211 else
2212 renderableTex->texture = rhi->newTextureArray(QRhiTexture::RGBA8, viewCount, size, 1, flags);
2213 needsBuild = true;
2214 } else if (renderableTex->texture->pixelSize() != size) {
2215 // Rebuilt in place, which counts as a replacement for the handles.
2216 registry.retire(renderableTex->texture);
2217 renderableTex->texture->setPixelSize(size);
2218 needsBuild = true;
2219 }
2220
2221 if (needsBuild) {
2222 if (!renderableTex->texture->create()) {
2223 qWarning("Failed to build ambient occlusion texture (size %dx%d)", size.width(), size.height());
2224 renderableTex->reset(&registry);
2225 return false;
2226 }
2227 renderableTex->resetRenderTarget();
2228 QRhiTextureRenderTargetDescription desc;
2229 QRhiColorAttachment colorAttachment(renderableTex->texture);
2230 colorAttachment.setMultiViewCount(viewCount);
2231 desc.setColorAttachments({ colorAttachment });
2232 renderableTex->rt = rhi->newTextureRenderTarget(desc);
2233 renderableTex->rt->setName(QByteArrayLiteral("Ambient occlusion"));
2234 renderableTex->rpDesc = renderableTex->rt->newCompatibleRenderPassDescriptor();
2235 renderableTex->rt->setRenderPassDescriptor(renderableTex->rpDesc);
2236 if (!renderableTex->rt->create()) {
2237 qWarning("Failed to build render target for ambient occlusion texture");
2238 renderableTex->reset(&registry);
2239 return false;
2240 }
2241 }
2242
2243 return true;
2244}
2245
2246void RenderHelpers::rhiRenderAoTexture(QSSGRhiContext *rhiCtx,
2247 QSSGPassKey passKey,
2248 QSSGRenderer &renderer,
2249 QSSGRhiShaderPipeline &shaderPipeline,
2250 QSSGRhiGraphicsPipelineState &ps,
2251 const QSSGAmbientOcclusionSettings &ao,
2252 const QSSGRhiRenderableTexture &rhiAoTexture,
2253 const QSSGRhiRenderableTexture &rhiDepthTexture,
2254 const QSSGRenderCamera &camera)
2255{
2256 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
2257
2258 // no texelFetch in GLSL <= 120 and GLSL ES 100
2259 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::TexelFetch)) {
2260 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
2261 // just clear and stop there
2262 cb->beginPass(rhiAoTexture.rt, Qt::white, { 1.0f, 0 });
2263 QSSGRHICTX_STAT(rhiCtx, beginRenderPass(rhiAoTexture.rt));
2264 cb->endPass();
2265 QSSGRHICTX_STAT(rhiCtx, endRenderPass());
2266 return;
2267 }
2268
2269 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(ps, &shaderPipeline);
2270
2271 const float R2 = ao.aoDistance * ao.aoDistance * 0.16f;
2272 const QSize textureSize = rhiAoTexture.texture->pixelSize();
2273 const float rw = float(textureSize.width());
2274 const float rh = float(textureSize.height());
2275 const float fov = camera.fov.asVerticalFov(rw / rh).radians();
2276 const float tanHalfFovY = tanf(0.5f * fov * (rh / rw));
2277 const float invFocalLenX = tanHalfFovY * (rw / rh);
2278
2279 const QVector4D aoProps(ao.aoStrength * 0.01f, ao.aoDistance * 0.4f, ao.aoSoftness * 0.02f, ao.aoBias);
2280 const QVector4D aoProps2(float(ao.aoSamplerate), (ao.aoDither) ? 1.0f : 0.0f, 0.0f, 0.0f);
2281 const QVector4D aoScreenConst(1.0f / R2, rh / (2.0f * tanHalfFovY), 1.0f / rw, 1.0f / rh);
2282 const QVector4D uvToEyeConst(2.0f * invFocalLenX, -2.0f * tanHalfFovY, -invFocalLenX, tanHalfFovY);
2283 const QVector2D cameraProps = camera.clipPlanes;
2284
2285 // layout(std140, binding = 0) uniform buf {
2286 // vec4 aoProperties;
2287 // vec4 aoProperties2;
2288 // vec4 aoScreenConst;
2289 // vec4 uvToEyeConst;
2290 // vec2 cameraProperties;
2291
2292 const int UBUF_SIZE = 72;
2293 QSSGRhiDrawCallData &dcd(rhiCtxD->drawCallData({ passKey, nullptr, nullptr, nullptr, 0 }));
2294 if (!dcd.ubuf) {
2295 dcd.ubuf = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, UBUF_SIZE);
2296 dcd.ubuf->create();
2297 }
2298
2299 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
2300 memcpy(ubufData, &aoProps, 16);
2301 memcpy(ubufData + 16, &aoProps2, 16);
2302 memcpy(ubufData + 32, &aoScreenConst, 16);
2303 memcpy(ubufData + 48, &uvToEyeConst, 16);
2304 memcpy(ubufData + 64, &cameraProps, 8);
2305 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
2306
2307 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
2308 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
2309 QSSGRhiShaderResourceBindingList bindings;
2310 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd.ubuf);
2311 // binding 1 is either a sampler2D or sampler2DArray, matching
2312 // rhiDepthTexture.texture, no special casing needed here
2313 bindings.addTexture(1, QRhiShaderResourceBinding::FragmentStage, rhiDepthTexture.texture, sampler);
2314 QRhiShaderResourceBindings *srb = rhiCtxD->srb(bindings);
2315
2316 renderer.rhiQuadRenderer()->prepareQuad(rhiCtx, nullptr);
2317 renderer.rhiQuadRenderer()->recordRenderQuadPass(rhiCtx, &ps, srb, rhiAoTexture.rt, {});
2318}
2319
2320bool RenderHelpers::rhiPrepareScreenTexture(QSSGRhiContext *rhiCtx,
2321 const QSize &size,
2322 bool wantsMips,
2323 QSSGRhiRenderableTexture *renderableTex,
2324 quint8 viewCount)
2325{
2326 QRhi *rhi = rhiCtx->rhi();
2327 QSSGRhiResourceRegistry &registry = QSSGRhiContextPrivate::get(rhiCtx)->resourceRegistry();
2328 bool needsBuild = false;
2329 QRhiTexture::Flags flags = QRhiTexture::RenderTarget;
2330 if (wantsMips)
2331 flags |= QRhiTexture::MipMapped | QRhiTexture::UsedWithGenerateMips;
2332
2333 if (!renderableTex->texture) {
2334 // always non-msaa, even if multisampling is used in the main pass
2335 if (viewCount <= 1)
2336 renderableTex->texture = rhi->newTexture(QRhiTexture::RGBA8, size, 1, flags);
2337 else
2338 renderableTex->texture = rhi->newTextureArray(QRhiTexture::RGBA8, viewCount, size, 1, flags);
2339 needsBuild = true;
2340 } else if (renderableTex->texture->pixelSize() != size) {
2341 // Rebuilt in place, which counts as a replacement for the handles.
2342 registry.retire(renderableTex->texture);
2343 renderableTex->texture->setPixelSize(size);
2344 needsBuild = true;
2345 }
2346
2347 if (!renderableTex->depthStencil && !renderableTex->depthTexture) {
2348 if (viewCount <= 1)
2349 renderableTex->depthStencil = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, size);
2350 else
2351 renderableTex->depthTexture = rhi->newTextureArray(QRhiTexture::D24S8, viewCount, size, 1, QRhiTexture::RenderTarget);
2352 needsBuild = true;
2353 } else {
2354 if (renderableTex->depthStencil && renderableTex->depthStencil->pixelSize() != size) {
2355 // Rebuilt in place, which counts as a replacement for the handles.
2356 registry.retire(renderableTex->depthStencil);
2357 renderableTex->depthStencil->setPixelSize(size);
2358 needsBuild = true;
2359 } else if (renderableTex->depthTexture && renderableTex->depthTexture->pixelSize() != size) {
2360 // Rebuilt in place, which counts as a replacement for the handles.
2361 registry.retire(renderableTex->depthTexture);
2362 renderableTex->depthTexture->setPixelSize(size);
2363 needsBuild = true;
2364 }
2365 }
2366
2367 if (needsBuild) {
2368 if (!renderableTex->texture->create()) {
2369 qWarning("Failed to build screen texture (size %dx%d)", size.width(), size.height());
2370 renderableTex->reset(&registry);
2371 return false;
2372 }
2373 if (renderableTex->depthStencil && !renderableTex->depthStencil->create()) {
2374 qWarning("Failed to build depth-stencil buffer for screen texture (size %dx%d)",
2375 size.width(), size.height());
2376 renderableTex->reset(&registry);
2377 return false;
2378 } else if (renderableTex->depthTexture && !renderableTex->depthTexture->create()) {
2379 qWarning("Failed to build depth-stencil texture array (multiview) for screen texture (size %dx%d)",
2380 size.width(), size.height());
2381 renderableTex->reset(&registry);
2382 return false;
2383 }
2384 renderableTex->resetRenderTarget();
2385 QRhiTextureRenderTargetDescription desc;
2386 QRhiColorAttachment colorAttachment(renderableTex->texture);
2387 colorAttachment.setMultiViewCount(viewCount);
2388 desc.setColorAttachments({ colorAttachment });
2389 if (renderableTex->depthStencil)
2390 desc.setDepthStencilBuffer(renderableTex->depthStencil);
2391 else if (renderableTex->depthTexture)
2392 desc.setDepthTexture(renderableTex->depthTexture);
2393 renderableTex->rt = rhi->newTextureRenderTarget(desc);
2394 renderableTex->rt->setName(QByteArrayLiteral("Screen texture"));
2395 renderableTex->rpDesc = renderableTex->rt->newCompatibleRenderPassDescriptor();
2396 renderableTex->rt->setRenderPassDescriptor(renderableTex->rpDesc);
2397 if (!renderableTex->rt->create()) {
2398 qWarning("Failed to build render target for screen texture");
2399 renderableTex->reset(&registry);
2400 return false;
2401 }
2402 }
2403
2404 return true;
2405}
2406
2407void RenderHelpers::rhiPrepareGrid(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, QSSGRenderLayer &layer, QSSGRenderCameraList &cameras, QSSGRenderer &renderer)
2408{
2409 QSSG_ASSERT(layer.renderData, return);
2410
2411 const auto *renderData = layer.renderData;
2412
2413 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
2414 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
2415 cb->debugMarkBegin(QByteArrayLiteral("Quick3D prepare grid"));
2416
2417 QSSGRhiShaderResourceBindingList bindings;
2418
2419 int uniformBinding = 0;
2420 const int ubufSize = cameras.count() >= 2 ? 276 : 148;
2421
2422 QSSGRhiDrawCallData &dcd(rhiCtxD->drawCallData({ passKey, nullptr, nullptr, nullptr, 0 })); // Change to Grid?
2423
2424 QRhi *rhi = rhiCtx->rhi();
2425 if (!dcd.ubuf) {
2426 dcd.ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, ubufSize);
2427 dcd.ubuf->create();
2428 }
2429
2430 // Param
2431 const auto clipPlanes = cameras[0]->clipPlanes;
2432 const float scale = layer.gridScale;
2433 const quint32 gridFlags = layer.gridFlags;
2434
2435 const float yFactor = rhi->isYUpInNDC() ? 1.0f : -1.0f;
2436
2437 quint32 ubufOffset = 0;
2438 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
2439
2440 QMatrix4x4 cameraGlobalTransform(Qt::Uninitialized);
2441 QMatrix4x4 viewProj(Qt::Uninitialized);
2442 for (qsizetype viewIdx = 0; viewIdx < cameras.count(); ++viewIdx) {
2443 cameraGlobalTransform = renderData->getGlobalTransform(*cameras[viewIdx]);
2444 cameras[viewIdx]->calculateViewProjectionMatrix(cameraGlobalTransform, viewProj);
2445 QMatrix4x4 invViewProj = viewProj.inverted();
2446 quint32 viewDataOffset = ubufOffset;
2447 memcpy(ubufData + viewDataOffset + viewIdx * 64, viewProj.constData(), 64);
2448 viewDataOffset += 64 * cameras.count();
2449 memcpy(ubufData + viewDataOffset + viewIdx * 64, invViewProj.constData(), 64);
2450 }
2451 ubufOffset += (64 + 64) * cameras.count();
2452
2453 memcpy(ubufData + ubufOffset, &clipPlanes, 8);
2454 ubufOffset += 8;
2455 memcpy(ubufData + ubufOffset, &scale, 4);
2456 ubufOffset += 4;
2457 memcpy(ubufData + ubufOffset, &yFactor, 4);
2458 ubufOffset += 4;
2459 memcpy(ubufData + ubufOffset, &gridFlags, 4);
2460
2461 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
2462
2463 bindings.addUniformBuffer(uniformBinding, RENDERER_VISIBILITY_ALL, dcd.ubuf);
2464
2465 layer.gridSrb = rhiCtxD->srb(bindings);
2466 renderer.rhiQuadRenderer()->prepareQuad(rhiCtx, nullptr);
2467
2468 cb->debugMarkEnd();
2469}
2470
2472 QSSGPassKey passKey,
2473 QSSGRenderLayer &layer,
2474 QSSGRenderCameraList &cameras,
2475 QSSGRenderer &renderer,
2476 QSSGReflectionMapEntry *entry = nullptr,
2477 QSSGRenderTextureCubeFace cubeFace = QSSGRenderTextureCubeFaceNone,
2478 uint tonemapMode = 0)
2479{
2480 QSSG_ASSERT(layer.renderData, return);
2481
2482 const auto *renderData = layer.renderData;
2483
2484 auto rhiCtx = context.rhiContext().get();
2485
2486 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
2487
2488 QSSGRenderImageTexture lightProbeTexture;
2489 switch (layer.background) {
2490 case QSSGRenderLayer::Background::SkyBox:
2491 lightProbeTexture = renderer.contextInterface()->bufferManager()->loadRenderImage(layer.lightProbe,
2492 QSSGBufferManager::MipModeBsdf);
2493 break;
2494 case QSSGRenderLayer::Background::SkyBoxCubeMap:
2495 lightProbeTexture = renderer.contextInterface()->bufferManager()->loadRenderImage(layer.skyBoxCubeMap,
2496 QSSGBufferManager::MipModeDisable);
2497 break;
2498 case QSSGRenderLayer::Background::SkyMaterial:
2499 lightProbeTexture = renderData->skyMaterialTexture;
2500 break;
2501 default:
2502 Q_UNREACHABLE_RETURN();
2503 }
2504
2505 if (lightProbeTexture.m_texture == nullptr) {
2506 // No valid texture this frame; drop any previously built SRB rather than
2507 // reuse one that may reference a texture ensureTextures() has since deleted.
2508 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
2509 // All 6 face SRBs bind the same light probe texture, so all of them (not
2510 // just the face passed in this call) are equally stale.
2511 for (QRhiShaderResourceBindings *&srb : entry->m_skyBoxSrbs)
2512 srb = nullptr;
2513 } else {
2514 layer.skyBoxSrb = nullptr;
2515 }
2516 return;
2517 }
2518
2519 const bool cubeMapMode = layer.background == QSSGRenderLayer::Background::SkyBoxCubeMap;
2520
2521 if (cubeFace == QSSGRenderTextureCubeFaceNone)
2522 layer.skyBoxIsRgbe8 = lightProbeTexture.m_flags.isRgbe8();
2523 if (cubeMapMode)
2524 layer.skyBoxIsSrgb = !lightProbeTexture.m_flags.isLinear();
2525
2526 QSSGRhiShaderResourceBindingList bindings;
2527
2528 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
2529 QRhiSampler::Linear,
2530 cubeMapMode ? QRhiSampler::None : QRhiSampler::Linear, // cube map doesn't have mipmaps
2531 QRhiSampler::Repeat,
2532 QRhiSampler::ClampToEdge,
2533 QRhiSampler::Repeat });
2534 int samplerBinding = 1; // the shader code is hand-written, so we don't need to look that up
2535 bindings.addTexture(samplerBinding, QRhiShaderResourceBinding::FragmentStage, lightProbeTexture.m_texture, sampler);
2536
2537 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
2538 const quintptr entryIdx = quintptr(cubeFace != QSSGRenderTextureCubeFaceNone) * cubeFaceIdx;
2539 QSSGRhiDrawCallData &dcd = rhiCtxD->drawCallData({ passKey, nullptr, nullptr, entry, entryIdx });
2540
2541 QRhi *rhi = rhiCtx->rhi();
2542 const quint32 ubufSize = cameras.count() >= 2 ? 416 : 240; // same ubuf layout for both skybox and skyboxcube
2543 if (!dcd.ubuf) {
2544 dcd.ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, int(ubufSize));
2545 dcd.ubuf->create();
2546 } else if (dcd.ubuf->size() != ubufSize) {
2547 // Resize in place. A new buffer would leave the srbs cached for the old one
2548 // behind, as the cache only releases those when the draw call data goes away.
2549 dcd.ubuf->setSize(ubufSize);
2550 dcd.ubuf->create();
2551 }
2552
2553 float adjustY = rhi->isYUpInNDC() ? 1.0f : -1.0f;
2554 const float exposure = layer.lightProbeSettings.probeExposure;
2555 // orientation
2556 const QMatrix3x3 &rotationMatrix(layer.lightProbeSettings.probeOrientation);
2557
2558 // The cubemap shader doesn't use blur or mipmapping, so it uses those for tonemapping and texture color space
2559 const float blurAmountOrSrgb = cubeMapMode ? layer.skyBoxIsSrgb : layer.skyboxBlurAmount;
2560 const float maxMipLevelOrTonemapMode = cubeMapMode ? float(tonemapMode) : float(lightProbeTexture.m_mipmapCount - 2);
2561
2562 const QVector4D skyboxProperties = {
2563 adjustY,
2564 exposure,
2565 blurAmountOrSrgb,
2566 maxMipLevelOrTonemapMode
2567 };
2568
2569 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
2570 quint32 ubufOffset = 0;
2571 // skyboxProperties
2572 memcpy(ubufData + ubufOffset, &skyboxProperties, 16);
2573 ubufOffset += 16;
2574 // orientation
2575 memcpy(ubufData + ubufOffset, rotationMatrix.constData(), 12);
2576 ubufOffset += 16;
2577 memcpy(ubufData + ubufOffset, (char *)rotationMatrix.constData() + 12, 12);
2578 ubufOffset += 16;
2579 memcpy(ubufData + ubufOffset, (char *)rotationMatrix.constData() + 24, 12);
2580 ubufOffset += 16;
2581
2582 for (qsizetype viewIdx = 0; viewIdx < cameras.count(); ++viewIdx) {
2583 const QMatrix4x4 &inverseProjection = cameras[viewIdx]->projection.inverted();
2584 const QMatrix4x4 &viewMatrix = renderData->getGlobalTransform(*cameras[viewIdx]);
2585 QMatrix4x4 viewProjection(Qt::Uninitialized); // For cube mode
2586 cameras[viewIdx]->calculateViewProjectionWithoutTranslation(viewMatrix, 0.1f, 5.0f, viewProjection);
2587
2588 quint32 viewDataOffset = ubufOffset;
2589 memcpy(ubufData + viewDataOffset + viewIdx * 64, viewProjection.constData(), 64);
2590 viewDataOffset += cameras.count() * 64;
2591 memcpy(ubufData + viewDataOffset + viewIdx * 64, inverseProjection.constData(), 64);
2592 viewDataOffset += cameras.count() * 64;
2593 memcpy(ubufData + viewDataOffset + viewIdx * 48, viewMatrix.constData(), 48);
2594 }
2595 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
2596
2597 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd.ubuf);
2598
2599 if (cubeFace != QSSGRenderTextureCubeFaceNone) {
2600 const auto cubeFaceIdx = QSSGBaseTypeHelpers::indexOfCubeFace(cubeFace);
2601 entry->m_skyBoxSrbs[cubeFaceIdx] = rhiCtxD->srb(bindings);
2602 } else {
2603 layer.skyBoxSrb = rhiCtxD->srb(bindings);
2604 }
2605
2606 if (cubeMapMode)
2607 renderer.rhiCubeRenderer()->prepareCube(rhiCtx, nullptr);
2608 else
2609 renderer.rhiQuadRenderer()->prepareQuad(rhiCtx, nullptr);
2610}
2611
2612void RenderHelpers::rhiPrepareSkyBox(const QSSGRenderContextInterface &context,
2613 QSSGPassKey passKey,
2614 QSSGRenderLayer &layer,
2615 QSSGRenderCameraList &cameras,
2616 QSSGRenderer &renderer,
2617 uint tonemapMode)
2618{
2619 auto rhiCtx = context.rhiContext().get();
2620 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
2621 cb->debugMarkBegin(QByteArrayLiteral("Quick3D prepare skybox"));
2622
2623 rhiPrepareSkyBox_helper(context, passKey, layer, cameras, renderer, nullptr, QSSGRenderTextureCubeFaceNone, tonemapMode);
2624
2625 cb->debugMarkEnd();
2626}
2627
2628void RenderHelpers::rhiPrepareSkyBoxForReflectionMap(const QSSGRenderContextInterface &context,
2629 QSSGPassKey passKey,
2630 QSSGRenderLayer &layer,
2631 QSSGRenderCamera &inCamera,
2632 QSSGRenderer &renderer,
2634 QSSGRenderTextureCubeFace cubeFace)
2635{
2636 QSSGRhiContext *rhiCtx = context.rhiContext().get();
2637
2638 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
2639 cb->debugMarkBegin(QByteArrayLiteral("Quick3D prepare skybox for reflection cube map"));
2640
2641 QSSGRenderCameraList cameras({ &inCamera });
2642 rhiPrepareSkyBox_helper(context, passKey, layer, cameras, renderer, entry, cubeFace);
2643
2644 cb->debugMarkEnd();
2645}
2646
2647bool RenderHelpers::rhiPrepareDepthPass(QSSGRhiContext *rhiCtx,
2648 QSSGPassKey passKey,
2649 const QSSGRhiGraphicsPipelineState &basePipelineState,
2650 QRhiRenderPassDescriptor *rpDesc,
2651 QSSGLayerRenderData &inData,
2652 const QSSGRenderableObjectList &sortedOpaqueObjects,
2653 const QSSGRenderableObjectList &sortedTransparentObjects,
2654 int samples,
2655 int viewCount)
2656{
2657 static const auto rhiPrepareDepthPassForObject = [](QSSGRhiContext *rhiCtx,
2658 QSSGPassKey passKey,
2659 QSSGLayerRenderData &inData,
2661 QRhiRenderPassDescriptor *rpDesc,
2662 QSSGRhiGraphicsPipelineState *ps) {
2663 QSSGRhiShaderPipelinePtr shaderPipeline;
2664 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
2665
2666 const bool isOpaqueDepthPrePass = obj->depthWriteMode == QSSGDepthDrawMode::OpaquePrePass;
2667 QSSGShaderFeatures featureSet;
2668 featureSet.set(QSSGShaderFeatures::Feature::DepthPass, true);
2669 if (isOpaqueDepthPrePass)
2670 featureSet.set(QSSGShaderFeatures::Feature::OpaqueDepthPrePass, true);
2671
2672 QSSGRhiDrawCallData *dcd = nullptr;
2673 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
2674 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*obj));
2675 const void *modelNode = &subsetRenderable.modelContext.model;
2676 dcd = &rhiCtxD->drawCallData({ passKey, modelNode, &subsetRenderable.material, nullptr, 0 });
2677 }
2678
2679 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset) {
2680 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*obj));
2681 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(subsetRenderable.getMaterial());
2682 ps->cullMode = QSSGRhiHelpers::toCullMode(material.cullMode);
2683
2684 shaderPipeline = shadersForDefaultMaterial(ps, subsetRenderable, featureSet);
2685 if (shaderPipeline) {
2686 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
2687 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
2688 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, ps, subsetRenderable, inData.renderedCameras, nullptr, nullptr);
2689 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
2690 } else {
2691 return false;
2692 }
2693 } else if (obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
2694 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*obj));
2695
2696 const auto &customMaterial = static_cast<const QSSGRenderCustomMaterial &>(subsetRenderable.getMaterial());
2697
2698 ps->cullMode = QSSGRhiHelpers::toCullMode(customMaterial.m_cullMode);
2699
2700 QSSGCustomMaterialSystem &customMaterialSystem(*subsetRenderable.renderer->contextInterface()->customMaterialSystem().get());
2701 shaderPipeline = customMaterialSystem.shadersForCustomMaterial(ps, customMaterial, subsetRenderable, inData.getDefaultMaterialPropertyTable(), featureSet);
2702
2703 if (shaderPipeline) {
2704 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
2705 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
2706 customMaterialSystem.updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, inData, ubufData, ps, customMaterial, subsetRenderable,
2707 inData.renderedCameras, nullptr, nullptr);
2708 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
2709 } else {
2710 return false;
2711 }
2712 }
2713
2714 // the rest is common, only relying on QSSGSubsetRenderableBase, not the subclasses
2715 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
2716 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*obj));
2717 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
2718 ia = subsetRenderable.subset.rhi.ia;
2719
2720 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
2721 int instanceBufferBinding = setupInstancing(&subsetRenderable, ps, rhiCtx, inData, cameraDatas[0].direction, cameraDatas[0].position,
2722 InstanceLevels::PerInstance, *shaderPipeline);
2723 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
2724
2725 QSSGRhiShaderResourceBindingList bindings;
2726 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd->ubuf);
2727
2728 // Depth and SSAO textures, in case a custom material's shader code does something with them.
2729 addDepthTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
2730
2731 if (isOpaqueDepthPrePass) {
2732 addOpaqueDepthPrePassBindings(rhiCtx,
2733 shaderPipeline.get(),
2734 subsetRenderable.firstImage,
2735 bindings,
2736 (obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset));
2737 }
2738
2739 // There is no normal texture at this stage. But the shader from a
2740 // custom material may rely on it. Bind a dummy texture then due to
2741 // the lack of other options.
2742 const int normalTextureBinding = shaderPipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
2743 if (normalTextureBinding >= 0) {
2744 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
2745 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
2746 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
2747 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
2748 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
2749 bindings.addTexture(normalTextureBinding, RENDERER_VISIBILITY_ALL, dummyTexture, sampler);
2750 }
2751
2752 // Skinning
2753 if (QRhiTexture *boneTexture = inData.getBonemapTexture(subsetRenderable.modelContext)) {
2754 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
2755 if (binding >= 0) {
2756 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
2757 QRhiSampler::Nearest,
2758 QRhiSampler::None,
2759 QRhiSampler::ClampToEdge,
2760 QRhiSampler::ClampToEdge,
2761 QRhiSampler::Repeat
2762 });
2763 bindings.addTexture(binding,
2764 QRhiShaderResourceBinding::VertexStage,
2765 boneTexture,
2766 boneSampler);
2767 }
2768 }
2769
2770 // Morphing
2771 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
2772 if (targetsTexture) {
2773 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
2774 if (binding >= 0) {
2775 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
2776 QRhiSampler::Nearest,
2777 QRhiSampler::None,
2778 QRhiSampler::ClampToEdge,
2779 QRhiSampler::ClampToEdge,
2780 QRhiSampler::ClampToEdge
2781 });
2782 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
2783 }
2784 }
2785 shaderPipeline->applyAndClearStorageBindings(RENDERER_VISIBILITY_ALL, bindings);
2786
2787 QRhiShaderResourceBindings *srb = drawCallDataSrb(rhiCtxD, *dcd, bindings);
2788
2789 subsetRenderable.rhiRenderData.depthPrePass.pipeline = rhiCtxD->pipeline(*ps,
2790 rpDesc,
2791 srb);
2792 subsetRenderable.rhiRenderData.depthPrePass.srb = srb;
2793 }
2794
2795 return true;
2796 };
2797
2798 // Phase 1 (prepare) for the Z prepass or the depth texture generation.
2799 // These renders opaque (Z prepass), or opaque and transparent (depth
2800 // texture), objects with depth test/write enabled, and color write
2801 // disabled, using a very simple set of shaders.
2802
2803 QSSGRhiGraphicsPipelineState ps = basePipelineState; // viewport and others are filled out already
2804 // We took a copy of the pipeline state since we do not want to conflict
2805 // with what rhiPrepare() collects for its own use. So here just change
2806 // whatever we need.
2807
2808 ps.samples = samples;
2809 ps.viewCount = viewCount;
2810 ps.flags |= { QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled, QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled };
2811 ps.targetBlend[0].colorWrite = {};
2812
2813 for (const QSSGRenderableObjectHandle &handle : sortedOpaqueObjects) {
2814 if (!rhiPrepareDepthPassForObject(rhiCtx, passKey, inData, handle.obj, rpDesc, &ps))
2815 return false;
2816 }
2817
2818 for (const QSSGRenderableObjectHandle &handle : sortedTransparentObjects) {
2819 if (!rhiPrepareDepthPassForObject(rhiCtx, passKey, inData, handle.obj, rpDesc, &ps))
2820 return false;
2821 }
2822
2823 return true;
2824}
2825
2826void RenderHelpers::rhiRenderDepthPass(QSSGRhiContext *rhiCtx,
2827 const QSSGRhiGraphicsPipelineState &pipelineState,
2828 const QSSGRenderableObjectList &sortedOpaqueObjects,
2829 const QSSGRenderableObjectList &sortedTransparentObjects,
2830 bool *needsSetViewport)
2831{
2832 static const auto rhiRenderDepthPassForImp = [](QSSGRhiContext *rhiCtx,
2833 const QSSGRhiGraphicsPipelineState &pipelineState,
2834 const QSSGRenderableObjectList &objects,
2835 bool *needsSetViewport) {
2836 for (const auto &oh : objects) {
2837 QSSGRenderableObject *obj = oh.obj;
2838
2839 // casts to SubsetRenderableBase so it works for both default and custom materials
2840 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
2841 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
2842 QSSGSubsetRenderable *subsetRenderable(static_cast<QSSGSubsetRenderable *>(obj));
2843
2844 QRhiBuffer *indexBuffer = subsetRenderable->subset.rhi.indexBuffer
2845 ? subsetRenderable->subset.rhi.indexBuffer->buffer()
2846 : nullptr;
2847
2848 QRhiGraphicsPipeline *ps = subsetRenderable->rhiRenderData.depthPrePass.pipeline;
2849 if (!ps)
2850 return;
2851
2852 QRhiShaderResourceBindings *srb = subsetRenderable->rhiRenderData.depthPrePass.srb;
2853 if (!srb)
2854 return;
2855
2856 QRhiCommandBuffer::VertexInput vertexBuffers[3];
2857 int vertexBufferCount = 0;
2858 quint32 instances = 1;
2859 if (!setupDrawInputs(rhiCtx, ps, *subsetRenderable,
2860 (subsetRenderable->usesAutoLod && indexBuffer)
2861 ? subsetRenderable->autoLodInstanceIndexBuffer : subsetRenderable->instanceIndexBuffer,
2862 vertexBuffers, vertexBufferCount, instances))
2863 return;
2864
2865 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
2866 cb->setGraphicsPipeline(ps);
2867 cb->setShaderResources(srb);
2868
2869 if (*needsSetViewport) {
2870 cb->setViewport(pipelineState.viewport);
2871 if (pipelineState.flags & QSSGRhiGraphicsPipelineState::Flag::UsesScissor)
2872 cb->setScissor(pipelineState.scissor);
2873 *needsSetViewport = false;
2874 }
2875
2876 if (subsetRenderable->usesAutoLod && indexBuffer) {
2877 RenderHelpers::rhiDrawAutoLodInstanced(rhiCtx, cb, vertexBuffers, vertexBufferCount, indexBuffer, *subsetRenderable);
2878 } else if (indexBuffer) {
2879 cb->setVertexInput(0, vertexBufferCount, vertexBuffers, indexBuffer, 0, subsetRenderable->subset.rhi.indexBuffer->indexFormat());
2880 cb->drawIndexed(subsetRenderable->subset.lodCount(subsetRenderable->subsetLevelOfDetail), instances, subsetRenderable->subset.lodOffset(subsetRenderable->subsetLevelOfDetail));
2881 QSSGRHICTX_STAT(rhiCtx, drawIndexed(subsetRenderable->subset.lodCount(subsetRenderable->subsetLevelOfDetail), instances));
2882 } else {
2883 cb->setVertexInput(0, vertexBufferCount, vertexBuffers);
2884 rhiDrawNonIndexed(rhiCtx, cb, *subsetRenderable, instances);
2885 }
2886 Q_QUICK3D_PROFILE_END_WITH_IDS(QQuick3DProfiler::Quick3DRenderCall, (subsetRenderable->subset.count | quint64(instances) << 32),
2887 QVector<int>({subsetRenderable->modelContext.model.profilingId,
2888 subsetRenderable->material.profilingId}));
2889 }
2890 }
2891 };
2892
2893 rhiRenderDepthPassForImp(rhiCtx, pipelineState, sortedOpaqueObjects, needsSetViewport);
2894 rhiRenderDepthPassForImp(rhiCtx, pipelineState, sortedTransparentObjects, needsSetViewport);
2895}
2896
2897bool RenderHelpers::rhiPrepareDepthTexture(QSSGRhiContext *rhiCtx,
2898 const QSize &size,
2899 QSSGRhiRenderableTexture *renderableTex,
2900 quint8 viewCount,
2901 int samples)
2902{
2903 QRhi *rhi = rhiCtx->rhi();
2904 QSSGRhiResourceRegistry &registry = QSSGRhiContextPrivate::get(rhiCtx)->resourceRegistry();
2905 bool needsBuild = false;
2906
2907 if (!renderableTex->texture) {
2908 QRhiTexture::Format format = QRhiTexture::D32F;
2909 if (!rhi->isTextureFormatSupported(format))
2910 format = QRhiTexture::D16;
2911 if (!rhi->isTextureFormatSupported(format))
2912 qWarning("Depth texture not supported");
2913 if (viewCount <= 1)
2914 renderableTex->texture = rhiCtx->rhi()->newTexture(format, size, samples, QRhiTexture::RenderTarget);
2915 else
2916 renderableTex->texture = rhiCtx->rhi()->newTextureArray(format, viewCount, size, 1, QRhiTexture::RenderTarget);
2917 needsBuild = true;
2918 } else if (renderableTex->texture->pixelSize() != size) {
2919 // Rebuilt in place, which counts as a replacement for the handles.
2920 registry.retire(renderableTex->texture);
2921 renderableTex->texture->setPixelSize(size);
2922 needsBuild = true;
2923 }
2924
2925 if (needsBuild) {
2926 if (!renderableTex->texture->create()) {
2927 qWarning("Failed to build depth texture (size %dx%d, format %d)",
2928 size.width(), size.height(), int(renderableTex->texture->format()));
2929 renderableTex->reset(&registry);
2930 return false;
2931 }
2932 renderableTex->resetRenderTarget();
2933 QRhiTextureRenderTargetDescription rtDesc;
2934 rtDesc.setDepthTexture(renderableTex->texture);
2935 renderableTex->rt = rhi->newTextureRenderTarget(rtDesc);
2936 renderableTex->rt->setName(QByteArrayLiteral("Depth texture"));
2937 renderableTex->rpDesc = renderableTex->rt->newCompatibleRenderPassDescriptor();
2938 renderableTex->rt->setRenderPassDescriptor(renderableTex->rpDesc);
2939 if (!renderableTex->rt->create()) {
2940 qWarning("Failed to build render target for depth texture");
2941 renderableTex->reset(&registry);
2942 return false;
2943 }
2944 }
2945
2946 return true;
2947}
2948
2949bool RenderHelpers::rhiPrepareNormalPass(QSSGRhiContext *rhiCtx,
2950 QSSGPassKey passKey,
2951 const QSSGRhiGraphicsPipelineState &basePipelineState,
2952 QRhiRenderPassDescriptor *rpDesc,
2953 QSSGLayerRenderData &inData,
2954 const QSSGRenderableObjectList &sortedOpaqueObjects)
2955{
2956 QSSGRhiGraphicsPipelineState ps = basePipelineState;
2957 ps.depthFunc = QRhiGraphicsPipeline::LessOrEqual;
2958 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::BlendEnabled, false);
2959
2960 for (const QSSGRenderableObjectHandle &handle : sortedOpaqueObjects) {
2961 QSSGRenderableObject *obj = handle.obj;
2962 QSSGRhiShaderPipelinePtr shaderPipeline;
2963 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
2964
2965 QSSGShaderFeatures featureSet;
2966 featureSet.set(QSSGShaderFeatures::Feature::NormalPass, true);
2967
2968 QSSGRhiDrawCallData *dcd = nullptr;
2969 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
2970 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
2971 const void *modelNode = &subsetRenderable.modelContext.model;
2972 dcd = &rhiCtxD->drawCallData({ passKey, modelNode, &subsetRenderable.material, nullptr, 0 });
2973 }
2974
2975 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset) {
2976 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
2977 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(subsetRenderable.getMaterial());
2978 ps.cullMode = QSSGRhiHelpers::toCullMode(material.cullMode);
2979
2980 shaderPipeline = shadersForDefaultMaterial(&ps, subsetRenderable, featureSet);
2981 if (shaderPipeline) {
2982 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
2983 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
2984 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, subsetRenderable, inData.renderedCameras, nullptr, nullptr);
2985 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
2986 }
2987 } else if (obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
2988 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
2989
2990 const auto &customMaterial = static_cast<const QSSGRenderCustomMaterial &>(subsetRenderable.getMaterial());
2991
2992 ps.cullMode = QSSGRhiHelpers::toCullMode(customMaterial.m_cullMode);
2993
2994 const auto &customMaterialSystem = subsetRenderable.renderer->contextInterface()->customMaterialSystem();
2995 shaderPipeline = customMaterialSystem->shadersForCustomMaterial(&ps, customMaterial, subsetRenderable, inData.getDefaultMaterialPropertyTable(), featureSet);
2996
2997 if (shaderPipeline) {
2998 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
2999 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
3000 customMaterialSystem->updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, customMaterial, subsetRenderable,
3001 inData.renderedCameras, nullptr, nullptr);
3002 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
3003 }
3004 }
3005
3006 // the rest is common, only relying on QSSGSubsetRenderableBase, not the subclasses
3007 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3008 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*obj));
3009 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(ps);
3010 ia = subsetRenderable.subset.rhi.ia;
3011
3012 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
3013 int instanceBufferBinding = setupInstancing(&subsetRenderable, &ps, rhiCtx, inData, cameraDatas[0].direction, cameraDatas[0].position,
3014 InstanceLevels::PerInstance, *shaderPipeline);
3015 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
3016
3017 QSSGRhiShaderResourceBindingList bindings;
3018 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd->ubuf);
3019
3020 // Texture maps
3021 QSSGRenderableImage *renderableImage = subsetRenderable.firstImage;
3022 while (renderableImage) {
3023 const char *samplerName = QSSGMaterialShaderGenerator::getSamplerName(renderableImage->m_mapType);
3024 const int samplerHint = int(renderableImage->m_mapType);
3025 int samplerBinding = shaderPipeline->bindingForTexture(samplerName, samplerHint);
3026 if (samplerBinding >= 0) {
3027 QRhiTexture *texture = renderableImage->m_texture.m_texture;
3028 if (samplerBinding >= 0 && texture) {
3029 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
3030 QSSGRhiSamplerDescription samplerDesc = {
3031 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
3032 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
3033 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
3034 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
3035 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
3036 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
3037 };
3038 rhiCtx->checkAndAdjustForNPoT(texture, &samplerDesc);
3039 QRhiSampler *sampler = rhiCtx->sampler(samplerDesc);
3040 bindings.addTexture(samplerBinding, RENDERER_VISIBILITY_ALL, texture, sampler);
3041 }
3042 } // else this is not necessarily an error, e.g. having metalness/roughness maps with metalness disabled
3043 renderableImage = renderableImage->m_nextImage;
3044 }
3045
3046 addDepthTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
3047
3048 // There is no normal texture at this stage, obviously.
3049 const int normalTextureBinding = shaderPipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
3050 if (normalTextureBinding >= 0) {
3051 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
3052 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
3053 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3054 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
3055 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3056 bindings.addTexture(normalTextureBinding, RENDERER_VISIBILITY_ALL, dummyTexture, sampler);
3057 }
3058
3059 // Shadow maps are not needed since lighting-related shading is mostly skipped in the normal texture's pass
3060
3061 // Skinning
3062 if (QRhiTexture *boneTexture = inData.getBonemapTexture(subsetRenderable.modelContext)) {
3063 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
3064 if (binding >= 0) {
3065 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3066 QRhiSampler::Nearest,
3067 QRhiSampler::None,
3068 QRhiSampler::ClampToEdge,
3069 QRhiSampler::ClampToEdge,
3070 QRhiSampler::Repeat
3071 });
3072 bindings.addTexture(binding,
3073 QRhiShaderResourceBinding::VertexStage,
3074 boneTexture,
3075 boneSampler);
3076 }
3077 }
3078
3079 // Morphing
3080 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
3081 if (targetsTexture) {
3082 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
3083 if (binding >= 0) {
3084 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3085 QRhiSampler::Nearest,
3086 QRhiSampler::None,
3087 QRhiSampler::ClampToEdge,
3088 QRhiSampler::ClampToEdge,
3089 QRhiSampler::ClampToEdge
3090 });
3091 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
3092 }
3093 }
3094
3095 shaderPipeline->applyAndClearStorageBindings(RENDERER_VISIBILITY_ALL, bindings);
3096 QRhiShaderResourceBindings *srb = drawCallDataSrb(rhiCtxD, *dcd, bindings);
3097
3098 subsetRenderable.rhiRenderData.normalPass.pipeline = rhiCtxD->pipeline(ps,
3099 rpDesc,
3100 srb);
3101 subsetRenderable.rhiRenderData.normalPass.srb = srb;
3102 }
3103 }
3104
3105 return true;
3106}
3107
3108void RenderHelpers::rhiRenderNormalPass(QSSGRhiContext *rhiCtx,
3109 const QSSGRhiGraphicsPipelineState &pipelineState,
3110 const QSSGRenderableObjectList &sortedOpaqueObjects,
3111 bool *needsSetViewport)
3112{
3113 for (const auto &oh : sortedOpaqueObjects) {
3114 QSSGRenderableObject *obj = oh.obj;
3115
3116 // casts to SubsetRenderableBase so it works for both default and custom materials
3117 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3118 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
3119 QSSGSubsetRenderable *subsetRenderable(static_cast<QSSGSubsetRenderable *>(obj));
3120
3121 QRhiBuffer *indexBuffer = subsetRenderable->subset.rhi.indexBuffer
3122 ? subsetRenderable->subset.rhi.indexBuffer->buffer()
3123 : nullptr;
3124
3125 QRhiGraphicsPipeline *graphicsPipeline = subsetRenderable->rhiRenderData.normalPass.pipeline;
3126 if (!graphicsPipeline)
3127 return;
3128
3129 QRhiShaderResourceBindings *srb = subsetRenderable->rhiRenderData.normalPass.srb;
3130 if (!srb)
3131 return;
3132
3133 QRhiCommandBuffer::VertexInput vertexBuffers[3];
3134 int vertexBufferCount = 0;
3135 quint32 instances = 1;
3136 if (!setupDrawInputs(rhiCtx, graphicsPipeline, *subsetRenderable,
3137 (subsetRenderable->usesAutoLod && indexBuffer)
3138 ? subsetRenderable->autoLodInstanceIndexBuffer : subsetRenderable->instanceIndexBuffer,
3139 vertexBuffers, vertexBufferCount, instances))
3140 return;
3141
3142 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
3143 cb->setGraphicsPipeline(graphicsPipeline);
3144 cb->setShaderResources(srb);
3145
3146 if (*needsSetViewport) {
3147 cb->setViewport(pipelineState.viewport);
3148 if (pipelineState.flags & QSSGRhiGraphicsPipelineState::Flag::UsesScissor)
3149 cb->setScissor(pipelineState.scissor);
3150 *needsSetViewport = false;
3151 }
3152
3153 if (subsetRenderable->usesAutoLod && indexBuffer) {
3154 RenderHelpers::rhiDrawAutoLodInstanced(rhiCtx, cb, vertexBuffers, vertexBufferCount, indexBuffer, *subsetRenderable);
3155 } else if (indexBuffer) {
3156 cb->setVertexInput(0, vertexBufferCount, vertexBuffers, indexBuffer, 0, subsetRenderable->subset.rhi.indexBuffer->indexFormat());
3157 cb->drawIndexed(subsetRenderable->subset.lodCount(subsetRenderable->subsetLevelOfDetail), instances, subsetRenderable->subset.lodOffset(subsetRenderable->subsetLevelOfDetail));
3158 QSSGRHICTX_STAT(rhiCtx, drawIndexed(subsetRenderable->subset.lodCount(subsetRenderable->subsetLevelOfDetail), instances));
3159 } else {
3160 cb->setVertexInput(0, vertexBufferCount, vertexBuffers);
3161 rhiDrawNonIndexed(rhiCtx, cb, *subsetRenderable, instances);
3162 }
3163 Q_QUICK3D_PROFILE_END_WITH_IDS(QQuick3DProfiler::Quick3DRenderCall, (subsetRenderable->subset.count | quint64(instances) << 32),
3164 QVector<int>({subsetRenderable->modelContext.model.profilingId,
3165 subsetRenderable->material.profilingId}));
3166 }
3167 }
3168}
3169
3171 QSSGPassKey passKey,
3172 const QSSGRhiGraphicsPipelineState &basePipelineState,
3173 QRhiRenderPassDescriptor *rpDesc,
3174 QSSGRenderGraphObject *overrideMaterial,
3175 QSSGLayerRenderData &inData,
3176 QSSGRenderableObjectList &inObjects,
3177 QSSGShaderFeatures featureSet)
3178{
3179 // Make sure we have a valid override material before acquireing a user pass slot!
3180 const qsizetype index = overrideMaterial ? inData.getUserRenderPassManager()->acquireUserPassSlot() : -1;
3181 // If the index is negative, it means there are no more available slots for user passes, so we can skip the preparation and rendering of this pass.
3182 if (index < 0)
3183 return index;
3184
3185 QSSGRhiGraphicsPipelineState ps = basePipelineState;
3186 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
3187
3188 const bool isCustomMaterial = (overrideMaterial->type == QSSGRenderGraphObject::Type::CustomMaterial);
3189 const bool isDefaultMaterial = (overrideMaterial->type == QSSGRenderGraphObject::Type::DefaultMaterial ||
3190 overrideMaterial->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
3191 overrideMaterial->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial);
3192
3193 if (!isCustomMaterial && !isDefaultMaterial) {
3194 qDebug() << "Override material must be a default or custom material.";
3195 return -1;
3196 }
3197
3198 for (const QSSGRenderableObjectHandle &handle : std::as_const(inObjects)) {
3199 QSSGRenderableObject *obj = handle.obj;
3200
3201 if (obj->type != QSSGRenderableObject::Type::DefaultMaterialMeshSubset &&
3202 obj->type != QSSGRenderableObject::Type::CustomMaterialMeshSubset)
3203 continue;
3204
3205 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
3206 const void *modelNode = &subsetRenderable.modelContext.model;
3207 // All user passes share the pass key, so the slot index tells them apart.
3208 QSSGRhiDrawCallData *dcd = &rhiCtxD->drawCallData({ passKey, modelNode, overrideMaterial, nullptr,
3209 quintptr(index) });
3210
3211 // Update the shader key to reflect the override material's properties
3212 // The subsetRenderable.shaderDescription was set during prepareModelsForRender for the original material,
3213 // but we need it to reflect the override material when paired with this model/subset.
3214 {
3215 QSSGRenderableObjectFlags renderableFlags = subsetRenderable.renderableFlags;
3216 float opacity = subsetRenderable.opacity;
3217
3218 // Determine lighting conditions from the subset's lights
3219 const bool hasAnyLights = !subsetRenderable.lights.isEmpty();
3220 const bool anyLightHasShadows = std::any_of(subsetRenderable.lights.begin(),
3221 subsetRenderable.lights.end(),
3222 [](const QSSGShaderLight &light) { return light.shadows; });
3223
3224 // We need a non-const reference to layerPrepResult flags
3225 // Make a copy since the prepare functions might modify it
3226 auto layerPrepFlags = inData.layerPrepResult.getFlags();
3227
3228 if (isCustomMaterial) {
3229 auto &material = static_cast<QSSGRenderCustomMaterial &>(*overrideMaterial);
3230 auto prepResult = inData.prepareCustomMaterialForRender(material, renderableFlags, opacity,
3231 false, hasAnyLights, anyLightHasShadows,
3232 layerPrepFlags);
3233 subsetRenderable.shaderDescription = prepResult.materialKey;
3234 } else {
3235 auto &material = static_cast<QSSGRenderDefaultMaterial &>(*overrideMaterial);
3236 auto prepResult = inData.prepareDefaultMaterialForRender(material, renderableFlags, opacity,
3237 hasAnyLights, anyLightHasShadows,
3238 layerPrepFlags);
3239 subsetRenderable.shaderDescription = prepResult.materialKey;
3240 }
3241 }
3242
3243 QSSGRhiShaderPipelinePtr shaderPipeline;
3244
3245 if (isCustomMaterial) {
3246 const auto &material = static_cast<const QSSGRenderCustomMaterial &>(*overrideMaterial);
3247 if (!ps.userSetCullMode)
3248 ps.cullMode = QSSGRhiHelpers::toCullMode(material.m_cullMode);
3249
3250 QSSGCustomMaterialSystem &customMaterialSystem(*subsetRenderable.renderer->contextInterface()->customMaterialSystem().get());
3251 shaderPipeline = customMaterialSystem.shadersForCustomMaterial(&ps, material, subsetRenderable,
3252 inData.getDefaultMaterialPropertyTable(), featureSet);
3253 if (shaderPipeline) {
3254 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
3255 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
3256 customMaterialSystem.updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, material,
3257 subsetRenderable, inData.renderedCameras, nullptr, nullptr);
3258 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
3259 }
3260 } else {
3261 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(*overrideMaterial);
3262 if (!ps.userSetCullMode)
3263 ps.cullMode = QSSGRhiHelpers::toCullMode(material.cullMode);
3264
3265 shaderPipeline = shadersForDefaultMaterial(&ps, subsetRenderable, featureSet);
3266 if (shaderPipeline) {
3267 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
3268 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
3269 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, subsetRenderable,
3270 inData.renderedCameras, nullptr, nullptr, overrideMaterial);
3271 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
3272 }
3273 }
3274
3275 if (!shaderPipeline)
3276 continue;
3277
3278 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(ps);
3279 ia = subsetRenderable.subset.rhi.ia;
3280
3281 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
3282 int instanceBufferBinding = setupInstancing(&subsetRenderable, &ps, rhiCtx, inData, cameraDatas[0].direction, cameraDatas[0].position,
3283 InstanceLevels::PerInstance, *shaderPipeline);
3284 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
3285
3286 QSSGRhiShaderResourceBindingList bindings;
3287 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd->ubuf);
3288
3289 // Texture maps from the renderable
3290 QSSGRenderableImage *renderableImage = subsetRenderable.firstImage;
3291 while (renderableImage) {
3292 const char *samplerName = QSSGMaterialShaderGenerator::getSamplerName(renderableImage->m_mapType);
3293 const int samplerHint = int(renderableImage->m_mapType);
3294 int samplerBinding = shaderPipeline->bindingForTexture(samplerName, samplerHint);
3295 if (samplerBinding >= 0) {
3296 QRhiTexture *texture = renderableImage->m_texture.m_texture;
3297 if (texture) {
3298 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
3299 QSSGRhiSamplerDescription samplerDesc = {
3300 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
3301 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
3302 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
3303 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
3304 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
3305 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
3306 };
3307 rhiCtx->checkAndAdjustForNPoT(texture, &samplerDesc);
3308 QRhiSampler *sampler = rhiCtx->sampler(samplerDesc);
3309 bindings.addTexture(samplerBinding, RENDERER_VISIBILITY_ALL, texture, sampler);
3310 }
3311 }
3312 renderableImage = renderableImage->m_nextImage;
3313 }
3314
3315 addDepthTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
3316
3317 // Dummy normal texture
3318 const int normalTextureBinding = shaderPipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
3319 if (normalTextureBinding >= 0) {
3320 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
3321 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
3322 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3323 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
3324 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3325 bindings.addTexture(normalTextureBinding, RENDERER_VISIBILITY_ALL, dummyTexture, sampler);
3326 }
3327
3328 // Skinning
3329 if (QRhiTexture *boneTexture = inData.getBonemapTexture(subsetRenderable.modelContext)) {
3330 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
3331 if (binding >= 0) {
3332 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3333 QRhiSampler::Nearest,
3334 QRhiSampler::None,
3335 QRhiSampler::ClampToEdge,
3336 QRhiSampler::ClampToEdge,
3337 QRhiSampler::Repeat
3338 });
3339 bindings.addTexture(binding,
3340 QRhiShaderResourceBinding::VertexStage,
3341 boneTexture,
3342 boneSampler);
3343 }
3344 }
3345
3346 // Morphing
3347 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
3348 if (targetsTexture) {
3349 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
3350 if (binding >= 0) {
3351 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3352 QRhiSampler::Nearest,
3353 QRhiSampler::None,
3354 QRhiSampler::ClampToEdge,
3355 QRhiSampler::ClampToEdge,
3356 QRhiSampler::ClampToEdge
3357 });
3358 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
3359 }
3360 }
3361
3362 // Lighting
3363 if (shaderPipeline->isLightingEnabled()) {
3364 bindings.addUniformBuffer(1, RENDERER_VISIBILITY_ALL, dcd->ubuf,
3365 shaderPipeline->ub0LightDataOffset(),
3366 sizeof(QSSGShaderLightsUniformData));
3367 bindings.addUniformBuffer(2, RENDERER_VISIBILITY_ALL, dcd->ubuf,
3368 shaderPipeline->ub0DirectionalLightDataOffset(),
3369 sizeof(QSSGShaderDirectionalLightsUniformData));
3370
3371 // Shadow map atlas
3372 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_texture"); binding >= 0) {
3373 QRhiTexture *texture = shaderPipeline->shadowMapAtlasTexture();
3374
3375 if (!texture) {
3376 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3377 texture = rhiCtx->dummyTexture({ }, resourceUpdates, QSize(1, 1), Qt::black, 2);
3378 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3379 }
3380
3381 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3382 QRhiSampler::Linear,
3383 QRhiSampler::None,
3384 QRhiSampler::ClampToEdge,
3385 QRhiSampler::ClampToEdge,
3386 QRhiSampler::Repeat });
3387
3388 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
3389 }
3390
3391 // Shadow map blue noise
3392 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture"); binding >= 0) {
3393 QRhiTexture *texture = shaderPipeline->shadowMapBlueNoiseTexture();
3394
3395 if (!texture) {
3396 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3397 texture = rhiCtx->dummyTexture({ }, resourceUpdates);
3398 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3399 }
3400
3401 QRhiSampler *sampler = rhiCtx->sampler(
3402 { QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None, QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
3403
3404 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
3405 }
3406
3407 // Light probe
3408 if (int binding = shaderPipeline->bindingForTexture("qt_lightProbe", int(QSSGRhiSamplerBindingHints::LightProbe));
3409 binding >= 0) {
3410 auto texture = shaderPipeline->lightProbeTexture();
3411 if (!texture) {
3412 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3413 texture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
3414 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3415 }
3416 Q_ASSERT(texture);
3417
3418 QPair<QSSGRenderTextureCoordOp, QSSGRenderTextureCoordOp> tiling = shaderPipeline->lightProbeTiling();
3419 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3420 QRhiSampler::Linear,
3421 QRhiSampler::Linear, // enables mipmapping
3422 QSSGRhiHelpers::toRhi(tiling.first),
3423 QSSGRhiHelpers::toRhi(tiling.second),
3424 QRhiSampler::Repeat });
3425 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
3426 }
3427 }
3428 shaderPipeline->applyAndClearStorageBindings(QRhiShaderResourceBinding::FragmentStage | QRhiShaderResourceBinding::VertexStage, bindings);
3429
3430 QRhiShaderResourceBindings *srb = drawCallDataSrb(rhiCtxD, *dcd, bindings);
3431
3432 QSSG_ASSERT(srb, continue);
3433 auto &rhiPassData = subsetRenderable.rhiRenderData.userPassData[index];
3434 rhiPassData.pipeline = rhiCtxD->pipeline(ps, rpDesc, srb);
3435 rhiPassData.srb = srb;
3436 }
3437
3438 return index;
3439}
3440
3442 QSSGPassKey passKey,
3443 const QSSGRhiGraphicsPipelineState &basePipelineState,
3444 QRhiRenderPassDescriptor *rpDesc,
3445 const QSSGLayerRenderData &inData,
3446 QSSGRenderableObjectList &inObjects,
3447 QSSGShaderFeatures featureSet)
3448{
3449 const qsizetype index = inData.getUserRenderPassManager()->acquireUserPassSlot();
3450 // If the index is negative, it means there are no more available slots for user passes, so we can't prepare the original material pass.
3451 if (index < 0)
3452 return index;
3453
3454 QSSGRhiGraphicsPipelineState ps = basePipelineState;
3455 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
3456
3457 for (const QSSGRenderableObjectHandle &handle : std::as_const(inObjects)) {
3458 QSSGRenderableObject *obj = handle.obj;
3459 QSSGRhiShaderPipelinePtr shaderPipeline;
3460
3461 QSSGRhiDrawCallData *dcd = nullptr;
3462 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset ||
3463 obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3464 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
3465 const void *modelNode = &subsetRenderable.modelContext.model;
3466 // All user passes share the pass key, so the slot index tells them apart.
3467 dcd = &rhiCtxD->drawCallData({ passKey, modelNode, &subsetRenderable.material, nullptr, quintptr(index) });
3468 }
3469
3470 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset) {
3471 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
3472 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(subsetRenderable.getMaterial());
3473 if (!ps.userSetCullMode)
3474 ps.cullMode = QSSGRhiHelpers::toCullMode(material.cullMode);
3475
3476 shaderPipeline = shadersForDefaultMaterial(&ps, subsetRenderable, featureSet);
3477 if (shaderPipeline) {
3478 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
3479 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
3480 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, subsetRenderable,
3481 inData.renderedCameras, nullptr, nullptr);
3482 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
3483 }
3484 } else if (obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3485 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
3486 const auto &material = static_cast<const QSSGRenderCustomMaterial &>(subsetRenderable.getMaterial());
3487 if (!ps.userSetCullMode)
3488 ps.cullMode = QSSGRhiHelpers::toCullMode(material.m_cullMode);
3489
3490 QSSGCustomMaterialSystem &customMaterialSystem(*subsetRenderable.renderer->contextInterface()->customMaterialSystem().get());
3491 shaderPipeline = customMaterialSystem.shadersForCustomMaterial(&ps, material, subsetRenderable,
3492 inData.getDefaultMaterialPropertyTable(), featureSet);
3493 if (shaderPipeline) {
3494 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
3495 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
3496 customMaterialSystem.updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, material,
3497 subsetRenderable, inData.renderedCameras, nullptr, nullptr);
3498 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
3499 }
3500 }
3501
3502 if (!shaderPipeline)
3503 continue;
3504
3505 // The rest is common for both default and custom materials
3506 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset ||
3507 obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3508 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*obj));
3509 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(ps);
3510 ia = subsetRenderable.subset.rhi.ia;
3511
3512 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
3513 int instanceBufferBinding = setupInstancing(&subsetRenderable, &ps, rhiCtx, inData, cameraDatas[0].direction, cameraDatas[0].position,
3514 InstanceLevels::PerInstance, *shaderPipeline);
3515 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
3516
3517 QSSGRhiShaderResourceBindingList bindings;
3518 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd->ubuf);
3519
3520 // Texture maps
3521 QSSGRenderableImage *renderableImage = subsetRenderable.firstImage;
3522 while (renderableImage) {
3523 const char *samplerName = QSSGMaterialShaderGenerator::getSamplerName(renderableImage->m_mapType);
3524 const int samplerHint = int(renderableImage->m_mapType);
3525 int samplerBinding = shaderPipeline->bindingForTexture(samplerName, samplerHint);
3526 if (samplerBinding >= 0) {
3527 QRhiTexture *texture = renderableImage->m_texture.m_texture;
3528 if (samplerBinding >= 0 && texture) {
3529 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
3530 QSSGRhiSamplerDescription samplerDesc = {
3531 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
3532 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
3533 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
3534 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
3535 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
3536 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
3537 };
3538 rhiCtx->checkAndAdjustForNPoT(texture, &samplerDesc);
3539 QRhiSampler *sampler = rhiCtx->sampler(samplerDesc);
3540 bindings.addTexture(samplerBinding, RENDERER_VISIBILITY_ALL, texture, sampler);
3541 }
3542 }
3543 renderableImage = renderableImage->m_nextImage;
3544 }
3545
3546 addDepthTextureBindings(rhiCtx, shaderPipeline.get(), bindings);
3547
3548 // Dummy normal texture
3549 const int normalTextureBinding = shaderPipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
3550 if (normalTextureBinding >= 0) {
3551 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
3552 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
3553 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3554 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
3555 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3556 bindings.addTexture(normalTextureBinding, RENDERER_VISIBILITY_ALL, dummyTexture, sampler);
3557 }
3558
3559 // Skinning
3560 if (QRhiTexture *boneTexture = inData.getBonemapTexture(subsetRenderable.modelContext)) {
3561 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
3562 if (binding >= 0) {
3563 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3564 QRhiSampler::Nearest,
3565 QRhiSampler::None,
3566 QRhiSampler::ClampToEdge,
3567 QRhiSampler::ClampToEdge,
3568 QRhiSampler::Repeat
3569 });
3570 bindings.addTexture(binding,
3571 QRhiShaderResourceBinding::VertexStage,
3572 boneTexture,
3573 boneSampler);
3574 }
3575 }
3576
3577 // Morphing
3578 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
3579 if (targetsTexture) {
3580 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
3581 if (binding >= 0) {
3582 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3583 QRhiSampler::Nearest,
3584 QRhiSampler::None,
3585 QRhiSampler::ClampToEdge,
3586 QRhiSampler::ClampToEdge,
3587 QRhiSampler::ClampToEdge
3588 });
3589 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
3590 }
3591 }
3592
3593 // Lighting
3594 if (shaderPipeline->isLightingEnabled()) {
3595 bindings.addUniformBuffer(1, RENDERER_VISIBILITY_ALL, dcd->ubuf,
3596 shaderPipeline->ub0LightDataOffset(),
3597 sizeof(QSSGShaderLightsUniformData));
3598 bindings.addUniformBuffer(2, RENDERER_VISIBILITY_ALL, dcd->ubuf,
3599 shaderPipeline->ub0DirectionalLightDataOffset(),
3600 sizeof(QSSGShaderDirectionalLightsUniformData));
3601
3602 // Shadow map atlas
3603 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_texture"); binding >= 0) {
3604 QRhiTexture *texture = shaderPipeline->shadowMapAtlasTexture();
3605
3606 if (!texture) {
3607 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3608 texture = rhiCtx->dummyTexture({ }, resourceUpdates);
3609 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3610 }
3611
3612 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3613 QRhiSampler::Linear,
3614 QRhiSampler::None,
3615 QRhiSampler::ClampToEdge,
3616 QRhiSampler::ClampToEdge,
3617 QRhiSampler::Repeat });
3618
3619 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
3620 }
3621
3622 // Shadow map blue noise
3623 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture"); binding >= 0) {
3624 if (auto shadowMapBlueNoise = shaderPipeline->shadowMapBlueNoiseTexture()) {
3625 int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture");
3626 if (binding >= 0) {
3627 QRhiTexture *texture = shadowMapBlueNoise;
3628 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3629 QRhiSampler::Linear,
3630 QRhiSampler::None,
3631 QRhiSampler::Repeat,
3632 QRhiSampler::Repeat,
3633 QRhiSampler::Repeat });
3634 Q_ASSERT(texture && sampler);
3635 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
3636 }
3637 } else {
3638 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3639 QRhiTexture *texture = rhiCtx->dummyTexture({}, resourceUpdates);
3640 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3641 QRhiSampler::Linear,
3642 QRhiSampler::None,
3643 QRhiSampler::Repeat,
3644 QRhiSampler::Repeat,
3645 QRhiSampler::Repeat });
3646 Q_ASSERT(texture && sampler);
3647 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
3648 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3649 }
3650 }
3651
3652 // Reflection probe or light probe
3653 if (featureSet.isSet(QSSGShaderFeatures::Feature::ReflectionProbe)) {
3654 int reflectionSampler = shaderPipeline->bindingForTexture("qt_reflectionMap");
3655 QRhiTexture* reflectionTexture = inData.getReflectionMapManager()->reflectionMapEntry(subsetRenderable.reflectionProbeIndex)->m_rhiPrefilteredCube;
3656 const auto mipMapFilter = reflectionTexture && reflectionTexture->flags().testFlag(QRhiTexture::Flag::MipMapped)
3657 ? QRhiSampler::Linear
3658 : QRhiSampler::None;
3659 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3660 QRhiSampler::Linear,
3661 mipMapFilter,
3662 QRhiSampler::ClampToEdge,
3663 QRhiSampler::ClampToEdge,
3664 QRhiSampler::Repeat });
3665 if (reflectionSampler >= 0) {
3666 // The shader samples the map even when the probe has no usable
3667 // texture, for example one in a format the GPU does not support
3668 if (!reflectionTexture) {
3669 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3670 reflectionTexture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
3671 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3672 }
3673 bindings.addTexture(reflectionSampler, QRhiShaderResourceBinding::FragmentStage, reflectionTexture, sampler);
3674 }
3675 }
3676
3677 if (int binding = shaderPipeline->bindingForTexture("qt_lightProbe", int(QSSGRhiSamplerBindingHints::LightProbe));
3678 binding >= 0) {
3679 auto texture = shaderPipeline->lightProbeTexture();
3680 if (!texture) {
3681 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3682 texture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
3683 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3684 }
3685 Q_ASSERT(texture);
3686
3687 QPair<QSSGRenderTextureCoordOp, QSSGRenderTextureCoordOp> tiling = shaderPipeline->lightProbeTiling();
3688 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3689 QRhiSampler::Linear,
3690 QRhiSampler::Linear, // enables mipmapping
3691 QSSGRhiHelpers::toRhi(tiling.first),
3692 QSSGRhiHelpers::toRhi(tiling.second),
3693 QRhiSampler::Repeat });
3694 bindings.addTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
3695 }
3696
3697 // Screen Texture
3698 if (shaderPipeline->screenTexture()) {
3699 const int screenTextureBinding = shaderPipeline->bindingForTexture("qt_screenTexture", int(QSSGRhiSamplerBindingHints::ScreenTexture));
3700 const int screenTextureArrayBinding = shaderPipeline->bindingForTexture("qt_screenTextureArray", int(QSSGRhiSamplerBindingHints::ScreenTextureArray));
3701 if (screenTextureBinding >= 0 || screenTextureArrayBinding >= 0) {
3702 QRhiSampler::Filter mipFilter = shaderPipeline->screenTexture()->flags().testFlag(QRhiTexture::MipMapped)
3703 ? QRhiSampler::Linear : QRhiSampler::None;
3704 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, mipFilter,
3705 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
3706 if (screenTextureBinding >= 0) {
3707 bindings.addTexture(screenTextureBinding,
3708 QRhiShaderResourceBinding::FragmentStage,
3709 shaderPipeline->screenTexture(), sampler);
3710 }
3711 if (screenTextureArrayBinding >= 0) {
3712 bindings.addTexture(screenTextureArrayBinding,
3713 QRhiShaderResourceBinding::FragmentStage,
3714 shaderPipeline->screenTexture(), sampler);
3715 }
3716 }
3717 }
3718
3719 if (shaderPipeline->lightmapTexture()) {
3720 int binding = shaderPipeline->bindingForTexture("qt_lightmap", int(QSSGRhiSamplerBindingHints::LightmapTexture));
3721 if (binding >= 0) {
3722 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
3723 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
3724 bindings.addTexture(binding,
3725 QRhiShaderResourceBinding::FragmentStage,
3726 shaderPipeline->lightmapTexture(), sampler);
3727 }
3728 }
3729 }
3730
3731 // Custom property textures
3732 {
3733 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3734 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3735
3736 int maxSamplerBinding = -1;
3737 QVector<QShaderDescription::InOutVariable> samplerVars =
3738 shaderPipeline->fragmentStage()->shader().description().combinedImageSamplers();
3739 const auto combinedSamplers = shaderPipeline->vertexStage()->shader().description().combinedImageSamplers();
3740 for (const QShaderDescription::InOutVariable &var : combinedSamplers) {
3741 auto it = std::find_if(samplerVars.cbegin(), samplerVars.cend(),
3742 [&var](const QShaderDescription::InOutVariable &v) { return var.binding == v.binding; });
3743 if (it == samplerVars.cend())
3744 samplerVars.append(var);
3745 }
3746
3747 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars))
3748 maxSamplerBinding = qMax(maxSamplerBinding, var.binding);
3749
3750 if (maxSamplerBinding >= 0) {
3751 int extraTexCount = shaderPipeline->extraTextureCount();
3752 for (int i = 0; i < extraTexCount; ++i) {
3753 QSSGRhiTexture &t(shaderPipeline->extraTextureAt(i));
3754 const int samplerBinding = shaderPipeline->bindingForTexture(t.name);
3755 if (samplerBinding >= 0) {
3756 rhiCtx->checkAndAdjustForNPoT(t.texture, &t.samplerDesc);
3757 QRhiSampler *sampler = rhiCtx->sampler(t.samplerDesc);
3758 bindings.addTexture(samplerBinding,
3759 QRhiShaderResourceBinding::FragmentStage,
3760 t.texture,
3761 sampler);
3762 }
3763 }
3764 }
3765 shaderPipeline->applyAndClearStorageBindings(QRhiShaderResourceBinding::FragmentStage | QRhiShaderResourceBinding::VertexStage, bindings);
3766 }
3767
3768 QRhiShaderResourceBindings *srb = drawCallDataSrb(rhiCtxD, *dcd, bindings);
3769
3770 QSSG_ASSERT(srb, continue);
3771
3772 auto &rhiPassData = subsetRenderable.rhiRenderData.userPassData[index];
3773 rhiPassData.pipeline = rhiCtxD->pipeline(ps, rpDesc, srb);
3774 rhiPassData.srb = srb;
3775 }
3776 }
3777
3778 return index;
3779}
3780
3781
3783 QSSGPassKey passKey,
3784 const QSSGRhiGraphicsPipelineState &basePipelineState,
3785 QRhiRenderPassDescriptor *rpDesc,
3786 const QSSGUserShaderAugmentation &shaderAugmentation,
3787 const QSSGLayerRenderData &inData,
3788 QSSGRenderableObjectList &inObjects,
3789 QSSGShaderFeatures featureSet)
3790{
3791 const qsizetype index = inData.getUserRenderPassManager()->acquireUserPassSlot();
3792
3793 // If there's no available slot, we can't prepare this pass. This can happen if the user shader augmentation tries to use more slots than the maximum allowed.
3794 if (index < 0)
3795 return index;
3796
3797 QSSGRhiGraphicsPipelineState ps = basePipelineState;
3798 for (const QSSGRenderableObjectHandle &handle : std::as_const(inObjects)) {
3799 QSSGRenderableObject *obj = handle.obj;
3800 QSSGRhiShaderPipelinePtr shaderPipeline;
3801 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
3802 const auto &bufferManager = inData.contextInterface()->bufferManager();
3803
3804 featureSet.set(QSSGShaderFeatures::Feature::UserRenderPass, true);
3805
3806 QSSGRhiDrawCallData *dcd = nullptr;
3807 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3808 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
3809 const void *modelNode = &subsetRenderable.modelContext.model;
3810 // All user passes share the pass key, so the slot index tells them apart.
3811 dcd = &rhiCtxD->drawCallData({ passKey, modelNode, &subsetRenderable.material, nullptr, quintptr(index) });
3812 }
3813
3814 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset) {
3815 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
3816 const auto &material = static_cast<const QSSGRenderDefaultMaterial &>(subsetRenderable.getMaterial());
3817 if (!ps.userSetCullMode)
3818 ps.cullMode = QSSGRhiHelpers::toCullMode(material.cullMode);
3819
3820 shaderPipeline = shadersForDefaultMaterial(&ps, subsetRenderable, featureSet, shaderAugmentation);
3821 if (shaderPipeline) {
3822 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
3823 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
3824 // Now do user augmentation specific uniform updates
3825 for (const auto &u : shaderAugmentation.propertyUniforms)
3826 shaderPipeline->setShaderResources(ubufData, *bufferManager, u.name, u.value, u.shaderDataType);
3827 updateUniformsForDefaultMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, subsetRenderable, inData.renderedCameras, nullptr, nullptr);
3828 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
3829 }
3830 } else if (obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3831 QSSGSubsetRenderable &subsetRenderable(*static_cast<QSSGSubsetRenderable *>(obj));
3832 const auto &material = static_cast<const QSSGRenderCustomMaterial &>(subsetRenderable.getMaterial());
3833 if (!ps.userSetCullMode)
3834 ps.cullMode = QSSGRhiHelpers::toCullMode(material.m_cullMode);
3835
3836 QSSGCustomMaterialSystem &customMaterialSystem(*subsetRenderable.renderer->contextInterface()->customMaterialSystem().get());
3837 // Don't apply a shader augmentation to an unshaded custom material (they should do their own augmentations with preprocessor conditionals)
3838 if (material.m_shadingMode == QSSGRenderCustomMaterial::ShadingMode::Unshaded)
3839 shaderPipeline = customMaterialSystem.shadersForCustomMaterial(&ps, material, subsetRenderable, inData.getDefaultMaterialPropertyTable(), featureSet);
3840 else
3841 shaderPipeline = customMaterialSystem.shadersForCustomMaterial(&ps, material, subsetRenderable, inData.getDefaultMaterialPropertyTable(), featureSet, shaderAugmentation);
3842
3843 if (shaderPipeline) {
3844 shaderPipeline->ensureCombinedUniformBuffer(&dcd->ubuf);
3845 char *ubufData = dcd->ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
3846 // Apply user augmentation specific uniform updates
3847 for (const auto &u : shaderAugmentation.propertyUniforms)
3848 shaderPipeline->setShaderResources(ubufData, *bufferManager, u.name, u.value, u.shaderDataType);
3849 customMaterialSystem.updateUniformsForCustomMaterial(*shaderPipeline, rhiCtx, inData, ubufData, &ps, material,
3850 subsetRenderable, inData.renderedCameras, nullptr, nullptr);
3851 dcd->ubuf->endFullDynamicBufferUpdateForCurrentFrame();
3852 }
3853 }
3854
3855 if (!shaderPipeline) {
3856 // bail
3857 qDebug() << "Failed to prepare user augmented pass for object.";
3858 return -1;
3859 }
3860
3861 // the rest is common, only relying on QSSGSubsetRenderableBase, not the subclasses
3862 if (obj->type == QSSGRenderableObject::Type::DefaultMaterialMeshSubset || obj->type == QSSGRenderableObject::Type::CustomMaterialMeshSubset) {
3863 QSSGSubsetRenderable &subsetRenderable(static_cast<QSSGSubsetRenderable &>(*obj));
3864 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(ps);
3865 ia = subsetRenderable.subset.rhi.ia;
3866
3867 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
3868 int instanceBufferBinding = setupInstancing(&subsetRenderable, &ps, rhiCtx, inData, cameraDatas[0].direction, cameraDatas[0].position,
3869 InstanceLevels::PerInstance, *shaderPipeline);
3870 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
3871
3872 QSSGRhiShaderResourceBindingList bindings;
3873 bindings.addUniformBuffer(0, RENDERER_VISIBILITY_ALL, dcd->ubuf);
3874
3875 // The generated shader declares a sampler for every custom
3876 // property texture, and some graphics APIs reject an srb that
3877 // leaves one of them unbound. Track which sampler bindings get
3878 // taken as they are added, so the unused ones can be filled with
3879 // dummy textures at the end.
3880 QVector<QShaderDescription::InOutVariable> samplerVars =
3881 shaderPipeline->fragmentStage()->shader().description().combinedImageSamplers();
3882 const auto combinedSamplers = shaderPipeline->vertexStage()->shader().description().combinedImageSamplers();
3883 for (const QShaderDescription::InOutVariable &var : combinedSamplers) {
3884 auto it = std::find_if(samplerVars.cbegin(), samplerVars.cend(),
3885 [&var](const QShaderDescription::InOutVariable &v) { return var.binding == v.binding; });
3886 if (it == samplerVars.cend())
3887 samplerVars.append(var);
3888 }
3889
3890 int maxSamplerBinding = -1;
3891 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars))
3892 maxSamplerBinding = qMax(maxSamplerBinding, var.binding);
3893
3894 QBitArray specifiedBindings(maxSamplerBinding + 1);
3895 const auto addTrackedTexture = [&](int binding, QRhiShaderResourceBinding::StageFlags stage,
3896 QRhiTexture *texture, QRhiSampler *sampler) {
3897 specifiedBindings.setBit(binding);
3898 bindings.addTexture(binding, stage, texture, sampler);
3899 };
3900
3901 // Texture maps
3902 QSSGRenderableImage *renderableImage = subsetRenderable.firstImage;
3903 while (renderableImage) {
3904 const char *samplerName = QSSGMaterialShaderGenerator::getSamplerName(renderableImage->m_mapType);
3905 const int samplerHint = int(renderableImage->m_mapType);
3906 int samplerBinding = shaderPipeline->bindingForTexture(samplerName, samplerHint);
3907 if (samplerBinding >= 0) {
3908 QRhiTexture *texture = renderableImage->m_texture.m_texture;
3909 if (samplerBinding >= 0 && texture) {
3910 const bool mipmapped = texture->flags().testFlag(QRhiTexture::MipMapped);
3911 QSSGRhiSamplerDescription samplerDesc = {
3912 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_minFilterType),
3913 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_magFilterType),
3914 mipmapped ? QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_mipFilterType) : QRhiSampler::None,
3915 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_horizontalTilingMode),
3916 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_verticalTilingMode),
3917 QSSGRhiHelpers::toRhi(renderableImage->m_imageNode.m_depthTilingMode)
3918 };
3919 rhiCtx->checkAndAdjustForNPoT(texture, &samplerDesc);
3920 QRhiSampler *sampler = rhiCtx->sampler(samplerDesc);
3921 addTrackedTexture(samplerBinding, RENDERER_VISIBILITY_ALL, texture, sampler);
3922 }
3923 } // else this is not necessarily an error, e.g. having metalness/roughness maps with metalness disabled
3924 renderableImage = renderableImage->m_nextImage;
3925 }
3926
3927 addDepthTextureBindings(rhiCtx, shaderPipeline.get(), bindings, &specifiedBindings);
3928
3929 // There is no normal texture at this stage, obviously.
3930 const int normalTextureBinding = shaderPipeline->bindingForTexture("qt_normalTexture", int(QSSGRhiSamplerBindingHints::NormalTexture));
3931 if (normalTextureBinding >= 0) {
3932 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
3933 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
3934 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3935 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
3936 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3937 addTrackedTexture(normalTextureBinding, RENDERER_VISIBILITY_ALL, dummyTexture, sampler);
3938 }
3939
3940 // Shadow maps are not needed since lighting-related shading is mostly skipped in the normal texture's pass
3941
3942 // Skinning
3943 if (QRhiTexture *boneTexture = inData.getBonemapTexture(subsetRenderable.modelContext)) {
3944 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
3945 if (binding >= 0) {
3946 QRhiSampler *boneSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3947 QRhiSampler::Nearest,
3948 QRhiSampler::None,
3949 QRhiSampler::ClampToEdge,
3950 QRhiSampler::ClampToEdge,
3951 QRhiSampler::Repeat
3952 });
3953 addTrackedTexture(binding,
3954 QRhiShaderResourceBinding::VertexStage,
3955 boneTexture,
3956 boneSampler);
3957 }
3958 }
3959
3960 // Morphing
3961 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
3962 if (targetsTexture) {
3963 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
3964 if (binding >= 0) {
3965 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
3966 QRhiSampler::Nearest,
3967 QRhiSampler::None,
3968 QRhiSampler::ClampToEdge,
3969 QRhiSampler::ClampToEdge,
3970 QRhiSampler::ClampToEdge
3971 });
3972 addTrackedTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
3973 }
3974 }
3975
3976 // Lighting
3977 if (shaderPipeline->isLightingEnabled()) {
3978 bindings.addUniformBuffer(1, RENDERER_VISIBILITY_ALL, dcd->ubuf,
3979 shaderPipeline->ub0LightDataOffset(),
3980 sizeof(QSSGShaderLightsUniformData));
3981 bindings.addUniformBuffer(2, RENDERER_VISIBILITY_ALL, dcd->ubuf,
3982 shaderPipeline->ub0DirectionalLightDataOffset(),
3983 sizeof(QSSGShaderDirectionalLightsUniformData));
3984
3985 // Shadow map atlas
3986 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_texture"); binding >= 0) {
3987 QRhiTexture *texture = shaderPipeline->shadowMapAtlasTexture();
3988
3989 if (!texture) {
3990 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
3991 texture = rhiCtx->dummyTexture({ }, resourceUpdates, QSize(1, 1), Qt::black, 2);
3992 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
3993 }
3994
3995 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
3996 QRhiSampler::Linear,
3997 QRhiSampler::None,
3998 QRhiSampler::ClampToEdge,
3999 QRhiSampler::ClampToEdge,
4000 QRhiSampler::Repeat });
4001
4002 addTrackedTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
4003 }
4004
4005 // Shadow map blue noise
4006 if (int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture"); binding >= 0) {
4007 if (auto shadowMapBlueNoise = shaderPipeline->shadowMapBlueNoiseTexture()) {
4008 int binding = shaderPipeline->bindingForTexture("qt_shadowmap_blue_noise_texture");
4009 if (binding >= 0) {
4010 QRhiTexture *texture = shadowMapBlueNoise;
4011 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
4012 QRhiSampler::Linear,
4013 QRhiSampler::None,
4014 QRhiSampler::Repeat,
4015 QRhiSampler::Repeat,
4016 QRhiSampler::Repeat });
4017 Q_ASSERT(texture && sampler);
4018 addTrackedTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
4019 }
4020 } else {
4021 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
4022 QRhiTexture *texture = rhiCtx->dummyTexture({}, resourceUpdates);
4023 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
4024 QRhiSampler::Linear,
4025 QRhiSampler::None,
4026 QRhiSampler::Repeat,
4027 QRhiSampler::Repeat,
4028 QRhiSampler::Repeat });
4029 Q_ASSERT(texture && sampler);
4030 addTrackedTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
4031 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
4032 }
4033 }
4034
4035 // Prioritize reflection texture over Light Probe texture because
4036 // reflection texture also contains the irradiance and pre filtered
4037 // values for the light probe.
4038 if (featureSet.isSet(QSSGShaderFeatures::Feature::ReflectionProbe)) {
4039 int reflectionSampler = shaderPipeline->bindingForTexture("qt_reflectionMap");
4040 QRhiTexture* reflectionTexture = inData.getReflectionMapManager()->reflectionMapEntry(subsetRenderable.reflectionProbeIndex)->m_rhiPrefilteredCube;
4041 const auto mipMapFilter = reflectionTexture && reflectionTexture->flags().testFlag(QRhiTexture::Flag::MipMapped)
4042 ? QRhiSampler::Linear
4043 : QRhiSampler::None;
4044 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
4045 QRhiSampler::Linear,
4046 mipMapFilter,
4047 QRhiSampler::ClampToEdge,
4048 QRhiSampler::ClampToEdge,
4049 QRhiSampler::Repeat });
4050 if (reflectionSampler >= 0) {
4051 if (!reflectionTexture) {
4052 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
4053 reflectionTexture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
4054 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
4055 }
4056 addTrackedTexture(reflectionSampler, QRhiShaderResourceBinding::FragmentStage, reflectionTexture, sampler);
4057 }
4058 }
4059 if (int binding = shaderPipeline->bindingForTexture("qt_lightProbe", int(QSSGRhiSamplerBindingHints::LightProbe));
4060 binding >= 0) {
4061 auto texture = shaderPipeline->lightProbeTexture();
4062 if (!texture) {
4063 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
4064 texture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
4065 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
4066 }
4067 Q_ASSERT(texture);
4068
4069 QPair<QSSGRenderTextureCoordOp, QSSGRenderTextureCoordOp> tiling = shaderPipeline->lightProbeTiling();
4070 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear,
4071 QRhiSampler::Linear,
4072 QRhiSampler::Linear, // enables mipmapping
4073 QSSGRhiHelpers::toRhi(tiling.first),
4074 QSSGRhiHelpers::toRhi(tiling.second),
4075 QRhiSampler::Repeat });
4076 addTrackedTexture(binding, QRhiShaderResourceBinding::FragmentStage, texture, sampler);
4077 }
4078
4079 // Screen Texture
4080 if (shaderPipeline->screenTexture()) {
4081 const int screenTextureBinding = shaderPipeline->bindingForTexture("qt_screenTexture", int(QSSGRhiSamplerBindingHints::ScreenTexture));
4082 const int screenTextureArrayBinding = shaderPipeline->bindingForTexture("qt_screenTextureArray", int(QSSGRhiSamplerBindingHints::ScreenTextureArray));
4083 if (screenTextureBinding >= 0 || screenTextureArrayBinding >= 0) {
4084 // linear min/mag, mipmap filtering depends on the
4085 // texture, with SCREEN_TEXTURE there are no mipmaps, but
4086 // once SCREEN_MIP_TEXTURE is seen the texture (the same
4087 // one) has mipmaps generated.
4088 QRhiSampler::Filter mipFilter = shaderPipeline->screenTexture()->flags().testFlag(QRhiTexture::MipMapped)
4089 ? QRhiSampler::Linear : QRhiSampler::None;
4090 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, mipFilter,
4091 QRhiSampler::Repeat, QRhiSampler::Repeat, QRhiSampler::Repeat });
4092 if (screenTextureBinding >= 0) {
4093 addTrackedTexture(screenTextureBinding,
4094 QRhiShaderResourceBinding::FragmentStage,
4095 shaderPipeline->screenTexture(), sampler);
4096 }
4097 if (screenTextureArrayBinding >= 0) {
4098 addTrackedTexture(screenTextureArrayBinding,
4099 QRhiShaderResourceBinding::FragmentStage,
4100 shaderPipeline->screenTexture(), sampler);
4101 }
4102 } // else ignore, not an error
4103 }
4104
4105 if (shaderPipeline->lightmapTexture()) {
4106 int binding = shaderPipeline->bindingForTexture("qt_lightmap", int(QSSGRhiSamplerBindingHints::LightmapTexture));
4107 if (binding >= 0) {
4108 QRhiSampler *sampler = rhiCtx->sampler({ QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
4109 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
4110 addTrackedTexture(binding,
4111 QRhiShaderResourceBinding::FragmentStage,
4112 shaderPipeline->lightmapTexture(), sampler);
4113 } // else ignore, not an error
4114 }
4115 }
4116
4117
4118 {
4119 if (maxSamplerBinding >= 0) {
4120 // custom property textures
4121 int extraTexCount = shaderPipeline->extraTextureCount();
4122 for (int i = 0; i < extraTexCount; ++i) {
4123 QSSGRhiTexture &t(shaderPipeline->extraTextureAt(i));
4124 const int samplerBinding = shaderPipeline->bindingForTexture(t.name);
4125 if (samplerBinding >= 0) {
4126 rhiCtx->checkAndAdjustForNPoT(t.texture, &t.samplerDesc);
4127 QRhiSampler *sampler = rhiCtx->sampler(t.samplerDesc);
4128 addTrackedTexture(samplerBinding,
4129 QRhiShaderResourceBinding::FragmentStage,
4130 t.texture,
4131 sampler);
4132 }
4133 }
4134 }
4135
4136 // Use a dummy texture for the samplers left unbound above.
4137 QRhiSampler *dummySampler = rhiCtx->sampler({ QRhiSampler::Nearest, QRhiSampler::Nearest, QRhiSampler::None,
4138 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge, QRhiSampler::Repeat });
4139 QRhiResourceUpdateBatch *resourceUpdates = rhiCtx->rhi()->nextResourceUpdateBatch();
4140 QRhiTexture *dummyTexture = rhiCtx->dummyTexture({}, resourceUpdates);
4141 QRhiTexture *dummyTextureArray = rhiCtx->dummyTexture({}, resourceUpdates, QSize(64, 64), Qt::black, qMax(2u, inData.layer.viewCount));
4142 QRhiTexture *dummyTexture3D = rhiCtx->dummyTexture(QRhiTexture::ThreeDimensional, resourceUpdates);
4143 QRhiTexture *dummyCubeTexture = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates);
4144 QRhiTexture *dummyCubeTextureArray = rhiCtx->dummyTexture(QRhiTexture::CubeMap, resourceUpdates, QSize(64, 64), Qt::black, qMax(2u, inData.layer.viewCount));
4145 rhiCtx->commandBuffer()->resourceUpdate(resourceUpdates);
4146
4147 for (const QShaderDescription::InOutVariable &var : std::as_const(samplerVars)) {
4148 if (!specifiedBindings.testBit(var.binding)) {
4149 QRhiTexture *t = nullptr;
4150 if (var.type == QShaderDescription::SamplerCube)
4151 t = dummyCubeTexture;
4152 else if (var.type == QShaderDescription::Sampler3D)
4153 t = dummyTexture3D;
4154 else if (var.type == QShaderDescription::Sampler2DArray)
4155 t = dummyTextureArray;
4156 else if (var.type == QShaderDescription::SamplerCubeArray)
4157 t = dummyCubeTextureArray;
4158 else
4159 t = dummyTexture;
4160 bindings.addTexture(var.binding, RENDERER_VISIBILITY_ALL, t, dummySampler);
4161 }
4162 }
4163 shaderPipeline->applyAndClearStorageBindings(QRhiShaderResourceBinding::FragmentStage | QRhiShaderResourceBinding::VertexStage, bindings);
4164 }
4165
4166 QRhiShaderResourceBindings *srb = drawCallDataSrb(rhiCtxD, *dcd, bindings);
4167 QSSG_ASSERT(srb, return -1);
4168 auto &rhiPassData = subsetRenderable.rhiRenderData.userPassData[index];
4169 rhiPassData.pipeline = rhiCtxD->pipeline(ps, rpDesc, srb);
4170 rhiPassData.srb = srb;
4171 }
4172 }
4173
4174 return index;
4175}
4176
4178 const QSize &size,
4179 QSSGRhiRenderableTexture *renderableTex){
4180 QRhi *rhi = rhiCtx->rhi();
4181 QSSGRhiResourceRegistry &registry = QSSGRhiContextPrivate::get(rhiCtx)->resourceRegistry();
4182 bool needsBuild = false;
4183 QRhiTexture::Flags flags = QRhiTexture::RenderTarget;
4184 if (!renderableTex->texture) {
4185 renderableTex->texture = rhi->newTexture(QRhiTexture::RGBA16F, size, 1, flags);
4186 needsBuild = true;
4187 } else if (renderableTex->texture->pixelSize() != size) {
4188 // Rebuilt in place, which counts as a replacement for the handles.
4189 registry.retire(renderableTex->texture);
4190 renderableTex->texture->setPixelSize(size);
4191 needsBuild = true;
4192 }
4193
4194 if (!renderableTex->depthStencil && !renderableTex->depthTexture) {
4195 renderableTex->depthStencil = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, size);
4196 needsBuild = true;
4197 } else {
4198 if (renderableTex->depthStencil && renderableTex->depthStencil->pixelSize() != size) {
4199 // Rebuilt in place, which counts as a replacement for the handles.
4200 registry.retire(renderableTex->depthStencil);
4201 renderableTex->depthStencil->setPixelSize(size);
4202 needsBuild = true;
4203 }
4204 }
4205
4206 if (needsBuild) {
4207 if (!renderableTex->texture->create()) {
4208 qWarning("Failed to build motionvector texture (size %dx%d)", size.width(), size.height());
4209 renderableTex->reset(&registry);
4210 return false;
4211 }
4212 if (renderableTex->depthStencil && !renderableTex->depthStencil->create()) {
4213 qWarning("Failed to build depth-stencil buffer for motionvector texture (size %dx%d)",
4214 size.width(), size.height());
4215 renderableTex->reset(&registry);
4216 return false;
4217 }
4218 renderableTex->resetRenderTarget();
4219 QRhiTextureRenderTargetDescription desc;
4220 QRhiColorAttachment colorAttachment(renderableTex->texture);
4221 desc.setColorAttachments({ colorAttachment });
4222 if (renderableTex->depthStencil)
4223 desc.setDepthStencilBuffer(renderableTex->depthStencil);
4224 renderableTex->rt = rhi->newTextureRenderTarget(desc);
4225 renderableTex->rt->setName(QByteArrayLiteral("Motionvector texture"));
4226 renderableTex->rpDesc = renderableTex->rt->newCompatibleRenderPassDescriptor();
4227 renderableTex->rt->setRenderPassDescriptor(renderableTex->rpDesc);
4228 if (!renderableTex->rt->create()) {
4229 qWarning("Failed to build render target for motionvector texture");
4230 renderableTex->reset(&registry);
4231 return false;
4232 }
4233 }
4234
4235 return true;
4236}
4237
4238void RenderHelpers::rhiPrepareMotionVectorRenderable(QSSGRhiContext *rhiCtx,
4239 QSSGPassKey passKey,
4240 const QSSGLayerRenderData &inData,
4241 const QMatrix4x4 &viewProjection,
4242 QSSGRenderableObject &inObject,
4243 QRhiRenderPassDescriptor *renderPassDescriptor,
4244 QSSGRhiGraphicsPipelineState *ps,
4245 QSSGRenderMotionVectorMap &motionVectorMapManager)
4246{
4247 if (inObject.type != QSSGRenderableObject::Type::DefaultMaterialMeshSubset &&
4248 inObject.type != QSSGRenderableObject::Type::CustomMaterialMeshSubset)
4249 return;
4250
4251 QSSGSubsetRenderable &subsetRenderable = static_cast<QSSGSubsetRenderable &>(inObject);
4252 auto &modelNode = subsetRenderable.modelContext.model;
4253
4254 bool skin = modelNode.usesBoneTexture();
4255 bool instance = modelNode.usesInstanceBuffer();
4256 bool morph = modelNode.morphTargets.size() > 0;
4257
4258 QSSGRhiShaderPipelinePtr shaderPipeline = inData.contextInterface()->shaderCache()->
4259 getBuiltInRhiShaders().getRhiMotionVectorShader(skin, instance, morph);
4260
4261 if (!shaderPipeline)
4262 return;
4263
4264 QSSGRhiShaderResourceBindingList bindings;
4265
4266 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
4267 QSSGRhiDrawCallData &dcd = rhiCtxD->drawCallData({ passKey, &modelNode, nullptr, nullptr, 0 });
4268
4269
4270 QSSGRenderTextureData *boneTextureData = nullptr;
4271 if (modelNode.skin)
4272 boneTextureData = modelNode.skin;
4273 else if (modelNode.skeleton)
4274 boneTextureData = &modelNode.skeleton->boneTexData;
4275
4276 QMatrix4x4 modelViewProjection = subsetRenderable.modelContext.modelViewProjections[0];
4277 QMatrix4x4 instanceLocal;
4278 QMatrix4x4 instanceGlobal;
4279
4280 if (instance) {
4281 instanceLocal = inData.getInstanceTransforms(modelNode).local;
4282 instanceGlobal = inData.getInstanceTransforms(modelNode).global;
4283 if (!skin)
4284 modelViewProjection = viewProjection;
4285 }
4286 auto motionData = motionVectorMapManager.trackMotionData(&modelNode,
4287 modelViewProjection,
4288 instanceLocal,
4289 instanceGlobal,
4290 boneTextureData,
4291 instance ? modelNode.instanceTable : nullptr,
4292 modelNode.morphWeights);
4293 float velocityAmount = subsetRenderable.modelContext.model.motionVectorScale;
4294 int morphTargetCount = modelNode.morphWeights.count();
4295
4296 // mat4 mvp; // 64
4297 // mat4 prevMVP; // 64
4298 // mat4 instanceLocal; // 64
4299 // mat4 instanceGlobal; // 64
4300 // mat4 prevInstanceLocal; // 64
4301 // mat4 prevInstanceGlobal; // 64
4302 // vec4 currentAndLastJitter; // 16
4303 // float velocityAmount; // 4
4304 // int morphTargetCount; // 4
4305 // vec2 padding; // 8
4306 const int ubufSize = 416;
4307
4308 if (!dcd.ubuf) {
4309 dcd.ubuf = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic,
4310 QRhiBuffer::UniformBuffer,
4311 ubufSize);
4312 dcd.ubuf->create();
4313 }
4314
4315 char *ubufData = dcd.ubuf->beginFullDynamicBufferUpdateForCurrentFrame();
4316 int ubufOffset = 0;
4317 memcpy(ubufData, modelViewProjection.constData(), 64);
4318 ubufOffset += 64;
4319 memcpy(ubufData + ubufOffset, motionData.prevModelViewProjection.constData(), 64);
4320 ubufOffset += 64;
4321 memcpy(ubufData + ubufOffset, instanceLocal.constData(), 64);
4322 ubufOffset += 64;
4323 memcpy(ubufData + ubufOffset, instanceGlobal.constData(), 64);
4324 ubufOffset += 64;
4325 memcpy(ubufData + ubufOffset, motionData.prevInstanceLocal.constData(), 64);
4326 ubufOffset += 64;
4327 memcpy(ubufData + ubufOffset, motionData.prevInstanceGlobal.constData(), 64);
4328 ubufOffset += 64;
4329 memcpy(ubufData + ubufOffset, &inData.layer.currentAndLastJitter, 16);
4330 ubufOffset += 16;
4331 memcpy(ubufData + ubufOffset, &velocityAmount, 4);
4332 ubufOffset += 4;
4333 memcpy(ubufData + ubufOffset, &morphTargetCount, 4);
4334 dcd.ubuf->endFullDynamicBufferUpdateForCurrentFrame();
4335
4336 bindings.addUniformBuffer(0, QRhiShaderResourceBinding::VertexStage |
4337 QRhiShaderResourceBinding::FragmentStage, dcd.ubuf);
4338
4339 QRhiSampler *nearestSampler = nullptr;
4340
4341 if (skin || instance) {
4342 nearestSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
4343 QRhiSampler::Nearest,
4344 QRhiSampler::None,
4345 QRhiSampler::ClampToEdge,
4346 QRhiSampler::ClampToEdge,
4347 QRhiSampler::Repeat
4348 });
4349 }
4350
4351 if (skin) {
4352 int binding = shaderPipeline->bindingForTexture("qt_boneTexture");
4353 if (binding >= 0) {
4354
4355 bindings.addTexture(binding,
4356 QRhiShaderResourceBinding::VertexStage,
4357 inData.getBonemapTexture(subsetRenderable.modelContext),
4358 nearestSampler);
4359 binding = shaderPipeline->bindingForTexture("lastBoneTexture");
4360 if (binding >= 0) {
4361 bindings.addTexture(binding,
4362 QRhiShaderResourceBinding::VertexStage,
4363 motionData.prevBoneTexture.m_texture,
4364 nearestSampler);
4365 }
4366 }
4367 }
4368
4369 if (instance) {
4370 int binding = shaderPipeline->bindingForTexture("lastInstanceTexture");
4371 if (binding >= 0) {
4372 bindings.addTexture(binding,
4373 QRhiShaderResourceBinding::VertexStage,
4374 motionData.prevInstanceTexture.m_texture,
4375 nearestSampler);
4376 }
4377 }
4378
4379 auto *targetsTexture = subsetRenderable.subset.rhi.targetsTexture;
4380 if (targetsTexture) {
4381 int binding = shaderPipeline->bindingForTexture("qt_morphTargetTexture");
4382 if (binding >= 0) {
4383 QRhiSampler *targetsSampler = rhiCtx->sampler({ QRhiSampler::Nearest,
4384 QRhiSampler::Nearest,
4385 QRhiSampler::None,
4386 QRhiSampler::ClampToEdge,
4387 QRhiSampler::ClampToEdge,
4388 QRhiSampler::ClampToEdge
4389 });
4390 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, subsetRenderable.subset.rhi.targetsTexture, targetsSampler);
4391
4392 if ((binding = shaderPipeline->bindingForTexture("morphWeightTexture")) >= 0)
4393 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, motionData.currentMorphWeightTexture.m_texture, targetsSampler);
4394
4395 if ((binding = shaderPipeline->bindingForTexture("lastMorphWeightTexture")) >= 0)
4396 bindings.addTexture(binding, QRhiShaderResourceBinding::VertexStage, motionData.prevMorphWeightTexture.m_texture, targetsSampler);
4397 }
4398 }
4399
4400 auto &ia = QSSGRhiInputAssemblerStatePrivate::get(*ps);
4401 ia = subsetRenderable.subset.rhi.ia;
4402 const QSSGRenderCameraDataList &cameraDatas(*inData.renderedCameraData);
4403 QVector3D cameraDirection = cameraDatas[0].direction;
4404 QVector3D cameraPosition = cameraDatas[0].position;
4405 // The motion vector shader reads the previous transform of an instance by its index in the
4406 // instance table, which the instances grouped by level of the automatic LOD do not keep.
4407 // Like for the shadow maps, draw the whole table at the original level instead.
4408 int instanceBufferBinding = setupInstancing(&subsetRenderable, ps, rhiCtx, inData, cameraDirection, cameraPosition,
4409 InstanceLevels::ModelWide, *shaderPipeline);
4410 QSSGRhiHelpers::bakeVertexInputLocations(&ia, *shaderPipeline, instanceBufferBinding);
4411 QSSGRhiGraphicsPipelineStatePrivate::setShaderPipeline(*ps, shaderPipeline.get());
4412
4413 QRhiShaderResourceBindings *&srb = dcd.srb;
4414 bool srbChanged = false;
4415 if (!srb || bindings != dcd.bindings) {
4416 srb = rhiCtxD->srb(bindings);
4417 rhiCtxD->releaseCachedSrb(dcd.bindings);
4418 dcd.bindings = bindings;
4419 srbChanged = true;
4420 }
4421
4422 subsetRenderable.rhiRenderData.motionVectorPass.srb = srb;
4423
4424 const auto pipelineKey = QSSGGraphicsPipelineStateKey::create(*ps, renderPassDescriptor, srb);
4425 if (dcd.pipeline
4426 && !srbChanged
4427 && dcd.renderTargetDescriptionHash == pipelineKey.extra.renderTargetDescriptionHash
4428 && dcd.renderTargetDescription == pipelineKey.renderTargetDescription
4429 && dcd.ps == *ps)
4430 {
4431 subsetRenderable.rhiRenderData.motionVectorPass.pipeline = dcd.pipeline;
4432 } else {
4433
4434 subsetRenderable.rhiRenderData.motionVectorPass.pipeline = rhiCtxD->pipeline(pipelineKey,
4435 renderPassDescriptor,
4436 srb);
4437 dcd.pipeline = subsetRenderable.rhiRenderData.motionVectorPass.pipeline;
4438 dcd.renderTargetDescriptionHash = pipelineKey.extra.renderTargetDescriptionHash;
4439 dcd.renderTargetDescription = pipelineKey.renderTargetDescription;
4440 dcd.ps = *ps;
4441 }
4442}
4443
4444void RenderHelpers::rhiRenderMotionVector(QSSGRhiContext *rhiCtx,
4445 const QSSGRhiGraphicsPipelineState &state,
4446 const QSSGRenderableObjectList *motionVectorPassObjects,
4447 int bucketsCount)
4448{
4449 bool needsSetViewport = true;
4450
4451 auto renderObjectList = [&](const QSSGRenderableObjectList &objects) {
4452 for (const auto &handle : objects) {
4453 QSSGRenderableObject &object = *handle.obj;
4454
4455 // Only handle mesh subsets
4456 if (object.type != QSSGRenderableObject::Type::DefaultMaterialMeshSubset &&
4457 object.type != QSSGRenderableObject::Type::CustomMaterialMeshSubset)
4458 continue;
4459
4460 QSSGSubsetRenderable &subsetRenderable = static_cast<QSSGSubsetRenderable &>(object);
4461
4462 QRhiGraphicsPipeline *ps = subsetRenderable.rhiRenderData.motionVectorPass.pipeline;
4463 QRhiShaderResourceBindings *srb = subsetRenderable.rhiRenderData.motionVectorPass.srb;
4464
4465 if (!ps || !srb)
4466 return;
4467
4468 QRhiBuffer *indexBuffer = subsetRenderable.subset.rhi.indexBuffer ? subsetRenderable.subset.rhi.indexBuffer->buffer() : nullptr;
4469
4470 QRhiCommandBuffer *cb = rhiCtx->commandBuffer();
4471 // QRhi optimizes out unnecessary binding of the same pipline
4472 cb->setGraphicsPipeline(ps);
4473 cb->setShaderResources(srb);
4474
4475 if (needsSetViewport) {
4476 cb->setViewport(state.viewport);
4477 if (state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::UsesScissor))
4478 cb->setScissor(state.scissor);
4479 needsSetViewport = false;
4480 }
4481
4482 QRhiCommandBuffer::VertexInput vertexBuffers[3];
4483 int vertexBufferCount = 0;
4484 quint32 instances = 1;
4485 if (!setupDrawInputs(rhiCtx, ps, subsetRenderable, subsetRenderable.instanceIndexBuffer,
4486 vertexBuffers, vertexBufferCount, instances))
4487 return;
4488 Q_QUICK3D_PROFILE_START(QQuick3DProfiler::Quick3DRenderCall);
4489 if (state.flags.testFlag(QSSGRhiGraphicsPipelineState::Flag::UsesStencilRef))
4490 cb->setStencilRef(state.stencilRef);
4491 if (indexBuffer) {
4492 cb->setVertexInput(0, vertexBufferCount, vertexBuffers, indexBuffer, 0, subsetRenderable.subset.rhi.indexBuffer->indexFormat());
4493 cb->drawIndexed(subsetRenderable.subset.lodCount(subsetRenderable.subsetLevelOfDetail), instances, subsetRenderable.subset.lodOffset(subsetRenderable.subsetLevelOfDetail));
4494 QSSGRHICTX_STAT(rhiCtx, drawIndexed(subsetRenderable.subset.lodCount(subsetRenderable.subsetLevelOfDetail), instances));
4495 } else {
4496 cb->setVertexInput(0, vertexBufferCount, vertexBuffers);
4497 rhiDrawNonIndexed(rhiCtx, cb, subsetRenderable, instances);
4498 }
4499 Q_QUICK3D_PROFILE_END_WITH_IDS(QQuick3DProfiler::Quick3DRenderCall, (subsetRenderable.subset.count | quint64(instances) << 32),
4500 QVector<int>({subsetRenderable.modelContext.model.profilingId,
4501 subsetRenderable.material.profilingId}));
4502 }
4503 };
4504
4505 for (int i = 0; i < bucketsCount; ++i)
4506 renderObjectList(motionVectorPassObjects[i]);
4507}
4508
4509QT_END_NAMESPACE
QSSGRenderableObjectFlags renderableFlags
friend class QSSGRenderContextInterface
qsizetype rhiPrepareOverrideMaterialUserPass(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, const QSSGRhiGraphicsPipelineState &basePipelineState, QRhiRenderPassDescriptor *rpDesc, QSSGRenderGraphObject *overrideMaterial, QSSGLayerRenderData &inData, QSSGRenderableObjectList &inObjects, QSSGShaderFeatures featureSet)
bool setupDrawInputs(QSSGRhiContext *rhiCtx, QRhiGraphicsPipeline *ps, const QSSGSubsetRenderable &renderable, QRhiBuffer *instanceIndexBuffer, QRhiCommandBuffer::VertexInput *vertexBuffers, int &vertexBufferCount, quint32 &instances)
void rhiRenderAoTexture(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, QSSGRenderer &renderer, QSSGRhiShaderPipeline &shaderPipeline, QSSGRhiGraphicsPipelineState &ps, const QSSGAmbientOcclusionSettings &ao, const QSSGRhiRenderableTexture &rhiAoTexture, const QSSGRhiRenderableTexture &rhiDepthTexture, const QSSGRenderCamera &camera)
bool anyAutoLodInstances(const QSSGSubsetRenderable &renderable)
bool bindInstanceIndices(QRhiGraphicsPipeline *ps, QRhiBuffer *instanceIndexBuffer, QRhiCommandBuffer::VertexInput *vertexBuffers, int *vertexBufferCount)
bool rhiPrepareNormalPass(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, const QSSGRhiGraphicsPipelineState &basePipelineState, QRhiRenderPassDescriptor *rpDesc, QSSGLayerRenderData &inData, const QSSGRenderableObjectList &sortedOpaqueObjects)
bool rhiPrepareMotionVectorTexture(QSSGRhiContext *rhiCtx, const QSize &size, QSSGRhiRenderableTexture *renderableTex)
void rhiRenderReflectionMap(const QSSGRenderContextInterface &context, QSSGPassKey passKey, const QSSGLayerRenderData &inData, QSSGRhiGraphicsPipelineState *ps, QSSGRenderReflectionMap &reflectionMapManager, const std::vector< QSSGRenderReflectionProbe * > &reflectionProbes, const QSSGRenderableObjectList &reflectionPassObjects, QSSGRenderer &renderer)
void rhiRenderNormalPass(QSSGRhiContext *rhiCtx, const QSSGRhiGraphicsPipelineState &ps, const QSSGRenderableObjectList &sortedOpaqueObjects, bool *needsSetViewport)
Q_QUICK3DRUNTIMERENDER_EXPORT void rhiRenderRenderable(QSSGRhiContext *rhiCtx, const QSSGRhiGraphicsPipelineState &state, QSSGRenderableObject &object, bool *needsSetViewport, QSSGRenderTextureCubeFace cubeFace=QSSGRenderTextureCubeFaceNone, qsizetype userPassIndex=-1)
void rhiDrawNonIndexed(QSSGRhiContext *rhiCtx, QRhiCommandBuffer *cb, const QSSGSubsetRenderable &renderable, quint32 instances)
qsizetype rhiPrepareAugmentedUserPass(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, const QSSGRhiGraphicsPipelineState &basePipelineState, QRhiRenderPassDescriptor *rpDesc, const QSSGUserShaderAugmentation &shaderAugmentation, const QSSGLayerRenderData &inData, QSSGRenderableObjectList &inObjects, QSSGShaderFeatures featureSet)
bool rhiPrepareDepthPass(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, const QSSGRhiGraphicsPipelineState &basePipelineState, QRhiRenderPassDescriptor *rpDesc, QSSGLayerRenderData &inData, const QSSGRenderableObjectList &sortedOpaqueObjects, const QSSGRenderableObjectList &sortedTransparentObjects, int samples, int viewCount)
qsizetype rhiPrepareOriginalMaterialUserPass(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, const QSSGRhiGraphicsPipelineState &basePipelineState, QRhiRenderPassDescriptor *rpDesc, const QSSGLayerRenderData &inData, QSSGRenderableObjectList &inObjects, QSSGShaderFeatures featureSet)
bool rhiPrepareScreenTexture(QSSGRhiContext *rhiCtx, const QSize &size, bool wantsMips, QSSGRhiRenderableTexture *renderableTex, quint8 viewCount)
void addAccumulatorImageBindings(QSSGRhiShaderPipeline *shaderPipeline, QSSGRhiShaderResourceBindingList &bindings)
bool rhiPrepareDepthTexture(QSSGRhiContext *rhiCtx, const QSize &size, QSSGRhiRenderableTexture *renderableTex, quint8 viewCount, int samples=1)
void rhiRenderMotionVector(QSSGRhiContext *rhiCtx, const QSSGRhiGraphicsPipelineState &state, const QSSGRenderableObjectList *motionVectorPassObjects, int bucketsCount)
void rhiDrawAutoLodInstanced(QSSGRhiContext *rhiCtx, QRhiCommandBuffer *cb, QRhiCommandBuffer::VertexInput *vertexBuffers, int vertexBufferCount, QRhiBuffer *indexBuffer, const QSSGSubsetRenderable &renderable)
Q_AUTOTEST_EXPORT bool rhiPrepareAoTexture(QSSGRhiContext *rhiCtx, const QSize &size, QSSGRhiRenderableTexture *renderableTex, quint8 viewCount)
void rhiRenderDepthPass(QSSGRhiContext *rhiCtx, const QSSGRhiGraphicsPipelineState &ps, const QSSGRenderableObjectList &sortedOpaqueObjects, const QSSGRenderableObjectList &sortedTransparentObjects, bool *needsSetViewport)
void addDebugFrustum(const QSSGBoxPoints &frustumPoints, const QColor &color, QSSGDebugDrawSystem *debugDrawSystem)
void addDebugBox(const QSSGBoxPoints &boxUnsorted, const QColor &color, QSSGDebugDrawSystem *debugDrawSystem)
void addDirectionalLightDebugBox(const QSSGBoxPoints &box, QSSGDebugDrawSystem *debugDrawSystem)
#define M_PI_2
Definition qmath.h:205
#define M_PI
Definition qmath.h:201
QVarLengthArray< QSSGShaderLight, 16 > QSSGShaderLightList
static void setupCubeShadowCameras(const QSSGLayerRenderData &inData, const QSSGRenderLight *inLight, float shadowMapFar, QSSGRenderCamera inCameras[6])
static void updateUniformsForDefaultMaterial(QSSGRhiShaderPipeline &shaderPipeline, QSSGRhiContext *rhiCtx, const QSSGLayerRenderData &inData, char *ubufData, QSSGRhiGraphicsPipelineState *ps, QSSGSubsetRenderable &subsetRenderable, const QSSGRenderCameraList &cameras, const QVector2D *depthAdjust, const QMatrix4x4 *alteredModelViewProjection, const QSSGRenderGraphObject *materialOverride=nullptr)
static QSSGRhiShaderPipelinePtr shadersForParticleMaterial(QSSGRhiGraphicsPipelineState *ps, QSSGParticlesRenderable &particleRenderable, const QSSGShaderFeatures &featureSet)
static QSSGRhiShaderPipelinePtr shadersForDefaultMaterial(QSSGRhiGraphicsPipelineState *ps, QSSGSubsetRenderable &subsetRenderable, const QSSGShaderFeatures &featureSet, const QSSGUserShaderAugmentation &shaderAugmentation={})
static std::unique_ptr< QSSGRenderCamera > computeShadowCameraFromFrustum(const QMatrix4x4 &lightMatrix, const QMatrix4x4 &lightMatrixInverted, const QVector3D &lightPivot, const QVector3D &lightForward, const QVector3D &lightUp, const float shadowMapResolution, const float pcfRadius, const QSSGBoxPoints &frustumPoints, float frustumStartT, float frustumEndT, float frustumRadius, bool lockShadowmapTexels, const QSSGBounds3 &castingBox, const QSSGBounds3 &receivingBox, QSSGDebugDrawSystem *debugDrawSystem, const bool drawCascades, const bool drawSceneCascadeIntersection)
static QRhiViewport calculateAtlasViewport(QSize atlasPixelSize, const QSSGShadowMapEntry::AtlasEntry &atlasEntry, bool yIsUp)
static QSSGBoxPoints sliceFrustum(const QSSGBoxPoints &frustumPoints, float t0, float t1)
static void rhiPrepareSkyBox_helper(const QSSGRenderContextInterface &context, QSSGPassKey passKey, QSSGRenderLayer &layer, QSSGRenderCameraList &cameras, QSSGRenderer &renderer, QSSGReflectionMapEntry *entry=nullptr, QSSGRenderTextureCubeFace cubeFace=QSSGRenderTextureCubeFaceNone, uint tonemapMode=0)
static QT_BEGIN_NAMESPACE constexpr float QSSG_PI
static void rhiPrepareResourcesForReflectionMap(const QSSGRenderContextInterface &context, QSSGPassKey passKey, const QSSGLayerRenderData &inData, QSSGReflectionMapEntry *pEntry, QSSGRhiGraphicsPipelineState *ps, const QSSGRenderableObjectList &sortedOpaqueObjects, QSSGRenderCamera &inCamera, QSSGRenderer &renderer, QSSGRenderTextureCubeFace cubeFace)
static void rhiPrepareResourcesForShadowMap(QSSGRhiContext *rhiCtx, const QSSGLayerRenderData &inData, QSSGPassKey passKey, QSSGShadowMapEntry *pEntry, QSSGRhiGraphicsPipelineState *ps, const QVector2D *depthAdjust, const QSSGRenderableObjectList &sortedOpaqueObjects, QSSGRenderCamera &inCamera, bool orthographic, QSSGRenderTextureCubeFace cubeFace, quint32 cascadeIndex)
static void addOpaqueDepthPrePassBindings(QSSGRhiContext *rhiCtx, QSSGRhiShaderPipeline *shaderPipeline, QSSGRenderableImage *renderableImage, QSSGRhiShaderResourceBindingList &bindings, bool isCustomMaterialMeshSubset=false)
static QSSGBoxPoints computeFrustumBounds(const QMatrix4x4 &projection)
static void addNormalTextureBindings(QSSGRhiContext *rhiCtx, QSSGRhiShaderPipeline *shaderPipeline, QSSGRhiShaderResourceBindingList &bindings)
static const QRhiShaderResourceBinding::StageFlags RENDERER_VISIBILITY_ALL
static QRhiShaderResourceBindings * drawCallDataSrb(QSSGRhiContextPrivate *rhiCtxD, QSSGRhiDrawCallData &dcd, const QSSGRhiShaderResourceBindingList &bindings)
static constexpr float QSSG_HALFPI
static int setupInstancing(QSSGSubsetRenderable *renderable, QSSGRhiGraphicsPipelineState *ps, QSSGRhiContext *rhiCtx, const QSSGLayerRenderData &inData, const QVector3D &cameraDirection, const QVector3D &cameraPosition, InstanceLevels instanceLevels, const QSSGRhiShaderPipeline &shaders)
void rhiPrepareRenderableImp(QSSGRhiContext *rhiCtx, QSSGPassKey passKey, const QSSGLayerRenderData &inData, QSSGRenderableObject &inObject, QRhiRenderPassDescriptor *renderPassDescriptor, QSSGRhiGraphicsPipelineState *ps, QSSGShaderFeatures featureSet, int samples, int viewCount, bool screenMapPass, QSSGRenderCamera *alteredCamera, QMatrix4x4 *alteredModelViewProjection, QSSGRenderTextureCubeFace cubeFace, QSSGReflectionMapEntry *entry, bool oit)
static void setupCubeReflectionCameras(const QSSGLayerRenderData &inData, const QSSGRenderReflectionProbe *inProbe, QSSGRenderCamera inCameras[6])
static void fillTargetBlend(QRhiGraphicsPipeline::TargetBlend *targetBlend, QSSGRenderDefaultMaterial::MaterialBlendMode materialBlend)
static void addDepthTextureBindings(QSSGRhiContext *rhiCtx, QSSGRhiShaderPipeline *shaderPipeline, QSSGRhiShaderResourceBindingList &bindings, QBitArray *specifiedBindings=nullptr)
static QVarLengthArray< std::unique_ptr< QSSGRenderCamera >, 4 > setupCascadingCamerasForShadowMap(const QSSGLayerRenderData &data, const QSSGRenderCamera &inCamera, const QSSGRenderLight *inLight, const int shadowMapResolution, const float pcfRadius, const float clipNear, const float clipFar, const QSSGBounds3 &castingObjectsBox, const QSSGBounds3 &receivingObjectsBox, bool lockShadowmapTexels, QSSGDebugDrawSystem *debugDrawSystem, bool drawCascades, bool drawSceneCascadeIntersection)