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
qssglayerrenderdata.cpp
Go to the documentation of this file.
1// Copyright (C) 2008-2012 NVIDIA Corporation.
2// Copyright (C) 2022 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6
8#include <QtQuick3DRuntimeRender/private/qssgrhiresourcehandle_p.h>
9
10#include <QtQuick3DRuntimeRender/private/qssgrenderer_p.h>
11#include <QtQuick3DRuntimeRender/private/qssgrenderlight_p.h>
12#include <QtQuick3DRuntimeRender/private/qssgrhicustommaterialsystem_p.h>
13#include <QtQuick3DRuntimeRender/private/qssgrhiquadrenderer_p.h>
14#include <QtQuick3DRuntimeRender/private/qssgrhiparticles_p.h>
15#include <QtQuick3DRuntimeRender/private/qssgrenderlayer_p.h>
16#include <QtQuick3DRuntimeRender/private/qssgrendereffect_p.h>
17#include <QtQuick3DRuntimeRender/private/qssgrendercamera_p.h>
18#include <QtQuick3DRuntimeRender/private/qssgrenderskeleton_p.h>
19#include <QtQuick3DRuntimeRender/private/qssgrenderjoint_p.h>
20#include <QtQuick3DRuntimeRender/private/qssgrendermorphtarget_p.h>
21#include <QtQuick3DRuntimeRender/private/qssgrenderparticles_p.h>
22#include <QtQuick3DRuntimeRender/private/qssgrendercomputepass_p.h>
23#include "../graphobjects/qssgrenderroot_p.h"
24#include "../qssgrendercontextcore.h"
25#include <QtQuick3DRuntimeRender/private/qssgrenderbuffermanager_p.h>
26#include <QtQuick3DRuntimeRender/private/qssgrendershadercache_p.h>
27#include <QtQuick3DRuntimeRender/private/qssgperframeallocator_p.h>
28#include <QtQuick3DRuntimeRender/private/qssgruntimerenderlogging_p.h>
29#include <QtQuick3DRuntimeRender/private/qssglightmapper_p.h>
30#include <QtQuick3DRuntimeRender/private/qssgdebugdrawsystem_p.h>
31#include <QtQuick3DRuntimeRender/private/qssgshadermaterialadapter_p.h>
32
33#include <QtQuick3DUtils/private/qssgutils_p.h>
34#include <QtQuick3DUtils/private/qssgassert_p.h>
35
36#include <QtQuick/private/qsgtexture_p.h>
37#include <QtQuick/private/qsgrenderer_p.h>
38
39#include <QtCore/qspan.h>
40
41#include <array>
42#include <numeric>
43
45#include "rendererimpl/qssgrenderhelpers_p.h"
46
48
49Q_STATIC_LOGGING_CATEGORY(lcQuick3DRender, "qt.quick3d.render");
50
51#define POS4BONETRANS(x) (sizeof(float) * 16 * (x) * 2)
52#define POS4BONENORM(x) (sizeof(float) * 16 * ((x) * 2 + 1))
53#define BONEDATASIZE4ID(x) POS4BONETRANS(x + 1)
54
55static bool checkParticleSupport(QRhi *rhi)
56{
57 QSSG_ASSERT(rhi, return false);
58
59 bool ret = true;
60 const bool supportRgba32f = rhi->isTextureFormatSupported(QRhiTexture::RGBA32F);
61 const bool supportRgba16f = rhi->isTextureFormatSupported(QRhiTexture::RGBA16F);
62 if (!supportRgba32f && !supportRgba16f) {
63 static bool warningShown = false;
64 if (!warningShown) {
65 qWarning () << "Particles not supported due to missing RGBA32F and RGBA16F texture format support";
66 warningShown = true;
67 }
68 ret = false;
69 }
70
71 return ret;
72}
73
75{
83
85 {
86 lhs.modelCount += rhs.modelCount;
87 lhs.particlesCount += rhs.particlesCount;
88 lhs.item2DCount += rhs.item2DCount;
89 lhs.cameraCount += rhs.cameraCount;
90 lhs.lightCount += rhs.lightCount;
91 lhs.reflectionProbeCount += rhs.reflectionProbeCount;
92 lhs.otherCount += rhs.otherCount;
93 return lhs;
94 }
95
96 friend QDebug operator<<(QDebug dbg, const LayerNodeStatResult &stat)
97 {
98 dbg.nospace() << "LayerNodeStatResult(modelCount: " << stat.modelCount
99 << ", particlesCount: " << stat.particlesCount
100 << ", item2DCount: " << stat.item2DCount
101 << ", cameraCount: " << stat.cameraCount
102 << ", lightCount: " << stat.lightCount
103 << ", reflectionProbeCount: " << stat.reflectionProbeCount
104 << ", otherCount: " << stat.otherCount
105 << ")";
106 return dbg.space();
107 }
108};
109
110static LayerNodeStatResult statLayerNodes(const QSSGLayerRenderData::LayerNodes &layerNodes, quint32 layerMask) {
111
113
114 for (auto *node : layerNodes) {
115 if (node->getGlobalState(QSSGRenderNode::GlobalState::Active)) {
116 if (!node->tag.isSet(layerMask))
117 ++stat.otherCount;
118 else if (node->type == QSSGRenderGraphObject::Type::Model)
119 ++stat.modelCount;
120 else if (node->type == QSSGRenderGraphObject::Type::Particles)
121 ++stat.particlesCount;
122 else if (node->type == QSSGRenderGraphObject::Type::Item2D)
123 ++stat.item2DCount;
124 else if (node->type == QSSGRenderGraphObject::Type::ReflectionProbe)
125 ++stat.reflectionProbeCount;
126 else if (QSSGRenderGraphObject::isCamera(node->type))
127 ++stat.cameraCount;
128 else if (QSSGRenderGraphObject::isLight(node->type))
129 ++stat.lightCount;
130 else
131 ++stat.otherCount;
132 }
133 }
134
135 return stat;
136}
137
138// These are meant to be pixel offsets, so you need to divide them by the width/height
139// of the layer respectively.
141 QVector2D(-0.170840f, -0.553840f), // 1x
142 QVector2D(0.162960f, -0.319340f), // 2x
143 QVector2D(0.360260f, -0.245840f), // 3x
144 QVector2D(-0.561340f, -0.149540f), // 4x
145 QVector2D(0.249460f, 0.453460f), // 5x
146 QVector2D(-0.336340f, 0.378260f), // 6x
147 QVector2D(0.340000f, 0.166260f), // 7x
148 QVector2D(0.235760f, 0.527760f), // 8x
149};
150
152{
153 qCWarning(lcQuick3DRender, "A model whose geometry has no position attribute needs a CustomMaterial "
154 "with a vertex shader to place its vertices. ShaderGeometry derives them "
155 "from VERTEX_INDEX; with a built-in material or a CustomMaterial without a "
156 "vertex shader nothing is shown.");
157}
158
159static bool isObjectCullable(const QSSGClippingFrustum &clipFrustum, const QSSGRenderableObject &obj)
160{
161 if (obj.isInstanced) {
162 // when instancing is enabled we can use the shadowmap bounds if they are set, otherwise we disable culling
163 if (obj.globalBoundsInstancing.isEmpty() || clipFrustum.intersectsWith(obj.globalBoundsInstancing))
164 return false;
165 } else if (obj.globalBounds.isEmpty() && !obj.renderableFlags.hasAttributePosition()) {
166 // Nothing to derive bounds from; setting them opts back into culling.
167 // The attribute test keeps this away from ordinary models.
168 return false;
169 } else if (clipFrustum.intersectsWith(obj.globalBounds)) {
170 return false;
171 }
172 return true;
173}
174
175qsizetype QSSGLayerRenderData::frustumCullingInline(const QSSGClippingFrustum &clipFrustum, QSSGRenderableObjectList &renderables)
176{
177 const qint32 end = renderables.size();
178 qint32 front = 0;
179 qint32 back = end - 1;
180
181 while (front <= back) {
182 const QSSGRenderableObject &obj = *renderables.at(front).obj;
183 if (isObjectCullable(clipFrustum, obj))
184 renderables.swapItemsAt(front, back--);
185 else
186 ++front;
187 }
188
189 return back + 1;
190}
191
192qsizetype QSSGLayerRenderData::filterLayerMaskInline(quint32 layerMask, QSSGRenderableObjectList &renderables)
193{
194 const qint32 end = renderables.size();
195 qint32 front = 0;
196 qint32 back = end - 1;
197
198 while (front <= back) {
199 const auto &b = renderables.at(front).tag;
200 if (layerMask & b.value())
201 ++front;
202 else
203 renderables.swapItemsAt(front, back--);
204 }
205
206 return back + 1;
207}
208
209[[nodiscard]] constexpr static inline bool nearestToFurthestCompare(const QSSGRenderableObjectHandle &lhs, const QSSGRenderableObjectHandle &rhs) noexcept
210{
212}
213
214[[nodiscard]] constexpr static inline bool furthestToNearestCompare(const QSSGRenderableObjectHandle &lhs, const QSSGRenderableObjectHandle &rhs) noexcept
215{
217}
218
219static void collectBoneTransforms(const QSSGLayerRenderData &renderData, QSSGRenderNode *node, QSSGRenderSkeleton *skeletonNode, const QVector<QMatrix4x4> &poses)
220{
221 if (node->type == QSSGRenderGraphObject::Type::Joint) {
222 QSSGRenderJoint *jointNode = static_cast<QSSGRenderJoint *>(node);
223 Q_ASSERT(!jointNode->isDirty(QSSGRenderNode::DirtyFlag::GlobalValuesDirty));
224 QMatrix4x4 globalTrans = renderData.getGlobalTransform(*jointNode);
225 // if user doesn't give the inverseBindPose, identity matrices are used.
226 if (poses.size() > jointNode->index)
227 globalTrans *= poses[jointNode->index];
228 memcpy(skeletonNode->boneData.data() + POS4BONETRANS(jointNode->index),
229 reinterpret_cast<const void *>(globalTrans.constData()),
230 sizeof(float) * 16);
231 // only upper 3x3 is meaningful
232 memcpy(skeletonNode->boneData.data() + POS4BONENORM(jointNode->index),
233 reinterpret_cast<const void *>(QMatrix4x4(globalTrans.normalMatrix()).constData()),
234 sizeof(float) * 11);
235 } else {
236 skeletonNode->containsNonJointNodes = true;
237 }
238 for (auto &child : node->children)
239 collectBoneTransforms(renderData, &child, skeletonNode, poses);
240}
241
242static bool hasDirtyNonJointNodes(QSSGRenderNode *node, bool &hasChildJoints)
243{
244 if (!node)
245 return false;
246 // we might be non-joint dirty node, but if we do not have child joints we need to return false
247 // Note! The frontend clears TransformDirty. Use dirty instead.
248 bool dirtyNonJoint = ((node->type != QSSGRenderGraphObject::Type::Joint)
249 && node->isDirty());
250
251 // Tell our parent we are joint
252 if (node->type == QSSGRenderGraphObject::Type::Joint)
253 hasChildJoints = true;
254 bool nodeHasChildJoints = false;
255 for (auto &child : node->children) {
256 bool ret = hasDirtyNonJointNodes(&child, nodeHasChildJoints);
257 // return if we have child joints and non-joint dirty nodes, else check other children
258 hasChildJoints |= nodeHasChildJoints;
259 if (ret && nodeHasChildJoints)
260 return true;
261 }
262 // return true if we have child joints and we are dirty non-joint
263 hasChildJoints |= nodeHasChildJoints;
264 return dirtyNonJoint && nodeHasChildJoints;
265}
266
267#define MAX_MORPH_TARGET 8
268#define MAX_MORPH_TARGET_INDEX_SUPPORTS_NORMALS 3
269#define MAX_MORPH_TARGET_INDEX_SUPPORTS_TANGENTS 1
270
272 : firstImage(nullptr), opacity(1.0f), materialKey(inKey), dirty(false)
273{
274}
275
276QSSGRenderCameraData QSSGLayerRenderData::getCameraDataImpl(const QSSGRenderCamera *camera) const
277{
278 QSSGRenderCameraData ret;
279 if (camera) {
280 // Calculate viewProjection and clippingFrustum for Render Camera
281 QMatrix4x4 viewProjection(Qt::Uninitialized);
282 const QMatrix4x4 cameraGlobalTransform = getGlobalTransform(*camera);
283 camera->calculateViewProjectionMatrix(cameraGlobalTransform, viewProjection);
284 std::optional<QSSGClippingFrustum> clippingFrustum;
285 const QVector3D camGlobalPos = QSSGRenderNode::getGlobalPos(cameraGlobalTransform);
286 if (camera->enableFrustumClipping) {
287 QSSGClipPlane nearPlane;
288 QMatrix3x3 theUpper33(cameraGlobalTransform.normalMatrix());
289 QVector3D dir(QSSGUtils::mat33::transform(theUpper33, QVector3D(0, 0, -1)));
290 dir.normalize();
291 nearPlane.normal = dir;
292 QVector3D theGlobalPos = camGlobalPos + camera->clipPlanes.clipNear() * dir;
293 nearPlane.d = -(QVector3D::dotProduct(dir, theGlobalPos));
294 // the near plane's bbox edges are calculated in the clipping frustum's
295 // constructor.
296 clippingFrustum = QSSGClippingFrustum{viewProjection, nearPlane};
297 }
298 ret = { viewProjection, clippingFrustum, camera->getScalingCorrectDirection(cameraGlobalTransform), camGlobalPos };
299 }
300
301 return ret;
302}
303
304// Returns the cached data for the active render camera(s) (if any)
305const QSSGRenderCameraDataList &QSSGLayerRenderData::getCachedCameraDatas()
306{
307 ensureCachedCameraDatas();
308 return *renderedCameraData;
309}
310
311void QSSGLayerRenderData::ensureCachedCameraDatas()
312{
313 if (renderedCameraData.has_value())
314 return;
315
316 QSSGRenderCameraDataList cameraData;
317 for (QSSGRenderCamera *cam : std::as_const(renderedCameras))
318 cameraData.append(getCameraDataImpl(cam));
319 renderedCameraData = std::move(cameraData);
320}
321
322[[nodiscard]] static inline float getCameraDistanceSq(const QSSGRenderableObject &obj,
323 const QSSGRenderCameraData &camera) noexcept
324{
325 const QVector3D difference = obj.worldCenterPoint - camera.position;
326 return QVector3D::dotProduct(difference, camera.direction) + obj.depthBiasSq;
327}
328
329// Per-frame cache of renderable objects post-sort.
330const QVector<QSSGRenderableObjectHandle> &QSSGLayerRenderData::getSortedOpaqueRenderableObjects(const QSSGRenderCamera &camera, size_t index, quint32 layerMask)
331{
332 index = index * size_t(index < opaqueObjectStore.size());
333 auto &sortedOpaqueObjects = sortedOpaqueObjectCache[index][{&camera, layerMask}];
334 if (!sortedOpaqueObjects.empty())
335 return sortedOpaqueObjects;
336
337 if (layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest))
338 sortedOpaqueObjects = std::as_const(opaqueObjectStore)[index];
339
340 if (camera.layerMask != layerMask) {
341 const auto filteredObjects = filterLayerMaskInline(layerMask, sortedOpaqueObjects);
342 sortedOpaqueObjects.resize(filteredObjects);
343 }
344
345 const auto &clippingFrustum = getCameraRenderData(&camera).clippingFrustum;
346 if (clippingFrustum.has_value()) { // Frustum culling
347 const auto visibleObjects = QSSGLayerRenderData::frustumCullingInline(clippingFrustum.value(), sortedOpaqueObjects);
348 sortedOpaqueObjects.resize(visibleObjects);
349 }
350
351 // Render nearest to furthest objects
352 std::sort(sortedOpaqueObjects.begin(), sortedOpaqueObjects.end(), nearestToFurthestCompare);
353
354 return sortedOpaqueObjects;
355}
356
357// If layer depth test is false, this may also contain opaque objects.
358const QVector<QSSGRenderableObjectHandle> &QSSGLayerRenderData::getSortedTransparentRenderableObjects(const QSSGRenderCamera &camera, size_t index, quint32 layerMask)
359{
360 index = index * size_t(index < transparentObjectStore.size());
361 auto &sortedTransparentObjects = sortedTransparentObjectCache[index][{&camera, layerMask}];
362
363 if (!sortedTransparentObjects.empty())
364 return sortedTransparentObjects;
365
366 sortedTransparentObjects = std::as_const(transparentObjectStore)[index];
367
368 if (!layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest)) {
369 const auto &opaqueObjects = std::as_const(opaqueObjectStore)[index];
370 sortedTransparentObjects.append(opaqueObjects);
371 }
372
373 if (camera.layerMask != layerMask) {
374 const auto filteredObjects = filterLayerMaskInline(layerMask, sortedTransparentObjects);
375 sortedTransparentObjects.resize(filteredObjects);
376 }
377
378 const auto &clippingFrustum = getCameraRenderData(&camera).clippingFrustum;
379 if (clippingFrustum.has_value()) { // Frustum culling
380 const auto visibleObjects = QSSGLayerRenderData::frustumCullingInline(clippingFrustum.value(), sortedTransparentObjects);
381 sortedTransparentObjects.resize(visibleObjects);
382 }
383
384 // render furthest to nearest.
385 std::sort(sortedTransparentObjects.begin(), sortedTransparentObjects.end(), furthestToNearestCompare);
386
387 return sortedTransparentObjects;
388}
389
390const QVector<QSSGRenderableObjectHandle> &QSSGLayerRenderData::getSortedScreenTextureRenderableObjects(const QSSGRenderCamera &camera, size_t index)
391{
392 index = index * size_t(index < screenTextureObjectStore.size());
393 const auto &screenTextureObjects = std::as_const(screenTextureObjectStore)[index];
394 auto &renderedScreenTextureObjects = sortedScreenTextureObjectCache[index][{&camera, camera.layerMask}];
395
396 if (!renderedScreenTextureObjects.empty())
397 return renderedScreenTextureObjects;
398 renderedScreenTextureObjects = screenTextureObjects;
399 if (!renderedScreenTextureObjects.empty()) {
400 // render furthest to nearest.
401 std::sort(renderedScreenTextureObjects.begin(), renderedScreenTextureObjects.end(), furthestToNearestCompare);
402 }
403 return renderedScreenTextureObjects;
404}
405
406const QVector<QSSGBakedLightingModel> &QSSGLayerRenderData::getSortedBakedLightingModels()
407{
408 if (!renderedBakedLightingModels.empty() || renderedCameras.isEmpty())
409 return renderedBakedLightingModels;
410 if (layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest) && !bakedLightingModels.empty()) {
411 renderedBakedLightingModels = bakedLightingModels;
412 for (QSSGBakedLightingModel &lm : renderedBakedLightingModels) {
413 // sort nearest to furthest (front to back)
414 std::sort(lm.renderables.begin(), lm.renderables.end(), nearestToFurthestCompare);
415 }
416 }
417 return renderedBakedLightingModels;
418}
419
420const QSSGLayerRenderData::RenderableItem2DEntries &QSSGLayerRenderData::getRenderableItem2Ds()
421{
422 if (!renderedItem2Ds.isEmpty() || renderedCameras.isEmpty())
423 return renderedItem2Ds;
424
425 // Maintain QML item order
426 renderedItem2Ds = { std::make_reverse_iterator(item2DsView.end()),
427 std::make_reverse_iterator(item2DsView.begin()) };
428
429 if (!renderedItem2Ds.isEmpty()) {
430 const QSSGRenderCameraDataList &cameraDatas(getCachedCameraDatas());
431 // with multiview this means using the left eye camera
432 const QSSGRenderCameraData &cameraDirectionAndPosition(cameraDatas[0]);
433 const QVector3D &cameraDirection = cameraDirectionAndPosition.direction;
434 const QVector3D &cameraPosition = cameraDirectionAndPosition.position;
435
436 const auto isItemNodeDistanceGreatThan = [this, cameraDirection, cameraPosition]
437 (const QSSGRenderItem2D *lhs, const QSSGRenderItem2D *rhs) {
438 if (!lhs->parent || !rhs->parent)
439 return false;
440
441 auto lhsGlobalTransform = getGlobalTransform(*lhs->parent);
442 auto rhsGlobalTransform = getGlobalTransform(*rhs->parent);
443
444 const QVector3D lhsDifference = QSSGRenderNode::getGlobalPos(lhsGlobalTransform) - cameraPosition;
445 const float lhsCameraDistanceSq = QVector3D::dotProduct(lhsDifference, cameraDirection);
446 const QVector3D rhsDifference = QSSGRenderNode::getGlobalPos(rhsGlobalTransform) - cameraPosition;
447 const float rhsCameraDistanceSq = QVector3D::dotProduct(rhsDifference, cameraDirection);
448 return lhsCameraDistanceSq > rhsCameraDistanceSq;
449 };
450
451 // Render furthest to nearest items (parent nodes).
452 std::stable_sort(renderedItem2Ds.begin(), renderedItem2Ds.end(), isItemNodeDistanceGreatThan);
453 }
454
455 return renderedItem2Ds;
456}
457
458// Depth Write List
459void QSSGLayerRenderData::updateSortedDepthObjectsListImp(const QSSGRenderCamera &camera, size_t index)
460{
461 auto &depthWriteObjects = sortedDepthWriteCache[index][{&camera, camera.layerMask}];
462 auto &depthPrepassObjects = sortedOpaqueDepthPrepassCache[index][{&camera, camera.layerMask}];
463
464 if (!depthWriteObjects.isEmpty() || !depthPrepassObjects.isEmpty())
465 return;
466
467 if (layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest)) {
468 if (hasDepthWriteObjects || (depthPrepassObjectsState & DepthPrepassObjectStateT(DepthPrepassObject::Opaque)) != 0) {
469 const auto &sortedOpaqueObjects = getSortedOpaqueRenderableObjects(camera, index); // front to back
470 for (const auto &opaqueObject : sortedOpaqueObjects) {
471 const auto depthMode = opaqueObject.obj->depthWriteMode;
472 if (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaqueOnly)
473 depthWriteObjects.append(opaqueObject);
474 else if (depthMode == QSSGDepthDrawMode::OpaquePrePass)
475 depthPrepassObjects.append(opaqueObject);
476 }
477 }
478 if (hasDepthWriteObjects || (depthPrepassObjectsState & DepthPrepassObjectStateT(DepthPrepassObject::Transparent)) != 0) {
479 const auto &sortedTransparentObjects = getSortedTransparentRenderableObjects(camera, index); // back to front
480 for (const auto &transparentObject : sortedTransparentObjects) {
481 const auto depthMode = transparentObject.obj->depthWriteMode;
482 if (depthMode == QSSGDepthDrawMode::Always)
483 depthWriteObjects.append(transparentObject);
484 else if (depthMode == QSSGDepthDrawMode::OpaquePrePass)
485 depthPrepassObjects.append(transparentObject);
486 }
487 }
488 if (hasDepthWriteObjects || (depthPrepassObjectsState & DepthPrepassObjectStateT(DepthPrepassObject::ScreenTexture)) != 0) {
489 const auto &sortedScreenTextureObjects = getSortedScreenTextureRenderableObjects(camera, index); // back to front
490 for (const auto &screenTextureObject : sortedScreenTextureObjects) {
491 const auto depthMode = screenTextureObject.obj->depthWriteMode;
492 if (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaqueOnly)
493 depthWriteObjects.append(screenTextureObject);
494 else if (depthMode == QSSGDepthDrawMode::OpaquePrePass)
495 depthPrepassObjects.append(screenTextureObject);
496 }
497 }
498 }
499}
500
501const std::unique_ptr<QSSGPerFrameAllocator> &QSSGLayerRenderData::perFrameAllocator(QSSGRenderContextInterface &ctx)
502{
503 return ctx.perFrameAllocator();
504}
505
506void QSSGLayerRenderData::saveRenderState(const QSSGRenderer &renderer)
507{
508 QSSG_CHECK(!savedRenderState.has_value());
509 const auto &rhiCtx = renderer.contextInterface()->rhiContext();
510 savedRenderState = std::make_optional<SavedRenderState>({ renderer.m_viewport,
511 renderer.m_scissorRect,
512 renderer.m_dpr,
513 rhiCtx->mainRenderPassDescriptor(),
514 rhiCtx->renderTarget(),
515 rhiCtx->commandBuffer(),
516 rhiCtx->mainPassSampleCount(),
517 rhiCtx->mainPassViewCount() });
518}
519
520void QSSGLayerRenderData::restoreRenderState(QSSGRenderer &renderer)
521{
522 QSSG_ASSERT(savedRenderState.has_value(), return);
523
524 renderer.m_viewport = savedRenderState->viewport;
525 renderer.m_scissorRect = savedRenderState->scissorRect;
526 renderer.m_dpr = savedRenderState->dpr;
527
528 const auto &rhiCtx = renderer.contextInterface()->rhiContext();
529 auto *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx.get());
530 rhiCtxD->setMainRenderPassDescriptor(savedRenderState->mainRenderPassDescriptor);
531 rhiCtxD->setRenderTarget(savedRenderState->renderTarget);
532 rhiCtxD->setCommandBuffer(savedRenderState->commandBuffer);
533 rhiCtxD->setMainPassSampleCount(savedRenderState->mainPassSampleCount);
534 rhiCtxD->setMainPassViewCount(savedRenderState->mainPassViewCount);
535
536 savedRenderState.reset();
537}
538
539static constexpr quint16 PREP_CTX_INDEX_MASK = 0xffff;
540static constexpr QSSGPrepContextId createPrepId(size_t index, quint32 frame) { return QSSGPrepContextId { ((quint64(frame) << 32) | index ) * quint64(index <= std::numeric_limits<quint16>::max()) }; }
541static constexpr size_t getPrepContextIndex(QSSGPrepContextId id) { return (static_cast<quint64>(id) & PREP_CTX_INDEX_MASK); }
542static constexpr bool verifyPrepContext(QSSGPrepContextId id, const QSSGRenderer &renderer) { return (getPrepContextIndex(id) > 0) && ((static_cast<quint64>(id) >> 32) == renderer.frameCount()); }
543
544QSSGPrepContextId QSSGLayerRenderData::getOrCreateExtensionContext(const QSSGRenderExtension &ext, QSSGRenderCamera *camera, quint32 slot)
545{
546 const auto frame = renderer->frameCount();
547 const auto index = extContexts.size();
548 // Sanity check... Shouldn't get anywhere close to the max in real world usage (unless somethings broken).
549 QSSG_ASSERT_X(index < PREP_CTX_INDEX_MASK - 1, "Reached maximum entries!", return QSSGPrepContextId::Invalid);
550 auto it = std::find_if(extContexts.cbegin(), extContexts.cend(), [&ext, slot](const ExtensionContext &e){ return (e.owner == &ext) && (e.slot == slot); });
551 if (it == extContexts.cend()) {
552 extContexts.push_back(ExtensionContext{ ext, camera, index, slot });
553 it = extContexts.cbegin() + index;
554 renderableModelStore.emplace_back();
555 modelContextStore.emplace_back();
556 renderableObjectStore.emplace_back();
557 screenTextureObjectStore.emplace_back();
558 opaqueObjectStore.emplace_back();
559 transparentObjectStore.emplace_back();
560 sortedOpaqueObjectCache.emplace_back();
561 sortedTransparentObjectCache.emplace_back();
562 sortedScreenTextureObjectCache.emplace_back();
563 sortedOpaqueDepthPrepassCache.emplace_back();
564 sortedDepthWriteCache.emplace_back();
565 QSSG_ASSERT(renderableModelStore.size() == extContexts.size(), renderableModelStore.resize(extContexts.size()));
566 QSSG_ASSERT(modelContextStore.size() == extContexts.size(), modelContextStore.resize(extContexts.size()));
567 QSSG_ASSERT(renderableObjectStore.size() == extContexts.size(), renderableObjectStore.resize(extContexts.size()));
568 QSSG_ASSERT(screenTextureObjectStore.size() == extContexts.size(), screenTextureObjectStore.resize(extContexts.size()));
569 QSSG_ASSERT(opaqueObjectStore.size() == extContexts.size(), opaqueObjectStore.resize(extContexts.size()));
570 QSSG_ASSERT(transparentObjectStore.size() == extContexts.size(), transparentObjectStore.resize(extContexts.size()));
571 QSSG_ASSERT(sortedOpaqueObjectCache.size() == extContexts.size(), sortedOpaqueObjectCache.resize(extContexts.size()));
572 QSSG_ASSERT(sortedTransparentObjectCache.size() == extContexts.size(), sortedTransparentObjectCache.resize(extContexts.size()));
573 QSSG_ASSERT(sortedScreenTextureObjectCache.size() == extContexts.size(), sortedScreenTextureObjectCache.resize(extContexts.size()));
574 QSSG_ASSERT(sortedOpaqueDepthPrepassCache.size() == extContexts.size(), sortedOpaqueDepthPrepassCache.resize(extContexts.size()));
575 QSSG_ASSERT(sortedDepthWriteCache.size() == extContexts.size(), sortedDepthWriteCache.resize(extContexts.size()));
576 }
577
578 return createPrepId(it->index, frame);
579}
580
581static void createRenderablesHelper(QSSGLayerRenderData &layer, const QSSGRenderNode::ChildList &children, QSSGLayerRenderData::RenderableNodeEntries &renderables, QSSGRenderHelpers::CreateFlags createFlags)
582{
583 const bool steal = ((createFlags & QSSGRenderHelpers::CreateFlag::Steal) != 0);
584 for (auto &chld : children) {
585 if (chld.type == QSSGRenderGraphObject::Type::Model) {
586 const auto &renderModel = static_cast<const QSSGRenderModel &>(chld);
587 auto &renderableModels = layer.renderableModels;
588 if (auto it = std::find_if(renderableModels.cbegin(), renderableModels.cend(), [&renderModel](const QSSGRenderableNodeEntry &e) { return (e.node == &renderModel); }); it != renderableModels.cend()) {
589 renderables.emplace_back(*it);
590 if (steal)
591 renderableModels.erase(it);
592 }
593 }
594
595 createRenderablesHelper(layer, chld.children, renderables, createFlags);
596 }
597}
598
599QSSGRenderablesId QSSGLayerRenderData::createRenderables(QSSGPrepContextId prepId, const QSSGNodeIdList &nodes, QSSGRenderHelpers::CreateFlags createFlags)
600{
601 QSSG_ASSERT_X(verifyPrepContext(prepId, *renderer), "Expired or invalid prep id", return {});
602
603 const size_t index = getPrepContextIndex(prepId);
604 QSSG_ASSERT(index < renderableModelStore.size(), return {});
605
606 auto &renderables = renderableModelStore[index];
607 if (renderables.size() != 0) {
608 qWarning() << "Renderables already created for this context - Previous renderables will be overwritten";
609 renderables.clear();
610 }
611
612 renderables.reserve(nodes.size());
613
614 // We now create the renderable node entries for all the models.
615 // NOTE: The nodes are not complete at this point...
616 const bool steal = ((createFlags & QSSGRenderHelpers::CreateFlag::Steal) != 0);
617 for (const auto &nodeId : nodes) {
618 auto *node = QSSGRenderGraphObjectUtils::getNode<QSSGRenderNode>(nodeId);
619 if (node && node->type == QSSGRenderGraphObject::Type::Model) {
620 auto *renderModel = static_cast<QSSGRenderModel *>(node);
621 // NOTE: Not ideal.
622 if (auto it = std::find_if(renderableModels.cbegin(), renderableModels.cend(), [renderModel](const QSSGRenderableNodeEntry &e) { return (e.node == renderModel); }); it != renderableModels.cend()) {
623 auto &inserted = renderables.emplace_back(*it);
624 inserted.overridden = {};
625 if (steal)
626 it->overridden |= QSSGRenderableNodeEntry::Overridden::Disabled;
627 } else {
628 renderables.emplace_back(*renderModel);
629 }
630 }
631
632 if (node && ((createFlags & QSSGRenderHelpers::CreateFlag::Recurse) != 0)) {
633 const auto &children = node->children;
634 createRenderablesHelper(*this, children, renderables, createFlags);
635 }
636 }
637
638 // NOTE: Modifying the renderables list isn't ideal and should be done differently
639 // but for now this is the easiest way to get the job done.
640 // We still need to let the layer know it should reset the list once a new
641 // frame starts.
642 renderablesModifiedByExtension = true;
643
644 return (renderables.size() != 0) ? static_cast<QSSGRenderablesId>(prepId) : QSSGRenderablesId{ QSSGRenderablesId::Invalid };
645}
646
647void QSSGLayerRenderData::setGlobalTransform(QSSGRenderablesId renderablesId, const QSSGRenderModel &model, const QMatrix4x4 &globalTransform)
648{
649 const auto prepId = static_cast<QSSGPrepContextId>(renderablesId);
650 QSSG_ASSERT_X(verifyPrepContext(prepId, *renderer), "Expired or invalid renderables id", return);
651 const size_t index = getPrepContextIndex(prepId);
652 QSSG_ASSERT_X(index < renderableModelStore.size(), "Missing call to createRenderables()?", return);
653
654 auto &renderables = renderableModelStore[index];
655 auto it = std::find_if(renderables.cbegin(), renderables.cend(), [&model](const QSSGRenderableNodeEntry &e) { return e.node == &model; });
656 if (it != renderables.cend()) {
657 it->extOverrides.globalTransform = globalTransform;
658 it->overridden |= QSSGRenderableNodeEntry::Overridden::GlobalTransform;
659 }
660}
661
662QMatrix4x4 QSSGLayerRenderData::getGlobalTransform(QSSGPrepContextId prepId, const QSSGRenderModel &model)
663{
664 QSSG_ASSERT_X(verifyPrepContext(prepId, *renderer), "Expired or invalid prep id", return {});
665 const size_t index = getPrepContextIndex(prepId);
666 QSSG_ASSERT_X(index < renderableModelStore.size(), "Missing call to createRenderables()?", return {});
667
668 QMatrix4x4 ret = getGlobalTransform(model);
669 auto &renderables = renderableModelStore[index];
670 auto it = std::find_if(renderables.cbegin(), renderables.cend(), [&model](const QSSGRenderableNodeEntry &e) { return e.node == &model; });
671 if (it != renderables.cend() && (it->overridden & QSSGRenderableNodeEntry::Overridden::GlobalTransform))
672 ret = it->extOverrides.globalTransform;
673
674 return ret;
675}
676
677void QSSGLayerRenderData::setGlobalOpacity(QSSGRenderablesId renderablesId, const QSSGRenderModel &model, float opacity)
678{
679 const auto prepId = static_cast<QSSGPrepContextId>(renderablesId);
680 QSSG_ASSERT_X(verifyPrepContext(prepId, *renderer), "Expired or invalid renderables id", return);
681 const size_t index = getPrepContextIndex(prepId);
682 QSSG_ASSERT_X(index < renderableModelStore.size(), "Missing call to createRenderables()?", return);
683
684 auto &renderables = renderableModelStore[index];
685 auto it = std::find_if(renderables.cbegin(), renderables.cend(), [&model](const QSSGRenderableNodeEntry &e) { return e.node == &model; });
686 if (it != renderables.cend()) {
687 it->extOverrides.globalOpacity = opacity;
688 it->overridden |= QSSGRenderableNodeEntry::Overridden::GlobalOpacity;
689 }
690}
691
692float QSSGLayerRenderData::getGlobalOpacity(QSSGPrepContextId prepId, const QSSGRenderModel &model)
693{
694 QSSG_ASSERT_X(verifyPrepContext(prepId, *renderer), "Expired or invalid prep id", return {});
695 const size_t index = getPrepContextIndex(prepId);
696 QSSG_ASSERT_X(index < renderableModelStore.size(), "Missing call to createRenderables()?", return {});
697
698 float ret = getGlobalOpacity(model);
699 auto &renderables = renderableModelStore[index];
700 auto it = std::find_if(renderables.cbegin(), renderables.cend(), [&model](const QSSGRenderableNodeEntry &e) { return e.node == &model; });
701 if (it != renderables.cend() && (it->overridden & QSSGRenderableNodeEntry::Overridden::GlobalOpacity))
702 ret = it->extOverrides.globalOpacity;
703
704 return ret;
705}
706
707void QSSGLayerRenderData::setModelMaterials(QSSGRenderablesId renderablesId, const QSSGRenderModel &model, const QList<QSSGResourceId> &materials)
708{
709 const auto prepId = static_cast<QSSGPrepContextId>(renderablesId);
710 QSSG_ASSERT_X(verifyPrepContext(prepId, *renderer), "Expired or invalid renderable id", return);
711 const size_t index = getPrepContextIndex(prepId);
712 QSSG_ASSERT(index < renderableModelStore.size(), return);
713
714 // Sanity check
715 if (materials.size() > 0 && !QSSG_GUARD(QSSGRenderGraphObject::isMaterial(QSSGRenderGraphObjectUtils::getResource(materials.at(0))->type)))
716 return;
717
718 auto &renderables = renderableModelStore[index];
719 auto it = std::find_if(renderables.cbegin(), renderables.cend(), [&model](const QSSGRenderableNodeEntry &e) { return e.node == &model; });
720 if (it != renderables.cend()) {
721 it->extOverrides.materials.resize(materials.size());
722 std::memcpy(it->extOverrides.materials.data(), materials.data(), it->extOverrides.materials.size() * sizeof(QSSGRenderGraphObject *));
723 it->overridden |= QSSGRenderableNodeEntry::Overridden::Materials;
724 }
725}
726
727void QSSGLayerRenderData::setModelMaterials(const QSSGRenderablesId renderablesId, const QList<QSSGResourceId> &materials)
728{
729 const auto prepId = static_cast<QSSGPrepContextId>(renderablesId);
730 QSSG_ASSERT_X(verifyPrepContext(prepId, *renderer), "Expired or invalid renderablesId or renderables id", return);
731
732 const size_t index = getPrepContextIndex(prepId);
733 QSSG_ASSERT(index < renderableModelStore.size(), return);
734
735 auto &renderables = renderableModelStore[index];
736 for (auto &renderable : renderables) {
737 auto &renderableMaterials = renderable.extOverrides.materials;
738 renderableMaterials.resize(materials.size());
739 std::memcpy(renderableMaterials.data(), materials.data(), renderableMaterials.size() * sizeof(QSSGRenderGraphObject *));
740 renderable.overridden |= QSSGRenderableNodeEntry::Overridden::Materials;
741 }
742}
743
744QSSGPrepResultId QSSGLayerRenderData::prepareModelsForRender(QSSGRenderContextInterface &contextInterface,
745 QSSGPrepContextId prepId,
746 QSSGRenderablesId renderablesId,
747 float lodThreshold)
748{
749 QSSG_ASSERT_X(renderablesId != QSSGRenderablesId::Invalid && verifyPrepContext(prepId, *renderer),
750 "Expired or invalid prep or renderables id", return QSSGPrepResultId::Invalid);
751 const size_t index = getPrepContextIndex(prepId);
752 QSSG_ASSERT(index < renderableModelStore.size(), return {});
753
754 const auto &extContext = extContexts.at(index);
755
756 QSSG_ASSERT_X(extContext.camera != nullptr, "No camera set!", return {});
757
758 const auto vp = contextInterface.renderer()->viewport();
759 const float dpr = contextInterface.renderer()->dpr();
760 const float ssaaMultiplier = layer.isSsaaEnabled() ? layer.ssaaMultiplier : 1.0f;
761
762 QSSGRenderCamera::calculateProjectionInternal(*extContext.camera, vp, { dpr, ssaaMultiplier } );
763
764 auto &renderables = renderableModelStore[index];
765
766 static const auto prepareModelMaterials = [](const RenderableNodeEntries &renderables) {
767 for (auto &renderable : renderables) {
768 if ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::Materials) == 0
769 && (renderable.overridden & QSSGRenderableNodeEntry::Overridden::Disabled) == 0) {
770 renderable.extOverrides.materials = static_cast<QSSGRenderModel *>(renderable.node)->materials;
771 }
772 }
773 };
774
775 prepareModelMaterials(renderables);
776
777 // ### multiview
778 QSSGRenderCameraList camera({ extContext.camera });
779 QSSGRenderCameraDataList cameraData({ getCameraRenderData(extContext.camera) });
780
781 auto &modelContexts = modelContextStore[index];
782 QSSG_ASSERT(modelContexts.isEmpty(), modelContexts.clear());
783
784 auto &renderableObjects = renderableObjectStore[index];
785 QSSG_ASSERT(renderableObjects.isEmpty(), renderableObjects.clear());
786
787 auto &opaqueObjects = opaqueObjectStore[index];
788 QSSG_ASSERT(opaqueObjects.isEmpty(), opaqueObjects.clear());
789
790 auto &transparentObjects = transparentObjectStore[index];
791 QSSG_ASSERT(transparentObjects.isEmpty(), transparentObjects.clear());
792
793 auto &screenTextureObjects = screenTextureObjectStore[index];
794 QSSG_ASSERT(screenTextureObjects.isEmpty(), screenTextureObjects.clear());
795
796 bool wasDirty = prepareModelsForRender(contextInterface,
797 renderables,
798 layerPrepResult.flags,
799 camera,
800 cameraData,
801 modelContexts,
802 opaqueObjects,
803 transparentObjects,
804 screenTextureObjects,
805 lodThreshold);
806
807 (void)wasDirty;
808
809 return static_cast<QSSGPrepResultId>(prepId);
810}
811
812static constexpr size_t pipelineStateIndex(QSSGRenderablesFilter filter)
813{
814 switch (filter) {
815 case QSSGRenderablesFilter::All:
816 return 0;
817 case QSSGRenderablesFilter::Opaque:
818 return 1;
819 case QSSGRenderablesFilter::Transparent:
820 return 2;
821 }
822
823 // GCC 8.x does not treat __builtin_unreachable() as constexpr
824# if !defined(Q_CC_GNU_ONLY) || (Q_CC_GNU >= 900)
825 // NOLINTNEXTLINE(qt-use-unreachable-return): Triggers on Clang, breaking GCC 8
826 Q_UNREACHABLE();
827# endif
828 return 0;
829}
830
831void QSSGLayerRenderData::prepareRenderables(QSSGRenderContextInterface &ctx,
832 QSSGPrepResultId prepId,
833 QRhiRenderPassDescriptor *renderPassDescriptor,
834 const QSSGRhiGraphicsPipelineState &ps,
835 QSSGRenderablesFilters filter)
836{
837 QSSG_ASSERT_X(verifyPrepContext(static_cast<QSSGPrepContextId>(prepId), *renderer), "Expired or invalid result id", return);
838 const size_t index = getPrepContextIndex(static_cast<QSSGPrepContextId>(prepId));
839 QSSG_ASSERT(index < renderableObjectStore.size() && index < extContexts.size(), return);
840
841 auto &extCtx = extContexts[index];
842 QSSG_ASSERT(extCtx.camera, return);
843 extCtx.filter |= filter;
844
845 QSSGShaderFeatures featureSet = getShaderFeatures();
846
847 QSSGPassKey passKey { reinterpret_cast<void *>(quintptr(extCtx.owner) ^ extCtx.slot) }; // TODO: Pass this along
848
849 if ((filter & QSSGRenderablesFilter::Opaque) != 0) {
850 auto psCpy = ps;
851 if (filter == QSSGRenderablesFilter::All) { // If 'All' we set our defaults
852 psCpy.depthFunc = QRhiGraphicsPipeline::LessOrEqual;
853 psCpy.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::BlendEnabled, false);
854 }
855 const auto &sortedRenderables = getSortedOpaqueRenderableObjects(*extCtx.camera, index);
856 OpaquePass::prep(ctx, *this, passKey, psCpy, featureSet, renderPassDescriptor, sortedRenderables);
857 const size_t psIndex = pipelineStateIndex(QSSGRenderablesFilter::Opaque);
858 extCtx.ps[psIndex] = psCpy;
859 }
860
861 if ((filter & QSSGRenderablesFilter::Transparent) != 0) {
862 auto psCpy = ps;
863 if (filter == QSSGRenderablesFilter::All) { // If 'All' we set our defaults
864 // transparent objects (or, without LayerEnableDepthTest, all objects)
865 psCpy.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::BlendEnabled, true);
866 psCpy.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled, false);
867 }
868 const auto &sortedRenderables = getSortedTransparentRenderableObjects(*extCtx.camera, index);
869 TransparentPass::prep(ctx, *this, passKey, psCpy, featureSet, renderPassDescriptor, sortedRenderables);
870 const size_t psIndex = pipelineStateIndex(QSSGRenderablesFilter::Transparent);
871 extCtx.ps[psIndex] = psCpy;
872 }
873}
874
875void QSSGLayerRenderData::renderRenderables(QSSGRenderContextInterface &ctx, QSSGPrepResultId prepId)
876{
877 QSSG_ASSERT_X(verifyPrepContext(static_cast<QSSGPrepContextId>(prepId), *renderer), "Expired or invalid result id", return);
878 const size_t index = getPrepContextIndex(static_cast<QSSGPrepContextId>(prepId));
879 QSSG_ASSERT(index < renderableObjectStore.size() && index < extContexts.size(), return);
880
881 const auto &extCtx = extContexts.at(index);
882 const auto filter = extCtx.filter;
883
884 if ((filter & QSSGRenderablesFilter::Opaque) != 0) {
885 const size_t psIndex = pipelineStateIndex(QSSGRenderablesFilter::Opaque);
886 const auto &ps = extCtx.ps[psIndex];
887 const auto &sortedRenderables = getSortedOpaqueRenderableObjects(*extCtx.camera, index);
888 OpaquePass::render(ctx, ps, sortedRenderables);
889 }
890
891 if ((filter & QSSGRenderablesFilter::Transparent) != 0) {
892 const size_t psIndex = pipelineStateIndex(QSSGRenderablesFilter::Transparent);
893 const auto &ps = extCtx.ps[psIndex];
894 const auto &sortedRenderables = getSortedTransparentRenderableObjects(*extCtx.camera, index);
895 TransparentPass::render(ctx, ps, sortedRenderables);
896 }
897}
898
899const QSSGRenderableObjectList &QSSGLayerRenderData::getSortedRenderedDepthWriteObjects(const QSSGRenderCamera &camera, size_t index)
900{
901 updateSortedDepthObjectsListImp(camera, index);
902 return sortedDepthWriteCache[index][{&camera, camera.layerMask}];
903}
904
905const QSSGRenderableObjectList &QSSGLayerRenderData::getSortedrenderedOpaqueDepthPrepassObjects(const QSSGRenderCamera &camera, size_t index)
906{
907 updateSortedDepthObjectsListImp(camera, index);
908 return sortedOpaqueDepthPrepassCache[index][{&camera, camera.layerMask}];
909}
910
911void QSSGLayerRenderData::getShadowCastingObjects(const QSSGRenderCamera &camera,
912 QSSGRenderableObjectList &outObjects,
913 QSSGBounds3 &outBoundsCasting,
914 QSSGBounds3 &outBoundsReceiving)
915{
916 constexpr int index = 0;
917
918 const QSSGRenderableObjectList transparentObjects = std::as_const(transparentObjectStore)[index];
919 const QSSGRenderableObjectList opaqueObjects = layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest)
920 ? std::as_const(opaqueObjectStore)[index]
921 : QSSGRenderableObjectList();
922 const QSSGRenderableObjectList screenTextureObjects = std::as_const(screenTextureObjectStore)[index];
923
924 outObjects.clear();
925 outObjects.reserve(transparentObjects.size() + opaqueObjects.size() + screenTextureObjects.size());
926
927 if (layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest)) {
928 if (hasDepthWriteObjects || (depthPrepassObjectsState & DepthPrepassObjectStateT(DepthPrepassObject::Opaque)) != 0) {
929 for (const auto &opaqueObject : std::as_const(opaqueObjects)) {
930 const auto depthMode = opaqueObject.obj->depthWriteMode;
931 if (opaqueObject.obj->renderableFlags.castsShadows() && opaqueObject.tag.value() & camera.layerMask
932 && (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaqueOnly
933 || depthMode == QSSGDepthDrawMode::OpaquePrePass))
934 outObjects.push_back(opaqueObject);
935 }
936 }
937 if (hasDepthWriteObjects || (depthPrepassObjectsState & DepthPrepassObjectStateT(DepthPrepassObject::Transparent)) != 0) {
938 for (const auto &transparentObject : std::as_const(transparentObjects)) {
939 const auto depthMode = transparentObject.obj->depthWriteMode;
940 if (transparentObject.obj->renderableFlags.castsShadows() && transparentObject.tag.value() & camera.layerMask
941 && (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaquePrePass))
942 outObjects.push_back(transparentObject);
943 }
944 }
945 if (hasDepthWriteObjects || (depthPrepassObjectsState & DepthPrepassObjectStateT(DepthPrepassObject::ScreenTexture)) != 0) {
946 for (const auto &screenTextureObject : std::as_const(screenTextureObjects)) {
947 const auto depthMode = screenTextureObject.obj->depthWriteMode;
948 if (screenTextureObject.obj->renderableFlags.castsShadows() && screenTextureObject.tag.value() & camera.layerMask
949 && (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaqueOnly
950 || depthMode == QSSGDepthDrawMode::OpaquePrePass))
951 outObjects.push_back(screenTextureObject);
952 }
953 }
954 }
955
956 outBoundsCasting = QSSGBounds3();
957 outBoundsReceiving = QSSGBounds3();
958
959 const auto &clippingFrustum = getCameraRenderData(&camera).clippingFrustum;
960 const bool doCulling = clippingFrustum.has_value();
961
962 for (const auto handles : { &opaqueObjects, &transparentObjects, &screenTextureObjects }) {
963 // Since we may have nodes that are not a child of the camera parent we go through all
964 // the opaque objects and include them in the bounds. Failing to do this can result in
965 // too small bounds.
966 for (const QSSGRenderableObjectHandle &handle : *handles) {
967 const QSSGRenderableObject &obj = *handle.obj;
968 if (!(handle.tag.value() & camera.layerMask))
969 continue;
970 // We skip objects not casting or receiving shadows since they don't influence or need to be covered by the shadow map
971 if (obj.renderableFlags.castsShadows()) {
972 if (!obj.globalBoundsInstancing.isEmpty())
973 outBoundsCasting.include(obj.globalBoundsInstancing);
974 else
975 outBoundsCasting.include(obj.globalBounds);
976 }
977 if (obj.renderableFlags.receivesShadows()) {
978 // We only cull receiving shadow objects from the bounds
979 if (doCulling && isObjectCullable(*clippingFrustum, obj))
980 ; // skip
981 else if (!obj.globalBoundsInstancing.isEmpty())
982 outBoundsReceiving.include(obj.globalBoundsInstancing);
983 else
984 outBoundsReceiving.include(obj.globalBounds);
985 }
986 }
987 }
988}
989
990/**
991 * Usage: T *ptr = RENDER_FRAME_NEW<T>(context, arg0, arg1, ...); is equivalent to: T *ptr = new T(arg0, arg1, ...);
992 * so RENDER_FRAME_NEW() takes the RCI + T's arguments
993 */
994template <typename T, typename... Args>
995[[nodiscard]] inline T *RENDER_FRAME_NEW(QSSGRenderContextInterface &ctx, Args&&... args)
996{
997 static_assert(std::is_trivially_destructible_v<T>, "Objects allocated using the per-frame allocator needs to be trivially destructible!");
998 return new (QSSGLayerRenderData::perFrameAllocator(ctx)->allocate(sizeof(T)))T(std::forward<Args>(args)...);
999}
1000
1001template <typename T>
1002[[nodiscard]] inline QSSGDataRef<T> RENDER_FRAME_NEW_BUFFER(QSSGRenderContextInterface &ctx, size_t count)
1003{
1004 static_assert(std::is_trivially_destructible_v<T>, "Objects allocated using the per-frame allocator needs to be trivially destructible!");
1005 const size_t asize = sizeof(T) * count;
1006 return { reinterpret_cast<T *>(QSSGLayerRenderData::perFrameAllocator(ctx)->allocate(asize)), qsizetype(count) };
1007}
1008
1009void QSSGLayerRenderData::prepareImageForRender(QSSGRenderImage &inImage,
1010 QSSGRenderableImage::Type inMapType,
1011 QSSGRenderableImage *&ioFirstImage,
1012 QSSGRenderableImage *&ioNextImage,
1013 QSSGRenderableObjectFlags &ioFlags,
1014 QSSGShaderDefaultMaterialKey &inShaderKey,
1015 quint32 inImageIndex,
1016 QSSGRenderDefaultMaterial *inMaterial)
1017{
1018 QSSGRenderContextInterface &contextInterface = *renderer->contextInterface();
1019 const auto &bufferManager = contextInterface.bufferManager();
1020
1021 if (inImage.clearDirty())
1022 ioFlags |= QSSGRenderableObjectFlag::Dirty;
1023
1024 // This is where the QRhiTexture gets created, if not already done. Note
1025 // that the bufferManager is per-QQuickWindow, and so per-render-thread.
1026 // Hence using the same Texture (backed by inImage as the backend node) in
1027 // multiple windows will work by each scene in each window getting its own
1028 // QRhiTexture. And that's why the QSSGRenderImageTexture cannot be a
1029 // member of the QSSGRenderImage. Conceptually this matches what we do for
1030 // models (QSSGRenderModel -> QSSGRenderMesh retrieved from the
1031 // bufferManager in each prepareModelForRender, etc.).
1032
1033 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(&inImage);
1034
1035 if (texture.m_texture) {
1036 if (texture.m_flags.hasTransparency()
1037 && (inMapType == QSSGRenderableImage::Type::Diffuse // note: Type::BaseColor is skipped here intentionally
1038 || inMapType == QSSGRenderableImage::Type::Opacity
1039 || inMapType == QSSGRenderableImage::Type::Translucency))
1040 {
1041 ioFlags |= QSSGRenderableObjectFlag::HasTransparency;
1042 }
1043
1044 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, inMapType, inImage, texture);
1045 QSSGShaderKeyImageMap &theKeyProp = defaultMaterialShaderKeyProperties.m_imageMaps[inImageIndex];
1046
1047 theKeyProp.setEnabled(inShaderKey, true);
1048 switch (inImage.m_mappingMode) {
1049 case QSSGRenderImage::MappingModes::Normal:
1050 break;
1051 case QSSGRenderImage::MappingModes::Environment:
1052 theKeyProp.setEnvMap(inShaderKey, true);
1053 break;
1054 case QSSGRenderImage::MappingModes::LightProbe:
1055 theKeyProp.setLightProbe(inShaderKey, true);
1056 break;
1057 }
1058
1059 bool hasA = false;
1060 bool hasG = false;
1061 bool hasB = false;
1062
1063
1064 //### TODO: More formats
1065 switch (texture.m_texture->format()) {
1066 case QRhiTexture::Format::RED_OR_ALPHA8:
1067 hasA = !renderer->contextInterface()->rhiContext()->rhi()->isFeatureSupported(QRhi::RedOrAlpha8IsRed);
1068 break;
1069 case QRhiTexture::Format::R8:
1070 // Leave BGA as false
1071 break;
1072 default:
1073 hasA = true;
1074 hasG = true;
1075 hasB = true;
1076 break;
1077 }
1078
1079 if (inImage.isImageTransformIdentity())
1080 theKeyProp.setIdentityTransform(inShaderKey, true);
1081
1082 if (inImage.m_indexUV == 1)
1083 theKeyProp.setUsesUV1(inShaderKey, true);
1084
1085 if (texture.m_flags.isLinear())
1086 theKeyProp.setLinear(inShaderKey, true);
1087
1088 if (texture.m_flags.isPreMultipliedAlpha())
1089 theKeyProp.setPreMultipliedAlpha(inShaderKey, true);
1090
1091 if (ioFirstImage == nullptr)
1092 ioFirstImage = theImage;
1093 else
1094 ioNextImage->m_nextImage = theImage;
1095
1096 ioNextImage = theImage;
1097
1098 if (inMaterial && inImageIndex >= QSSGShaderDefaultMaterialKeyProperties::SingleChannelImagesFirst) {
1099 QSSGRenderDefaultMaterial::TextureChannelMapping value = QSSGRenderDefaultMaterial::R;
1100
1101 const quint32 scIndex = inImageIndex - QSSGShaderDefaultMaterialKeyProperties::SingleChannelImagesFirst;
1102 QSSGShaderKeyTextureChannel &channelKey = defaultMaterialShaderKeyProperties.m_textureChannels[scIndex];
1103 switch (inImageIndex) {
1104 case QSSGShaderDefaultMaterialKeyProperties::OpacityMap:
1105 value = inMaterial->opacityChannel;
1106 break;
1107 case QSSGShaderDefaultMaterialKeyProperties::RoughnessMap:
1108 value = inMaterial->roughnessChannel;
1109 break;
1110 case QSSGShaderDefaultMaterialKeyProperties::MetalnessMap:
1111 value = inMaterial->metalnessChannel;
1112 break;
1113 case QSSGShaderDefaultMaterialKeyProperties::OcclusionMap:
1114 value = inMaterial->occlusionChannel;
1115 break;
1116 case QSSGShaderDefaultMaterialKeyProperties::TranslucencyMap:
1117 value = inMaterial->translucencyChannel;
1118 break;
1119 case QSSGShaderDefaultMaterialKeyProperties::HeightMap:
1120 value = inMaterial->heightChannel;
1121 break;
1122 case QSSGShaderDefaultMaterialKeyProperties::ClearcoatMap:
1123 value = inMaterial->clearcoatChannel;
1124 break;
1125 case QSSGShaderDefaultMaterialKeyProperties::ClearcoatRoughnessMap:
1126 value = inMaterial->clearcoatRoughnessChannel;
1127 break;
1128 case QSSGShaderDefaultMaterialKeyProperties::SheenRoughnessMap:
1129 value = inMaterial->sheenRoughnessChannel;
1130 break;
1131 case QSSGShaderDefaultMaterialKeyProperties::IridescenceMap:
1132 value = inMaterial->iridescenceChannel;
1133 break;
1134 case QSSGShaderDefaultMaterialKeyProperties::IridescenceThicknessMap:
1135 value = inMaterial->iridescenceThicknessChannel;
1136 break;
1137 case QSSGShaderDefaultMaterialKeyProperties::TransmissionMap:
1138 value = inMaterial->transmissionChannel;
1139 break;
1140 case QSSGShaderDefaultMaterialKeyProperties::ThicknessMap:
1141 value = inMaterial->thicknessChannel;
1142 break;
1143 case QSSGShaderDefaultMaterialKeyProperties::BaseColorMap:
1144 value = inMaterial->baseColorChannel;
1145 break;
1146 case QSSGShaderDefaultMaterialKeyProperties::SpecularAmountMap:
1147 value = inMaterial->specularAmountChannel;
1148 break;
1149 case QSSGShaderDefaultMaterialKeyProperties::EmissiveMap:
1150 value = inMaterial->emissiveChannel;
1151 break;
1152 default:
1153 break;
1154 }
1155 bool useDefault = false;
1156 switch (value) {
1157 case QSSGRenderDefaultMaterial::TextureChannelMapping::G:
1158 useDefault = !hasG;
1159 break;
1160 case QSSGRenderDefaultMaterial::TextureChannelMapping::B:
1161 useDefault = !hasB;
1162 break;
1163 case QSSGRenderDefaultMaterial::TextureChannelMapping::A:
1164 useDefault = !hasA;
1165 break;
1166 default:
1167 break;
1168 }
1169 if (useDefault)
1170 value = QSSGRenderDefaultMaterial::R; // Always Fallback to Red
1171 channelKey.setTextureChannel(QSSGShaderKeyTextureChannel::TexturChannelBits(value), inShaderKey);
1172 }
1173 }
1174}
1175
1176void QSSGLayerRenderData::setVertexInputPresence(const QSSGRenderableObjectFlags &renderableFlags,
1177 QSSGShaderDefaultMaterialKey &key)
1178{
1179 quint32 vertexAttribs = 0;
1180 if (renderableFlags.hasAttributePosition())
1181 vertexAttribs |= QSSGShaderKeyVertexAttribute::Position;
1182 if (renderableFlags.hasAttributeNormal())
1183 vertexAttribs |= QSSGShaderKeyVertexAttribute::Normal;
1184 if (renderableFlags.hasAttributeTexCoord0())
1185 vertexAttribs |= QSSGShaderKeyVertexAttribute::TexCoord0;
1186 if (renderableFlags.hasAttributeTexCoord1())
1187 vertexAttribs |= QSSGShaderKeyVertexAttribute::TexCoord1;
1188 if (renderableFlags.hasAttributeTexCoordLightmap())
1189 vertexAttribs |= QSSGShaderKeyVertexAttribute::TexCoordLightmap;
1190 if (renderableFlags.hasAttributeTangent())
1191 vertexAttribs |= QSSGShaderKeyVertexAttribute::Tangent;
1192 if (renderableFlags.hasAttributeBinormal())
1193 vertexAttribs |= QSSGShaderKeyVertexAttribute::Binormal;
1194 if (renderableFlags.hasAttributeColor())
1195 vertexAttribs |= QSSGShaderKeyVertexAttribute::Color;
1196 if (renderableFlags.hasAttributeJointAndWeight())
1197 vertexAttribs |= QSSGShaderKeyVertexAttribute::JointAndWeight;
1198 defaultMaterialShaderKeyProperties.m_vertexAttributes.setValue(key, vertexAttribs);
1199}
1200
1201QSSGDefaultMaterialPreparationResult QSSGLayerRenderData::prepareDefaultMaterialForRender(
1202 QSSGRenderDefaultMaterial &inMaterial,
1203 QSSGRenderableObjectFlags &inExistingFlags,
1204 float inOpacity, bool hasAnyLights,
1205 bool anyLightHasShadows,
1206 QSSGLayerRenderPreparationResultFlags &ioFlags)
1207{
1208 QSSGRenderDefaultMaterial *theMaterial = &inMaterial;
1209 QSSGDefaultMaterialPreparationResult retval(QSSGShaderDefaultMaterialKey(qHash(features)));
1210 retval.renderableFlags = inExistingFlags;
1211 QSSGRenderableObjectFlags &renderableFlags(retval.renderableFlags);
1212 QSSGShaderDefaultMaterialKey &theGeneratedKey(retval.materialKey);
1213 retval.opacity = inOpacity;
1214 float &subsetOpacity(retval.opacity);
1215
1216 if (theMaterial->isDirty())
1217 renderableFlags |= QSSGRenderableObjectFlag::Dirty;
1218
1219 subsetOpacity *= theMaterial->opacity;
1220
1221 QSSGRenderableImage *firstImage = nullptr;
1222
1223 const bool lighting = theMaterial->lighting != QSSGRenderDefaultMaterial::MaterialLighting::NoLighting;
1224 defaultMaterialShaderKeyProperties.m_hasLighting.setValue(theGeneratedKey, lighting);
1225 if (lighting) {
1226 defaultMaterialShaderKeyProperties.m_hasPunctualLights.setValue(theGeneratedKey, hasAnyLights);
1227 defaultMaterialShaderKeyProperties.m_hasShadows.setValue(theGeneratedKey, anyLightHasShadows);
1228 const bool validSky = layer.skyMaterial != nullptr && layer.skyMaterial->enableIBL;
1229 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey, layer.lightProbe != nullptr || validSky);
1230 }
1231
1232 defaultMaterialShaderKeyProperties.m_specularAAEnabled.setValue(theGeneratedKey, layer.specularAAEnabled);
1233
1234 // isDoubleSided
1235 defaultMaterialShaderKeyProperties.m_isDoubleSided.setValue(theGeneratedKey, theMaterial->cullMode == QSSGCullFaceMode::Disabled);
1236
1237 // default materials never define their on position
1238 defaultMaterialShaderKeyProperties.m_overridesPosition.setValue(theGeneratedKey, false);
1239
1240 // ... so a mesh with no position attribute cannot be drawn with one:
1241 // every vertex would collapse to the model's origin.
1242 if (!renderableFlags.hasAttributePosition() && warnOnce(OneShotWarning::MissingPosition))
1243 warnMissingPosition();
1244
1245 // default materials dont make use of raw projection or inverse projection matrices
1246 defaultMaterialShaderKeyProperties.m_usesProjectionMatrix.setValue(theGeneratedKey, false);
1247 defaultMaterialShaderKeyProperties.m_usesInverseProjectionMatrix.setValue(theGeneratedKey, false);
1248 // nor they do rely on VAR_COLOR
1249 defaultMaterialShaderKeyProperties.m_usesVarColor.setValue(theGeneratedKey, false);
1250
1251 // alpha Mode
1252 defaultMaterialShaderKeyProperties.m_alphaMode.setValue(theGeneratedKey, theMaterial->alphaMode);
1253
1254 // vertex attribute presence flags
1255 setVertexInputPresence(renderableFlags, theGeneratedKey);
1256
1257 // set the flag indicating the need for gl_PointSize
1258 defaultMaterialShaderKeyProperties.m_usesPointsTopology.setValue(theGeneratedKey, renderableFlags.isPointsTopology());
1259
1260 // propagate the flag indicating the presence of a lightmap
1261 defaultMaterialShaderKeyProperties.m_lightmapEnabled.setValue(theGeneratedKey, renderableFlags.rendersWithLightmap());
1262 defaultMaterialShaderKeyProperties.m_metallicRoughnessEnabled.setValue(theGeneratedKey, theMaterial->type == QSSGRenderDefaultMaterial::Type::PrincipledMaterial);
1263 defaultMaterialShaderKeyProperties.m_specularGlossyEnabled.setValue(theGeneratedKey, theMaterial->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial);
1264
1265
1266 // debug modes
1267 defaultMaterialShaderKeyProperties.m_debugMode.setValue(theGeneratedKey, int(layer.debugMode));
1268
1269 // fog
1270 defaultMaterialShaderKeyProperties.m_fogEnabled.setValue(theGeneratedKey, layer.fog.enabled);
1271
1272 // multiview
1273 defaultMaterialShaderKeyProperties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
1274 defaultMaterialShaderKeyProperties.m_usesViewIndex.setValue(theGeneratedKey, layer.viewCount >= 2);
1275
1276 if (!defaultMaterialShaderKeyProperties.m_hasIbl.getValue(theGeneratedKey) && theMaterial->iblProbe) {
1277 features.set(QSSGShaderFeatures::Feature::LightProbe, true);
1278 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey, true);
1279 // features.set(ShaderFeatureDefines::enableIblFov(),
1280 // m_Renderer.GetLayerRenderData()->m_Layer.m_ProbeFov < 180.0f );
1281 }
1282
1283 if (subsetOpacity >= QSSGRendererPrivate::minimumRenderOpacity) {
1284
1285 // Set the semi-transparency flag as specified in PrincipledMaterial's
1286 // blendMode and alphaMode:
1287 // - the default SourceOver blendMode does not imply alpha blending on
1288 // its own,
1289 // - but other blendMode values do,
1290 // - an alphaMode of Blend guarantees blending to be enabled regardless
1291 // of anything else.
1292 // Additionally:
1293 // - Opacity and texture map alpha are handled elsewhere (that's when a
1294 // blendMode of SourceOver or an alphaMode of Default/Opaque can in the
1295 // end still result in HasTransparency),
1296 // - the presence of an opacityMap guarantees alpha blending regardless
1297 // of its content.
1298
1299 if (theMaterial->blendMode != QSSGRenderDefaultMaterial::MaterialBlendMode::SourceOver
1300 || theMaterial->opacityMap
1301 || theMaterial->alphaMode == QSSGRenderDefaultMaterial::Blend)
1302 {
1303 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1304 }
1305
1306 const bool specularEnabled = theMaterial->isSpecularEnabled();
1307 const bool metalnessEnabled = theMaterial->isMetalnessEnabled();
1308 defaultMaterialShaderKeyProperties.m_specularEnabled.setValue(theGeneratedKey, specularEnabled || metalnessEnabled);
1309 defaultMaterialShaderKeyProperties.m_specularModel.setSpecularModel(theGeneratedKey, theMaterial->specularModel);
1310 defaultMaterialShaderKeyProperties.m_diffuseModel.setDiffuseModel(theGeneratedKey, theMaterial->diffuseModel);
1311 defaultMaterialShaderKeyProperties.m_fresnelScaleBiasEnabled.setValue(theGeneratedKey, theMaterial->isFresnelScaleBiasEnabled());
1312 defaultMaterialShaderKeyProperties.m_clearcoatFresnelScaleBiasEnabled.setValue(theGeneratedKey, theMaterial->isClearcoatFresnelScaleBiasEnabled());
1313 defaultMaterialShaderKeyProperties.m_fresnelEnabled.setValue(theGeneratedKey, theMaterial->isFresnelEnabled());
1314 defaultMaterialShaderKeyProperties.m_baseColorSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isBaseColorSingleChannelEnabled());
1315 defaultMaterialShaderKeyProperties.m_specularSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isSpecularAmountSingleChannelEnabled());
1316 defaultMaterialShaderKeyProperties.m_emissiveSingleChannelEnabled.setValue(theGeneratedKey, theMaterial->isEmissiveSingleChannelEnabled());
1317 defaultMaterialShaderKeyProperties.m_invertOpacityMapValue.setValue(theGeneratedKey, theMaterial->isInvertOpacityMapValue());
1318 defaultMaterialShaderKeyProperties.m_vertexColorsEnabled.setValue(theGeneratedKey, theMaterial->isVertexColorsEnabled());
1319 defaultMaterialShaderKeyProperties.m_vertexColorsMaskEnabled.setValue(theGeneratedKey, theMaterial->isVertexColorsMaskEnabled());
1320 defaultMaterialShaderKeyProperties.m_vertexColorRedMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorRedMask.toInt()));
1321 defaultMaterialShaderKeyProperties.m_vertexColorGreenMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorGreenMask.toInt()));
1322 defaultMaterialShaderKeyProperties.m_vertexColorBlueMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorBlueMask.toInt()));
1323 defaultMaterialShaderKeyProperties.m_vertexColorAlphaMask.setValue(theGeneratedKey, quint16(theMaterial->vertexColorAlphaMask.toInt()));
1324 defaultMaterialShaderKeyProperties.m_clearcoatEnabled.setValue(theGeneratedKey, theMaterial->isClearcoatEnabled());
1325 defaultMaterialShaderKeyProperties.m_sheenEnabled.setValue(theGeneratedKey, theMaterial->isSheenEnabled());
1326 defaultMaterialShaderKeyProperties.m_anisotropyEnabled.setValue(theGeneratedKey, theMaterial->isAnisotropyEnabled());
1327 defaultMaterialShaderKeyProperties.m_iridescenceEnabled.setValue(theGeneratedKey, theMaterial->isIridescenceEnabled());
1328 defaultMaterialShaderKeyProperties.m_dispersionEnabled.setValue(theGeneratedKey, theMaterial->isDispersionEnabled());
1329 defaultMaterialShaderKeyProperties.m_transmissionEnabled.setValue(theGeneratedKey, theMaterial->isTransmissionEnabled());
1330
1331 // Run through the material's images and prepare them for render.
1332 // this may in fact set pickable on the renderable flags if one of the images
1333 // links to a sub presentation or any offscreen rendered object.
1334 QSSGRenderableImage *nextImage = nullptr;
1335#define CHECK_IMAGE_AND_PREPARE(img, imgtype, shadercomponent)
1336 if ((img))
1337 prepareImageForRender(*(img), imgtype, firstImage, nextImage, renderableFlags,
1338 theGeneratedKey, shadercomponent, &inMaterial)
1339
1340 if (theMaterial->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
1341 theMaterial->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial) {
1342 CHECK_IMAGE_AND_PREPARE(theMaterial->colorMap,
1343 QSSGRenderableImage::Type::BaseColor,
1344 QSSGShaderDefaultMaterialKeyProperties::BaseColorMap);
1345 CHECK_IMAGE_AND_PREPARE(theMaterial->occlusionMap,
1346 QSSGRenderableImage::Type::Occlusion,
1347 QSSGShaderDefaultMaterialKeyProperties::OcclusionMap);
1348 CHECK_IMAGE_AND_PREPARE(theMaterial->heightMap,
1349 QSSGRenderableImage::Type::Height,
1350 QSSGShaderDefaultMaterialKeyProperties::HeightMap);
1351 CHECK_IMAGE_AND_PREPARE(theMaterial->clearcoatMap,
1352 QSSGRenderableImage::Type::Clearcoat,
1353 QSSGShaderDefaultMaterialKeyProperties::ClearcoatMap);
1354 CHECK_IMAGE_AND_PREPARE(theMaterial->clearcoatRoughnessMap,
1355 QSSGRenderableImage::Type::ClearcoatRoughness,
1356 QSSGShaderDefaultMaterialKeyProperties::ClearcoatRoughnessMap);
1357 CHECK_IMAGE_AND_PREPARE(theMaterial->clearcoatNormalMap,
1358 QSSGRenderableImage::Type::ClearcoatNormal,
1359 QSSGShaderDefaultMaterialKeyProperties::ClearcoatNormalMap);
1360 CHECK_IMAGE_AND_PREPARE(theMaterial->sheenColorMap,
1361 QSSGRenderableImage::Type::SheenColor,
1362 QSSGShaderDefaultMaterialKeyProperties::SheenColorMap);
1363 CHECK_IMAGE_AND_PREPARE(theMaterial->sheenRoughnessMap,
1364 QSSGRenderableImage::Type::SheenRoughness,
1365 QSSGShaderDefaultMaterialKeyProperties::SheenRoughnessMap);
1366 CHECK_IMAGE_AND_PREPARE(theMaterial->anisotropyMap,
1367 QSSGRenderableImage::Type::Anisotropy,
1368 QSSGShaderDefaultMaterialKeyProperties::AnisotropyMap);
1369 CHECK_IMAGE_AND_PREPARE(theMaterial->iridescenceMap,
1370 QSSGRenderableImage::Type::Iridescence,
1371 QSSGShaderDefaultMaterialKeyProperties::IridescenceMap);
1372 CHECK_IMAGE_AND_PREPARE(theMaterial->iridescenceThicknessMap,
1373 QSSGRenderableImage::Type::IridescenceThickness,
1374 QSSGShaderDefaultMaterialKeyProperties::IridescenceThicknessMap);
1375 CHECK_IMAGE_AND_PREPARE(theMaterial->transmissionMap,
1376 QSSGRenderableImage::Type::Transmission,
1377 QSSGShaderDefaultMaterialKeyProperties::TransmissionMap);
1378 CHECK_IMAGE_AND_PREPARE(theMaterial->thicknessMap,
1379 QSSGRenderableImage::Type::Thickness,
1380 QSSGShaderDefaultMaterialKeyProperties::ThicknessMap);
1381 if (theMaterial->type == QSSGRenderGraphObject::Type::PrincipledMaterial) {
1382 CHECK_IMAGE_AND_PREPARE(theMaterial->metalnessMap,
1383 QSSGRenderableImage::Type::Metalness,
1384 QSSGShaderDefaultMaterialKeyProperties::MetalnessMap);
1385 }
1386 } else {
1387 CHECK_IMAGE_AND_PREPARE(theMaterial->colorMap,
1388 QSSGRenderableImage::Type::Diffuse,
1389 QSSGShaderDefaultMaterialKeyProperties::DiffuseMap);
1390 }
1391 CHECK_IMAGE_AND_PREPARE(theMaterial->emissiveMap, QSSGRenderableImage::Type::Emissive, QSSGShaderDefaultMaterialKeyProperties::EmissiveMap);
1392 CHECK_IMAGE_AND_PREPARE(theMaterial->specularReflection,
1393 QSSGRenderableImage::Type::Specular,
1394 QSSGShaderDefaultMaterialKeyProperties::SpecularMap);
1395 CHECK_IMAGE_AND_PREPARE(theMaterial->roughnessMap,
1396 QSSGRenderableImage::Type::Roughness,
1397 QSSGShaderDefaultMaterialKeyProperties::RoughnessMap);
1398 CHECK_IMAGE_AND_PREPARE(theMaterial->opacityMap, QSSGRenderableImage::Type::Opacity, QSSGShaderDefaultMaterialKeyProperties::OpacityMap);
1399 CHECK_IMAGE_AND_PREPARE(theMaterial->bumpMap, QSSGRenderableImage::Type::Bump, QSSGShaderDefaultMaterialKeyProperties::BumpMap);
1400 CHECK_IMAGE_AND_PREPARE(theMaterial->specularMap,
1401 QSSGRenderableImage::Type::SpecularAmountMap,
1402 QSSGShaderDefaultMaterialKeyProperties::SpecularAmountMap);
1403 CHECK_IMAGE_AND_PREPARE(theMaterial->normalMap, QSSGRenderableImage::Type::Normal, QSSGShaderDefaultMaterialKeyProperties::NormalMap);
1404 CHECK_IMAGE_AND_PREPARE(theMaterial->translucencyMap,
1405 QSSGRenderableImage::Type::Translucency,
1406 QSSGShaderDefaultMaterialKeyProperties::TranslucencyMap);
1407 }
1408#undef CHECK_IMAGE_AND_PREPARE
1409
1410 if (subsetOpacity < QSSGRendererPrivate::minimumRenderOpacity) {
1411 subsetOpacity = 0.0f;
1412 // You can still pick against completely transparent objects(or rather their bounding
1413 // box)
1414 // you just don't render them.
1415 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1416 renderableFlags |= QSSGRenderableObjectFlag::CompletelyTransparent;
1417 }
1418
1419 if (subsetOpacity > 1.f - QSSGRendererPrivate::minimumRenderOpacity)
1420 subsetOpacity = 1.f;
1421 else
1422 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1423
1424 if (inMaterial.isTransmissionEnabled()) {
1425 ioFlags.setRequiresScreenTexture(true);
1426 ioFlags.setRequiresMipmapsForScreenTexture(true);
1427 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1428 }
1429
1430 if (renderableFlags.hasTransparency()) {
1431 if (orderIndependentTransparencyEnabled)
1432 defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.setValue(theGeneratedKey, int(layer.oitMethod));
1433 if (layer.oitMethodDirty)
1434 renderableFlags |= QSSGRenderableObjectFlag::Dirty;
1435 }
1436
1437 retval.firstImage = firstImage;
1438 if (retval.renderableFlags.isDirty())
1439 retval.dirty = true;
1440 if (retval.dirty)
1441 renderer->addMaterialDirtyClear(&inMaterial);
1442 return retval;
1443}
1444
1445QSSGDefaultMaterialPreparationResult QSSGLayerRenderData::prepareCustomMaterialForRender(
1446 QSSGRenderCustomMaterial &inMaterial, QSSGRenderableObjectFlags &inExistingFlags,
1447 float inOpacity, bool alreadyDirty, bool hasAnyLights, bool anyLightHasShadows,
1448 QSSGLayerRenderPreparationResultFlags &ioFlags)
1449{
1450 QSSGDefaultMaterialPreparationResult retval(QSSGShaderDefaultMaterialKey(qHash(features)));
1451 retval.renderableFlags = inExistingFlags;
1452 QSSGRenderableObjectFlags &renderableFlags(retval.renderableFlags);
1453 QSSGShaderDefaultMaterialKey &theGeneratedKey(retval.materialKey);
1454 retval.opacity = inOpacity;
1455 float &subsetOpacity(retval.opacity);
1456
1457 if (subsetOpacity < QSSGRendererPrivate::minimumRenderOpacity) {
1458 subsetOpacity = 0.0f;
1459 // You can still pick against completely transparent objects(or rather their bounding
1460 // box)
1461 // you just don't render them.
1462 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1463 renderableFlags |= QSSGRenderableObjectFlag::CompletelyTransparent;
1464 }
1465
1466 if (subsetOpacity > 1.f - QSSGRendererPrivate::minimumRenderOpacity)
1467 subsetOpacity = 1.f;
1468 else
1469 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1470
1471 defaultMaterialShaderKeyProperties.m_hasLighting.setValue(theGeneratedKey, true);
1472 defaultMaterialShaderKeyProperties.m_hasPunctualLights.setValue(theGeneratedKey, hasAnyLights);
1473 defaultMaterialShaderKeyProperties.m_hasShadows.setValue(theGeneratedKey, anyLightHasShadows);
1474 defaultMaterialShaderKeyProperties.m_hasIbl.setValue(theGeneratedKey, layer.lightProbe != nullptr || layer.skyMaterial != nullptr);
1475 defaultMaterialShaderKeyProperties.m_specularEnabled.setValue(theGeneratedKey, true);
1476
1477 defaultMaterialShaderKeyProperties.m_specularAAEnabled.setValue(theGeneratedKey, layer.specularAAEnabled);
1478
1479 // isDoubleSided
1480 defaultMaterialShaderKeyProperties.m_isDoubleSided.setValue(theGeneratedKey, inMaterial.m_cullMode == QSSGCullFaceMode::Disabled);
1481
1482 // Custom Materials are always Metallic Roughness Workflow
1483 defaultMaterialShaderKeyProperties.m_metallicRoughnessEnabled.setValue(theGeneratedKey, true);
1484
1485 // Does the material override the position output
1486 const bool overridesPosition = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::OverridesPosition);
1487 defaultMaterialShaderKeyProperties.m_overridesPosition.setValue(theGeneratedKey, overridesPosition);
1488
1489 // Optional usage of PROJECTION_MATRIX and/or INVERSE_PROJECTION_MATRIX
1490 const bool usesProjectionMatrix = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ProjectionMatrix);
1491 defaultMaterialShaderKeyProperties.m_usesProjectionMatrix.setValue(theGeneratedKey, usesProjectionMatrix);
1492 const bool usesInvProjectionMatrix = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::InverseProjectionMatrix);
1493 defaultMaterialShaderKeyProperties.m_usesInverseProjectionMatrix.setValue(theGeneratedKey, usesInvProjectionMatrix);
1494
1495 // vertex attribute presence flags
1496 setVertexInputPresence(renderableFlags, theGeneratedKey);
1497
1498 // Without a vertex shader nothing places the vertices, see the default material case.
1499 if (!renderableFlags.hasAttributePosition()
1500 && !inMaterial.m_customShaderPresence.testFlag(QSSGRenderCustomMaterial::CustomShaderPresenceFlag::Vertex)
1501 && warnOnce(OneShotWarning::MissingPosition)) {
1502 warnMissingPosition();
1503 }
1504
1505 // set the flag indicating the need for gl_PointSize
1506 defaultMaterialShaderKeyProperties.m_usesPointsTopology.setValue(theGeneratedKey, renderableFlags.isPointsTopology());
1507
1508 // propagate the flag indicating the presence of a lightmap
1509 defaultMaterialShaderKeyProperties.m_lightmapEnabled.setValue(theGeneratedKey, renderableFlags.rendersWithLightmap());
1510
1511 // debug modes
1512 defaultMaterialShaderKeyProperties.m_debugMode.setValue(theGeneratedKey, int(layer.debugMode));
1513
1514 // fog
1515 defaultMaterialShaderKeyProperties.m_fogEnabled.setValue(theGeneratedKey, layer.fog.enabled);
1516
1517 // multiview
1518 defaultMaterialShaderKeyProperties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
1519 defaultMaterialShaderKeyProperties.m_usesViewIndex.setValue(theGeneratedKey,
1520 inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ViewIndex));
1521
1522 // Knowing whether VAR_COLOR is used becomes relevant when there is no
1523 // custom vertex shader, but VAR_COLOR is present in the custom fragment
1524 // snippet, because that case needs special care.
1525 const bool usesVarColor = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::VarColor);
1526 defaultMaterialShaderKeyProperties.m_usesVarColor.setValue(theGeneratedKey, usesVarColor);
1527
1528 const bool usesClearcoat = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Clearcoat);
1529 defaultMaterialShaderKeyProperties.m_clearcoatEnabled.setValue(theGeneratedKey, usesClearcoat);
1530
1531 const bool usesSheen = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Sheen);
1532 defaultMaterialShaderKeyProperties.m_sheenEnabled.setValue(theGeneratedKey, usesSheen);
1533
1534 const bool usesAnisotropy = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Anisotropy);
1535 defaultMaterialShaderKeyProperties.m_anisotropyEnabled.setValue(theGeneratedKey, usesAnisotropy);
1536
1537 const bool usesIridescence = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Iridescence);
1538 defaultMaterialShaderKeyProperties.m_iridescenceEnabled.setValue(theGeneratedKey, usesIridescence);
1539
1540 const bool usesDispersion = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Dispersion);
1541 defaultMaterialShaderKeyProperties.m_dispersionEnabled.setValue(theGeneratedKey, usesDispersion);
1542
1543 const bool usesClearcoatFresnelScaleBias = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ClearcoatFresnelScaleBias);
1544 defaultMaterialShaderKeyProperties.m_clearcoatFresnelScaleBiasEnabled.setValue(theGeneratedKey, usesClearcoatFresnelScaleBias);
1545
1546 const bool usesFresnelScaleBias = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::FresnelScaleBias);
1547 defaultMaterialShaderKeyProperties.m_fresnelScaleBiasEnabled.setValue(theGeneratedKey, usesFresnelScaleBias);
1548
1549 const bool usesTransmission = inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Transmission);
1550 defaultMaterialShaderKeyProperties.m_transmissionEnabled.setValue(theGeneratedKey, usesTransmission);
1551
1552 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Blending))
1553 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1554
1555 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenTexture)) {
1556 ioFlags.setRequiresScreenTexture(true);
1557 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1558 }
1559
1560 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::ScreenMipTexture)) {
1561 ioFlags.setRequiresScreenTexture(true);
1562 ioFlags.setRequiresMipmapsForScreenTexture(true);
1563 renderableFlags |= QSSGRenderableObjectFlag::RequiresScreenTexture;
1564 }
1565
1566 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::DepthTexture))
1567 ioFlags.setRequiresDepthTexture(true);
1568
1569 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::NormalTexture)) {
1570 ioFlags.setRequiresNormalTexture(true);
1571 renderableFlags |= QSSGRenderableObjectFlag::RequiresNormalTexture;
1572 }
1573
1574 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::AoTexture)) {
1575 ioFlags.setRequiresDepthTexture(true);
1576 ioFlags.setRequiresSsaoPass(true);
1577 }
1578 if (orderIndependentTransparencyEnabled && renderableFlags.hasTransparency())
1579 defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.setValue(theGeneratedKey, int(layer.oitMethod));
1580
1581 retval.firstImage = nullptr;
1582
1583 if (inMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::MotionVectorTexture))
1584 ioFlags.setRequiresMotionVectorPass(true);
1585
1586 if (retval.dirty || alreadyDirty)
1587 renderer->addMaterialDirtyClear(&inMaterial);
1588 return retval;
1589}
1590
1591void QSSGLayerRenderData::setLightmapTexture(const QSSGModelContext &modelContext, QRhiTexture *lightmapTexture)
1592{
1593 lightmapTextures[&modelContext] = lightmapTexture;
1594}
1595
1596QRhiTexture *QSSGLayerRenderData::getLightmapTexture(const QSSGModelContext &modelContext) const
1597{
1598 QRhiTexture *ret = nullptr;
1599 if (modelContext.model.hasLightmap()) {
1600 const auto it = lightmapTextures.constFind(&modelContext);
1601 ret = (it != lightmapTextures.cend()) ? *it : nullptr;
1602 }
1603
1604 return ret;
1605}
1606
1607void QSSGLayerRenderData::setBonemapTexture(const QSSGModelContext &modelContext, QRhiTexture *bonemapTexture)
1608{
1609 bonemapTextures[&modelContext] = bonemapTexture;
1610}
1611
1612QRhiTexture *QSSGLayerRenderData::getBonemapTexture(const QSSGModelContext &modelContext) const
1613{
1614 QRhiTexture *ret = nullptr;
1615 if (modelContext.model.usesBoneTexture()) {
1616 const auto it = bonemapTextures.constFind(&modelContext);
1617 ret = (it != bonemapTextures.cend()) ? *it : nullptr;
1618 }
1619
1620 return ret;
1621}
1622
1623static bool hasCustomBlendMode(const QSSGRenderCustomMaterial &material)
1624{
1625 // Check SrcOver
1626
1627 // srcAlpha is same for all
1628 if (material.m_srcAlphaBlend != QRhiGraphicsPipeline::One)
1629 return true;
1630
1631 // SrcOver srcColor is SrcAlpha
1632 if (material.m_srcBlend != QRhiGraphicsPipeline::SrcAlpha)
1633 return true;
1634
1635 if (material.m_dstBlend == QRhiGraphicsPipeline::OneMinusSrcAlpha
1636 && material.m_dstAlphaBlend == QRhiGraphicsPipeline::OneMinusSrcAlpha)
1637 return false;
1638 return true;
1639}
1640
1641// Whether an instanced subset gets the automatic per-instance level of detail, where each
1642// instance is put in a level by its own size on screen: its distance from the
1643// camera and the largest scale it is drawn with. With an orthographic camera the distance
1644// does not change the size, and the level follows the scale and the magnification of the
1645// camera, as for a single model.
1646//
1647// The instances are drawn grouped by level, so the instance number of the draw call is not the
1648// row in the instance table, which the shaders that read INSTANCE_INDEX get from the rows of
1649// the levels, see prepareAutoLodInstanceIndices().
1650// A model that sets instancingLodFactor keeps the model wide level, which that picks by hand.
1651// A depth sorted table keeps the model wide level too, so that it is drawn in one draw call in
1652// the sorted order. Drawn per level, the order would only hold within each level: the instances
1653// of a level are not all farther than those of the nearer levels, as a larger instance switches
1654// level farther away.
1655// instancingLodMin and instancingLodMax do not turn this off: they limit the instances the
1656// model draws to a range of distances, and the levels are selected among those, see
1657// prepareAutoLodInstancing().
1658static bool usesAutoInstanceLod(const QSSGRenderModel &model,
1659 const QSSGRenderSubset &subset,
1660 float lodThreshold)
1661{
1662 if (lodThreshold <= 0.0f || model.levelOfDetailBias <= 0.0f || subset.lods.isEmpty())
1663 return false;
1664 // One indexed draw is issued per level.
1665 if (!subset.rhi.indexBuffer)
1666 return false;
1667 if (model.instancingLodFactor >= 0.0f)
1668 return false;
1669 if (model.instanceTable && model.instanceTable->isDepthSortingEnabled())
1670 return false;
1671 return true;
1672}
1673
1675 QSSGLayerRenderData &data,
1676 const QSSGRenderGeometry &geometry,
1677 QSSGSubsetRenderable &renderable)
1678{
1679 const auto &indirectDraw = geometry.indirectDraw();
1680 if (!indirectDraw.buffer || indirectDraw.drawCount == 0)
1681 return;
1682
1683 if (!contextInterface.rhiContext()->rhi()->isFeatureSupported(QRhi::DrawIndirect)) {
1684 if (data.warnOnce(QSSGLayerRenderData::OneShotWarning::IndirectDrawUnsupported)) {
1685 qCWarning(lcQuick3DRender, "IndirectShaderGeometry requires indirect draw support, which this "
1686 "graphics API or device does not provide. Nothing is drawn.");
1687 }
1688 return;
1689 }
1690
1691 QRhiBuffer *buffer = contextInterface.bufferManager()->loadBuffer(*indirectDraw.buffer);
1692 if (!buffer)
1693 return;
1694
1695 // A buffer from a render extension is created by the user.
1696 if (!buffer->usage().testFlag(QRhiBuffer::IndirectBuffer)) {
1697 if (data.warnOnce(QSSGLayerRenderData::OneShotWarning::IndirectBufferUsage)) {
1698 qCWarning(lcQuick3DRender, "IndirectShaderGeometry: the buffer was not created with "
1699 "QRhiBuffer::IndirectBuffer usage. Nothing is drawn.");
1700 }
1701 return;
1702 }
1703
1704 // Reading past the end is undefined on the GPU, so catch it here.
1705 const quint64 required = quint64(indirectDraw.offset)
1706 + quint64(indirectDraw.drawCount - 1) * indirectDraw.stride
1707 + sizeof(QRhiIndirectDrawCommand);
1708 if (required > buffer->size()) {
1709 if (data.warnOnce(QSSGLayerRenderData::OneShotWarning::IndirectBufferSize)) {
1710 qCWarning(lcQuick3DRender, "IndirectShaderGeometry: offset, drawCount and stride need %llu bytes, "
1711 "but the buffer has only %u. Nothing is drawn.",
1712 required, buffer->size());
1713 }
1714 return;
1715 }
1716
1717 renderable.indirectBuffer = buffer;
1718 renderable.indirectOffset = indirectDraw.offset;
1719 renderable.indirectDrawCount = indirectDraw.drawCount;
1720 renderable.indirectStride = indirectDraw.stride;
1721}
1722
1723// inModel is const to emphasize the fact that its members cannot be written
1724// here: in case there is a scene shared between multiple View3Ds in different
1725// QQuickWindows, each window may run this in their own render thread, while
1726// inModel is the same.
1727bool QSSGLayerRenderData::prepareModelsForRender(QSSGRenderContextInterface &contextInterface,
1728 const RenderableNodeEntries &renderableModels,
1729 QSSGLayerRenderPreparationResultFlags &ioFlags,
1730 const QSSGRenderCameraList &allCameras,
1731 const QSSGRenderCameraDataList &allCameraData,
1732 TModelContextPtrList &modelContexts,
1733 QSSGRenderableObjectList &opaqueObjects,
1734 QSSGRenderableObjectList &transparentObjects,
1735 QSSGRenderableObjectList &screenTextureObjects,
1736 float lodThreshold)
1737{
1738 const auto &rhiCtx = contextInterface.rhiContext();
1739 const auto &bufferManager = contextInterface.bufferManager();
1740
1741 const auto &debugDrawSystem = contextInterface.debugDrawSystem();
1742 if (debugDrawSystem && layer.drawLevelsOfDetail)
1743 debugDrawSystem->setEnabled(true);
1744 const bool maybeDebugDraw = debugDrawSystem && debugDrawSystem->isEnabled();
1745 const bool debugDrawMeshLod = maybeDebugDraw
1746 && (layer.drawLevelsOfDetail || debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod));
1747
1748 bool wasDirty = false;
1749
1750 // The automatic per-instance LOD keeps its data per layer, for the camera the layer is
1751 // rendered with, see prepareAutoLodInstancing(). The preparation context of an extension
1752 // with a camera of its own gets the model wide level instead.
1753 const bool isLayerCamera = !allCameras.isEmpty() && !renderedCameras.isEmpty()
1754 && allCameras.first() == renderedCameras.first();
1755
1756 for (const QSSGRenderableNodeEntry &renderable : renderableModels) {
1757 if ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::Disabled) != 0)
1758 continue;
1759
1760 const QSSGRenderModel &model = *static_cast<QSSGRenderModel *>(renderable.node);
1761 const auto &lights = renderable.lights;
1762 QSSGRenderMesh *theMesh = modelData->getMesh(model);
1763 if (!theMesh)
1764 continue;
1765
1766 const bool altGlobalTransform = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::GlobalTransform) != 0);
1767 const auto &globalTransform = altGlobalTransform ? renderable.extOverrides.globalTransform : getGlobalTransform(model);
1768 QMatrix3x3 normalMatrix { Qt::Uninitialized };
1769 QSSGLayerRenderData::ModelViewProjections mvps;
1770 if (altGlobalTransform) {
1771 QSSGRenderNode::calculateNormalMatrix(globalTransform, normalMatrix);
1772 size_t mvpCount = 0;
1773 for (const auto &cameraData : allCameraData) {
1774 QSSGRenderNode::calculateMVPAndNormalMatrix(globalTransform, cameraData.viewProjection, mvps[mvpCount++], normalMatrix);
1775 }
1776 } else {
1777 if (model.usesBoneTexture()) {
1778 // FIXME:
1779 // For skinning, node's global transformation will be ignored and
1780 // an identity matrix will be used for the normalMatrix
1781 size_t mvpCount = 0;
1782 for (const QSSGRenderCameraData &cameraData : allCameraData) {
1783 mvps[mvpCount++] = cameraData.viewProjection;
1784 normalMatrix = QMatrix3x3();
1785 }
1786 } else {
1787 normalMatrix = getNormalMatrix(model);
1788 mvps = getModelMvps(model);
1789 }
1790 }
1791 const bool altModelOpacity = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::GlobalOpacity) != 0);
1792 const float modelGlobalOpacity = altModelOpacity ? renderable.extOverrides.globalOpacity : getGlobalOpacity(model);
1793 QSSGModelContext &theModelContext = *RENDER_FRAME_NEW<QSSGModelContext>(contextInterface, model, globalTransform, normalMatrix, mvps);
1794 modelContexts.push_back(&theModelContext);
1795
1796 if (model.usesBufferlessInstancing()) {
1797 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing) && warnOnce(OneShotWarning::BufferlessInstancingUnsupported)) {
1798 qCWarning(lcQuick3DRender, "ShaderInstancing requires instancing support, which this "
1799 "graphics API or device does not provide.");
1800 }
1801 if ((model.instancingLodMin >= 0 || model.instancingLodMax >= 0) && warnOnce(OneShotWarning::BufferlessInstancingLod)) {
1802 qCWarning(lcQuick3DRender, "Model.instancingLodMin/instancingLodMax have no effect with "
1803 "ShaderInstancing: instance level of detail needs per-instance "
1804 "data to read. Cull in the vertex shader instead.");
1805 }
1806 }
1807 // We might over-allocate here, as the material list technically can contain an invalid (nullptr) material.
1808 // We'll fix that by adjusting the size at the end for now...
1809 const auto &meshSubsets = theMesh->subsets;
1810 const auto meshSubsetCount = meshSubsets.size();
1811 theModelContext.subsets = RENDER_FRAME_NEW_BUFFER<QSSGSubsetRenderable>(contextInterface, meshSubsetCount);
1812
1813 // Prepare boneTexture for skinning
1814 if (model.skin) {
1815 auto boneTexture = bufferManager->loadSkinmap(model.skin);
1816 setBonemapTexture(theModelContext, boneTexture.m_texture);
1817 } else if (model.skeleton) {
1818 auto boneTexture = bufferManager->loadSkinmap(&(model.skeleton->boneTexData));
1819 setBonemapTexture(theModelContext, boneTexture.m_texture);
1820 }
1821
1822 // many renderableFlags are the same for all the subsets
1823 QSSGRenderableObjectFlags renderableFlagsForModel;
1824
1825 bool usesBlendParticles = particlesEnabled && theModelContext.model.particleBuffer != nullptr
1826 && model.particleBuffer->particleCount();
1827
1828 if (meshSubsetCount > 0) {
1829 const QSSGRenderSubset &theSubset = meshSubsets.at(0);
1830
1831 renderableFlagsForModel.setCastsShadows(model.castsShadows);
1832 renderableFlagsForModel.setReceivesShadows(model.receivesShadows);
1833 renderableFlagsForModel.setReceivesReflections(model.receivesReflections);
1834 renderableFlagsForModel.setCastsReflections(model.castsReflections);
1835
1836 renderableFlagsForModel.setUsedInBakedLighting(model.usedInBakedLighting);
1837 if (model.hasLightmap()) {
1838 QSSGRenderImageTexture lmImageTexture = bufferManager->loadLightmap(model);
1839 if (lmImageTexture.m_texture) {
1840 renderableFlagsForModel.setRendersWithLightmap(true);
1841 setLightmapTexture(theModelContext, lmImageTexture.m_texture);
1842 }
1843 }
1844
1845 // TODO: This should be a oneshot thing, move the flags over!
1846 // With the RHI we need to be able to tell the material shader
1847 // generator to not generate vertex input attributes that are not
1848 // provided by the mesh. (because unlike OpenGL, other graphics
1849 // APIs may treat unbound vertex inputs as a fatal error)
1850 bool hasJoint = false;
1851 bool hasWeight = false;
1852 bool hasMorphTarget = theSubset.rhi.targetsTexture != nullptr;
1853 for (const QSSGRhiInputAssemblerState::InputSemantic &sem : std::as_const(theSubset.rhi.ia.inputs)) {
1854 if (sem == QSSGRhiInputAssemblerState::PositionSemantic) {
1855 renderableFlagsForModel.setHasAttributePosition(true);
1856 } else if (sem == QSSGRhiInputAssemblerState::NormalSemantic) {
1857 renderableFlagsForModel.setHasAttributeNormal(true);
1858 } else if (sem == QSSGRhiInputAssemblerState::TexCoord0Semantic) {
1859 renderableFlagsForModel.setHasAttributeTexCoord0(true);
1860 } else if (sem == QSSGRhiInputAssemblerState::TexCoord1Semantic) {
1861 renderableFlagsForModel.setHasAttributeTexCoord1(true);
1862 } else if (sem == QSSGRhiInputAssemblerState::TexCoordLightmapSemantic) {
1863 renderableFlagsForModel.setHasAttributeTexCoordLightmap(true);
1864 } else if (sem == QSSGRhiInputAssemblerState::TangentSemantic) {
1865 renderableFlagsForModel.setHasAttributeTangent(true);
1866 } else if (sem == QSSGRhiInputAssemblerState::BinormalSemantic) {
1867 renderableFlagsForModel.setHasAttributeBinormal(true);
1868 } else if (sem == QSSGRhiInputAssemblerState::ColorSemantic) {
1869 renderableFlagsForModel.setHasAttributeColor(true);
1870 // For skinning, we will set the HasAttribute only
1871 // if the mesh has both joint and weight
1872 } else if (sem == QSSGRhiInputAssemblerState::JointSemantic) {
1873 hasJoint = true;
1874 } else if (sem == QSSGRhiInputAssemblerState::WeightSemantic) {
1875 hasWeight = true;
1876 }
1877 }
1878 renderableFlagsForModel.setHasAttributeJointAndWeight(hasJoint && hasWeight);
1879 renderableFlagsForModel.setHasAttributeMorphTarget(hasMorphTarget);
1880
1881 // Deferred until the attribute scan above has run:
1882 // motionvector.vert is hand-written and declares attr_pos at
1883 // location 0, so a model without one would read an unbound input.
1884 renderableFlagsForModel.setMotionVectorParticipant(
1885 model.motionVectorEnabled && !usesBlendParticles
1886 && renderableFlagsForModel.hasAttributePosition());
1887 }
1888
1889 QSSGRenderableObjectList bakedLightingObjects;
1890 const bool anyLightHasShadows = std::find_if(lights.begin(),
1891 lights.end(),
1892 [](const QSSGShaderLight &light) { return light.shadows; })
1893 != lights.end();
1894 const bool hasAnyLights = !lights.isEmpty();
1895 QSSGRenderLight::SoftShadowQuality maxSoftShadowQuality = QSSGRenderLight::SoftShadowQuality::Hard;
1896 if (anyLightHasShadows) {
1897 // Iterate the light list to find the maximum shadow quality of lights that cast shadows
1898 for (const QSSGShaderLight &light : lights) {
1899 if (light.shadows && light.light->m_softShadowQuality > maxSoftShadowQuality)
1900 maxSoftShadowQuality = light.light->m_softShadowQuality;
1901 }
1902 }
1903
1904
1905 // Subset(s)
1906 auto &renderableSubsets = theModelContext.subsets;
1907 const bool hasMaterialOverrides = ((renderable.overridden & QSSGRenderableNodeEntry::Overridden::Materials) != 0);
1908 const auto &materials = hasMaterialOverrides ? renderable.extOverrides.materials : modelData->getMaterials(model);
1909 const auto materialCount = materials.size();
1910 QSSGRenderGraphObject *lastMaterial = !materials.isEmpty() ? materials.last() : nullptr;
1911 int idx = 0, subsetIdx = 0;
1912 for (; idx < meshSubsetCount; ++idx) {
1913 // If the materials list < size of subsets, then use the last material for the rest
1914 QSSGRenderGraphObject *theMaterialObject = (idx >= materialCount) ? lastMaterial : materials[idx];
1915 if (!theMaterialObject)
1916 continue;
1917
1918 const QSSGRenderSubset &theSubset = meshSubsets.at(idx);
1919 QSSGRenderableObjectFlags renderableFlags = renderableFlagsForModel;
1920 float subsetOpacity = modelGlobalOpacity;
1921
1922 renderableFlags.setPointsTopology(theSubset.rhi.ia.topology == QRhiGraphicsPipeline::Points);
1923 QSSGRenderableObject *theRenderableObject = &renderableSubsets[subsetIdx++];
1924
1925 const bool usesInstanceBuffer = theModelContext.model.usesInstanceBuffer()
1926 && rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing);
1927 const bool usesBufferlessInstancing = theModelContext.model.usesBufferlessInstancing()
1928 && rhiCtx->rhi()->isFeatureSupported(QRhi::Instancing);
1929 // With bufferless instancing, transparency comes from the CustomMaterial, as without instancing
1930 if (usesInstanceBuffer && theModelContext.model.instanceTable->hasTransparency())
1931 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1932 if (theModelContext.model.hasTransparency)
1933 renderableFlags |= QSSGRenderableObjectFlag::HasTransparency;
1934
1935 // Level Of Detail
1936 quint32 subsetLevelOfDetail = 0;
1937 // Automatic per-instance LOD: subsetLevelOfDetail is not used for these, the draw
1938 // call is made per level, see prepareAutoLodInstancing().
1939 const bool autoInstanceLod = usesInstanceBuffer && isLayerCamera
1940 && usesAutoInstanceLod(model, theSubset, lodThreshold);
1941 if (!theSubset.lods.isEmpty() && lodThreshold > 0.0f) {
1942 // Accounts for FOV
1943 float lodDistanceMultiplier = camerasView[0]->getLevelOfDetailMultiplier();
1944 float distanceThreshold = 0.0f;
1945 const auto scale = QSSGUtils::mat44::getScale(globalTransform);
1946 float modelScale = qMax(scale.x(), qMax(scale.y(), scale.z()));
1947 QSSGBounds3 transformedBounds = theSubset.bounds;
1948 transformedBounds.transform(globalTransform);
1949 if (camerasView[0]->type != QSSGRenderGraphObject::Type::OrthographicCamera) {
1950 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod))
1951 debugDrawSystem->drawBounds(transformedBounds, QColor(Qt::red));
1952 const QMatrix4x4 cameraGlobalTranform = getGlobalTransform(*camerasView[0]);
1953 const QVector3D cameraNormal = QSSGRenderNode::getScalingCorrectDirection(cameraGlobalTranform);
1954 const QVector3D cameraPosition = QSSGRenderNode::getGlobalPos(cameraGlobalTranform);
1955 const QSSGPlane cameraPlane = QSSGPlane(cameraPosition, cameraNormal);
1956 const QVector3D lodSupportMin = transformedBounds.getSupport(-cameraNormal);
1957 const QVector3D lodSupportMax = transformedBounds.getSupport(cameraNormal);
1958 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLod))
1959 debugDrawSystem->drawPoint(lodSupportMin, QColor("orange"));
1960
1961 const float distanceMin = cameraPlane.distance(lodSupportMin);
1962 const float distanceMax = cameraPlane.distance(lodSupportMax);
1963
1964 if (distanceMin * distanceMax < 0.0)
1965 distanceThreshold = 0.0;
1966 else if (distanceMin >= 0.0)
1967 distanceThreshold = distanceMin;
1968 else if (distanceMax <= 0.0)
1969 distanceThreshold = -distanceMax;
1970
1971 } else {
1972 // Orthographic Projection
1973 distanceThreshold = 1.0;
1974 }
1975
1976 int currentLod = -1;
1977 if (model.levelOfDetailBias > 0.0f) {
1978 const int lodsCount = theSubset.lods.size();
1979 if (model.instanceTable) {
1980 // Without automatic per-instance LOD (set up below) the level is the same
1981 // for all instances and given by the instancingLodFactor. lods only holds
1982 // the simplified levels, so map the factor over lodsCount + 1 levels:
1983 // 0 selects the original mesh (currentLod == -1), 1 the coarsest level.
1984 if (!autoInstanceLod)
1985 currentLod = qRound(lodsCount * qBound(0.f, model.instancingLodFactor, 1.f)) - 1;
1986 } else {
1987 const float threshold = distanceThreshold * lodDistanceMultiplier;
1988 const float modelBias = 1 / model.levelOfDetailBias;
1989 for (qsizetype i = 0; i < lodsCount; ++i) {
1990 float subsetDistance = theSubset.lods[i].distance * modelScale * modelBias;
1991 float screenSize = subsetDistance / threshold;
1992 if (screenSize > lodThreshold)
1993 break;
1994 currentLod = i;
1995 }
1996 }
1997 }
1998 Q_ASSERT(currentLod >= -1);
1999 subsetLevelOfDetail = currentLod + 1;
2000 // The box would only cover the base mesh at the model transform, not the instances.
2001 if (debugDrawMeshLod && !autoInstanceLod && !model.instanceTable)
2002 debugDrawSystem->drawBounds(transformedBounds, QSSGDebugDrawSystem::levelOfDetailColor(subsetLevelOfDetail));
2003 }
2004
2005 QVector3D theModelCenter(theSubset.bounds.center());
2006 theModelCenter = QSSGUtils::mat44::transform(globalTransform, theModelCenter);
2007 if (maybeDebugDraw && debugDrawSystem->isEnabled(QSSGDebugDrawSystem::Mode::MeshLodNormal)) {
2008 const QMatrix4x4 allCamera0GlobalTransform = getGlobalTransform(*allCameras[0]);
2009 debugDrawSystem->debugNormals(*bufferManager, theModelContext, theSubset, subsetLevelOfDetail, (theModelCenter - QSSGRenderNode::getGlobalPos(allCamera0GlobalTransform)).length() * 0.01);
2010 }
2011
2012 auto checkF32TypeIndex = [&rhiCtx](QRhiVertexInputAttribute::Format f) {
2013 if ((f == QRhiVertexInputAttribute::Format::Float4)
2014 || (f == QRhiVertexInputAttribute::Format::Float3)
2015 || (f == QRhiVertexInputAttribute::Format::Float2)
2016 || (f == QRhiVertexInputAttribute::Format::Float)) {
2017 return true;
2018 }
2019 if (!rhiCtx->rhi()->isFeatureSupported(QRhi::IntAttributes))
2020 qWarning() << "WARN: Model has non-integer type indices for skinning but current RHI backend doesn't support it!";
2021 return false;
2022 };
2023
2024 if (theMaterialObject->type == QSSGRenderGraphObject::Type::DefaultMaterial ||
2025 theMaterialObject->type == QSSGRenderGraphObject::Type::PrincipledMaterial ||
2026 theMaterialObject->type == QSSGRenderGraphObject::Type::SpecularGlossyMaterial) {
2027 QSSGRenderDefaultMaterial &theMaterial(static_cast<QSSGRenderDefaultMaterial &>(*theMaterialObject));
2028 QSSGDefaultMaterialPreparationResult theMaterialPrepResult(prepareDefaultMaterialForRender(theMaterial, renderableFlags, subsetOpacity, hasAnyLights, anyLightHasShadows, ioFlags));
2029 QSSGShaderDefaultMaterialKey &theGeneratedKey(theMaterialPrepResult.materialKey);
2030 subsetOpacity = theMaterialPrepResult.opacity;
2031 QSSGRenderableImage *firstImage(theMaterialPrepResult.firstImage);
2032 wasDirty |= theMaterialPrepResult.dirty;
2033 renderableFlags = theMaterialPrepResult.renderableFlags;
2034 if (renderableFlags.hasTransparency())
2035 ioFlags.setHasCustomBlendMode(theMaterial.blendMode != QSSGRenderDefaultMaterial::MaterialBlendMode::SourceOver);
2036
2037 // Blend particles
2038 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey, usesBlendParticles);
2039
2040 if (defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.getValue(theGeneratedKey) == int(QSSGRenderLayer::OITMethod::LinkedList))
2041 defaultMaterialShaderKeyProperties.m_oitMSAA.setValue(theGeneratedKey, rhiCtx->mainPassSampleCount() > 1);
2042
2043 // Skin
2044 const auto boneCount = model.skin ? model.skin->boneCount :
2045 model.skeleton ? model.skeleton->boneCount : 0;
2046 defaultMaterialShaderKeyProperties.m_boneCount.setValue(theGeneratedKey, boneCount);
2047 if (auto idJoint = theSubset.rhi.ia.inputs.indexOf(QSSGRhiInputAssemblerState::JointSemantic); idJoint != -1) {
2048 const auto attr = theSubset.rhi.ia.inputLayout.attributeAt(idJoint);
2049 defaultMaterialShaderKeyProperties.m_usesFloatJointIndices.setValue(theGeneratedKey, checkF32TypeIndex(attr->format()));
2050 }
2051
2052 // SoftShadow quality
2053 defaultMaterialShaderKeyProperties.m_shadowSoftness.setShadowSoftness(theGeneratedKey, maxSoftShadowQuality);
2054
2055 // Instancing
2056 defaultMaterialShaderKeyProperties.m_usesInstanceBuffer.setValue(theGeneratedKey, usesInstanceBuffer);
2057 defaultMaterialShaderKeyProperties.m_usesBufferlessInstancing.setValue(theGeneratedKey, usesBufferlessInstancing);
2058 // Morphing
2059 defaultMaterialShaderKeyProperties.m_targetCount.setValue(theGeneratedKey,
2060 theSubset.rhi.ia.targetCount);
2061 defaultMaterialShaderKeyProperties.m_targetPositionOffset.setValue(theGeneratedKey,
2062 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::PositionSemantic]);
2063 defaultMaterialShaderKeyProperties.m_targetNormalOffset.setValue(theGeneratedKey,
2064 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::NormalSemantic]);
2065 defaultMaterialShaderKeyProperties.m_targetTangentOffset.setValue(theGeneratedKey,
2066 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TangentSemantic]);
2067 defaultMaterialShaderKeyProperties.m_targetBinormalOffset.setValue(theGeneratedKey,
2068 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::BinormalSemantic]);
2069 defaultMaterialShaderKeyProperties.m_targetTexCoord0Offset.setValue(theGeneratedKey,
2070 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord0Semantic]);
2071 defaultMaterialShaderKeyProperties.m_targetTexCoord1Offset.setValue(theGeneratedKey,
2072 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord1Semantic]);
2073 defaultMaterialShaderKeyProperties.m_targetColorOffset.setValue(theGeneratedKey,
2074 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::ColorSemantic]);
2075
2076 new (theRenderableObject) QSSGSubsetRenderable(QSSGSubsetRenderable::Type::DefaultMaterialMeshSubset,
2077 renderableFlags,
2078 theModelCenter,
2079 renderer,
2080 theSubset,
2081 theModelContext,
2082 subsetOpacity,
2083 subsetLevelOfDetail,
2084 theMaterial,
2085 firstImage,
2086 theGeneratedKey,
2087 lights,
2088 anyLightHasShadows);
2089 wasDirty = wasDirty || renderableFlags.isDirty();
2090 } else if (theMaterialObject->type == QSSGRenderGraphObject::Type::CustomMaterial) {
2091 QSSGRenderCustomMaterial &theMaterial(static_cast<QSSGRenderCustomMaterial &>(*theMaterialObject));
2092
2093 const auto &theMaterialSystem(contextInterface.customMaterialSystem());
2094 wasDirty |= theMaterialSystem->prepareForRender(theModelContext.model, theSubset, theMaterial);
2095
2096 if (theMaterial.m_renderFlags.testFlag(QSSGRenderCustomMaterial::RenderFlag::Blending))
2097 ioFlags.setHasCustomBlendMode(!hasCustomBlendMode(theMaterial));
2098
2099 QSSGDefaultMaterialPreparationResult theMaterialPrepResult(
2100 prepareCustomMaterialForRender(theMaterial, renderableFlags, subsetOpacity, wasDirty,
2101 hasAnyLights, anyLightHasShadows, ioFlags));
2102 QSSGShaderDefaultMaterialKey &theGeneratedKey(theMaterialPrepResult.materialKey);
2103 subsetOpacity = theMaterialPrepResult.opacity;
2104 QSSGRenderableImage *firstImage(theMaterialPrepResult.firstImage);
2105 renderableFlags = theMaterialPrepResult.renderableFlags;
2106
2107 if (model.particleBuffer && model.particleBuffer->particleCount())
2108 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey, true);
2109 else
2110 defaultMaterialShaderKeyProperties.m_blendParticles.setValue(theGeneratedKey, false);
2111
2112 if (defaultMaterialShaderKeyProperties.m_orderIndependentTransparency.getValue(theGeneratedKey) == int(QSSGRenderLayer::OITMethod::LinkedList))
2113 defaultMaterialShaderKeyProperties.m_oitMSAA.setValue(theGeneratedKey, rhiCtx->mainPassSampleCount() > 1);
2114
2115 // SoftShadow quality
2116 defaultMaterialShaderKeyProperties.m_shadowSoftness.setShadowSoftness(theGeneratedKey, maxSoftShadowQuality);
2117
2118 // Skin
2119 const auto boneCount = model.skin ? model.skin->boneCount :
2120 model.skeleton ? model.skeleton->boneCount : 0;
2121 defaultMaterialShaderKeyProperties.m_boneCount.setValue(theGeneratedKey, boneCount);
2122 if (auto idJoint = theSubset.rhi.ia.inputs.indexOf(QSSGRhiInputAssemblerState::JointSemantic); idJoint != -1) {
2123 const auto attr = theSubset.rhi.ia.inputLayout.attributeAt(idJoint);
2124 defaultMaterialShaderKeyProperties.m_usesFloatJointIndices.setValue(theGeneratedKey, checkF32TypeIndex(attr->format()));
2125 }
2126
2127 // Instancing
2128 defaultMaterialShaderKeyProperties.m_usesInstanceBuffer.setValue(theGeneratedKey, usesInstanceBuffer);
2129 defaultMaterialShaderKeyProperties.m_usesBufferlessInstancing.setValue(theGeneratedKey, usesBufferlessInstancing);
2130 // Morphing
2131 defaultMaterialShaderKeyProperties.m_targetCount.setValue(theGeneratedKey,
2132 theSubset.rhi.ia.targetCount);
2133 defaultMaterialShaderKeyProperties.m_targetPositionOffset.setValue(theGeneratedKey,
2134 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::PositionSemantic]);
2135 defaultMaterialShaderKeyProperties.m_targetNormalOffset.setValue(theGeneratedKey,
2136 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::NormalSemantic]);
2137 defaultMaterialShaderKeyProperties.m_targetTangentOffset.setValue(theGeneratedKey,
2138 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TangentSemantic]);
2139 defaultMaterialShaderKeyProperties.m_targetBinormalOffset.setValue(theGeneratedKey,
2140 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::BinormalSemantic]);
2141 defaultMaterialShaderKeyProperties.m_targetTexCoord0Offset.setValue(theGeneratedKey,
2142 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord0Semantic]);
2143 defaultMaterialShaderKeyProperties.m_targetTexCoord1Offset.setValue(theGeneratedKey,
2144 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::TexCoord1Semantic]);
2145 defaultMaterialShaderKeyProperties.m_targetColorOffset.setValue(theGeneratedKey,
2146 theSubset.rhi.ia.targetOffsets[QSSGRhiInputAssemblerState::ColorSemantic]);
2147
2148 if (theMaterial.m_iblProbe)
2149 theMaterial.m_iblProbe->clearDirty();
2150
2151 new (theRenderableObject) QSSGSubsetRenderable(QSSGSubsetRenderable::Type::CustomMaterialMeshSubset,
2152 renderableFlags,
2153 theModelCenter,
2154 renderer,
2155 theSubset,
2156 theModelContext,
2157 subsetOpacity,
2158 subsetLevelOfDetail,
2159 theMaterial,
2160 firstImage,
2161 theGeneratedKey,
2162 lights,
2163 anyLightHasShadows);
2164 }
2165 if (theRenderableObject) { // NOTE: Should just go in with the ctor args
2166 theRenderableObject->camdistSq = getCameraDistanceSq(*theRenderableObject, allCameraData[0]);
2167
2168 // Set up automatic per-instance LOD, see usesAutoInstanceLod().
2169 if (autoInstanceLod) {
2170 auto *sr = static_cast<QSSGSubsetRenderable *>(theRenderableObject);
2171 // The camera the levels are selected for, see isLayerCamera.
2172 const float lodDistMult = allCameras.first()->getLevelOfDetailMultiplier();
2173 sr->usesAutoLod = true;
2174 sr->autoLodTint = layer.drawLevelsOfDetail;
2175 sr->autoLodLevelCount = qMin(int(theSubset.lods.size()) + 1,
2176 QSSGSubsetRenderable::MaxAutoLodLevels);
2177 sr->autoLodThresholdFactor = 1.0f / (model.levelOfDetailBias * lodDistMult * lodThreshold);
2178 // Used in this frame even when the model is culled later, which keeps the
2179 // data when the model is out of view, see releaseUnusedAutoLodData().
2180 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(contextInterface.rhiContext().get());
2181 rhiCtxD->instanceBufferData(&model).subsetLodData[{ &theSubset, &layer }].lastUsedFrame = renderer->frameCount();
2182 }
2183
2184 // IndirectShaderGeometry: the draw arguments are read from a GPU buffer.
2185 // Leaving indirectBuffer null skips the draw.
2186 if (model.geometry && model.geometry->indirectDraw().enabled)
2187 prepareIndirectDraw(contextInterface, *this, *model.geometry,
2188 *static_cast<QSSGSubsetRenderable *>(theRenderableObject));
2189 }
2190 }
2191
2192 // If the indices don't match then something's off and we need to adjust the subset renderable list size.
2193 if (Q_UNLIKELY(idx != subsetIdx))
2194 renderableSubsets.mSize = subsetIdx; // subsetIdx == next_subsetIdx == size
2195
2196 for (auto &ro : renderableSubsets) {
2197 const auto depthMode = ro.depthWriteMode;
2198 hasDepthWriteObjects |= (depthMode == QSSGDepthDrawMode::Always || depthMode == QSSGDepthDrawMode::OpaqueOnly);
2199 enum ObjectType : quint8 { ScreenTexture, Transparent, Opaque };
2200 static constexpr DepthPrepassObject ppState[][2] = { {DepthPrepassObject::None, DepthPrepassObject::ScreenTexture},
2201 {DepthPrepassObject::None, DepthPrepassObject::Transparent},
2202 {DepthPrepassObject::None, DepthPrepassObject::Opaque} };
2203
2204 if (ro.renderableFlags.requiresScreenTexture()) {
2205 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::ScreenTexture][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2206 screenTextureObjects.push_back({&ro, ro.camdistSq, model.tag});
2207 } else if (ro.renderableFlags.hasTransparency()) {
2208 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::Transparent][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2209 transparentObjects.push_back({&ro, ro.camdistSq, model.tag});
2210 } else {
2211 depthPrepassObjectsState |= DepthPrepassObjectStateT(ppState[ObjectType::Opaque][size_t(depthMode == QSSGDepthDrawMode::OpaquePrePass)]);
2212 opaqueObjects.push_back({&ro, ro.camdistSq, model.tag});
2213 }
2214
2215 if (ro.renderableFlags.usedInBakedLighting())
2216 bakedLightingObjects.push_back({&ro, ro.camdistSq, model.tag});
2217 }
2218
2219 // A ShaderGeometry has no vertex data to unwrap and bake
2220 if (!bakedLightingObjects.isEmpty() && model.geometry
2221 && model.geometry->meshData().isVertexCountOnly()) {
2222 if (warnOnce(OneShotWarning::BakedLightingWithoutVertexData))
2223 qCWarning(lcQuick3DRender, "Models without vertex data (ShaderGeometry/IndirectShaderGeometry) cannot be used with baked lighting.");
2224 bakedLightingObjects.clear();
2225 }
2226
2227 if (!bakedLightingObjects.isEmpty())
2228 bakedLightingModels.push_back(QSSGBakedLightingModel(&model, bakedLightingObjects));
2229 }
2230
2231 return wasDirty;
2232}
2233
2234bool QSSGLayerRenderData::prepareParticlesForRender(const RenderableNodeEntries &renderableParticles, const QSSGRenderCameraData &cameraData, QSSGLayerRenderPreparationResultFlags &ioFlags)
2235{
2236 QSSG_ASSERT(particlesEnabled, return false);
2237
2238 QSSGRenderContextInterface &contextInterface = *renderer->contextInterface();
2239
2240 bool dirty = false;
2241
2242 //
2243 auto &opaqueObjects = opaqueObjectStore[0];
2244 auto &transparentObjects = transparentObjectStore[0];
2245 auto &screenTextureObjects = screenTextureObjectStore[0];
2246
2247 for (auto &renderable : renderableParticles) {
2248 QSSGShaderParticleMaterialKeyProperties &properties = particleMaterialShaderKeyProperties;
2249
2250 QSSGRenderParticles &particles = *static_cast<QSSGRenderParticles *>(renderable.node);
2251 QSSGShaderParticleMaterialKey &theGeneratedKey(particles.materialKey);
2252 const auto &lights = renderable.lights;
2253
2254 QSSGRenderableObjectFlags renderableFlags;
2255 renderableFlags.setCastsShadows(false);
2256 renderableFlags.setReceivesShadows(false);
2257 renderableFlags.setHasAttributePosition(true);
2258 renderableFlags.setHasAttributeNormal(true);
2259 renderableFlags.setHasAttributeTexCoord0(true);
2260 renderableFlags.setHasAttributeColor(true);
2261 renderableFlags.setHasTransparency(particles.m_hasTransparency);
2262 renderableFlags.setCastsReflections(particles.m_castsReflections);
2263 if (particles.m_hasTransparency && particles.m_blendMode != QSSGRenderParticles::BlendMode::SourceOver)
2264 ioFlags.setHasCustomBlendMode(true);
2265
2266 properties.m_isLineParticle.setValue(theGeneratedKey, particles.m_featureLevel >= QSSGRenderParticles::FeatureLevel::Line);
2267 const bool animated = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimated
2268 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Animated
2269 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::AnimatedVLight
2270 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimatedVLight;
2271 const bool mapped = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMapped
2272 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::Mapped
2273 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::MappedVLight
2274 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMappedVLight;
2275 const bool lit = particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineVLight
2276 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::AnimatedVLight
2277 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::MappedVLight
2278 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineMappedVLight
2279 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::LineAnimatedVLight
2280 || particles.m_featureLevel == QSSGRenderParticles::FeatureLevel::SimpleVLight;
2281 properties.m_isAnimated.setValue(theGeneratedKey, animated);
2282 properties.m_isMapped.setValue(theGeneratedKey, mapped);
2283 properties.m_hasLighting.setValue(theGeneratedKey, lit);
2284 properties.m_viewCount.setValue(theGeneratedKey, layer.viewCount);
2285 if (renderableFlags.hasTransparency() && orderIndependentTransparencyEnabled) {
2286 properties.m_orderIndependentTransparency.setValue(theGeneratedKey, int(layer.oitMethod));
2287 if (layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList)
2288 properties.m_oitMSAA.setValue(theGeneratedKey, contextInterface.rhiContext()->mainPassSampleCount() > 1);
2289 } else {
2290 properties.m_orderIndependentTransparency.setValue(theGeneratedKey, int(0));
2291 }
2292
2293 float opacity = getGlobalOpacity(particles);
2294 const QMatrix4x4 globalTransform = getGlobalTransform(particles);
2295 QVector3D center(particles.m_particleBuffer.bounds().center());
2296 center = QSSGUtils::mat44::transform(globalTransform, center);
2297
2298 QSSGRenderableImage *firstImage = nullptr;
2299 if (particles.m_sprite) {
2300 const auto &bufferManager = contextInterface.bufferManager();
2301
2302 if (particles.m_sprite->clearDirty())
2303 dirty = true;
2304
2305 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(particles.m_sprite);
2306 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, QSSGRenderableImage::Type::Diffuse, *particles.m_sprite, texture);
2307 firstImage = theImage;
2308 properties.m_isSpriteLinear.setValue(theGeneratedKey, texture.m_flags.isLinear());
2309 }
2310
2311 QSSGRenderableImage *colorTable = nullptr;
2312 if (particles.m_colorTable) {
2313 const auto &bufferManager = contextInterface.bufferManager();
2314
2315 if (particles.m_colorTable->clearDirty())
2316 dirty = true;
2317
2318 const QSSGRenderImageTexture texture = bufferManager->loadRenderImage(particles.m_colorTable);
2319
2320 QSSGRenderableImage *theImage = RENDER_FRAME_NEW<QSSGRenderableImage>(contextInterface, QSSGRenderableImage::Type::Diffuse, *particles.m_colorTable, texture);
2321 colorTable = theImage;
2322 properties.m_isColorTableLinear.setValue(theGeneratedKey, texture.m_flags.isLinear());
2323 }
2324
2325 if (opacity > 0.0f && particles.m_particleBuffer.particleCount()) {
2326 auto *theRenderableObject = RENDER_FRAME_NEW<QSSGParticlesRenderable>(contextInterface,
2327 renderableFlags,
2328 center,
2329 renderer,
2330 globalTransform,
2331 particles,
2332 firstImage,
2333 colorTable,
2334 lights,
2335 opacity,
2336 theGeneratedKey);
2337 if (theRenderableObject) {
2338 if (theRenderableObject->renderableFlags.requiresScreenTexture())
2339 screenTextureObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2340 else if (theRenderableObject->renderableFlags.hasTransparency())
2341 transparentObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2342 else
2343 opaqueObjects.push_back({theRenderableObject, getCameraDistanceSq(*theRenderableObject, cameraData), particles.tag});
2344 }
2345 }
2346 }
2347
2348 return dirty;
2349}
2350
2351void QSSGLayerRenderData::prepareResourceLoaders()
2352{
2353 QSSGRenderContextInterface &contextInterface = *renderer->contextInterface();
2354 const auto &bufferManager = contextInterface.bufferManager();
2355
2356 for (const auto resourceLoader : std::as_const(layer.resourceLoaders))
2357 bufferManager->processResourceLoader(static_cast<QSSGRenderResourceLoader *>(resourceLoader));
2358}
2359
2360void QSSGLayerRenderData::prepareReflectionProbesForRender()
2361{
2362 const auto probeCount = reflectionProbesView.size();
2363 requestReflectionMapManager(); // ensure that we have a reflection map manager
2364
2365 for (int i = 0; i < probeCount; i++) {
2366 QSSGRenderReflectionProbe* probe = reflectionProbesView[i];
2367
2368 QMatrix4x4 probeTransform = getGlobalTransform(*probe);
2369
2370 int reflectionObjectCount = 0;
2371 QVector3D probeExtent = probe->boxSize / 2;
2372 QSSGBounds3 probeBound = QSSGBounds3::centerExtents(QSSGRenderNode::getGlobalPos(probeTransform) + probe->boxOffset, probeExtent);
2373
2374 const auto injectProbe = [&](const QSSGRenderableObjectHandle &handle) {
2375 if (handle.obj->renderableFlags.testFlag(QSSGRenderableObjectFlag::ReceivesReflections)
2376 && !(handle.obj->type == QSSGRenderableObject::Type::Particles)) {
2377 QSSGSubsetRenderable* renderableObj = static_cast<QSSGSubsetRenderable*>(handle.obj);
2378 QSSGBounds3 nodeBound = renderableObj->bounds;
2379 QVector4D vmin(nodeBound.minimum, 1.0);
2380 QVector4D vmax(nodeBound.maximum, 1.0);
2381 const QMatrix4x4 &renderableTransform = renderableObj->modelContext.globalTransform;
2382 vmin = renderableTransform * vmin;
2383 vmax = renderableTransform * vmax;
2384 nodeBound.minimum = vmin.toVector3D();
2385 nodeBound.maximum = vmax.toVector3D();
2386 if (probeBound.intersects(nodeBound)) {
2387 QVector3D nodeBoundCenter = nodeBound.center();
2388 QVector3D probeBoundCenter = probeBound.center();
2389 float distance = nodeBoundCenter.distanceToPoint(probeBoundCenter);
2390 if (renderableObj->reflectionProbeIndex == -1 || distance < renderableObj->distanceFromReflectionProbe) {
2391 renderableObj->reflectionProbeIndex = i;
2392 renderableObj->distanceFromReflectionProbe = distance;
2393 renderableObj->reflectionProbe.parallaxCorrection = probe->parallaxCorrection;
2394 renderableObj->reflectionProbe.probeCubeMapCenter = QSSGRenderNode::getGlobalPos(probeTransform);
2395 renderableObj->reflectionProbe.probeBoxMax = probeBound.maximum;
2396 renderableObj->reflectionProbe.probeBoxMin = probeBound.minimum;
2397 renderableObj->reflectionProbe.enabled = true;
2398 reflectionObjectCount++;
2399 }
2400 }
2401 }
2402 };
2403
2404 const auto &transparentObjects = std::as_const(transparentObjectStore[0]);
2405 const auto &opaqueObjects = std::as_const(opaqueObjectStore[0]);
2406 const auto &screenTextureObjects = std::as_const(screenTextureObjectStore[0]);
2407
2408 for (const auto &handle : std::as_const(transparentObjects))
2409 injectProbe(handle);
2410
2411 for (const auto &handle : std::as_const(opaqueObjects))
2412 injectProbe(handle);
2413
2414 for (const auto &handle : std::as_const(screenTextureObjects))
2415 injectProbe(handle);
2416
2417 if (probe->texture)
2418 reflectionMapManager->addTexturedReflectionMapEntry(i, *probe);
2419 else if (reflectionObjectCount > 0)
2420 reflectionMapManager->addReflectionMapEntry(i, *probe);
2421 }
2422}
2423
2424static bool scopeLight(QSSGRenderNode *node, QSSGRenderNode *lightScope)
2425{
2426 // check if the node is parent of the lightScope
2427 while (node) {
2428 if (node == lightScope)
2429 return true;
2430 node = node->parent;
2431 }
2432 return false;
2433}
2434
2435static const int REDUCED_MAX_LIGHT_COUNT_THRESHOLD_BYTES = 5200; // 325 vec4s
2436
2437static inline int effectiveMaxLightCount(const QSSGShaderFeatures &features)
2438{
2439 if (features.isSet(QSSGShaderFeatures::Feature::ReduceMaxNumLights))
2440 return QSSG_REDUCED_MAX_NUM_LIGHTS;
2441
2442 return QSSG_MAX_NUM_LIGHTS;
2443}
2444
2445static inline int effectiveMaxDirectionalLightCount(const QSSGShaderFeatures &features)
2446{
2447 if (features.isSet(QSSGShaderFeatures::Feature::ReduceMaxNumLights))
2448 return QSSG_REDUCED_MAX_NUM_DIRECTIONAL_LIGHTS;
2449
2450 return QSSG_MAX_NUM_DIRECTIONAL_LIGHTS;
2451}
2452
2453static void updateDirtySkeletons(const QSSGLayerRenderData &renderData, const QSSGLayerRenderData::QSSGModelsView &renderableNodes)
2454{
2455 // First model using skeleton clears the dirty flag so we need another mechanism
2456 // to tell to the other models the skeleton is dirty.
2457 QSet<QSSGRenderSkeleton *> dirtySkeletons;
2458 for (const auto &modelNode : std::as_const(renderableNodes)) {
2459 QSSGRenderSkeleton *skeletonNode = modelNode->skeleton;
2460 bool hcj = false;
2461 if (skeletonNode) {
2462 const bool dirtySkeleton = dirtySkeletons.contains(skeletonNode);
2463 const bool hasDirtyNonJoints = (skeletonNode->containsNonJointNodes
2464 && (hasDirtyNonJointNodes(skeletonNode, hcj) || dirtySkeleton));
2465 if (skeletonNode->skinningDirty || hasDirtyNonJoints) {
2466 Q_ASSERT(!skeletonNode->isDirty(QSSGRenderNode::DirtyFlag::GlobalValuesDirty));
2467 skeletonNode->boneTransformsDirty = false;
2468 if (hasDirtyNonJoints && !dirtySkeleton)
2469 dirtySkeletons.insert(skeletonNode);
2470 skeletonNode->skinningDirty = false;
2471 const qsizetype dataSize = BONEDATASIZE4ID(skeletonNode->maxIndex);
2472 if (skeletonNode->boneData.size() < dataSize)
2473 skeletonNode->boneData.resize(dataSize);
2474 skeletonNode->containsNonJointNodes = false;
2475 for (auto &child : skeletonNode->children)
2476 collectBoneTransforms(renderData, &child, skeletonNode, modelNode->inverseBindPoses);
2477 }
2478 skeletonNode->boneCount = skeletonNode->boneData.size() / 2 / 4 / 16;
2479 const int boneTexWidth = qCeil(qSqrt(skeletonNode->boneCount * 4 * 2));
2480 skeletonNode->boneTexData.setSize(QSize(boneTexWidth, boneTexWidth));
2481 skeletonNode->boneData.resize(boneTexWidth * boneTexWidth * 16);
2482 skeletonNode->boneTexData.setTextureData(skeletonNode->boneData);
2483 }
2484 const int numMorphTarget = modelNode->morphTargets.size();
2485 for (int i = 0; i < numMorphTarget; ++i) {
2486 auto morphTarget = static_cast<const QSSGRenderMorphTarget *>(modelNode->morphTargets.at(i));
2487 modelNode->morphWeights[i] = morphTarget->weight;
2488 modelNode->morphAttributes[i] = morphTarget->attributes;
2490 modelNode->morphAttributes[i] &= 0x1; // MorphTarget.Position
2492 modelNode->morphAttributes[i] &= 0x3; // MorphTarget.Position | MorphTarget.Normal
2493 }
2494 }
2495
2496 dirtySkeletons.clear();
2497}
2498
2499QSSGNodeIdList QSSGLayerRenderData::filter(const QSSGGlobalRenderNodeData::LayerNodeView &layerNodes,
2500 quint32 layerMask,
2501 quint32 typeMask)
2502{
2503 QSSGNodeIdList res;
2504 for (auto *n : layerNodes) {
2505 // Check mask
2506 if (((quint32(n->type) & typeMask) == typeMask) && n->tag.isSet(layerMask))
2507 res.push_back(QSSGNodeId(reinterpret_cast<quintptr>(n)));
2508 }
2509
2510 return res;
2511}
2512
2513void QSSGLayerRenderData::categorizeAndFilterNodes(const QSSGGlobalRenderNodeData::LayerNodeView &layerNodes,
2514 QSSGLayerRenderData::NodeCollection &nodeCollection,
2515 quint32 layerMask)
2516{
2517 auto &modelsView = nodeCollection.modelsView;
2518 auto &particlesView = nodeCollection.particlesView;
2519 auto &item2DsView = nodeCollection.item2DsView;
2520 auto &camerasView = nodeCollection.camerasView;
2521 auto &lightsView = nodeCollection.lightsView;
2522 auto &reflectionProbesView = nodeCollection.reflectionProbesView;
2523 auto &nonCategorizedView = nodeCollection.nonCategorizedView;
2524
2525 auto &layerNodesCategorized = nodeCollection.layerNodesCategorized;
2526
2527 modelsView.clear();
2528 particlesView.clear();
2529 item2DsView.clear();
2530 camerasView.clear();
2531 lightsView.clear();
2532 reflectionProbesView.clear();
2533 nonCategorizedView.clear();
2534
2535 enum NodeType : size_t { Model = 0, Particles, Item2D, Camera, ImportedCamera, Light, ReflectionProbe, Other, Inactive };
2536 const auto nodeType = [layerMask](QSSGRenderNode *node) -> NodeType {
2537 if (!(node->getGlobalState(QSSGRenderNode::GlobalState::Active)))
2538 return NodeType::Inactive;
2539 if (!(node->tag.isSet(layerMask)))
2540 return NodeType::Other;
2541 switch (node->type) {
2542 case QSSGRenderGraphObject::Type::Model: return NodeType::Model;
2543 case QSSGRenderGraphObject::Type::Particles: return NodeType::Particles;
2544 case QSSGRenderGraphObject::Type::Item2D: return NodeType::Item2D;
2545 case QSSGRenderGraphObject::Type::ReflectionProbe: return NodeType::ReflectionProbe;
2546 default: break;
2547 }
2548
2549 if (QSSGRenderGraphObject::isCamera(node->type)) {
2550 // NOTE: To keep compatibility with old code, we collect shared and non-shared cameras differently,
2551 // so that shared cameras (import scene) are picked after non-shared ones.
2552 const bool isImported = node->getGlobalState(QSSGRenderNode::GlobalState::Imported);
2553 constexpr NodeType cameraTypes[2] { NodeType::Camera, NodeType::ImportedCamera };
2554 return cameraTypes[size_t(isImported)];
2555 }
2556 if (QSSGRenderGraphObject::isLight(node->type))
2557 return NodeType::Light;
2558
2559 return NodeType::Other;
2560 };
2561 // sort nodes by type - We could do this on insert, but it's not given that it would be beneficial.
2562 // Depending on how we want to handle the nodes later it might just not give us anything
2563 // so, keep it simple for now.
2564 // We could also speed up this by having the pointer and the type in the same struct and sort without
2565 // indirection. However, that' slightly less convenient and the idea here is that we don't process
2566 // this list unless things change, which is not something that should happen often if the user is
2567 // concerned about performance, as it means we need to reevaluate the whole scene anyway.
2568 {
2569 // Sort the nodes by type (we copy the pointers to avoid sorting the original list,
2570 // which is stored based on the nodes' order in the world tree).
2571 layerNodesCategorized = { layerNodes.begin(), layerNodes.end() };
2572 // NOTE: Due to the ordering of item2ds, we need to use stable_sort.
2573 std::stable_sort(layerNodesCategorized.begin(), layerNodesCategorized.end(), [nodeType](QSSGRenderNode *a, QSSGRenderNode *b) {
2574 return nodeType(a) < nodeType(b);
2575 });
2576 }
2577
2578 // Group nodes by type inline and keep track of the individual parts using QSSGDataViews
2579 const LayerNodeStatResult stat = statLayerNodes(layerNodesCategorized, layerMask);
2580
2581 // Go through the sorted nodes and create the views
2582 size_t next = 0;
2583
2584 if (stat.modelCount > 0) {
2585 modelsView = QSSGModelsView((QSSGRenderModel **)(layerNodesCategorized.data() + next), stat.modelCount);
2586 next = modelsView.size();
2587 }
2588 if (stat.particlesCount > 0) {
2589 particlesView = QSSGParticlesView((QSSGRenderParticles **)(layerNodesCategorized.data() + next), stat.particlesCount);
2590 next += particlesView.size();
2591 }
2592 if (stat.item2DCount > 0) {
2593 item2DsView = QSSGItem2DsView((QSSGRenderItem2D **)(layerNodesCategorized.data() + next), stat.item2DCount);
2594 next += item2DsView.size();
2595 }
2596 if (stat.cameraCount > 0) {
2597 camerasView = QSSGCamerasView((QSSGRenderCamera **)(layerNodesCategorized.data() + next), stat.cameraCount);
2598 next += camerasView.size();
2599 }
2600 if (stat.lightCount > 0) {
2601 lightsView = QSSGLightsView((QSSGRenderLight **)(layerNodesCategorized.data() + next), stat.lightCount);
2602 next += lightsView.size();
2603 }
2604 if (stat.reflectionProbeCount > 0) {
2605 reflectionProbesView = QSSGReflectionProbesView((QSSGRenderReflectionProbe **)(layerNodesCategorized.data() + next), stat.reflectionProbeCount);
2606 next += reflectionProbesView.size();
2607 }
2608 if (stat.otherCount > 0) {
2609 nonCategorizedView = QSSGNonCategorizedView((QSSGRenderNode **)(layerNodesCategorized.data() + next), stat.otherCount);
2610 next += nonCategorizedView.size();
2611 (void)next;
2612 }
2613}
2614
2615void QSSGLayerRenderData::updateFilteredLayerNodes(quint32 layerMask)
2616{
2617 categorizeAndFilterNodes(layerNodes, nodeCollection, layerMask);
2618
2619 // FIXME: Compatability with old code (Will remove later).
2620 // NOTE: see resetForFrame() as well for extensions usage
2621 renderableModels.clear();
2622 renderableParticles.clear();
2623 renderableModels.reserve(modelsView.size());
2624 renderableParticles.reserve(particlesView.size());
2625
2626 renderableModels = {modelsView.begin(), modelsView.end()};
2627 renderableParticles = {particlesView.begin(), particlesView.end()};
2628}
2629
2630void QSSGLayerRenderData::prepareForRender()
2631{
2632 QSSG_ASSERT_X(layerPrepResult.isNull(), "Prep-result was not reset for render!", layerPrepResult = {});
2633
2634 QRect theViewport(renderer->viewport());
2635 const auto &rhiCtx = renderer->contextInterface()->rhiContext();
2636
2637 // NOTE: The renderer won't change in practice (after being set the first time), but just update
2638 // it anyways.
2639 frameData.m_ctx = renderer->contextInterface();
2640 frameData.clear();
2641
2642 // Create base pipeline state
2643 ps = {}; // Reset
2644 ps.viewport = { float(theViewport.x()), float(theViewport.y()), float(theViewport.width()), float(theViewport.height()), 0.0f, 1.0f };
2645 if (layer.scissorRect.isValid()) {
2646 ps.flags |= QSSGRhiGraphicsPipelineState::Flag::UsesScissor;
2647 ps.scissor = { theViewport.x() + layer.scissorRect.x(),
2648 theViewport.y() + theViewport.height() - (layer.scissorRect.y() + layer.scissorRect.height()),
2649 layer.scissorRect.width(),
2650 layer.scissorRect.height() };
2651 }
2652
2653 // calculate viewport origin
2654 auto *rt = rhiCtx->renderTarget();
2655 if (!rt || renderer->contextInterface()->rhi()->isYUpInFramebuffer())
2656 m_viewportOrigin = QVector2D(theViewport.x(), theViewport.y());
2657 else
2658 m_viewportOrigin = QVector2D(theViewport.x(), rt->pixelSize().height() - theViewport.y() - theViewport.height());
2659
2660 ps.depthFunc = QRhiGraphicsPipeline::LessOrEqual;
2661 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::BlendEnabled, false);
2662
2663 // Enable Wireframe mode
2664 ps.polygonMode = layer.wireframeMode ? QRhiGraphicsPipeline::Line : QRhiGraphicsPipeline::Fill;
2665
2666 bool wasDirty = false;
2667 bool wasDataDirty = false;
2668 wasDirty = layer.isDirty();
2669
2670 const bool shouldDisableInternalPasses = (layer.renderOverrides & size_t(QSSGRenderLayer::RenderOverrides::DisableInternalPasses)) != 0;
2671 wasDirty |= (shouldDisableInternalPasses != disableMainPasses);
2672 disableMainPasses = shouldDisableInternalPasses;
2673
2674 // NOTE: Prep-state is implicitly set to "DataPrep"
2675 layerPrepResult = { theViewport, layer };
2676
2677 // SSAO
2678 const bool SSAOEnabled = layer.ssaoEnabled();
2679 layerPrepResult.flags.setRequiresSsaoPass(SSAOEnabled);
2680 features.set(QSSGShaderFeatures::Feature::Ssao, SSAOEnabled);
2681
2682 // Effects
2683 bool requiresDepthTexture = SSAOEnabled;
2684 bool requiresNormalTexture = false;
2685 bool requiresMotionVectorTexture = false;
2686 for (QSSGRenderEffect *theEffect = layer.firstEffect; theEffect; theEffect = theEffect->m_nextEffect) {
2687 if (theEffect->isDirty()) {
2688 wasDirty = true;
2689 theEffect->clearDirty();
2690 }
2691 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesDepthTexture))
2692 requiresDepthTexture = true;
2693 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesNormalTexture))
2694 requiresNormalTexture = true;
2695 if (theEffect->testFlag(QSSGRenderEffect::Flags::UsesMotionVectorTexture))
2696 requiresMotionVectorTexture = true;
2697 }
2698
2699 orderIndependentTransparencyEnabled = (layer.oitMethod != QSSGRenderLayer::OITMethod::None);
2700 if (layer.oitMethod == QSSGRenderLayer::OITMethod::WeightedBlended) {
2701 orderIndependentTransparencyEnabled = rhiCtx->rhi()->isFeatureSupported(QRhi::PerRenderTargetBlending);
2702 if (rhiCtx->mainPassSampleCount() > 1)
2703 orderIndependentTransparencyEnabled &= rhiCtx->rhi()->isFeatureSupported(QRhi::TexelFetch) && rhiCtx->rhi()->isFeatureSupported(QRhi::SampleVariables);
2704 if (!orderIndependentTransparencyEnabled && warnOnce(OneShotWarning::OitUnsupported))
2705 qCWarning(lcQuick3DRender) << "WeightedBlended OIT is requested, but it is not supported.";
2706 } else if (layer.oitMethod == QSSGRenderLayer::OITMethod::LinkedList) {
2707 orderIndependentTransparencyEnabled = rhiCtx->rhi()->isTextureFormatSupported(QRhiTexture::RGBA32UI, QRhiTexture::UsedWithLoadStore);
2708 if (rhiCtx->mainPassSampleCount() > 1)
2709 orderIndependentTransparencyEnabled &= rhiCtx->rhi()->isFeatureSupported(QRhi::SampleVariables);
2710 if (!orderIndependentTransparencyEnabled && warnOnce(OneShotWarning::OitUnsupported))
2711 qCWarning(lcQuick3DRender) << "LinkedList OIT is requested, but it is not supported.";
2712 }
2713 if (layer.oitMethodDirty) {
2714 oitRenderContext.reset();
2715 QSSGRhiResourceRegistry *registry = &QSSGRhiContextPrivate::get(rhiCtx.get())->resourceRegistry();
2716 for (auto &renderResult : renderResults)
2717 renderResult.reset(registry);
2718 }
2719
2720 layerPrepResult.flags.setRequiresDepthTexture(requiresDepthTexture);
2721
2722 layerPrepResult.flags.setRequiresNormalTexture(requiresNormalTexture);
2723
2724 layerPrepResult.flags.setRequiresMotionVectorPass(requiresMotionVectorTexture);
2725
2726 // Tonemapping. Except when there are effects, then it is up to the
2727 // last pass of the last effect to perform tonemapping.
2728 if (!layer.firstEffect)
2729 QSSGLayerRenderData::setTonemapFeatures(features, layer.tonemapMode);
2730
2731 // We may not be able to have an array of 15 light struct elements in
2732 // the shaders. Switch on the reduced-max-number-of-lights feature
2733 // if necessary. In practice this is relevant with OpenGL ES 3.0 or
2734 // 2.0, because there are still implementations in use that only
2735 // support the spec mandated minimum of 224 vec4s (so 3584 bytes).
2736 if (rhiCtx->rhi()->resourceLimit(QRhi::MaxUniformBufferRange) < REDUCED_MAX_LIGHT_COUNT_THRESHOLD_BYTES) {
2737 features.set(QSSGShaderFeatures::Feature::ReduceMaxNumLights, true);
2738 static bool notified = false;
2739 if (!notified) {
2740 notified = true;
2741 qCDebug(lcQuick3DRender, "Qt Quick 3D maximum number of lights has been reduced from %d to %d due to the graphics driver's limitations",
2742 QSSG_MAX_NUM_LIGHTS, QSSG_REDUCED_MAX_NUM_LIGHTS);
2743 }
2744 }
2745
2746 // IBL source configuration
2747 const auto &lightProbeSettings = layer.lightProbeSettings;
2748 if (layer.lightProbe) {
2749 if (layer.lightProbe->m_format == QSSGRenderTextureFormat::Unknown) {
2750 // Choose on a format that makes sense for a light probe
2751 // At this point it's just a suggestion
2752 if (renderer->contextInterface()->rhiContext()->rhi()->isTextureFormatSupported(QRhiTexture::RGBA16F))
2753 layer.lightProbe->m_format = QSSGRenderTextureFormat::RGBA16F;
2754 else
2755 layer.lightProbe->m_format = QSSGRenderTextureFormat::RGBE8;
2756 }
2757
2758 if (layer.lightProbe->clearDirty())
2759 wasDataDirty = true;
2760
2761 features.set(QSSGShaderFeatures::Feature::LightProbe, true);
2762 features.set(QSSGShaderFeatures::Feature::IblOrientation, !lightProbeSettings.probeOrientation.isIdentity());
2763 if (layer.lightProbe->m_format.format == QSSGRenderTextureFormat::Format::RGBE8)
2764 features.set(QSSGShaderFeatures::Feature::RGBELightProbe, true);
2765
2766 } else if (layer.skyMaterial) {
2767 if (layer.skyMaterial->enableIBL) {
2768 features.set(QSSGShaderFeatures::Feature::LightProbe, true);
2769 features.set(QSSGShaderFeatures::Feature::IblOrientation, !lightProbeSettings.probeOrientation.isIdentity());
2770 }
2771 layerPrepResult.flags.setRequiresSkyMaterialPass(true);
2772 }
2773
2774 const bool forceIblExposureValues = (features.isSet(QSSGShaderFeatures::Feature::LightProbe)
2775 && layer.tonemapMode == QSSGRenderLayer::TonemapMode::Custom);
2776 features.set(QSSGShaderFeatures::Feature::ForceIblExposure, forceIblExposureValues);
2777
2778 frameData.m_ctx->bufferManager()->setLightmapSource(layer.lightmapSource);
2779
2780 // Update the node data version for this layer.
2781 // This version should only change if the world tree was re-indexed.
2782 version = nodeData->version();
2783
2784 // We're using/updating the node data directly.
2785 // NOTE: These are the transforms and opacities for all nodes for all layers/views.
2786 // We'll just use or update the ones the one for this layer.
2787 auto &globalTransforms = nodeData->globalTransforms;
2788 auto &globalOpacities = nodeData->globalOpacities;
2789 auto &instanceTransforms = nodeData->instanceTransforms;
2790
2791 ///////// 2 - START LAYER
2792 QSSGRenderDataHelpers::GlobalStateResultT globalStateResult = QSSGRenderDataHelpers::GlobalStateResult::None;
2793
2794 const bool layerTreeWasDirty = layer.isDirty(QSSGRenderLayer::DirtyFlag::TreeDirty);
2795 layer.clearDirty(QSSGRenderLayer::DirtyFlag::TreeDirty);
2796 if (layerTreeWasDirty) {
2797 wasDataDirty = true;
2798 layerNodes = nodeData->getLayerNodeView(layer);
2799 } else {
2800 using GlobalStateResult = QSSGRenderDataHelpers::GlobalStateResult;
2801 // If the active state or tags of a node changed, it may affect the filtered node list for this layer. If so, we need to re-filter the nodes.
2802 constexpr QSSGRenderDataHelpers::GlobalStateResultT FilterAffectingChanges = GlobalStateResult::ActiveChanged
2803 | GlobalStateResult::TagChanged;
2804 bool sharedStateChanged = false;
2805 for (auto &node : layerNodes) {
2806 const auto result = QSSGRenderDataHelpers::updateGlobalNodeState(node, version);
2807 globalStateResult |= result;
2808 // If the node is shared and the change affects the filtered node list, we need to re-filter the nodes for this layer.
2809 // The reason we need to do that is because the first layer processing the node will clear the dirty flag making the
2810 // change invisible to the other layers sharing the node (we'll call bumpStateGeneration() further down).
2811 const bool affectsFilter = ((result & FilterAffectingChanges) != 0);
2812 const bool isShared = node->getGlobalState(QSSGRenderNode::GlobalState::Imported);
2813 sharedStateChanged |= (affectsFilter && isShared);
2814 }
2815
2816 if (sharedStateChanged)
2817 nodeData->bumpStateGeneration();
2818
2819 bool transformAndOpacityDirty = false;
2820 for (auto &node : layerNodes)
2821 transformAndOpacityDirty |= QSSGRenderDataHelpers::calcGlobalNodeData<QSSGRenderDataHelpers::Strategy::Update>(node, version, globalTransforms, globalOpacities);
2822
2823 // FIXME: We shouldn't need to re-create all the instance transforms even when instancing isn't used...
2824 if (transformAndOpacityDirty) {
2825 for (const auto &node : layerNodes)
2826 wasDataDirty |= QSSGRenderDataHelpers::calcInstanceTransforms(node, version, globalTransforms, instanceTransforms);
2827 }
2828
2829 wasDataDirty |= transformAndOpacityDirty;
2830 }
2831
2832 // If the viewport visibility changed, we mark the data as dirty to ensure a proper update
2833 // happens. This is important because if there are shared imported nodes between layers,
2834 // they might have been updated by one of the other layers and therefore considered "clean", causing
2835 // things like progressiveAA to not work correctly when toggling the visibility of a layer.
2836 const bool viewportVisibilityDirty = layer.isDirty(QSSGRenderLayer::DirtyFlag::VisibilityDirty);
2837 layer.clearDirty(QSSGRenderLayer::DirtyFlag::VisibilityDirty);
2838 if (viewportVisibilityDirty)
2839 wasDataDirty = true;
2840
2841 // Check if we have an explicit camera!
2842 // NOTE: We only do layering if we have an explicit camera!!!
2843
2844 const bool hasExplicitCamera = (layer.explicitCameras.size() != 0);
2845 bool cameraLayerMaskDirty = false;
2846 quint32 layerMask = QSSGRenderCamera::LayerMaskAll;
2847 if (hasExplicitCamera) {
2848 QSSGRenderCamera *explicitCamera = layer.explicitCameras[0];
2849 // For now we add the reserved bits to the camera layer mask.
2850 // In the future we might want to control which reserved bits are added.
2851 layerMask = explicitCamera->tag.value() | QSSGRenderCamera::ReservedLayerMask;
2852 cameraLayerMaskDirty = explicitCamera->isDirty(QSSGRenderCamera::DirtyFlag::LayerMaskDirty);
2853 explicitCamera->clearDirty(QSSGRenderCamera::DirtyFlag::LayerMaskDirty);
2854 }
2855
2856 // Pick up active and tag changes on shared nodes that were consumed by another layer.
2857 const bool sharedStateDirty = (stateGeneration != nodeData->stateGeneration());
2858 stateGeneration = nodeData->stateGeneration();
2859
2860 const bool restatNodes = (layerTreeWasDirty
2861 || (globalStateResult & (QSSGRenderDataHelpers::GlobalStateResult::ActiveChanged | QSSGRenderDataHelpers::GlobalStateResult::TagChanged))
2862 || cameraLayerMaskDirty
2863 || sharedStateDirty);
2864
2865 if (restatNodes)
2866 updateFilteredLayerNodes(layerMask);
2867
2868 // Cameras
2869 // 1. If there's an explicit camera set and it's active (visible) we'll use that.
2870 // 2. ... if the explicitly set camera is not visible, no further attempts will be done.
2871 // 3. If no explicit camera is set, we'll search and pick the first active camera.
2872 QSSGRenderCamera::Configuration cameraConfig { renderer->dpr(), layer.isSsaaEnabled() ? layer.ssaaMultiplier : 1.0f };
2873 renderedCameras.clear();
2874 if (!layer.explicitCameras.isEmpty()) {
2875 for (QSSGRenderCamera *cam : std::as_const(layer.explicitCameras)) {
2876 // 1.
2877 if (cam->getGlobalState(QSSGRenderCamera::GlobalState::Active)) {
2878 const bool computeFrustumSucceeded = cam->calculateProjection(theViewport, cameraConfig);
2879 if (Q_LIKELY(computeFrustumSucceeded))
2880 renderedCameras.append(cam);
2881 else
2882 qCCritical(INTERNAL_ERROR, "Failed to calculate camera frustum");
2883 }
2884 }
2885 // 2.
2886 } else if (QSSG_GUARD_X(layer.viewCount == 1, "Multiview rendering requires explicit cameras to be set!.")) {
2887 // NOTE: This path can never be hit with multiview, hence the guard.
2888 // (Multiview will always have explicit cameras set.)
2889
2890 // 3.
2891 for (auto iter = camerasView.begin(); renderedCameras.isEmpty() && iter != camerasView.end(); iter++) {
2892 QSSGRenderCamera *theCamera = *iter;
2893 if (theCamera->getGlobalState(QSSGRenderCamera::GlobalState::Active)) {
2894 const bool computeFrustumSucceeded = theCamera->calculateProjection(theViewport, cameraConfig);
2895 if (Q_LIKELY(computeFrustumSucceeded))
2896 renderedCameras.append(theCamera);
2897 else
2898 qCCritical(INTERNAL_ERROR, "Failed to calculate camera frustum");
2899 }
2900 }
2901
2902 // Now check if the camera has a layer mask, if it does we need to filter the nodes again!
2903 // Issue a warning letting the user know that they should set an explicit camera!
2904 // If you are reading this due to seeing the warning: Not requiring an explicit camera was
2905 // a mistake, but we kept it for compatability reasons unfortunately.
2906 if (renderedCameras.size() > 0 && (renderedCameras[0]->layerMask & QSSGRenderCamera::LayerMaskUserAll) != QSSGRenderCamera::LayerMaskUserAll) {
2907 if (warnOnce(OneShotWarning::NonExplicitCameraWithLayerMask)) {
2908 qWarning() << "Scenes with non-explicit cameras with a layer detected!"
2909 " Set the camera explicitly to avoid unnecessary evaluation of scene nodes!";
2910 }
2911
2912 // Now filter the nodes, again.
2913 layerMask = renderedCameras[0]->layerMask;
2914 updateFilteredLayerNodes(layerMask);
2915 }
2916 }
2917
2918 float meshLodThreshold = 1.0f;
2919 if (!renderedCameras.isEmpty())
2920 meshLodThreshold = renderedCameras[0]->levelOfDetailPixelThreshold / theViewport.width();
2921
2922 layer.renderedCamerasMutex.lock();
2923 layer.renderedCameras = renderedCameras;
2924 layer.renderedCamerasMutex.unlock();
2925
2926 // Meshes, materials, MVP, and normal matrices for the models
2927 const QSSGRenderCameraDataList &renderCameraData = getCachedCameraDatas();
2928 modelData->updateModelData(modelsView, renderer, renderCameraData);
2929
2930 // Item2Ds
2931 item2DData->updateItem2DData(item2DsView, renderer, renderCameraData);
2932
2933 // ResourceLoaders
2934 prepareResourceLoaders();
2935
2936 // Skeletons
2937 updateDirtySkeletons(*this, modelsView);
2938
2939 // Lights
2940 int directionalLightsCount = 0;
2941 int positionalLightsCount = 0;
2942 const int maxLightCount = effectiveMaxLightCount(features);
2943 const int maxDirectionalLights = effectiveMaxDirectionalLightCount(features);
2944 QSSGShaderLightList renderableLights;
2945 int shadowMapCount = 0;
2946 bool hasScopedLights = false;
2947
2948 // Determine which lights will actually Render
2949 // Determine how many lights will need shadow maps
2950 // NOTE: This culling is specific to our Forward renderer
2951 {
2952 auto it = std::make_reverse_iterator(lightsView.end());
2953 const auto end = it + qMin(maxLightCount, lightsView.size());
2954 for (; it != end; ++it) {
2955 QSSGRenderLight *renderLight = (*it);
2956 QMatrix4x4 renderLightTransform = getGlobalTransform(*renderLight);
2957 if (renderLight->type == QSSGRenderGraphObject::Type::DirectionalLight)
2958 directionalLightsCount++;
2959 else
2960 positionalLightsCount++;
2961
2962 if (positionalLightsCount > maxLightCount)
2963 continue;
2964 if (directionalLightsCount > maxDirectionalLights)
2965 continue;
2966
2967
2968 hasScopedLights |= (renderLight->m_scope != nullptr);
2969 const bool castShadows = renderLight->m_castShadow && !renderLight->m_fullyBaked;
2970 shadowMapCount += int(castShadows);
2971 const auto &direction = renderLight->getScalingCorrectDirection(renderLightTransform);
2972 renderableLights.push_back(QSSGShaderLight{ renderLight, castShadows, direction });
2973 }
2974 }
2975
2976 if (positionalLightsCount > maxLightCount && warnOnce(OneShotWarning::TooManyLights))
2977 qWarning("Too many lights in scene, maximum is %d", maxLightCount);
2978
2979 if (directionalLightsCount > maxDirectionalLights && warnOnce(OneShotWarning::TooManyDirectionalLights))
2980 qWarning("Too many directional lights in scene, maximum is %d", maxDirectionalLights);
2981
2982 if (shadowMapCount > 0) { // Setup Shadow Maps Entries for Lights casting shadows
2983 requestShadowMapManager(); // Ensure we have a shadow map manager
2984 layerPrepResult.flags.setRequiresShadowMapPass(true);
2985 // Any light with castShadow=true triggers shadow mapping
2986 // in the generated shaders. The fact that some (or even
2987 // all) objects may opt out from receiving shadows plays no
2988 // role here whatsoever.
2989 features.set(QSSGShaderFeatures::Feature::Ssm, true);
2990 shadowMapManager->addShadowMaps(renderableLights);
2991 } else if (shadowMapManager) {
2992 // No shadows but a shadow manager so clear old resources
2993 shadowMapManager->releaseCachedResources();
2994 }
2995
2996 // Give each renderable a copy of the lights available
2997 // Also setup scoping for scoped lights
2998
2999 QSSG_ASSERT(globalLights.isEmpty(), globalLights.clear());
3000 if (hasScopedLights) { // Filter out scoped lights from the global lights list
3001 for (const auto &shaderLight : std::as_const(renderableLights)) {
3002 if (!shaderLight.light->m_scope)
3003 globalLights.push_back(shaderLight);
3004 }
3005
3006 const auto prepareLightsWithScopedLights = [&renderableLights, this](QVector<QSSGRenderableNodeEntry> &renderableNodes) {
3007 for (qint32 idx = 0, end = renderableNodes.size(); idx < end; ++idx) {
3008 QSSGRenderableNodeEntry &theNodeEntry(renderableNodes[idx]);
3009 QSSGShaderLightList filteredLights;
3010 for (const auto &light : std::as_const(renderableLights)) {
3011 if (light.light->m_scope && !scopeLight(theNodeEntry.node, light.light->m_scope))
3012 continue;
3013 filteredLights.push_back(light);
3014 }
3015
3016 if (filteredLights.isEmpty()) { // Node without scoped lights, just reference the global light list.
3017 theNodeEntry.lights = QSSGDataView(globalLights);
3018 } else {
3019 // This node has scoped lights, i.e., it's lights differ from the global list
3020 // we therefore create a bespoke light list for it. Technically this might be the same for
3021 // more then this one node, but the overhead for tracking that is not worth it.
3022 auto customLightList = RENDER_FRAME_NEW_BUFFER<QSSGShaderLight>(*renderer->contextInterface(), filteredLights.size());
3023 std::copy(filteredLights.cbegin(), filteredLights.cend(), customLightList.begin());
3024 theNodeEntry.lights = customLightList;
3025 }
3026 }
3027 };
3028
3029 prepareLightsWithScopedLights(renderableModels);
3030 prepareLightsWithScopedLights(renderableParticles);
3031 } else { // Just a simple copy
3032 globalLights = renderableLights;
3033 // No scoped lights, all nodes can just reference the global light list.
3034 const auto prepareLights = [this](QVector<QSSGRenderableNodeEntry> &renderableNodes) {
3035 for (qint32 idx = 0, end = renderableNodes.size(); idx < end; ++idx) {
3036 QSSGRenderableNodeEntry &theNodeEntry(renderableNodes[idx]);
3037 theNodeEntry.lights = QSSGDataView(globalLights);
3038 }
3039 };
3040
3041 prepareLights(renderableModels);
3042 prepareLights(renderableParticles);
3043 }
3044
3045 {
3046 // Give user provided passes a chance to modify the renderable data before starting
3047 // Note: All non-active extensions should be filtered out by now
3048 Q_STATIC_ASSERT(USERPASSES == size_t(QSSGRenderLayer::RenderExtensionStage::Count));
3049 for (size_t i = 0; i != size_t(QSSGRenderLayer::RenderExtensionStage::Count); ++i) {
3050 const auto &renderExtensions = layer.renderExtensions[i];
3051 auto &userPass = userPasses[i];
3052 for (auto rit = renderExtensions.crbegin(), rend = renderExtensions.crend(); rit != rend; ++rit) {
3053 if ((*rit)->prepareData(frameData)) {
3054 wasDirty |= true;
3055 userPass.extensions.push_back(*rit);
3056 }
3057 }
3058 }
3059 }
3060
3061 // User render passes
3062 {
3063 const auto &userRenderPassManager = requestUserRenderPassManager();
3064 userRenderPassManager->updateUserPassOrder(layerTreeWasDirty); // NOTE: If the tree was dirty we need to force an update.
3065 const bool willRender = !renderedCameras.isEmpty() && layerPrepResult.isLayerVisible();
3066 userRenderPassManager->selectPassesForFrame(*renderer->contextInterface()->bufferManager(), willRender,
3067 earlyUserPasses.userPasses, userRenderPasses.userPasses);
3068 }
3069
3070 // Set required texture flags if a compute pass that will run is using them,
3071 // so that the passes producing the textures do not run for nothing.
3072 const bool computeSupported = rhiCtx->rhi()->isFeatureSupported(QRhi::Compute);
3073 for (const auto *userPass : std::as_const(userRenderPasses.userPasses)) {
3074 if (!computeSupported || userPass->type != QSSGRenderGraphObject::Type::ComputePass)
3075 continue;
3076 const auto *computePass = static_cast<const QSSGRenderComputePass *>(userPass);
3077 if (!computePass->willDispatch())
3078 continue;
3079 const auto &identifiers = computePass->computeShader.identifiers;
3080 if (identifiers.contains(QByteArrayLiteral("SCREEN_TEXTURE")))
3081 layerPrepResult.flags.setRequiresScreenTexture(true);
3082 if (identifiers.contains(QByteArrayLiteral("SCREEN_MIP_TEXTURE"))) {
3083 layerPrepResult.flags.setRequiresScreenTexture(true);
3084 layerPrepResult.flags.setRequiresMipmapsForScreenTexture(true);
3085 }
3086 if (identifiers.contains(QByteArrayLiteral("DEPTH_TEXTURE")))
3087 layerPrepResult.flags.setRequiresDepthTexture(true);
3088 if (identifiers.contains(QByteArrayLiteral("AO_TEXTURE"))) {
3089 layerPrepResult.flags.setRequiresDepthTexture(true);
3090 layerPrepResult.flags.setRequiresSsaoPass(true);
3091 }
3092 if (computePass->computeShader.needsNormalTexture)
3093 layerPrepResult.flags.setRequiresNormalTexture(true);
3094 }
3095
3096 auto &opaqueObjects = opaqueObjectStore[0];
3097 auto &transparentObjects = transparentObjectStore[0];
3098 auto &screenTextureObjects = screenTextureObjectStore[0];
3099
3100 if (!renderedCameras.isEmpty()) { // NOTE: We shouldn't really get this far without a camera...
3101 wasDirty |= prepareModelsForRender(*renderer->contextInterface(), renderableModels, layerPrepResult.flags, renderedCameras, getCachedCameraDatas(), modelContexts, opaqueObjects, transparentObjects, screenTextureObjects, meshLodThreshold);
3102 if (particlesEnabled) {
3103 const auto &cameraDatas = getCachedCameraDatas();
3104 wasDirty |= prepareParticlesForRender(renderableParticles, cameraDatas[0], layerPrepResult.flags);
3105 }
3106 // If there's item2Ds we set wasDirty.
3107 wasDirty |= (item2DsView.size() != 0);
3108 }
3109 if (orderIndependentTransparencyEnabled) {
3110 // OIT blending mode must be SourceOver and have transparent objects
3111 if (transparentObjects.size() > 0 && !layerPrepResult.flags.hasCustomBlendMode()) {
3112 if (layer.oitMethod != QSSGRenderLayer::OITMethod::None) {
3113 if (rhiCtx->mainPassSampleCount() > 1)
3114 layerPrepResult.flags.setRequiresDepthTextureMS(true);
3115 else
3116 layerPrepResult.flags.setRequiresDepthTexture(true);
3117 }
3118 } else {
3119 orderIndependentTransparencyEnabled = false;
3120 if (warnOnce(OneShotWarning::OitInvalidBlendMode)) {
3121 qCWarning(lcQuick3DRender) << "Order Independent Transparency requested, but disabled due to invalid blend modes.";
3122 qCWarning(lcQuick3DRender) << "Use SourceOver blend mode for Order Independent Transparency.";
3123 }
3124 }
3125 }
3126 layer.oitMethodDirty = false;
3127
3128 prepareReflectionProbesForRender();
3129
3130 wasDirty = wasDirty || wasDataDirty;
3131 layerPrepResult.flags.setWasDirty(wasDirty);
3132 layerPrepResult.flags.setLayerDataDirty(wasDataDirty);
3133
3134 //
3135 const bool animating = wasDirty;
3136 if (animating)
3137 layer.progAAPassIndex = 0;
3138
3139 const bool progressiveAA = layer.isProgressiveAAEnabled() && !animating;
3140 layer.progressiveAAIsActive = progressiveAA;
3141 const bool temporalAA = layer.isTemporalAAEnabled() && !progressiveAA;
3142
3143 layer.temporalAAIsActive = temporalAA;
3144
3145 QVector2D vertexOffsetsAA;
3146
3147 if (progressiveAA && layer.progAAPassIndex > 0 && layer.progAAPassIndex < quint32(layer.antialiasingQuality)) {
3148 int idx = layer.progAAPassIndex - 1;
3149 vertexOffsetsAA = s_ProgressiveAAVertexOffsets[idx] / QVector2D{ float(theViewport.width()/2.0), float(theViewport.height()/2.0) };
3150 }
3151
3152 if (temporalAA) {
3153 if (layer.temporalAAMode == QSSGRenderLayer::TAAMode::MotionVector && layer.tempAAPassIndex > 0) {
3154 if (layer.tempAAPassIndex >= quint32(MAX_AA_LEVELS) + 1)
3155 layer.tempAAPassIndex = 1;
3156 int idx = layer.tempAAPassIndex - 1;
3157 vertexOffsetsAA = s_ProgressiveAAVertexOffsets[idx] / QVector2D{ float(theViewport.width()/2.0), float(theViewport.height()/2.0) };
3158 layer.currentAndLastJitter = QVector4D(vertexOffsetsAA, layer.currentAndLastJitter.x(), layer.currentAndLastJitter.y());
3159 layerPrepResult.flags.setRequiresMotionVectorPass(true);
3160 layerPrepResult.flags.setRequiresDepthTexture(true);
3161 }else {
3162 const int t = 1 - 2 * (layer.tempAAPassIndex % 2);
3163 const float f = t * layer.temporalAAStrength;
3164 vertexOffsetsAA = { f / float(theViewport.width()/2.0), f / float(theViewport.height()/2.0) };
3165 }
3166 }
3167
3168 if (!renderedCameras.isEmpty()) {
3169 if (temporalAA || progressiveAA /*&& !vertexOffsetsAA.isNull()*/) {
3170 QMatrix4x4 offsetProjection = renderedCameras[0]->projection;
3171 QMatrix4x4 invProjection = renderedCameras[0]->projection.inverted();
3172 if (renderedCameras[0]->type == QSSGRenderCamera::Type::OrthographicCamera) {
3173 offsetProjection(0, 3) -= vertexOffsetsAA.x();
3174 offsetProjection(1, 3) -= vertexOffsetsAA.y();
3175 } else if (renderedCameras[0]->type == QSSGRenderCamera::Type::PerspectiveCamera) {
3176 offsetProjection(0, 2) += vertexOffsetsAA.x();
3177 offsetProjection(1, 2) += vertexOffsetsAA.y();
3178 }
3179 for (auto &modelContext : std::as_const(modelContexts)) {
3180 for (int mvpIdx = 0; mvpIdx < renderedCameras.count(); ++mvpIdx)
3181 modelContext->modelViewProjections[mvpIdx] = offsetProjection * invProjection * modelContext->modelViewProjections[mvpIdx];
3182 }
3183 }
3184 }
3185
3186 const bool hasItem2Ds = (item2DsView.size() > 0);
3187 const bool layerEnableDepthTest = layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthTest);
3188 const bool layerEnabledDepthPrePass = layer.layerFlags.testFlag(QSSGRenderLayer::LayerFlag::EnableDepthPrePass);
3189 const bool depthTestEnableDefault = layerEnableDepthTest && (!opaqueObjects.isEmpty() || depthPrepassObjectsState || hasDepthWriteObjects);
3190 const bool zPrePassForced = (depthPrepassObjectsState != 0);
3191 zPrePassActive = zPrePassForced || (layerEnabledDepthPrePass && layerEnableDepthTest && (hasDepthWriteObjects || hasItem2Ds));
3192 const bool depthWriteEnableDefault = depthTestEnableDefault && (!layerEnabledDepthPrePass || !zPrePassActive);
3193
3194 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthTestEnabled, depthTestEnableDefault);
3195 ps.flags.setFlag(QSSGRhiGraphicsPipelineState::Flag::DepthWriteEnabled, depthWriteEnableDefault);
3196
3197
3198 // All data prep is done, from now on the layer content shouldn't change.
3199 layerPrepResult.setState(QSSGLayerRenderPreparationResult::State::Done);
3200
3201 // Prepare passes
3202 QSSG_ASSERT(activePasses.isEmpty(), activePasses.clear());
3203 if (earlyUserPasses.hasData())
3204 activePasses.push_back(&earlyUserPasses);
3205
3206 // If needed, generate a depth texture with the opaque objects. This
3207 // and normal and the SSAO texture must come first since other passes may want to
3208 // expose these textures to their shaders.
3209 if (layerPrepResult.flags.requiresDepthTexture())
3210 activePasses.push_back(&depthMapPass);
3211 if (layerPrepResult.flags.requiresDepthTextureMS())
3212 activePasses.push_back(&depthMapPassMS);
3213
3214 if (layerPrepResult.flags.requiresNormalTexture())
3215 activePasses.push_back(&normalPass);
3216
3217 // Screen space ambient occlusion. Relies on the depth texture and generates an AO map.
3218 if (layerPrepResult.flags.requiresSsaoPass())
3219 activePasses.push_back(&ssaoMapPass);
3220
3221 // Shadows. Generates a 2D or cube shadow map. (opaque + pre-pass transparent objects)
3222 if (layerPrepResult.flags.requiresShadowMapPass())
3223 activePasses.push_back(&shadowMapPass);
3224
3225 if (zPrePassActive && !disableMainPasses)
3226 activePasses.push_back(&zPrePassPass);
3227
3228 // Screen texture with opaque objects.
3229 if (layerPrepResult.flags.requiresScreenTexture())
3230 activePasses.push_back(&screenMapPass);
3231
3232 // Layer has SkyMaterial.
3233 if (layerPrepResult.flags.requiresSkyMaterialPass())
3234 activePasses.push_back(&skyMaterialPass);
3235
3236 // Reflection pass
3237 if (reflectionProbesView.size() != 0)
3238 activePasses.push_back(&reflectionMapPass);
3239
3240 auto &textureExtensionPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::TextureProviders)];
3241 if (textureExtensionPass.hasData())
3242 activePasses.push_back(&textureExtensionPass);
3243
3244 auto &underlayPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::Underlay)];
3245 if (underlayPass.hasData())
3246 activePasses.push_back(&underlayPass);
3247
3248 // Generated User render passes (QML)
3249 if (userRenderPasses.hasData())
3250 activePasses.push_back(&userRenderPasses);
3251
3252 const bool hasOpaqueObjects = (opaqueObjects.size() > 0);
3253
3254 if (hasOpaqueObjects && !disableMainPasses)
3255 activePasses.push_back(&opaquePass);
3256
3257 // MotionVector Pass
3258 if (layerPrepResult.flags.requiresMotionVectorPass())
3259 activePasses.push_back(&motionVectorMapPass);
3260
3261 // NOTE: When the a screen texture is used, the skybox pass will be called twice. First from
3262 // the screen texture pass and later as part of the normal run through the list.
3263 if (renderer->contextInterface()->rhiContext()->rhi()->isFeatureSupported(QRhi::TexelFetch)) {
3264 if (layer.background == QSSGRenderLayer::Background::SkyBoxCubeMap && layer.skyBoxCubeMap && !disableMainPasses)
3265 activePasses.push_back(&skyboxCubeMapPass);
3266 else if (layer.background == QSSGRenderLayer::Background::SkyBox && layer.lightProbe && !disableMainPasses)
3267 activePasses.push_back(&skyboxPass);
3268 else if (layer.background == QSSGRenderLayer::Background::SkyMaterial && layer.skyMaterial && !disableMainPasses) {
3269 if (layer.skyMaterial->skyboxMode != QSSGRenderSkyMaterial::SkyboxMode::Cubemap)
3270 activePasses.push_back(&skyMaterialBackgroundPass);
3271 else
3272 activePasses.push_back(&skyboxPass);
3273 }
3274 }
3275
3276 if (hasItem2Ds && !disableMainPasses)
3277 activePasses.push_back(&item2DPass);
3278
3279 if (layerPrepResult.flags.requiresScreenTexture())
3280 activePasses.push_back(&reflectionPass);
3281
3282 // Note: Transparent pass includeds opaque objects when layerEnableDepthTest is false.
3283 if ((transparentObjects.size() > 0 || (!layerEnableDepthTest && hasOpaqueObjects)) && !disableMainPasses) {
3284 if (orderIndependentTransparencyEnabled) {
3285 activePasses.push_back(&oitRenderPass);
3286 activePasses.push_back(&oitCompositePass);
3287 oitRenderPass.setMethod(layer.oitMethod);
3288 oitCompositePass.setMethod(layer.oitMethod);
3289 } else {
3290 activePasses.push_back(&transparentPass);
3291 }
3292 }
3293
3294 auto &overlayPass = userPasses[size_t(QSSGRenderLayer::RenderExtensionStage::Overlay)];
3295 if (overlayPass.hasData())
3296 activePasses.push_back(&overlayPass);
3297
3298 if (layer.gridEnabled)
3299 activePasses.push_back(&infiniteGridPass);
3300
3301 if (const auto &dbgDrawSystem = renderer->contextInterface()->debugDrawSystem(); dbgDrawSystem && dbgDrawSystem->isEnabled() && !disableMainPasses)
3302 activePasses.push_back(&debugDrawPass);
3303}
3304
3305template<typename T>
3306static void clearTable(std::vector<T> &entry)
3307{
3308 for (auto &e : entry)
3309 e.clear();
3310}
3311void QSSGLayerRenderData::resolveLayerIblTexture(QSSGPassKey passKey)
3312{
3313 if (layer.skyMaterial) {
3314 // In the ScreenSpace skybox modes the visible background is evaluated directly on
3315 // screen (SkyMaterialBackgroundPass), so the cube is only produced when something
3316 // actually consumes it: image-based lighting, reflection probes, the cube-sampling
3317 // background (Cubemap mode), or a screen-read texture (SkyboxPass draws the cube
3318 // into it for e.g. refraction).
3319 const bool needCube = layer.skyMaterial->enableIBL
3320 || layer.skyMaterial->skyboxMode == QSSGRenderSkyMaterial::SkyboxMode::Cubemap
3321 || reflectionProbesView.size() != 0 || layerPrepResult.flags.requiresScreenTexture();
3322 if (needCube)
3323 skyMaterialTexture = requestSkyMaterialManager()->resolve(layer.skyMaterial, passKey);
3324 else
3325 skyMaterialTexture = {};
3326 }
3327}
3328
3329void QSSGLayerRenderData::resetForFrame()
3330{
3331 for (const auto &pass : activePasses)
3332 pass->resetForFrame();
3333 activePasses.clear();
3334 bakedLightingModels.clear();
3335 layerPrepResult = {};
3336 renderedCameraData.reset();
3337 renderedItem2Ds.clear();
3338 renderedBakedLightingModels.clear();
3339 lightmapTextures.clear();
3340 bonemapTextures.clear();
3341 globalLights.clear();
3342 modelContexts.clear();
3343 features = QSSGShaderFeatures();
3344 skyMaterialTexture = { };
3345 hasDepthWriteObjects = false;
3346 depthPrepassObjectsState = { DepthPrepassObjectStateT(DepthPrepassObject::None) };
3347 zPrePassActive = false;
3348 savedRenderState.reset();
3349 computeLightsUpdated = false;
3350
3351 clearTable(renderableModelStore);
3352 clearTable(modelContextStore);
3353 clearTable(renderableObjectStore);
3354 clearTable(opaqueObjectStore);
3355 clearTable(transparentObjectStore);
3356 clearTable(screenTextureObjectStore);
3357
3358 clearTable(sortedOpaqueObjectCache);
3359 clearTable(sortedTransparentObjectCache);
3360 clearTable(sortedScreenTextureObjectCache);
3361 clearTable(sortedOpaqueDepthPrepassCache);
3362 clearTable(sortedDepthWriteCache);
3363
3364 // Until we have a better solution for extensions...
3365 if (renderablesModifiedByExtension) {
3366 renderableModels.clear();
3367 renderableParticles.clear();
3368 renderableModels.reserve(modelsView.size());
3369 renderableParticles.reserve(particlesView.size());
3370
3371 renderableModels = {modelsView.begin(), modelsView.end()};
3372 renderableParticles = {particlesView.begin(), particlesView.end()};
3373
3374 renderablesModifiedByExtension = false;
3375 }
3376
3377 if (userRenderPassManager)
3378 userRenderPassManager->resetForFrame();
3379}
3380
3381QSSGLayerRenderPreparationResult::QSSGLayerRenderPreparationResult(const QRectF &inViewport, QSSGRenderLayer &inLayer)
3382 : layer(&inLayer)
3383 , m_state(State::DataPrep)
3384{
3385 viewport = inViewport;
3386}
3387
3389{
3390 return viewport.height() >= 2.0f && viewport.width() >= 2.0f;
3391}
3392
3394{
3395 return viewport.size().toSize();
3396}
3397
3398QSSGLayerRenderData::QSSGLayerRenderData(QSSGRenderLayer &inLayer, QSSGRenderer &inRenderer)
3399 : layer(inLayer)
3400 , renderer(&inRenderer)
3401 , orderIndependentTransparencyEnabled(false)
3402 , particlesEnabled(checkParticleSupport(inRenderer.contextInterface()->rhi()))
3403{
3404 depthMapPassMS.setMultisamplingEnabled(true);
3405 Q_ASSERT(extContexts.size() == 1);
3406
3407 // Set-up the world root node and create the data store for the models.
3408 auto *root = layer.rootNode;
3409 nodeData = root->globalNodeData();
3410 modelData = std::make_unique<QSSGRenderModelData>(nodeData);
3411 item2DData = std::make_unique<QSSGRenderItem2DData>(nodeData);
3412
3413 inRenderer.registerItem2DData(*item2DData);
3414}
3415
3416QSSGLayerRenderData::~QSSGLayerRenderData()
3417{
3418 QSSGRhiResourceRegistry *registry = nullptr;
3419 if (const auto &rhiCtx = renderer->contextInterface()->rhiContext())
3420 registry = &QSSGRhiContextPrivate::get(rhiCtx.get())->resourceRegistry();
3421
3422 for (auto &renderResult : renderResults)
3423 renderResult.reset(registry);
3424 oitRenderContext.reset();
3425 computeLightContext.reset();
3426
3427 if (userRenderPassManager)
3428 userRenderPassManager->releaseAll(registry);
3429
3430 // Draw call data for content rendered by this layer is keyed on the pass
3431 // objects owned here; release those entries now so content that outlives
3432 // the layer, e.g. models and materials in a shared import scene, does not
3433 // leave stale entries behind as views come and go.
3434 if (const auto &rhiCtx = renderer->contextInterface()->rhiContext(); rhiCtx && rhiCtx->isValid()) {
3435 auto *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx.get());
3436 const QSSGRenderPass *passes[] = { &shadowMapPass, &reflectionMapPass, &zPrePassPass, &ssaoMapPass,
3437 &depthMapPass, &depthMapPassMS, &skyMaterialPass, &screenMapPass,
3438 &reflectionPass, &item2DPass, &skyboxPass, &skyMaterialBackgroundPass,
3439 &skyboxCubeMapPass, &earlyUserPasses, &userRenderPasses, &opaquePass, &transparentPass,
3440 &oitRenderPass, &oitCompositePass, &infiniteGridPass, &debugDrawPass,
3441 &normalPass, &motionVectorMapPass };
3442 for (const QSSGRenderPass *pass : passes)
3443 rhiCtxD->cleanupDrawCallDataForCid(pass);
3444 for (const auto &userPass : userPasses)
3445 rhiCtxD->cleanupDrawCallDataForCid(&userPass);
3446 rhiCtxD->releaseAutoLodData(&layer);
3447 // Extension-driven renderables are keyed on the owning extension
3448 // combined with the prep context slot (see prepareRenderables()), so
3449 // release those per context as well.
3450 for (const auto &extCtx : extContexts) {
3451 if (extCtx.owner) {
3452 const auto cid = reinterpret_cast<const void *>(quintptr(extCtx.owner) ^ extCtx.slot);
3453 rhiCtxD->cleanupDrawCallDataForCid(cid);
3454 }
3455 }
3456 }
3457
3458 renderer->unregisterItem2DData(*item2DData);
3459}
3460
3461// Instance buffers are passed around as bytes: convert to entries in one place,
3462// clamped to what the buffer can actually hold.
3463static QSpan<const QSSGRenderInstanceTableEntry> instanceEntries(const void *data, qsizetype byteSize, int count)
3464{
3465 const qsizetype available = byteSize / qsizetype(sizeof(QSSGRenderInstanceTableEntry));
3466 return { reinterpret_cast<const QSSGRenderInstanceTableEntry *>(data),
3467 qBound(qsizetype(0), qsizetype(count), available) };
3468}
3469
3471{
3472 return { reinterpret_cast<QSSGRenderInstanceTableEntry *>(data.data()),
3473 data.size() / qsizetype(sizeof(QSSGRenderInstanceTableEntry)) };
3474}
3475
3476// Where the origin of the model is drawn for an instance, in world space. Instances are drawn at
3477//
3478// globalInstanceTransform * tableEntry[i] * localInstanceTransform * vertex
3479//
3480// The local translation is zero unless the model has an instanceRoot. A skinned model is drawn
3481// without the local transform, as its joints place the vertices, so with an instanceRoot it is
3482// drawn off this position by the local translation.
3483static QVector3D instanceWorldPosition(const QSSGRenderInstanceTableEntry &instance,
3484 const QMatrix4x4 &globalInstanceTransform,
3485 const QVector3D &localInstanceTranslation)
3486{
3487 const QVector3D tablePosition(instance.row0.w(), instance.row1.w(), instance.row2.w());
3488 const QVector3D entryTranslation(QVector3D::dotProduct(instance.row0.toVector3D(), localInstanceTranslation),
3489 QVector3D::dotProduct(instance.row1.toVector3D(), localInstanceTranslation),
3490 QVector3D::dotProduct(instance.row2.toVector3D(), localInstanceTranslation));
3491 return globalInstanceTransform.map(tablePosition + entryTranslation);
3492}
3493
3494// Sorts back to front along the camera direction, by where the instances are drawn.
3495static void sortInstances(QSpan<QSSGRenderInstanceTableEntry> sortedInstances, QList<QSSGRhiSortData> &sortData,
3496 QSpan<const QSSGRenderInstanceTableEntry> instances,
3497 const QMatrix4x4 &globalInstanceTransform, const QVector3D &localInstanceTranslation,
3498 const QVector3D &cameraDirection)
3499{
3500 const int count = int(qMin(instances.size(), sortedInstances.size()));
3501 sortData.resize(count);
3502 // create sort data
3503 for (int i = 0; i < count; ++i) {
3504 const QVector3D pos = instanceWorldPosition(instances[i], globalInstanceTransform, localInstanceTranslation);
3505 sortData[i] = {QVector3D::dotProduct(pos, cameraDirection), i};
3506 }
3507
3508 // sort
3509 std::sort(sortData.begin(), sortData.end(), [](const QSSGRhiSortData &a, const QSSGRhiSortData &b){
3510 return a.d > b.d;
3511 });
3512
3513 // copy instances
3514 for (int i = 0; i < count; ++i)
3515 sortedInstances[i] = instances[sortData[i].indexOrOffset];
3516}
3517
3518// The point p transformed by the 3x4 matrix of an instance.
3519static QVector3D instanceMap(const QSSGRenderInstanceTableEntry &instance, const QVector3D &p)
3520{
3521 return { instance.row0.x() * p.x() + instance.row0.y() * p.y() + instance.row0.z() * p.z() + instance.row0.w(),
3522 instance.row1.x() * p.x() + instance.row1.y() * p.y() + instance.row1.z() * p.z() + instance.row1.w(),
3523 instance.row2.x() * p.x() + instance.row2.y() * p.y() + instance.row2.z() * p.z() + instance.row2.w() };
3524}
3525
3526// The columns of the 3x3 rotation and scale part of global * instance * local, the axes of
3527// the mesh as an instance is drawn.
3528static std::array<QVector3D, 3> instanceWorldAxes(const QSSGRenderInstanceTableEntry &instance,
3529 const QSSGRhiInstancePlacement &placement)
3530{
3531 std::array<QVector3D, 3> axes;
3532 for (int i = 0; i < 3; ++i) {
3533 const QVector3D &axis = placement.localAxes[i];
3534 const QVector3D inInstance(instance.row0.x() * axis.x() + instance.row0.y() * axis.y() + instance.row0.z() * axis.z(),
3535 instance.row1.x() * axis.x() + instance.row1.y() * axis.y() + instance.row1.z() * axis.z(),
3536 instance.row2.x() * axis.x() + instance.row2.y() * axis.y() + instance.row2.z() * axis.z());
3537 axes[i] = placement.global.mapVector(inInstance);
3538 }
3539 return axes;
3540}
3541
3542// The square of the largest scale an instance is drawn with, the longest of its axes. Without a
3543// scale in the instance this is the scale of the model.
3544static float instanceWorldScaleSq(const std::array<QVector3D, 3> &axes)
3545{
3546 return qMax(axes[0].lengthSquared(), qMax(axes[1].lengthSquared(), axes[2].lengthSquared()));
3547}
3548
3549// The square of at most how much the transform of an instance stretches a vector, which scales
3550// its bounding sphere. It is never too small, so the sphere always holds the instance. A vector
3551// v of length 1 is mapped to v.x * axes[0] + v.y * axes[1] + v.z * axes[2], whose squared length
3552// is the sum of v[i] * v[j] * dot(axes[i], axes[j]) over all i and j. As |v[i] * v[j]| is at most
3553// (v[i] * v[i] + v[j] * v[j]) / 2, that is at most the largest sum, over one axis, of the
3554// absolute dot products of that axis with all three. With perpendicular axes, the dot products
3555// of different axes are 0, and this is exactly the longest axis squared. A non-uniform scale
3556// under a rotation further up skews the axes, and the result grows with how much.
3557static float instanceWorldStretchSq(const std::array<QVector3D, 3> &axes)
3558{
3559 float result = 0.0f;
3560 for (int i = 0; i < 3; ++i) {
3561 float rowSum = axes[i].lengthSquared();
3562 for (int j = 0; j < 3; ++j) {
3563 if (j != i)
3564 rowSum += std::abs(QVector3D::dotProduct(axes[i], axes[j]));
3565 }
3566 result = qMax(result, rowSum);
3567 }
3568 return result;
3569}
3570
3572 const QSSGSubsetRenderable &renderable)
3573{
3574 const auto &[local, global] = layerData.getInstanceTransforms(renderable.modelContext.model);
3575 const QSSGBounds3 &bounds = renderable.subset.bounds;
3576 QSSGRhiInstancePlacement placement;
3577 placement.global = global;
3578 for (int i = 0; i < 3; ++i)
3579 placement.localAxes[i] = local.column(i).toVector3D();
3580 placement.boundsCenter = local.map(bounds.center());
3581 placement.boundsRadius = bounds.extents().length();
3582 return placement;
3583}
3584
3585// Distributes instances across LOD levels by their distance from the camera.
3586// lodDistancesSq[i] is the squared world-space distance at which LOD level (i+1) activates for an
3587// instance drawn with a scale of 1. The distances grow with the largest scale the instance is
3588// drawn with, as they do for a single model, since what selects the level is the size on screen.
3589// As for a single model, which measures to its bounds, the distance is the depth along the view
3590// direction to the nearest point of the bounding sphere of the instance, 0 when the sphere
3591// reaches the camera plane. With an orthographic camera the distance does not change the size
3592// on screen, and it is 1 there, as for a single model, so the level follows the scale of the
3593// instance and the magnification of the camera, which is in lodDistancesSq.
3594// Index 0 = full detail, 1 = first reduction, etc.
3595// When frustum is non-null, instances whose world-space bounding sphere lies entirely outside the
3596// frustum are left out of all the levels (not drawn at all).
3597// The instances of each level are put in subsetLod.data one level after the other, and their
3598// rows in the table in subsetLod.instanceIndices: sourceInstanceIndices has the row of each of
3599// instances, which are the table itself when it is empty.
3600// levelOfInstance is scratch space.
3601static void distributeInstancesToLods(QSSGRhiInstanceBufferData::SubsetLodData &subsetLod,
3602 QList<quint8> &levelOfInstance,
3603 QSpan<const QSSGRenderInstanceTableEntry> instances,
3604 QSpan<const qint32> sourceInstanceIndices,
3605 const QSSGRhiInstancePlacement &placement,
3606 const QVector3D &cameraPosition,
3607 const QVector3D &cameraDirection,
3608 bool orthographic,
3609 QSpan<const float> lodDistancesSq,
3610 const QSSGClippingFrustum *frustum,
3611 bool tint)
3612{
3613 constexpr int maxLevels = QSSGRhiInstanceBufferData::MaxAutoLodLevels;
3614 const int numLods = int(lodDistancesSq.size()) + 1;
3615 Q_ASSERT(numLods <= maxLevels);
3616
3617 // Do not hold on to the memory of a much larger distribution, such as after the camera
3618 // moved away from a part of the table, or of a much larger table. Arrays less than twice
3619 // what they need, plus 4096 elements, at most 16 KiB here, are kept, so that the arrays of
3620 // small tables are not reallocated whenever the instances in view change.
3621 const auto resizeScratch = [](auto &array, qsizetype size) {
3622 const bool shrink = array.capacity() > 2 * size + 4096;
3623 array.resize(size);
3624 if (shrink)
3625 array.squeeze();
3626 };
3627
3628 // First find the level of each instance, so that the data is allocated for the number of
3629 // instances in view, and each level starts where the previous one ends.
3630 constexpr quint8 culled = 0xFF;
3631 const qsizetype count = instances.size();
3632 // The instances in a range keep their rows in sourceInstanceIndices, while the table itself is
3633 // in the order of its rows.
3634 const bool ranged = !sourceInstanceIndices.isEmpty();
3635 Q_ASSERT(!ranged || sourceInstanceIndices.size() >= count);
3636 resizeScratch(levelOfInstance, count);
3637 std::array<qsizetype, maxLevels> levelCounts {};
3638
3639 for (qsizetype instanceIndex = 0; instanceIndex < count; ++instanceIndex) {
3640 const QSSGRenderInstanceTableEntry &instance = instances[instanceIndex];
3641 const std::array<QVector3D, 3> axes = instanceWorldAxes(instance, placement);
3642 const QVector3D center = placement.global.map(instanceMap(instance, placement.boundsCenter));
3643 const float radius = std::sqrt(instanceWorldStretchSq(axes)) * placement.boundsRadius;
3644
3645 // Leaves out the instance when its bounding sphere is entirely outside one of the
3646 // planes of the frustum: intersectsWith() accepts a point down to -radius behind each.
3647 if (frustum && !frustum->intersectsWith(center, -radius)) {
3648 levelOfInstance[instanceIndex] = culled;
3649 continue;
3650 }
3651
3652 float distSq = 1.0f;
3653 if (!orthographic) {
3654 const QVector3D toCenter = center - cameraPosition;
3655 const float depth = std::abs(QVector3D::dotProduct(toCenter, cameraDirection));
3656 const float distance = qMax(0.0f, depth - radius);
3657 distSq = distance * distance;
3658 }
3659 const float scaleSq = instanceWorldScaleSq(axes);
3660
3661 // The first level whose distance is not reached ends the search, as for a
3662 // single model.
3663 int lod = 0;
3664 for (int l = 0; l < lodDistancesSq.size(); ++l) {
3665 if (distSq < lodDistancesSq[l] * scaleSq)
3666 break;
3667 lod = l + 1;
3668 }
3669
3670 levelOfInstance[instanceIndex] = quint8(lod);
3671 ++levelCounts[lod];
3672 }
3673
3674 std::array<qsizetype, maxLevels> nextInstance {};
3675 qsizetype total = 0;
3676 subsetLod.counts = {};
3677 for (int l = 0; l < numLods; ++l) {
3678 nextInstance[l] = total;
3679 total += levelCounts[l];
3680 subsetLod.counts[l] = int(levelCounts[l]);
3681 }
3682 subsetLod.levelCount = numLods;
3683
3684 resizeScratch(subsetLod.data, total * qsizetype(sizeof(QSSGRenderInstanceTableEntry)));
3685 resizeScratch(subsetLod.instanceIndices, total);
3686 auto *dest = reinterpret_cast<QSSGRenderInstanceTableEntry *>(subsetLod.data.data());
3687 for (qsizetype instanceIndex = 0; instanceIndex < count; ++instanceIndex) {
3688 const quint8 level = levelOfInstance[instanceIndex];
3689 if (level == culled)
3690 continue;
3691 const qsizetype next = nextInstance[level]++;
3692 dest[next] = instances[instanceIndex];
3693 if (tint) {
3694 const QVector4D c = QSSGUtils::color::sRGBToLinear(QSSGDebugDrawSystem::levelOfDetailColor(quint32(level)));
3695 dest[next].color = QVector4D(c.toVector3D(), instances[instanceIndex].color.w());
3696 }
3697 subsetLod.instanceIndices[next] = ranged ? sourceInstanceIndices[instanceIndex]
3698 : qint32(instanceIndex);
3699 }
3700 ++subsetLod.generation;
3701 subsetLod.instanceIndicesDirty = true;
3702}
3703
3704// Keeps the instances whose distance from the camera to where they are drawn is in
3705// [minThreshold, maxThreshold); a negative threshold is no limit. The kept instances of the
3706// table, or of its depth sorted copy, go to instanceData.lodData, and their rows in the table to
3707// instanceData.lodInstanceIndices.
3708static int cullLodInstances(QSSGRhiInstanceBufferData &instanceData,
3709 const QSSGRenderInstanceTable &table,
3710 const QMatrix4x4 &globalInstanceTransform,
3711 const QVector3D &localInstanceTranslation,
3712 const QVector3D &cameraPosition, float minThreshold, float maxThreshold)
3713{
3714 // Either the depth sorted copy or the table itself, both with count() entries.
3715 const bool sorted = table.isDepthSortingEnabled();
3716 const auto instances = sorted
3717 ? instanceEntries(instanceData.sortedData.constData(), instanceData.sortedData.size(), table.count())
3718 : instanceEntries(table.constData(), table.dataSize(), table.count());
3719 instanceData.lodData.resize(table.dataSize());
3720 const auto lodInstances = instanceEntries(instanceData.lodData);
3721 QList<qint32> &lodInstanceIndices = instanceData.lodInstanceIndices;
3722
3723 const qsizetype count = qMin(instances.size(), lodInstances.size());
3724 // A negative threshold is unset, so it must not be squared.
3725 const float minDistanceSq = minThreshold >= 0.0f ? minThreshold * minThreshold : 0.0f;
3726 const float maxDistanceSq = maxThreshold >= 0.0f ? maxThreshold * maxThreshold : std::numeric_limits<float>::infinity();
3727
3728 // The depth sorted copy keeps the row of each of its instances in sortData, while the table
3729 // itself is in the order of its rows.
3730 Q_ASSERT(!sorted || instanceData.sortData.size() >= count);
3731 lodInstanceIndices.resize(count);
3732 int realSize = 0;
3733 for (qsizetype i = 0; i < count; ++i) {
3734 const QSSGRenderInstanceTableEntry &instance = instances[i];
3735 const QVector3D position = instanceWorldPosition(instance, globalInstanceTransform, localInstanceTranslation);
3736 const float distanceSq = (cameraPosition - position).lengthSquared();
3737 if (distanceSq >= minDistanceSq && distanceSq < maxDistanceSq) {
3738 lodInstanceIndices[realSize] = sorted ? instanceData.sortData[i].indexOrOffset : qint32(i);
3739 lodInstances[realSize++] = instance;
3740 }
3741 }
3742 lodInstanceIndices.resize(realSize);
3743
3744 return realSize;
3745}
3746
3747// Whether the shaders of the material read INSTANCE_INDEX, which gives every pipeline of the
3748// material the qt_instanceIndex input, see QSSGMaterialVertexPipeline::beginVertexGeneration().
3749// The buffer of the rows is created for the material rather than for the shaders of a pass, as
3750// prepareInstancing() prepares the instances once per frame for all the passes. Each pipeline
3751// takes the input from its own shaders, which therefore agree, see bindInstanceIndices().
3752static bool usesInstanceIndex(const QSSGRenderGraphObject &material)
3753{
3754 return material.type == QSSGRenderGraphObject::Type::CustomMaterial
3755 && static_cast<const QSSGRenderCustomMaterial &>(material).m_renderFlags.testFlag(
3756 QSSGRenderCustomMaterial::RenderFlag::InstanceIndex);
3757}
3758
3759// INSTANCE_INDEX is the row of an instance in the instance table. The buffer prepareInstancing()
3760// uploads holds the instances in a different order, or only some of them, when the table is depth
3761// sorted or the model has an instancingLodMin or instancingLodMax range, so the instance number
3762// of the draw call, gl_InstanceIndex, is not that row. The shaders that read INSTANCE_INDEX get
3763// it from this buffer, with the row of each instance in the buffer: the qt_instanceIndex input,
3764// see bakeVertexInputLocations(). Returns the buffer, or null when it cannot be created.
3765static QRhiBuffer *prepareInstanceIndices(QSSGRhiContext *rhiCtx,
3766 QSSGRhiInstanceBufferData &instanceData,
3767 const QSSGRenderInstanceTable &table, bool usesLod)
3768{
3769 const bool sorted = table.isDepthSortingEnabled();
3770 const qsizetype count = usesLod ? instanceData.lodInstanceIndices.size()
3771 : (sorted ? instanceData.sortData.size()
3772 : qsizetype(table.count()));
3773 // A QRhiBuffer cannot be empty, so there is room for one index when no instance is drawn.
3774 const quint32 size = quint32(qMax(count, 1) * sizeof(qint32));
3775 bool update = instanceData.instanceIndicesDirty;
3776 if (!instanceData.instanceIndexBuffer || instanceData.instanceIndexBuffer->size() < size) {
3777 if (!instanceData.instanceIndexBuffer) {
3778 instanceData.instanceIndexBuffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic,
3779 QRhiBuffer::VertexBuffer,
3780 size);
3781 } else {
3782 instanceData.instanceIndexBuffer->setSize(size);
3783 }
3784 if (!instanceData.instanceIndexBuffer->create()) {
3785 qWarning("Failed to create the buffer of the instance table rows for INSTANCE_INDEX");
3786 delete instanceData.instanceIndexBuffer;
3787 instanceData.instanceIndexBuffer = nullptr;
3788 return nullptr;
3789 }
3790 update = true;
3791 }
3792 if (update && count > 0) {
3793 QByteArray indices(count * qsizetype(sizeof(qint32)), Qt::Uninitialized);
3794 auto *dest = reinterpret_cast<qint32 *>(indices.data());
3795 if (usesLod) {
3796 std::copy(instanceData.lodInstanceIndices.cbegin(),
3797 instanceData.lodInstanceIndices.cend(), dest);
3798 } else if (sorted) {
3799 std::transform(instanceData.sortData.cbegin(), instanceData.sortData.cend(), dest,
3800 [](const QSSGRhiSortData &s) { return qint32(s.indexOrOffset); });
3801 } else {
3802 std::iota(dest, dest + count, qint32(0));
3803 }
3804 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
3805 rub->updateDynamicBuffer(instanceData.instanceIndexBuffer, 0, quint32(indices.size()),
3806 indices.constData());
3807 rhiCtx->commandBuffer()->resourceUpdate(rub);
3808 }
3809 instanceData.instanceIndicesDirty = false;
3810 return instanceData.instanceIndexBuffer;
3811}
3812
3813bool QSSGLayerRenderData::prepareInstancing(QSSGRhiContext *rhiCtx,
3814 QSSGSubsetRenderable *renderable,
3815 const QVector3D &cameraDirection,
3816 const QVector3D &cameraPosition,
3817 float minThreshold,
3818 float maxThreshold,
3819 const QSSGLayerRenderData &layerData)
3820{
3821 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
3822 auto &modelContext = renderable->modelContext;
3823 auto &instanceBuffer = renderable->instanceBuffer; // intentional ref2ptr
3824 if (!modelContext.model.usesInstanceBuffer() || instanceBuffer)
3825 return instanceBuffer;
3826 const InstanceTransforms instanceTransforms = layerData.getInstanceTransforms(modelContext.model);
3827 auto *table = modelContext.model.instanceTable;
3828 bool usesLod = minThreshold >= 0 || maxThreshold >= 0;
3829 // Drop the count of an earlier LOD range, or instanceCount() is invalid.
3830 if (!usesLod)
3831 modelContext.model.instanceLodCount = -1;
3832 // Culled or sorted data depends on the transform of the model, so it cannot be shared
3833 // with the other models that use the same table.
3834 const bool perModel = usesLod || table->isDepthSortingEnabled();
3835 if (!perModel)
3836 rhiCtxD->releaseModelInstanceCopy(&modelContext.model);
3837 QSSGRhiInstanceBufferData &instanceData(perModel ? rhiCtxD->instanceBufferData(&modelContext.model) : rhiCtxD->instanceBufferData(table));
3838 quint32 instanceBufferSize = table->dataSize();
3839 // Create or resize the instance buffer ### if (instanceData.owned)
3840 bool sortingChanged = table->isDepthSortingEnabled() != instanceData.sorting;
3841 bool cameraDirectionChanged = !qFuzzyCompare(instanceData.sortedCameraDirection, cameraDirection);
3842 bool cameraPositionChanged = !qFuzzyCompare(instanceData.cameraPosition, cameraPosition);
3843 const QMatrix4x4 &globalInstanceTransform = instanceTransforms.global;
3844 // Where the origin of the model is within each instance, see instanceWorldPosition().
3845 const QVector3D localInstanceTranslation = instanceTransforms.local.column(3).toVector3D();
3846 // The distances and the depth order change when the model or its parent moves while
3847 // the camera stands still.
3848 bool transformChanged = instanceData.globalInstanceTransform != globalInstanceTransform
3849 || instanceData.localInstanceTranslation != localInstanceTranslation;
3850 bool updateInstanceBuffer = table != instanceData.table
3851 || table->generation() != instanceData.tableGeneration
3852 || sortingChanged
3853 || ((cameraDirectionChanged || transformChanged) && table->isDepthSortingEnabled());
3854 bool instanceBufferSizeChanged = instanceData.buffer && instanceBufferSize != instanceData.buffer->size();
3855 // The culled data also changes when the range itself does. Only the copy of a model holds
3856 // culled data: the models that share a table can each leave the range unset with a
3857 // different negative value, and must not upload the table again for each other.
3858 bool rangeChanged = perModel && (instanceData.lodMin != minThreshold || instanceData.lodMax != maxThreshold);
3859 bool updateForLod = (cameraPositionChanged || instanceBufferSizeChanged || transformChanged || rangeChanged) && usesLod;
3860 // A depth sorted copy of the model holds only the culled instances when the range is removed.
3861 if (rangeChanged && !usesLod)
3862 updateInstanceBuffer = true;
3863 // A range set again after it was unset, which dropped the count, while the copy kept the
3864 // instances it was culled with.
3865 if (usesLod && modelContext.model.instanceLodCount < 0)
3866 updateForLod = true;
3867 if (sortingChanged && !table->isDepthSortingEnabled()) {
3868 instanceData.sortedData.clear();
3869 instanceData.sortData.clear();
3870 instanceData.sortedCameraDirection = {};
3871 }
3872 instanceData.sorting = table->isDepthSortingEnabled();
3873 if (instanceData.buffer && instanceData.buffer->size() < instanceBufferSize) {
3874 updateInstanceBuffer = true;
3875 // qDebug() << "Resizing instance buffer";
3876 instanceData.buffer->setSize(instanceBufferSize);
3877 instanceData.buffer->create();
3878 }
3879 if (!instanceData.buffer) {
3880 // qDebug() << "Creating instance buffer";
3881 updateInstanceBuffer = true;
3882 instanceData.buffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::VertexBuffer, instanceBufferSize);
3883 instanceData.buffer->create();
3884 }
3885 // Redo the culling on every full upload, also the first, when the camera can be at the
3886 // stored position, which starts out as the origin.
3887 if (updateInstanceBuffer && usesLod)
3888 updateForLod = true;
3889 if (updateInstanceBuffer || updateForLod) {
3890 Q_ASSERT(table->stride() == sizeof(QSSGRenderInstanceTableEntry));
3891 const void *data = nullptr;
3892 if (table->isDepthSortingEnabled()) {
3893 if (updateInstanceBuffer) {
3894 instanceData.sortedData.resize(table->dataSize());
3895 sortInstances(instanceEntries(instanceData.sortedData),
3896 instanceData.sortData,
3897 instanceEntries(table->constData(), table->dataSize(), table->count()),
3898 globalInstanceTransform,
3899 localInstanceTranslation,
3900 cameraDirection);
3901 }
3902 data = instanceData.sortedData.constData();
3903 instanceData.sortedCameraDirection = cameraDirection;
3904 } else {
3905 data = table->constData();
3906 }
3907 if (data) {
3908 if (updateForLod) {
3909 modelContext.model.instanceLodCount = cullLodInstances(instanceData,
3910 *table,
3911 globalInstanceTransform,
3912 localInstanceTranslation,
3913 cameraPosition,
3914 minThreshold,
3915 maxThreshold);
3916 data = instanceData.lodData.constData();
3917
3918 // Force clear the buffer to upload empty instance data.
3919 // If this step is skipped, the updateDynamicBuffer function will load data for all instances.
3920 if (!modelContext.model.instanceLodCount)
3921 instanceData.lodData.clear();
3922
3923 instanceBufferSize = modelContext.model.instanceLodCount * sizeof(QSSGRenderInstanceTableEntry);
3924 }
3925
3926 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
3927 rub->updateDynamicBuffer(instanceData.buffer, 0, instanceBufferSize, data);
3928 rhiCtx->commandBuffer()->resourceUpdate(rub);
3929 //qDebug() << "****** UPDATING INST BUFFER. Size" << instanceBufferSize;
3930 } else {
3931 qWarning() << "NO DATA IN INSTANCE TABLE";
3932 }
3933 // The rows for INSTANCE_INDEX follow the data, see prepareInstanceIndices(), and so do
3934 // the levels of the automatic per-instance LOD, see prepareAutoLodInstancing().
3935 instanceData.instanceIndicesDirty = true;
3936 ++instanceData.generation;
3937 if (!usesLod)
3938 instanceData.lodInstanceIndices.clear();
3939 instanceData.table = table;
3940 instanceData.tableGeneration = table->generation();
3941 instanceData.cameraPosition = cameraPosition;
3942 instanceData.globalInstanceTransform = globalInstanceTransform;
3943 instanceData.localInstanceTranslation = localInstanceTranslation;
3944 instanceData.lodMin = minThreshold;
3945 instanceData.lodMax = maxThreshold;
3946 }
3947 instanceBuffer = instanceData.buffer;
3948 if (instanceBuffer && usesInstanceIndex(renderable->material))
3949 renderable->instanceIndexBuffer = prepareInstanceIndices(rhiCtx, instanceData, *table,
3950 usesLod);
3951 return instanceBuffer;
3952}
3953
3954// The rows in the instance table of the instances of the levels set up by
3955// prepareAutoLodInstancing(), for the shaders that read INSTANCE_INDEX, as prepareInstanceIndices()
3956// does for the instance buffer of the model. The draw call of each level binds them from the
3957// first instance of the level, see RenderHelpers::rhiDrawAutoLodInstanced(). Returns the buffer,
3958// or null when it cannot be created.
3959static QRhiBuffer *prepareAutoLodInstanceIndices(QSSGRhiContext *rhiCtx,
3960 QSSGRhiInstanceBufferData::SubsetLodData &subsetLod)
3961{
3962 // As many rows as the buffer of the levels has room for instances, so that it is resized
3963 // with that one.
3964 const quint32 size = subsetLod.buffer->size() / quint32(sizeof(QSSGRenderInstanceTableEntry))
3965 * quint32(sizeof(qint32));
3966 bool update = subsetLod.instanceIndicesDirty;
3967 if (!subsetLod.instanceIndexBuffer || subsetLod.instanceIndexBuffer->size() != size) {
3968 if (!subsetLod.instanceIndexBuffer) {
3969 subsetLod.instanceIndexBuffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic,
3970 QRhiBuffer::VertexBuffer, size);
3971 } else {
3972 subsetLod.instanceIndexBuffer->setSize(size);
3973 }
3974 if (!subsetLod.instanceIndexBuffer->create()) {
3975 qWarning("Failed to create the buffer of the instance table rows for INSTANCE_INDEX");
3976 delete subsetLod.instanceIndexBuffer;
3977 subsetLod.instanceIndexBuffer = nullptr;
3978 return nullptr;
3979 }
3980 update = true;
3981 }
3982 if (update && !subsetLod.instanceIndices.isEmpty()) {
3983 const quint32 indicesSize = quint32(subsetLod.instanceIndices.size() * sizeof(qint32));
3984 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
3985 rub->updateDynamicBuffer(subsetLod.instanceIndexBuffer, 0, indicesSize,
3986 subsetLod.instanceIndices.constData());
3987 rhiCtx->commandBuffer()->resourceUpdate(rub);
3988 }
3989 subsetLod.instanceIndicesDirty = false;
3990 return subsetLod.instanceIndexBuffer;
3991}
3992
3993void QSSGLayerRenderData::prepareAutoLodInstancing(QSSGRhiContext *rhiCtx,
3994 QSSGSubsetRenderable *renderable,
3995 const QSSGLayerRenderData &layerData)
3996{
3997 QSSGRhiContextPrivate *rhiCtxD = QSSGRhiContextPrivate::get(rhiCtx);
3998 auto &modelContext = renderable->modelContext;
3999 if (!modelContext.model.instancing() || !renderable->usesAutoLod)
4000 return;
4001
4002 auto *table = modelContext.model.instanceTable;
4003 const QSSGRenderCameraDataList &cameraDatas = *layerData.renderedCameraData;
4004 const QVector3D &cameraPosition = cameraDatas[0].position;
4005 const QVector3D cameraDirection = cameraDatas[0].direction.normalized();
4006 const bool orthographic = layerData.renderedCameras[0]->type == QSSGRenderGraphObject::Type::OrthographicCamera;
4007 // The instances are culled by the frustum of the camera when it has frustumCullingEnabled
4008 // set. Not with multiview, where they are drawn once for all the cameras.
4009 const QSSGClippingFrustum *frustum = (cameraDatas.size() == 1 && cameraDatas[0].clippingFrustum.has_value())
4010 ? &cameraDatas[0].clippingFrustum.value()
4011 : nullptr;
4012
4013 QSSGRhiInstanceBufferData &instanceData = rhiCtxD->instanceBufferData(&modelContext.model);
4014 QSSGRhiInstanceBufferData::SubsetLodData &subsetLod = instanceData.subsetLodData[{ &renderable->subset, &layerData.layer }];
4015 // With instancingLodMin or instancingLodMax set, prepareInstancing() keeps the instances in
4016 // that range of distances from the camera in the entry of the model, and the levels are
4017 // selected among those. Otherwise the model draws the table itself. The table is not depth
4018 // sorted, see usesAutoInstanceLod().
4019 const bool ranged = renderable->instancingLodMin >= 0.0f || renderable->instancingLodMax >= 0.0f;
4020
4021 const QSSGRhiInstancePlacement placement = instancePlacement(layerData, *renderable);
4022 const bool projectionChanged = subsetLod.orthographic != orthographic;
4023 // With frustum culling, the view projection decides which instances are drawn, so any
4024 // change of it selects the levels again, also for an orthographic camera.
4025 const bool cullingChanged = subsetLod.culled != (frustum != nullptr);
4026 const bool vpChanged = frustum && subsetLod.cameraViewProjection != cameraDatas[0].viewProjection;
4027 const bool tableChanged = table != subsetLod.table || table->generation() != subsetLod.tableGeneration;
4028 const int expectedLevels = renderable->autoLodLevelCount;
4029 const bool levelsChanged = subsetLod.levelCount != expectedLevels;
4030 // The squared distances at which the levels switch for an instance drawn with a scale of 1.
4031 // The distances themselves are compared, rather than their inputs, since a new mesh can
4032 // replace the subset with different distances.
4033 decltype(subsetLod.lodDistancesSq) lodDistancesSq;
4034 const auto &lods = renderable->subset.lods;
4035 const int numSwitches = qMin(int(lods.size()), expectedLevels - 1);
4036 for (int i = 0; i < numSwitches; ++i) {
4037 const float d = lods[i].distance * renderable->autoLodThresholdFactor;
4038 lodDistancesSq.push_back(d * d);
4039 }
4040 const bool distancesChanged = subsetLod.lodDistancesSq != lodDistancesSq;
4041 const bool placementChanged = subsetLod.placement != placement;
4042 // The copy in instanceData that the levels are built from was rebuilt, see
4043 // prepareInstancing(): the camera or the model moved, or the range or the table changed.
4044 const bool sourceChanged = subsetLod.sourceGeneration != instanceData.generation;
4045 // With a perspective camera the level follows the depth of each instance, so the levels are
4046 // selected again when the camera moves or turns, as prepareInstancing() does for a range.
4047 const bool cameraMoved = !orthographic
4048 && (!qFuzzyCompare(subsetLod.cameraPosition, cameraPosition)
4049 || !qFuzzyCompare(subsetLod.cameraDirection, cameraDirection));
4050 const bool tintChanged = subsetLod.tinted != renderable->autoLodTint;
4051
4052 if (cameraMoved || projectionChanged || cullingChanged || vpChanged || tableChanged || levelsChanged
4053 || distancesChanged || placementChanged || sourceChanged || tintChanged || !subsetLod.valid) {
4054 const auto sourceInstances = ranged
4055 ? instanceEntries(instanceData.lodData.constData(), instanceData.lodData.size(), modelContext.model.instanceLodCount)
4056 : instanceEntries(table->constData(), table->dataSize(), table->count());
4057
4058 // The rows in the table of the source instances, for INSTANCE_INDEX.
4059 const QSpan<const qint32> sourceInstanceIndices = ranged ? QSpan<const qint32>(instanceData.lodInstanceIndices) : QSpan<const qint32>();
4060 distributeInstancesToLods(subsetLod, rhiCtxD->m_autoLodLevelOfInstance, sourceInstances, sourceInstanceIndices, placement,
4061 cameraPosition, cameraDirection, orthographic, lodDistancesSq, frustum,
4062 renderable->autoLodTint);
4063
4064 // One buffer holds all the levels. The instances in view change as the camera moves, so
4065 // it grows with room to spare, up to the size of all the source instances, and only
4066 // shrinks when it is much larger than needed. It is never empty, as a QRhiBuffer cannot be.
4067 constexpr quint32 entrySize = sizeof(QSSGRenderInstanceTableEntry);
4068 const quint32 dataSize = quint32(subsetLod.data.size());
4069 const quint32 needed = qMax(dataSize, entrySize);
4070 const quint32 sourceSize = qMax(quint32(sourceInstances.size()) * entrySize, needed);
4071 const quint32 currentSize = subsetLod.buffer ? subsetLod.buffer->size() : 0;
4072 if (currentSize < needed || currentSize > 4 * needed + 65536) {
4073 const quint32 bufferSize = qMin(needed + needed / 2, sourceSize);
4074 if (!subsetLod.buffer)
4075 subsetLod.buffer = rhiCtx->rhi()->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::VertexBuffer, bufferSize);
4076 else
4077 subsetLod.buffer->setSize(bufferSize);
4078 if (!subsetLod.buffer->create()) {
4079 qWarning("Failed to create the instance buffer of the automatic level of detail");
4080 // Draw none of the instances rather than from a buffer without memory, and try
4081 // again in the next frame.
4082 delete subsetLod.buffer;
4083 subsetLod.buffer = nullptr;
4084 subsetLod.valid = false;
4085 renderable->autoLodBuffer = nullptr;
4086 renderable->autoLodInstanceCounts = {};
4087 return;
4088 }
4089 }
4090 if (dataSize > 0) {
4091 QRhiResourceUpdateBatch *rub = rhiCtx->rhi()->nextResourceUpdateBatch();
4092 rub->updateDynamicBuffer(subsetLod.buffer, 0, dataSize, subsetLod.data.constData());
4093 rhiCtx->commandBuffer()->resourceUpdate(rub);
4094 }
4095
4096 subsetLod.cameraPosition = cameraPosition;
4097 subsetLod.cameraDirection = cameraDirection;
4098 subsetLod.cameraViewProjection = frustum ? cameraDatas[0].viewProjection : QMatrix4x4{};
4099 subsetLod.culled = frustum != nullptr;
4100 subsetLod.orthographic = orthographic;
4101 subsetLod.table = table;
4102 subsetLod.tableGeneration = table->generation();
4103 subsetLod.lodDistancesSq = lodDistancesSq;
4104 subsetLod.sourceGeneration = instanceData.generation;
4105 subsetLod.placement = placement;
4106 subsetLod.tinted = renderable->autoLodTint;
4107 subsetLod.valid = true;
4108 }
4109
4110 // The buffer and the counts for the draw calls.
4111 renderable->autoLodBuffer = subsetLod.buffer;
4112 renderable->autoLodInstanceCounts = subsetLod.counts;
4113 if (usesInstanceIndex(renderable->material))
4114 renderable->autoLodInstanceIndexBuffer = prepareAutoLodInstanceIndices(rhiCtx, subsetLod);
4115}
4116
4117QSSGFrameData &QSSGLayerRenderData::getFrameData()
4118{
4119 return frameData;
4120}
4121
4122void QSSGLayerRenderData::initializeLightmapBaking(QSSGLightmapBaker::Context &ctx)
4123{
4124 ctx.callbacks.modelsToBake = [this]() { return getSortedBakedLightingModels(); };
4125
4126 lightmapBaker = std::make_unique<QSSGLightmapBaker>(ctx);
4127}
4128
4129void QSSGLayerRenderData::maybeProcessLightmapBaking()
4130{
4131 if (lightmapBaker) {
4132 const QSSGLightmapBaker::Status status = lightmapBaker->process();
4133 if (status == QSSGLightmapBaker::Status::Finished)
4134 lightmapBaker.reset();
4135 }
4136}
4137
4138QSSGRenderGraphObject *QSSGLayerRenderData::getCamera(QSSGCameraId id) const
4139{
4140 QSSGRenderGraphObject *ret = nullptr;
4141 if (auto res = reinterpret_cast<QSSGRenderGraphObject *>(id))
4142 ret = res;
4143
4144 return ret;
4145}
4146
4147QSSGRenderCameraData QSSGLayerRenderData::getCameraRenderData(const QSSGRenderCamera *camera_)
4148{
4149 if ((!camera_ || camera_ == renderedCameras[0]) && renderedCameraData.has_value())
4150 return renderedCameraData.value()[0];
4151 if (camera_)
4152 return getCameraDataImpl(camera_);
4153 return {};
4154}
4155
4156QSSGRenderCameraData QSSGLayerRenderData::getCameraRenderData(const QSSGRenderCamera *camera_) const
4157{
4158 if ((!camera_ || camera_ == renderedCameras[0]) && renderedCameraData.has_value())
4159 return renderedCameraData.value()[0];
4160 if (camera_)
4161 return getCameraDataImpl(camera_);
4162 return {};
4163}
4164
4165QSSGRenderContextInterface *QSSGLayerRenderData::contextInterface() const
4166{
4167 return renderer ? renderer->contextInterface() : nullptr;
4168}
4169
4170QSSGLayerRenderData::GlobalRenderProperties QSSGLayerRenderData::globalRenderProperties(const QSSGRenderContextInterface &ctx)
4171{
4172 GlobalRenderProperties props {};
4173 if (const auto &rhiCtx = ctx.rhiContext(); rhiCtx->isValid()) {
4174 QRhi *rhi = rhiCtx->rhi();
4175 props.isYUpInFramebuffer = rhi->isYUpInFramebuffer();
4176 props.isYUpInNDC = rhi->isYUpInNDC();
4177 props.isClipDepthZeroToOne = rhi->isClipDepthZeroToOne();
4178 }
4179
4180 return props;
4181}
4182
4183const QSSGRenderShadowMapPtr &QSSGLayerRenderData::requestShadowMapManager()
4184{
4185 if (!shadowMapManager && QSSG_GUARD(renderer && renderer->contextInterface()))
4186 shadowMapManager.reset(new QSSGRenderShadowMap(*renderer->contextInterface()));
4187 return shadowMapManager;
4188}
4189
4190const QSSGRenderReflectionMapPtr &QSSGLayerRenderData::requestReflectionMapManager()
4191{
4192 if (!reflectionMapManager && QSSG_GUARD(renderer && renderer->contextInterface()))
4193 reflectionMapManager.reset(new QSSGRenderReflectionMap(*renderer->contextInterface()));
4194 return reflectionMapManager;
4195}
4196
4197const QSSGRenderSkyMaterialManagerPtr &QSSGLayerRenderData::requestSkyMaterialManager()
4198{
4199 if (!skyMaterialManager && QSSG_GUARD(renderer && renderer->contextInterface()))
4200 skyMaterialManager.reset(new QSSGRenderSkyMaterialManager(*renderer->contextInterface()));
4201 return skyMaterialManager;
4202}
4203
4204const QSSGUserRenderPassManagerPtr &QSSGLayerRenderData::requestUserRenderPassManager()
4205{
4206 if (!userRenderPassManager) {
4207 userRenderPassManager = QSSGUserRenderPassManager::create();
4208 renderer->contextInterface()->bufferManager()->registerUserRenderPassManager(userRenderPassManager);
4209 }
4210 return userRenderPassManager;
4211}
4212
4213const QSSGRenderMotionVectorMapPtr &QSSGLayerRenderData::requestMotionVectorMapManager()
4214{
4215 if (!motionVectorMapManager && QSSG_GUARD(renderer && renderer->contextInterface()))
4216 motionVectorMapManager.reset(new QSSGRenderMotionVectorMap(*renderer->contextInterface()));
4217 return motionVectorMapManager;
4218}
4219
4220QT_END_NAMESPACE
QSSGLayerRenderPreparationResult(const QRectF &inViewport, QSSGRenderLayer &inLayer)
QSSGRenderableObjectFlags renderableFlags
friend class QSSGRenderContextInterface
Combined button and popup list for selecting options.
#define POS4BONETRANS(x)
#define POS4BONENORM(x)
static constexpr size_t getPrepContextIndex(QSSGPrepContextId id)
static bool scopeLight(QSSGRenderNode *node, QSSGRenderNode *lightScope)
static QSSGRhiInstancePlacement instancePlacement(const QSSGLayerRenderData &layerData, const QSSGSubsetRenderable &renderable)
static constexpr bool furthestToNearestCompare(const QSSGRenderableObjectHandle &lhs, const QSSGRenderableObjectHandle &rhs) noexcept
static int effectiveMaxDirectionalLightCount(const QSSGShaderFeatures &features)
static QRhiBuffer * prepareInstanceIndices(QSSGRhiContext *rhiCtx, QSSGRhiInstanceBufferData &instanceData, const QSSGRenderInstanceTable &table, bool usesLod)
static constexpr bool verifyPrepContext(QSSGPrepContextId id, const QSSGRenderer &renderer)
static void warnMissingPosition()
#define MAX_MORPH_TARGET_INDEX_SUPPORTS_NORMALS
static float instanceWorldScaleSq(const std::array< QVector3D, 3 > &axes)
static QVector3D instanceWorldPosition(const QSSGRenderInstanceTableEntry &instance, const QMatrix4x4 &globalInstanceTransform, const QVector3D &localInstanceTranslation)
static bool isObjectCullable(const QSSGClippingFrustum &clipFrustum, const QSSGRenderableObject &obj)
static void clearTable(std::vector< T > &entry)
static constexpr quint16 PREP_CTX_INDEX_MASK
static QVector3D instanceMap(const QSSGRenderInstanceTableEntry &instance, const QVector3D &p)
static void prepareIndirectDraw(QSSGRenderContextInterface &contextInterface, QSSGLayerRenderData &data, const QSSGRenderGeometry &geometry, QSSGSubsetRenderable &renderable)
#define MAX_MORPH_TARGET_INDEX_SUPPORTS_TANGENTS
static bool usesAutoInstanceLod(const QSSGRenderModel &model, const QSSGRenderSubset &subset, float lodThreshold)
static void updateDirtySkeletons(const QSSGLayerRenderData &renderData, const QSSGLayerRenderData::QSSGModelsView &renderableNodes)
static QSpan< QSSGRenderInstanceTableEntry > instanceEntries(QByteArray &data)
static bool hasCustomBlendMode(const QSSGRenderCustomMaterial &material)
static QSpan< const QSSGRenderInstanceTableEntry > instanceEntries(const void *data, qsizetype byteSize, int count)
static const int REDUCED_MAX_LIGHT_COUNT_THRESHOLD_BYTES
static bool checkParticleSupport(QRhi *rhi)
#define BONEDATASIZE4ID(x)
static void collectBoneTransforms(const QSSGLayerRenderData &renderData, QSSGRenderNode *node, QSSGRenderSkeleton *skeletonNode, const QVector< QMatrix4x4 > &poses)
#define CHECK_IMAGE_AND_PREPARE(img, imgtype, shadercomponent)
static constexpr bool nearestToFurthestCompare(const QSSGRenderableObjectHandle &lhs, const QSSGRenderableObjectHandle &rhs) noexcept
static constexpr size_t pipelineStateIndex(QSSGRenderablesFilter filter)
static void sortInstances(QSpan< QSSGRenderInstanceTableEntry > sortedInstances, QList< QSSGRhiSortData > &sortData, QSpan< const QSSGRenderInstanceTableEntry > instances, const QMatrix4x4 &globalInstanceTransform, const QVector3D &localInstanceTranslation, const QVector3D &cameraDirection)
QSSGDataRef< T > RENDER_FRAME_NEW_BUFFER(QSSGRenderContextInterface &ctx, size_t count)
static const QVector2D s_ProgressiveAAVertexOffsets[QSSGLayerRenderData::MAX_AA_LEVELS]
static float instanceWorldStretchSq(const std::array< QVector3D, 3 > &axes)
static int cullLodInstances(QSSGRhiInstanceBufferData &instanceData, const QSSGRenderInstanceTable &table, const QMatrix4x4 &globalInstanceTransform, const QVector3D &localInstanceTranslation, const QVector3D &cameraPosition, float minThreshold, float maxThreshold)
static std::array< QVector3D, 3 > instanceWorldAxes(const QSSGRenderInstanceTableEntry &instance, const QSSGRhiInstancePlacement &placement)
static bool hasDirtyNonJointNodes(QSSGRenderNode *node, bool &hasChildJoints)
static int effectiveMaxLightCount(const QSSGShaderFeatures &features)
static QRhiBuffer * prepareAutoLodInstanceIndices(QSSGRhiContext *rhiCtx, QSSGRhiInstanceBufferData::SubsetLodData &subsetLod)
static constexpr QSSGPrepContextId createPrepId(size_t index, quint32 frame)
T * RENDER_FRAME_NEW(QSSGRenderContextInterface &ctx, Args &&... args)
static LayerNodeStatResult statLayerNodes(const QSSGLayerRenderData::LayerNodes &layerNodes, quint32 layerMask)
static void distributeInstancesToLods(QSSGRhiInstanceBufferData::SubsetLodData &subsetLod, QList< quint8 > &levelOfInstance, QSpan< const QSSGRenderInstanceTableEntry > instances, QSpan< const qint32 > sourceInstanceIndices, const QSSGRhiInstancePlacement &placement, const QVector3D &cameraPosition, const QVector3D &cameraDirection, bool orthographic, QSpan< const float > lodDistancesSq, const QSSGClippingFrustum *frustum, bool tint)
static float getCameraDistanceSq(const QSSGRenderableObject &obj, const QSSGRenderCameraData &camera) noexcept
static bool usesInstanceIndex(const QSSGRenderGraphObject &material)
static void createRenderablesHelper(QSSGLayerRenderData &layer, const QSSGRenderNode::ChildList &children, QSSGLayerRenderData::RenderableNodeEntries &renderables, QSSGRenderHelpers::CreateFlags createFlags)
friend QDebug operator<<(QDebug dbg, const LayerNodeStatResult &stat)
friend LayerNodeStatResult & operator+=(LayerNodeStatResult &lhs, const LayerNodeStatResult &rhs)
QSSGDefaultMaterialPreparationResult(QSSGShaderDefaultMaterialKey inMaterialKey)