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
qsgbatchrenderer.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
3// Copyright (C) 2016 Robin Burchell <robin.burchell@viroteck.net>
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5// Qt-Security score:significant reason:default
6
8
9#include <qmath.h>
10
11#include <QtCore/QElapsedTimer>
12#include <QtCore/QtNumeric>
13#include <QtCore/qalgorithms.h>
14
15#include <QtGui/QGuiApplication>
16
17#include <private/qnumeric_p.h>
19
21
22#include <QtQuick/private/qsgnode_p.h>
23
24#include <algorithm>
25
27
28int qt_sg_envInt(const char *name, int defaultValue);
29
31{
32
33#define DECLARE_DEBUG_VAR(variable)
34 static bool debug_ ## variable()
35 { static bool value = qgetenv("QSG_RENDERER_DEBUG").contains(QT_STRINGIFY(variable)); return value; }
43DECLARE_DEBUG_VAR(noalpha)
44DECLARE_DEBUG_VAR(noopaque)
46#undef DECLARE_DEBUG_VAR
47
48#define QSGNODE_TRAVERSE(NODE) for (QSGNode *child = NODE->firstChild(); child; child = child->nextSibling())
49#define SHADOWNODE_TRAVERSE(NODE) for (Node *child = NODE->firstChild(); child; child = child->sibling())
50
51static inline int size_of_type(int type)
52{
53 static int sizes[] = {
54 sizeof(char),
55 sizeof(unsigned char),
56 sizeof(short),
57 sizeof(unsigned short),
58 sizeof(int),
59 sizeof(unsigned int),
60 sizeof(float),
61 2,
62 3,
63 4,
64 sizeof(double)
65 };
66 Q_ASSERT(type >= QSGGeometry::ByteType && type <= QSGGeometry::DoubleType);
67 return sizes[type - QSGGeometry::ByteType];
68}
69
74
76
77static bool isTranslate(const QMatrix4x4 &m) { return m.flags() <= QMatrix4x4::Translation; }
78static bool isScale(const QMatrix4x4 &m) { return m.flags() <= QMatrix4x4::Scale; }
79static bool is2DSafe(const QMatrix4x4 &m) { return m.flags() < QMatrix4x4::Rotation; }
80
81const float OPAQUE_LIMIT = 0.999f;
82
86
87const float VIEWPORT_MIN_DEPTH = 0.0f;
88const float VIEWPORT_MAX_DEPTH = 1.0f;
89
90const quint32 DEFAULT_BUFFER_POOL_SIZE_LIMIT = 2 * 1024 * 1024; // 2 MB for m_vboPool and m_iboPool each
91
94
95template <class Int>
96inline Int aligned(Int v, Int byteAlign)
97{
98 return (v + byteAlign - 1) & ~(byteAlign - 1);
99}
100
102{
103 switch (a.type) {
104 case QSGGeometry::FloatType:
105 if (a.tupleSize == 4)
106 return QRhiVertexInputAttribute::Float4;
107 if (a.tupleSize == 3)
108 return QRhiVertexInputAttribute::Float3;
109 if (a.tupleSize == 2)
110 return QRhiVertexInputAttribute::Float2;
111 if (a.tupleSize == 1)
112 return QRhiVertexInputAttribute::Float;
113 break;
114 case QSGGeometry::UnsignedByteType:
115 if (a.tupleSize == 4)
116 return QRhiVertexInputAttribute::UNormByte4;
117 if (a.tupleSize == 2)
118 return QRhiVertexInputAttribute::UNormByte2;
119 if (a.tupleSize == 1)
120 return QRhiVertexInputAttribute::UNormByte;
121 break;
122 default:
123 break;
124 }
125 qWarning("Unsupported attribute type 0x%x with %d components", a.type, a.tupleSize);
126 Q_UNREACHABLE_RETURN(QRhiVertexInputAttribute::Float);
127}
128
129static QRhiVertexInputLayout calculateVertexInputLayout(const QSGMaterialShader *s, const QSGGeometry *geometry, bool batchable)
130{
131 Q_ASSERT(geometry);
132 const QSGMaterialShaderPrivate *sd = QSGMaterialShaderPrivate::get(s);
133 if (!sd->vertexShader) {
134 qWarning("No vertex shader in QSGMaterialShader %p", s);
135 return QRhiVertexInputLayout();
136 }
137
138 const int attrCount = geometry->attributeCount();
139 QVarLengthArray<QRhiVertexInputAttribute, 8> inputAttributes;
140 inputAttributes.reserve(attrCount + 1);
141 quint32 offset = 0;
142 for (int i = 0; i < attrCount; ++i) {
143 const QSGGeometry::Attribute &a = geometry->attributes()[i];
144 if (!sd->vertexShader->vertexInputLocations.contains(a.position)) {
145 qWarning("Vertex input %d is present in material but not in shader. This is wrong.",
146 a.position);
147 }
148 inputAttributes.append(QRhiVertexInputAttribute(VERTEX_BUFFER_BINDING, a.position, qsg_vertexInputFormat(a), offset));
149 offset += a.tupleSize * size_of_type(a.type);
150 }
151 if (batchable) {
152 inputAttributes.append(QRhiVertexInputAttribute(ZORDER_BUFFER_BINDING, sd->vertexShader->qt_order_attrib_location,
153 QRhiVertexInputAttribute::Float, 0));
154 }
155
156 Q_ASSERT(VERTEX_BUFFER_BINDING == 0 && ZORDER_BUFFER_BINDING == 1); // not very flexible
157 QVarLengthArray<QRhiVertexInputBinding, 2> inputBindings;
158 inputBindings.append(QRhiVertexInputBinding(geometry->sizeOfVertex()));
159 if (batchable)
160 inputBindings.append(QRhiVertexInputBinding(sizeof(float)));
161
162 QRhiVertexInputLayout inputLayout;
163 inputLayout.setBindings(inputBindings.cbegin(), inputBindings.cend());
164 inputLayout.setAttributes(inputAttributes.cbegin(), inputAttributes.cend());
165
166 return inputLayout;
167}
168
169QRhiCommandBuffer::IndexFormat qsg_indexFormat(const QSGGeometry *geometry)
170{
171 switch (geometry->indexType()) {
172 case QSGGeometry::UnsignedShortType:
173 return QRhiCommandBuffer::IndexUInt16;
174 break;
175 case QSGGeometry::UnsignedIntType:
176 return QRhiCommandBuffer::IndexUInt32;
177 break;
178 default:
179 Q_UNREACHABLE_RETURN(QRhiCommandBuffer::IndexUInt16);
180 }
181}
182
183QRhiGraphicsPipeline::Topology qsg_topology(int geomDrawMode, QRhi *rhi)
184{
185 QRhiGraphicsPipeline::Topology topology = QRhiGraphicsPipeline::Triangles;
186 switch (geomDrawMode) {
187 case QSGGeometry::DrawPoints:
188 topology = QRhiGraphicsPipeline::Points;
189 break;
190 case QSGGeometry::DrawLines:
191 topology = QRhiGraphicsPipeline::Lines;
192 break;
193 case QSGGeometry::DrawLineStrip:
194 topology = QRhiGraphicsPipeline::LineStrip;
195 break;
196 case QSGGeometry::DrawTriangles:
197 topology = QRhiGraphicsPipeline::Triangles;
198 break;
199 case QSGGeometry::DrawTriangleStrip:
200 topology = QRhiGraphicsPipeline::TriangleStrip;
201 break;
202 case QSGGeometry::DrawTriangleFan:
203 {
204 static bool triangleFanSupported = false;
205 static bool triangleFanSupportChecked = false;
206 if (!triangleFanSupportChecked) {
207 triangleFanSupportChecked = true;
208 triangleFanSupported = rhi->isFeatureSupported(QRhi::TriangleFanTopology);
209 }
210 if (triangleFanSupported) {
211 topology = QRhiGraphicsPipeline::TriangleFan;
212 break;
213 }
214 Q_FALLTHROUGH();
215 }
216 default:
217 qWarning("Primitive topology 0x%x not supported", geomDrawMode);
218 break;
219 }
220 return topology;
221}
222
223void qsg_setMultiViewFlagsOnMaterial(QSGMaterial *material, int multiViewCount)
224{
225 material->setFlag(QSGMaterial::MultiView2, multiViewCount == 2);
226 material->setFlag(QSGMaterial::MultiView3, multiViewCount == 3);
227 material->setFlag(QSGMaterial::MultiView4, multiViewCount == 4);
228}
229
230ShaderManager::Shader *ShaderManager::prepareMaterial(QSGMaterial *material,
231 const QSGGeometry *geometry,
232 QSGRendererInterface::RenderMode renderMode,
233 int multiViewCount)
234{
235 qsg_setMultiViewFlagsOnMaterial(material, multiViewCount);
236
237 QSGMaterialType *type = material->type();
238 ShaderKey key = { type, renderMode, multiViewCount };
239 Shader *shader = rewrittenShaders.value(key, nullptr);
240 if (shader)
241 return shader;
242
243 shader = new Shader;
244 QSGMaterialShader *s = static_cast<QSGMaterialShader *>(material->createShader(renderMode));
245 context->initializeRhiShader(s, QShader::BatchableVertexShader);
246 shader->materialShader = s;
247 shader->inputLayout = calculateVertexInputLayout(s, geometry, true);
248 QSGMaterialShaderPrivate *sD = QSGMaterialShaderPrivate::get(s);
249 shader->stages = {
250 { QRhiShaderStage::Vertex, sD->shader(QShader::VertexStage), QShader::BatchableVertexShader },
251 { QRhiShaderStage::Fragment, sD->shader(QShader::FragmentStage) }
252 };
253
254 shader->lastOpacity = 0;
255
256 rewrittenShaders[key] = shader;
257 return shader;
258}
259
260ShaderManager::Shader *ShaderManager::prepareMaterialNoRewrite(QSGMaterial *material,
261 const QSGGeometry *geometry,
262 QSGRendererInterface::RenderMode renderMode,
263 int multiViewCount)
264{
265 qsg_setMultiViewFlagsOnMaterial(material, multiViewCount);
266
267 QSGMaterialType *type = material->type();
268 ShaderKey key = { type, renderMode, multiViewCount };
269 Shader *shader = stockShaders.value(key, nullptr);
270 if (shader)
271 return shader;
272
273 shader = new Shader;
274 QSGMaterialShader *s = static_cast<QSGMaterialShader *>(material->createShader(renderMode));
275 context->initializeRhiShader(s, QShader::StandardShader);
276 shader->materialShader = s;
277 shader->inputLayout = calculateVertexInputLayout(s, geometry, false);
278 QSGMaterialShaderPrivate *sD = QSGMaterialShaderPrivate::get(s);
279 shader->stages = {
280 { QRhiShaderStage::Vertex, sD->shader(QShader::VertexStage) },
281 { QRhiShaderStage::Fragment, sD->shader(QShader::FragmentStage) }
282 };
283
284 shader->lastOpacity = 0;
285
286 stockShaders[key] = shader;
287
288 return shader;
289}
290
291void ShaderManager::invalidated()
292{
293 qDeleteAll(stockShaders);
294 stockShaders.clear();
295 qDeleteAll(rewrittenShaders);
296 rewrittenShaders.clear();
297
298 qDeleteAll(pipelineCache);
299 pipelineCache.clear();
300 ++pipelineCacheGeneration;
301
302 qDeleteAll(srbPool);
303 srbPool.clear();
304}
305
307{
308 for (ShaderManager::Shader *sms : std::as_const(stockShaders)) {
309 QSGMaterialShader *s = sms->materialShader;
310 if (s) {
311 QSGMaterialShaderPrivate *sd = QSGMaterialShaderPrivate::get(s);
312 sd->clearCachedRendererData();
313 }
314 }
315 for (ShaderManager::Shader *sms : std::as_const(rewrittenShaders)) {
316 QSGMaterialShader *s = sms->materialShader;
317 if (s) {
318 QSGMaterialShaderPrivate *sd = QSGMaterialShaderPrivate::get(s);
319 sd->clearCachedRendererData();
320 }
321 }
322}
323
325{
326 static int extraIndent = 0;
327 ++extraIndent;
328
329 QByteArray ind(indent + extraIndent + 10, ' ');
330
331 if (!i) {
332 qDebug("%s - no info", ind.constData());
333 } else {
334 qDebug() << ind.constData() << "- parent:" << i->parentRoot << "orders" << i->firstOrder << "->" << i->lastOrder << ", avail:" << i->availableOrders;
335 for (QSet<Node *>::const_iterator it = i->subRoots.constBegin();
336 it != i->subRoots.constEnd(); ++it) {
337 qDebug() << ind.constData() << "-" << *it;
338 qsg_dumpShadowRoots((*it)->rootInfo(), indent);
339 }
340 }
341
342 --extraIndent;
343}
344
346{
347#ifndef QT_NO_DEBUG_OUTPUT
348 static int indent = 0;
349 ++indent;
350
351 QByteArray ind(indent, ' ');
352
353 if (n->type() == QSGNode::ClipNodeType || n->isBatchRoot) {
354 qDebug() << ind.constData() << "[X]" << n->sgNode << Qt::hex << uint(n->sgNode->flags());
356 } else {
357 QDebug d = qDebug();
358 d << ind.constData() << "[ ]" << n->sgNode << Qt::hex << uint(n->sgNode->flags());
359 if (n->type() == QSGNode::GeometryNodeType)
360 d << "order" << Qt::dec << n->element()->order;
361 }
362
365
366 --indent;
367#else
368 Q_UNUSED(n);
369#endif
370}
371
372Updater::Updater(Renderer *r)
373 : renderer(r)
374 , m_roots(32)
375 , m_rootMatrices(8)
376{
377 m_roots.add(0);
378 m_combined_matrix_stack.add(&m_identityMatrix);
379 m_rootMatrices.add(m_identityMatrix);
380}
381
382void Updater::updateStates(QSGNode *n)
383{
384 m_current_clip = nullptr;
385
386 m_added = 0;
387 m_transformChange = 0;
388 m_opacityChange = 0;
389
390 Node *sn = renderer->m_nodes.value(n, 0);
391 Q_ASSERT(sn);
392
393 if (Q_UNLIKELY(debug_roots()))
395
396 if (Q_UNLIKELY(debug_build())) {
397 qDebug("Updater::updateStates()");
398 if (sn->dirtyState & (QSGNode::DirtyNodeAdded << 16))
399 qDebug(" - nodes have been added");
400 if (sn->dirtyState & (QSGNode::DirtyMatrix << 16))
401 qDebug(" - transforms have changed");
402 if (sn->dirtyState & (QSGNode::DirtyOpacity << 16))
403 qDebug(" - opacity has changed");
404 if (uint(sn->dirtyState) & uint(QSGNode::DirtyForceUpdate << 16))
405 qDebug(" - forceupdate");
406 }
407
408 if (Q_UNLIKELY(renderer->m_visualizer->mode() == Visualizer::VisualizeChanges))
409 renderer->m_visualizer->visualizeChangesPrepare(sn);
410
411 visitNode(sn);
412}
413
415{
416 if (m_added == 0 && n->dirtyState == 0 && m_force_update == 0 && m_transformChange == 0 && m_opacityChange == 0)
417 return;
418
419 int count = m_added;
420 if (n->dirtyState & QSGNode::DirtyNodeAdded)
421 ++m_added;
422
423 int force = m_force_update;
424 if (n->dirtyState & QSGNode::DirtyForceUpdate)
425 ++m_force_update;
426
427 switch (n->type()) {
428 case QSGNode::OpacityNodeType:
430 break;
431 case QSGNode::TransformNodeType:
433 break;
434 case QSGNode::GeometryNodeType:
436 break;
437 case QSGNode::ClipNodeType:
439 break;
440 case QSGNode::RenderNodeType:
441 if (m_added)
442 n->renderNodeElement()->root = m_roots.last();
443 Q_FALLTHROUGH(); // to visit children
444 default:
446 break;
447 }
448
449 m_added = count;
450 m_force_update = force;
451 n->dirtyState = {};
452}
453
455{
457
458 QSGClipNode *cn = static_cast<QSGClipNode *>(n->sgNode);
459
460 if (m_roots.last() && m_added > 0)
461 renderer->registerBatchRoot(n, m_roots.last());
462
463 cn->setRendererClipList(m_current_clip);
464 m_current_clip = cn;
465 m_roots << n;
466 m_rootMatrices.add(m_rootMatrices.last() * *m_combined_matrix_stack.last());
467 extra->matrix = m_rootMatrices.last();
468 cn->setRendererMatrix(&extra->matrix);
469 m_combined_matrix_stack << &m_identityMatrix;
470
472
473 m_current_clip = cn->clipList();
474 m_rootMatrices.pop_back();
475 m_combined_matrix_stack.pop_back();
476 m_roots.pop_back();
477}
478
480{
481 QSGOpacityNode *on = static_cast<QSGOpacityNode *>(n->sgNode);
482
483 qreal combined = m_opacity_stack.last() * on->opacity();
484 on->setCombinedOpacity(combined);
485 m_opacity_stack.add(combined);
486
487 if (m_added == 0 && n->dirtyState & QSGNode::DirtyOpacity) {
488 bool was = n->isOpaque;
489 bool is = on->opacity() > OPAQUE_LIMIT;
490 if (was != is) {
491 renderer->m_rebuild = Renderer::FullRebuild;
492 n->isOpaque = is;
493 }
494 ++m_opacityChange;
496 --m_opacityChange;
497 } else {
498 if (m_added > 0)
499 n->isOpaque = on->opacity() > OPAQUE_LIMIT;
501 }
502
503 m_opacity_stack.pop_back();
504}
505
507{
508 bool popMatrixStack = false;
509 bool popRootStack = false;
510 bool dirty = n->dirtyState & QSGNode::DirtyMatrix;
511
512 QSGTransformNode *tn = static_cast<QSGTransformNode *>(n->sgNode);
513
514 if (n->isBatchRoot) {
515 if (m_added > 0 && m_roots.last())
516 renderer->registerBatchRoot(n, m_roots.last());
517 tn->setCombinedMatrix(m_rootMatrices.last() * *m_combined_matrix_stack.last() * tn->matrix());
518
519 // The only change in this subtree is ourselves and we are a batch root, so
520 // only update subroots and return, saving tons of child-processing (flickable-panning)
521
522 if (!n->becameBatchRoot && m_added == 0 && m_force_update == 0 && m_opacityChange == 0 && dirty && (n->dirtyState & ~QSGNode::DirtyMatrix) == 0) {
523 BatchRootInfo *info = renderer->batchRootInfo(n);
524 for (QSet<Node *>::const_iterator it = info->subRoots.constBegin();
525 it != info->subRoots.constEnd(); ++it) {
526 updateRootTransforms(*it, n, tn->combinedMatrix());
527 }
528 return;
529 }
530
531 n->becameBatchRoot = false;
532
533 m_combined_matrix_stack.add(&m_identityMatrix);
534 m_roots.add(n);
535 m_rootMatrices.add(tn->combinedMatrix());
536
537 popMatrixStack = true;
538 popRootStack = true;
539 } else if (!tn->matrix().isIdentity()) {
540 tn->setCombinedMatrix(*m_combined_matrix_stack.last() * tn->matrix());
541 m_combined_matrix_stack.add(&tn->combinedMatrix());
542 popMatrixStack = true;
543 } else {
544 tn->setCombinedMatrix(*m_combined_matrix_stack.last());
545 }
546
547 if (dirty)
548 ++m_transformChange;
549
551
552 if (dirty)
553 --m_transformChange;
554 if (popMatrixStack)
555 m_combined_matrix_stack.pop_back();
556 if (popRootStack) {
557 m_roots.pop_back();
558 m_rootMatrices.pop_back();
559 }
560}
561
563{
564 QSGGeometryNode *gn = static_cast<QSGGeometryNode *>(n->sgNode);
565
566 gn->setRendererMatrix(m_combined_matrix_stack.last());
567 gn->setRendererClipList(m_current_clip);
568 gn->setInheritedOpacity(m_opacity_stack.last());
569
570 if (m_added) {
571 Element *e = n->element();
572 e->root = m_roots.last();
573 e->translateOnlyToRoot = isTranslate(*gn->matrix());
574
575 if (e->root) {
576 BatchRootInfo *info = renderer->batchRootInfo(e->root);
577 while (info != nullptr) {
578 info->availableOrders--;
579 if (info->availableOrders < 0) {
580 renderer->m_rebuild |= Renderer::BuildRenderLists;
581 } else {
582 renderer->m_rebuild |= Renderer::BuildRenderListsForTaggedRoots;
583 renderer->m_taggedRoots << e->root;
584 }
585 if (info->parentRoot != nullptr)
586 info = renderer->batchRootInfo(info->parentRoot);
587 else
588 info = nullptr;
589 }
590 } else {
591 renderer->m_rebuild |= Renderer::FullRebuild;
592 }
593 } else {
594 if (m_transformChange) {
595 Element *e = n->element();
596 e->translateOnlyToRoot = isTranslate(*gn->matrix());
597 }
598 if (m_opacityChange) {
599 Element *e = n->element();
600 if (e->batch)
601 renderer->invalidateBatchAndOverlappingRenderOrders(e->batch);
602 }
603 }
604
606}
607
608void Updater::updateRootTransforms(Node *node, Node *root, const QMatrix4x4 &combined)
609{
610 BatchRootInfo *info = renderer->batchRootInfo(node);
611 QMatrix4x4 m;
612 Node *n = node;
613
614 while (n != root) {
615 if (n->type() == QSGNode::TransformNodeType)
616 m = static_cast<QSGTransformNode *>(n->sgNode)->matrix() * m;
617 n = n->parent();
618 }
619
620 m = combined * m;
621
622 if (node->type() == QSGNode::ClipNodeType) {
623 static_cast<ClipBatchRootInfo *>(info)->matrix = m;
624 } else {
625 Q_ASSERT(node->type() == QSGNode::TransformNodeType);
626 static_cast<QSGTransformNode *>(node->sgNode)->setCombinedMatrix(m);
627 }
628
629 for (QSet<Node *>::const_iterator it = info->subRoots.constBegin();
630 it != info->subRoots.constEnd(); ++it) {
631 updateRootTransforms(*it, node, m);
632 }
633}
634
635int qsg_positionAttribute(QSGGeometry *g)
636{
637 int vaOffset = 0;
638 for (int a=0; a<g->attributeCount(); ++a) {
639 const QSGGeometry::Attribute &attr = g->attributes()[a];
640 if (attr.isVertexCoordinate && attr.tupleSize == 2 && attr.type == QSGGeometry::FloatType) {
641 return vaOffset;
642 }
643 vaOffset += attr.tupleSize * size_of_type(attr.type);
644 }
645 return -1;
646}
647
648
649void Rect::map(const QMatrix4x4 &matrix)
650{
651 const float *m = matrix.constData();
652 if (isScale(matrix)) {
653 tl.x = tl.x * m[0] + m[12];
654 tl.y = tl.y * m[5] + m[13];
655 br.x = br.x * m[0] + m[12];
656 br.y = br.y * m[5] + m[13];
657 if (tl.x > br.x)
658 qSwap(tl.x, br.x);
659 if (tl.y > br.y)
660 qSwap(tl.y, br.y);
661 } else {
662 Pt mtl = tl;
663 Pt mtr = { br.x, tl.y };
664 Pt mbl = { tl.x, br.y };
665 Pt mbr = br;
666
667 mtl.map(matrix);
668 mtr.map(matrix);
669 mbl.map(matrix);
670 mbr.map(matrix);
671
672 set(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
673 (*this) |= mtl;
674 (*this) |= mtr;
675 (*this) |= mbl;
676 (*this) |= mbr;
677 }
678}
679
681{
682 Q_ASSERT(!boundsComputed);
683 boundsComputed = true;
684
685 QSGGeometry *g = node->geometry();
686 int offset = qsg_positionAttribute(g);
687 if (offset == -1) {
688 // No position attribute means overlaps with everything..
689 bounds.set(-FLT_MAX, -FLT_MAX, FLT_MAX, FLT_MAX);
690 return;
691 }
692
693 bounds.set(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
694 char *vd = (char *) g->vertexData() + offset;
695 for (int i=0; i<g->vertexCount(); ++i) {
696 bounds |= *(Pt *) vd;
697 vd += g->sizeOfVertex();
698 }
699 bounds.map(*node->matrix());
700
701 if (!qt_is_finite(bounds.tl.x) || bounds.tl.x == FLT_MAX)
702 bounds.tl.x = -FLT_MAX;
703 if (!qt_is_finite(bounds.tl.y) || bounds.tl.y == FLT_MAX)
704 bounds.tl.y = -FLT_MAX;
705 if (!qt_is_finite(bounds.br.x) || bounds.br.x == -FLT_MAX)
706 bounds.br.x = FLT_MAX;
707 if (!qt_is_finite(bounds.br.y) || bounds.br.y == -FLT_MAX)
708 bounds.br.y = FLT_MAX;
709
710 Q_ASSERT(bounds.tl.x <= bounds.br.x);
711 Q_ASSERT(bounds.tl.y <= bounds.br.y);
712
713 boundsOutsideFloatRange = bounds.isOutsideFloatRange();
714
715 // Antialiased materials (smooth rectangles and images, curve fills)
716 // extrude their edges in the vertex shader, beyond the vertex positions:
717 // by up to a device pixel, sqrt(2) device pixels for curve fills. They
718 // all need the matrix for that. Grow their bounds, which only serve the
719 // alpha batching overlap checks, so that elements whose antialiased
720 // edges meet are not reordered. Two units cover the extrusion for any
721 // device pixel ratio of 0.71 and above.
722 if (node->activeMaterial()->flags().testFlag(QSGMaterial::RequiresFullMatrixExceptTranslate)) {
723 const float margin = 2.0f;
724 bounds.tl.x -= margin;
725 bounds.tl.y -= margin;
726 bounds.br.x += margin;
727 bounds.br.y += margin;
728 }
729}
730
732{
733 Element *n = first;
734 // Skip to the first node other than e which has not been removed
735 while (n && (n == e || n->removed))
736 n = n->nextInBatch;
737
738 // Only 'e' in this batch, so a material change doesn't change anything as long as
739 // its blending is still in sync with this batch...
740 if (!n)
741 return BatchIsCompatible;
742
743 QSGMaterial *m = e->node->activeMaterial();
744 QSGMaterial *nm = n->node->activeMaterial();
745 return (nm->type() == m->type() && nm->viewCount() == m->viewCount() && nm->compare(m) == 0)
748}
749
750/*
751 * Marks this batch as dirty or in the case where the geometry node has
752 * changed to be incompatible with this batch, return false so that
753 * the caller can mark the entire sg for a full rebuild...
754 */
755bool Batch::geometryWasChanged(QSGGeometryNode *gn)
756{
757 Element *e = first;
758 Q_ASSERT_X(e, "Batch::geometryWasChanged", "Batch is expected to 'valid' at this time");
759 // 'gn' is the first node in the batch, compare against the next one.
760 while (e && (e->node == gn || e->removed))
761 e = e->nextInBatch;
762 if (!e || e->node->geometry()->attributes() == gn->geometry()->attributes()) {
763 needsUpload = true;
764 return true;
765 } else {
766 return false;
767 }
768}
769
771{
772 if (!needsPurge)
773 return;
774
775 // remove from front of batch..
776 while (first && first->removed) {
778 }
779
780 // Then continue and remove other nodes further out in the batch..
781 if (first) {
782 Element *e = first;
783 while (e->nextInBatch) {
784 if (e->nextInBatch->removed)
786 else
787 e = e->nextInBatch;
788
789 }
790 }
791
792 needsPurge = false;
793}
794
795/*
796 * Iterates through all geometry nodes in this batch and unsets their batch,
797 * thus forcing them to be rebuilt
798 */
800{
802 Element *e = first;
803 first = nullptr;
804 root = nullptr;
805 while (e) {
806 e->batch = nullptr;
808 e->nextInBatch = nullptr;
809 e = n;
810 }
811}
812
814 bool only = true;
815 Element *e = first;
816 while (e && only) {
817 only &= e->translateOnlyToRoot;
818 e = e->nextInBatch;
819 }
820 return only;
821}
822
823/*
824 * Iterates through all the nodes in the batch and returns true if the
825 * nodes are all safe to batch. There are two separate criteria:
826 *
827 * - The matrix is such that the z component of the result is of no
828 * consequence.
829 *
830 * - The bounds are inside the stable floating point range. This applies
831 * to desktop only where we in this case can trigger a fallback to
832 * unmerged in which case we pass the geometry straight through and
833 * just apply the matrix.
834 *
835 * NOTE: This also means a slight performance impact for geometries which
836 * are defined to be outside the stable floating point range and still
837 * use single precision float, but given that this implicitly fixes
838 * huge lists and tables, it is worth it.
839 */
840bool Batch::isSafeToBatch() const {
841 Element *e = first;
842 while (e) {
843 if (e->boundsOutsideFloatRange)
844 return false;
845 if (!is2DSafe(*e->node->matrix()))
846 return false;
847 e = e->nextInBatch;
848 }
849 return true;
850}
851
852static int qsg_countNodesInBatch(const Batch *batch)
853{
854 int sum = 0;
855 Element *e = batch->first;
856 while (e) {
857 ++sum;
858 e = e->nextInBatch;
859 }
860 return sum;
861}
862
863static int qsg_countNodesInBatches(const QDataBuffer<Batch *> &batches)
864{
865 int sum = 0;
866 for (int i=0; i<batches.size(); ++i) {
867 sum += qsg_countNodesInBatch(batches.at(i));
868 }
869 return sum;
870}
871
874 , m_context(ctx)
879 , m_partialRebuild(false)
880 , m_partialRebuildRoot(nullptr)
881 , m_forceNoDepthBuffer(false)
882 , m_opaqueBatches(16)
883 , m_alphaBatches(16)
884 , m_batchPool(16)
888 , m_vboPool(16)
889 , m_iboPool(16)
890 , m_vboPoolCost(0)
891 , m_iboPoolCost(0)
893 , m_zRange(0)
894#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES)
897#endif
899 , m_currentMaterial(nullptr)
900 , m_currentShader(nullptr)
901 , m_vertexUploadPool(256)
903{
904 m_rhi = m_context->rhi();
905 Q_ASSERT(m_rhi); // no more direct OpenGL code path in Qt 6
906
908
910 if (qEnvironmentVariableIntValue("QSG_RHI_UINT32_INDEX"))
911 m_uint32IndexForRhi = true;
912
913 bool ok = false;
914 int padding = qEnvironmentVariableIntValue("QSG_BATCHRENDERER_MINIMUM_ORDER_PADDING", &ok);
915 if (ok)
917
918 m_visualizer = new RhiVisualizer(this);
919
920 setNodeUpdater(new Updater(this));
921
922 // The shader manager is shared between renderers (think for example Item
923 // layers that create a new Renderer each) with the same rendercontext (and
924 // so same QRhi).
926 if (!m_shaderManager) {
928 m_shaderManager->setObjectName(QStringLiteral("__qt_ShaderManager"));
931 }
932
933 m_batchNodeThreshold = qt_sg_envInt("QSG_RENDERER_BATCH_NODE_THRESHOLD", 64);
934 m_batchVertexThreshold = qt_sg_envInt("QSG_RENDERER_BATCH_VERTEX_THRESHOLD", 1024);
935 m_srbPoolThreshold = qt_sg_envInt("QSG_RENDERER_SRB_POOL_THRESHOLD", 1024);
936 m_bufferPoolSizeLimit = qt_sg_envInt("QSG_RENDERER_BUFFER_POOL_LIMIT", DEFAULT_BUFFER_POOL_SIZE_LIMIT);
937
939 qDebug("Batch thresholds: nodes: %d vertices: %d srb pool: %d buffer pool: %d",
941 }
942}
943
944static void qsg_wipeBuffer(Buffer *buffer)
945{
946 delete buffer->buf;
947
948 // The free here is ok because we're in one of two situations.
949 // 1. We're using the upload pool in which case unmap will have set the
950 // data pointer to 0 and calling free on 0 is ok.
951 // 2. We're using dedicated buffers because of visualization or IBO workaround
952 // and the data something we malloced and must be freed.
953 free(buffer->data);
954}
955
956static void qsg_wipeBatch(Batch *batch)
957{
958 qsg_wipeBuffer(&batch->vbo);
959 qsg_wipeBuffer(&batch->ibo);
960 batch->stencilClipState.reset();
961 delete batch;
962}
963
965{
966 if (m_rhi) {
967 // Clean up batches and buffers
968 for (int i = 0; i < m_opaqueBatches.size(); ++i)
970 for (int i = 0; i < m_alphaBatches.size(); ++i)
972 for (int i = 0; i < m_batchPool.size(); ++i)
974 for (int i = 0; i < m_vboPool.size(); ++i)
975 delete m_vboPool.at(i);
976 for (int i = 0; i < m_iboPool.size(); ++i)
977 delete m_iboPool.at(i);
978 delete m_uniformBuffer;
979 }
980
981 for (Node *n : std::as_const(m_nodes)) {
982 if (n->type() == QSGNode::GeometryNodeType) {
983 Element *e = n->element();
984 if (!e->removed)
986 } else if (n->type() == QSGNode::ClipNodeType) {
987 delete n->clipInfo();
988 } else if (n->type() == QSGNode::RenderNodeType) {
990 if (!e->removed)
992 }
993
995 }
996
997 // Remaining elements...
998 for (int i=0; i<m_elementsToDelete.size(); ++i)
1000
1002
1003 delete m_visualizer;
1004}
1005
1007{
1008 // If this is from the dtor, then the shader manager and its already
1009 // prepared shaders will stay around for other renderers -> the cached data
1010 // in the rhi shaders have to be purged as it may refer to samplers we
1011 // are going to destroy.
1013
1016 delete m_dummyTexture;
1018}
1019
1021{
1023
1025
1026 m_samplers.clear();
1027 m_dummyTexture = nullptr;
1028
1030
1035
1036 // m_uniformBuffer stays, the elements' srbs refer to it
1039
1040 for (int i = 0; i < m_vboPool.size(); ++i)
1041 delete m_vboPool.at(i);
1042 m_vboPool.reset();
1043 m_vboPoolCost = 0;
1044
1045 for (int i = 0; i < m_iboPool.size(); ++i)
1046 delete m_iboPool.at(i);
1047 m_iboPool.reset();
1048 m_iboPoolCost = 0;
1049}
1050
1052{
1053 if (b->vbo.buf != nullptr && m_vboPoolCost + b->vbo.buf->size() <= quint32(m_bufferPoolSizeLimit)) {
1054 m_vboPool.add(b->vbo.buf);
1055 m_vboPoolCost += b->vbo.buf->size();
1056 } else {
1057 delete b->vbo.buf;
1058 }
1059 if (b->ibo.buf != nullptr && m_iboPoolCost + b->ibo.buf->size() <= quint32(m_bufferPoolSizeLimit)) {
1060 m_iboPool.add(b->ibo.buf);
1061 m_iboPoolCost += b->ibo.buf->size();
1062 } else {
1063 delete b->ibo.buf;
1064 }
1065 b->vbo.buf = nullptr;
1066 b->ibo.buf = nullptr;
1067 b->invalidate();
1068 for (int i=0; i<m_batchPool.size(); ++i)
1069 if (b == m_batchPool.at(i))
1070 return;
1071 m_batchPool.add(b);
1072}
1073
1075{
1077 // Common case, use a shared memory pool for uploading vertex data to avoid
1078 // excessive reevaluation
1080 if (byteSize > quint32(pool.size()))
1082 buffer->data = pool.data();
1083 } else if (buffer->size != byteSize) {
1084 free(buffer->data);
1085 buffer->data = (char *) malloc(byteSize);
1087 }
1088 buffer->size = byteSize;
1089}
1090
1092{
1093 // Batches are pooled and reused which means the QRhiBuffer will be
1094 // still valid in a recycled Batch. We only hit the newBuffer() path
1095 // when there are no buffers to recycle.
1097 if (!buffer->buf && bufferPool->isEmpty()) {
1100 buffer->size);
1101 if (!buffer->buf->create()) {
1102 qWarning("Failed to build vertex/index buffer of size %u", buffer->size);
1103 delete buffer->buf;
1104 buffer->buf = nullptr;
1105 }
1106 } else {
1107 if (!buffer->buf) {
1110 for (qsizetype i = 0; i < bufferPool->size(); ++i) {
1112 if (!buffer->buf
1114 || (testBuffer->size() >= expectedSize && testBuffer->size() < buffer->buf->size())
1115 || (testBuffer->size() < expectedSize && testBuffer->size() > buffer->buf->size())) {
1118 if (buffer->buf->size() == expectedSize)
1119 break;
1120 }
1121 }
1122
1127 }
1128 if (isIndexBuf)
1130 else
1133 }
1134
1135 bool needsRebuild = false;
1136 if (buffer->buf->size() < buffer->size) {
1138 needsRebuild = true;
1139 }
1140 if (buffer->buf->type() != QRhiBuffer::Dynamic
1142 {
1145 needsRebuild = true;
1146 }
1147 if (needsRebuild) {
1148 if (!buffer->buf->create()) {
1149 qWarning("Failed to (re)build vertex/index buffer of size %u", buffer->size);
1150 delete buffer->buf;
1151 buffer->buf = nullptr;
1152 }
1153 }
1154 }
1155 if (buffer->buf) {
1156 if (buffer->buf->type() != QRhiBuffer::Dynamic) {
1159 } else {
1162 else
1164 }
1165 }
1167 buffer->data = nullptr;
1168}
1169
1171{
1173 if (!info) {
1174 if (node->type() == QSGNode::ClipNodeType)
1175 info = new ClipBatchRootInfo;
1176 else {
1178 info = new BatchRootInfo;
1179 }
1180 node->data = info;
1181 }
1182 return info;
1183}
1184
1186{
1188 if (!childInfo->parentRoot)
1189 return;
1191
1194 childInfo->parentRoot = nullptr;
1195}
1196
1198{
1203}
1204
1206{
1208 if (subInfo->parentRoot == root)
1209 return false;
1210 if (subInfo->parentRoot) {
1213 }
1217 return true;
1218}
1219
1221{
1222 if (node->type() == QSGNode::ClipNodeType || node->isBatchRoot) {
1223 // When we reach a batchroot, we only need to update it. Its subtree
1224 // is relative to that root, so no need to recurse further.
1226 return;
1227 } else if (node->type() == QSGNode::GeometryNodeType) {
1228 // Only need to change the root as nodeChanged anyway flags a full update.
1229 Element *e = node->element();
1230 if (e) {
1231 e->root = root;
1232 e->boundsComputed = false;
1233 }
1234 } else if (node->type() == QSGNode::RenderNodeType) {
1236 if (e)
1237 e->root = root;
1238 }
1239
1242}
1243
1245{
1246 if (node->type() == QSGNode::GeometryNodeType) {
1247 QSGGeometryNode *gn = static_cast<QSGGeometryNode *>(node->sgNode);
1249 Element *e = node->element();
1250 if (e) {
1251 e->boundsComputed = false;
1252 if (e->batch) {
1253 if (!e->batch->isOpaque) {
1255 } else if (e->batch->merged) {
1256 e->batch->needsUpload = true;
1257 }
1258 }
1259 }
1260 }
1261
1264}
1265
1267{
1269 if (node->isSubtreeBlocked())
1270 return;
1271
1273 snode->sgNode = node;
1275 if (shadowParent)
1277
1278 if (node->type() == QSGNode::GeometryNodeType) {
1280 if (!snode->data) {
1281 // Removed elements are normally released in prepareRenderPass().
1282 // Without rendering (e.g. a layer that is not updated) they pile up,
1283 // so release them here instead of growing the allocator, but only:
1284 // - when it is full, and
1285 // - when at least half of it is waiting for release, since the
1286 // cleanup is O(n) and replacing nodes one by one would run it on
1287 // every allocation.
1288 // render node elements do not use the allocator, but they are few.
1292 }
1293 snode->element()->setNode(static_cast<QSGGeometryNode *>(node));
1294
1295 } else if (node->type() == QSGNode::ClipNodeType) {
1298
1299 } else if (node->type() == QSGNode::RenderNodeType) {
1300 QSGRenderNode *rn = static_cast<QSGRenderNode *>(node);
1302 snode->data = e;
1306 m_forceNoDepthBuffer = true;
1308 }
1309
1312}
1313
1315{
1316 // Prefix traversal as removeBatchRootFromParent below removes nodes
1317 // in a bottom-up manner. Note that we *cannot* use SHADOWNODE_TRAVERSE
1318 // here, because we delete 'child' (when recursed, down below), so we'd
1319 // have a use-after-free.
1320 {
1321 Node *child = node->firstChild();
1322 while (child) {
1323 // Remove (and delete) child
1324 node->remove(child);
1326 child = node->firstChild();
1327 }
1328 }
1329
1330 if (node->type() == QSGNode::GeometryNodeType) {
1331 Element *e = node->element();
1332 if (e) {
1333 e->removed = true;
1335 e->node = nullptr;
1336 if (e->root) {
1339 }
1340 if (e->batch) {
1341 e->batch->needsUpload = true;
1342 e->batch->needsPurge = true;
1343 }
1344
1345 }
1346
1347 } else if (node->type() == QSGNode::ClipNodeType) {
1349 delete node->clipInfo();
1352
1353 } else if (node->isBatchRoot) {
1355 delete node->rootInfo();
1358
1359 } else if (node->type() == QSGNode::RenderNodeType) {
1361 if (e) {
1362 e->removed = true;
1365 m_forceNoDepthBuffer = false;
1366 // Must have a full rebuild given useDepthBuffer() now returns
1367 // a different value than before, meaning there can once again
1368 // be an opaque pass.
1370 }
1371
1372 if (e->batch != nullptr)
1373 e->batch->needsPurge = true;
1374 }
1375 }
1376
1378
1380}
1381
1383{
1384 if (Q_UNLIKELY(debug_change())) qDebug(" - new batch root");
1386 node->isBatchRoot = true;
1387 node->becameBatchRoot = true;
1388
1389 Node *p = node->parent();
1390 while (p) {
1391 if (p->type() == QSGNode::ClipNodeType || p->isBatchRoot) {
1393 break;
1394 }
1395 p = p->parent();
1396 }
1397
1400}
1401
1402
1404{
1405#ifndef QT_NO_DEBUG_OUTPUT
1406 if (Q_UNLIKELY(debug_change())) {
1407 QDebug debug = qDebug();
1408 debug << "dirty:";
1410 debug << "Geometry";
1412 debug << "Material";
1413 if (state & QSGNode::DirtyMatrix)
1414 debug << "Matrix";
1416 debug << "Added";
1418 debug << "Removed";
1419 if (state & QSGNode::DirtyOpacity)
1420 debug << "Opacity";
1422 debug << "SubtreeBlocked";
1424 debug << "ForceUpdate";
1425
1426 // when removed, some parts of the node could already have been destroyed
1427 // so don't debug it out.
1429 debug << (void *) node << node->type();
1430 else
1431 debug << node;
1432 }
1433#endif
1434 // As this function calls nodeChanged recursively, we do it at the top
1435 // to avoid that any of the others are processed twice.
1437 Node *sn = m_nodes.value(node);
1438
1439#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES)
1440 // Force a batch rebuild if this includes an opacity change. Batches
1441 // may otherwise end up in the wrong order when their first element is
1442 // removed (QTBUG-85965). Not needed without this define, since then a
1443 // batch never skips over overlapping elements of other batches.
1444 if (state & QSGNode::DirtyOpacity)
1446#endif
1447
1448 bool blocked = node->isSubtreeBlocked();
1449 if (blocked && sn) {
1451 Q_ASSERT(m_nodes.value(node) == 0);
1452 } else if (!blocked && !sn) {
1454 }
1455 return;
1456 }
1457
1458 if (state & QSGNode::DirtyNodeAdded) {
1461 return;
1462 }
1463 if (node == rootNode())
1464 nodeWasAdded(node, nullptr);
1465 else
1467 }
1468
1469 // Mark this node dirty in the shadow tree.
1471
1472 // Blocked subtrees won't have shadow nodes, so we can safely abort
1473 // here..
1474 if (!shadowNode) {
1476 return;
1477 }
1478
1480
1485 } else {
1486 int vertices = 0;
1490 }
1491 }
1492 }
1493
1495 QSGGeometryNode *gn = static_cast<QSGGeometryNode *>(node);
1497
1498 if (e) {
1503 }
1504
1505 e->boundsComputed = false;
1506 Batch *b = e->batch;
1507 if (b) {
1508 if (!e->batch->geometryWasChanged(gn) || !e->batch->isOpaque) {
1510 } else {
1511 b->needsUpload = true;
1512 }
1513 }
1514 }
1515 }
1516
1519 if (e) {
1520 bool blended = hasMaterialWithBlending(static_cast<QSGGeometryNode *>(node));
1521 if (e->isMaterialBlended != blended) {
1524 } else if (e->batch) {
1527 } else {
1529 }
1530 }
1531 }
1532
1533 // Mark the shadow tree dirty all the way back to the root...
1539 if (dirtyChain != 0) {
1541 Node *sn = shadowNode->parent();
1542 while (sn) {
1544 sn = sn->parent();
1545 }
1546 }
1547
1548 // Delete happens at the very end because it deletes the shadownode.
1551 if (parent)
1554 Q_ASSERT(m_nodes.value(node) == 0);
1555 }
1556
1558}
1559
1560/*
1561 * Traverses the tree and builds two list of geometry nodes. One for
1562 * the opaque and one for the translucent. These are populated
1563 * in the order they should visually appear in, meaning first
1564 * to the back and last to the front.
1565 *
1566 * We split opaque and translucent as we can perform different
1567 * types of reordering / batching strategies on them, depending
1568 *
1569 * Note: It would be tempting to use the shadow nodes instead of the QSGNodes
1570 * for traversal to avoid hash lookups, but the order of the children
1571 * is important and they are not preserved in the shadow tree, so we must
1572 * use the actual QSGNode tree.
1573 */
1575{
1576 if (node->isSubtreeBlocked())
1577 return;
1578
1581
1582 if (node->type() == QSGNode::GeometryNodeType) {
1583 QSGGeometryNode *gn = static_cast<QSGGeometryNode *>(node);
1584
1586 Q_ASSERT(e);
1587
1589 if (opaque && useDepthBuffer())
1591 else
1593
1595 // Used while rebuilding partial roots.
1596 if (m_partialRebuild)
1597 e->orphaned = false;
1598
1599 } else if (node->type() == QSGNode::ClipNodeType || shadowNode->isBatchRoot) {
1602 if (node == m_partialRebuildRoot) {
1607 } else {
1616 }
1617 return;
1618 } else if (node->type() == QSGNode::RenderNodeType) {
1622 Q_ASSERT(e);
1623 }
1624
1627}
1628
1630{
1634 it != i->subRoots.constEnd(); ++it) {
1635 tagSubRoots(*it);
1636 }
1637}
1638
1639static void qsg_addOrphanedElements(QDataBuffer<Element *> &orphans, const QDataBuffer<Element *> &renderList)
1640{
1641 orphans.reset();
1642 for (int i=0; i<renderList.size(); ++i) {
1643 Element *e = renderList.at(i);
1644 if (e && !e->removed) {
1645 e->orphaned = true;
1646 orphans.add(e);
1647 }
1648 }
1649}
1650
1651static void qsg_addBackOrphanedElements(QDataBuffer<Element *> &orphans, QDataBuffer<Element *> &renderList)
1652{
1653 for (int i=0; i<orphans.size(); ++i) {
1654 Element *e = orphans.at(i);
1655 if (e->orphaned)
1656 renderList.add(e);
1657 }
1658 orphans.reset();
1659}
1660
1661/*
1662 * To rebuild the tagged roots, we start by putting all subroots of tagged
1663 * roots into the list of tagged roots. This is to make the rest of the
1664 * algorithm simpler.
1665 *
1666 * Second, we invalidate all batches which belong to tagged roots, which now
1667 * includes the entire subtree under a given root
1668 *
1669 * Then we call buildRenderLists for all tagged subroots which do not have
1670 * parents which are tagged, aka, we traverse only the topmosts roots.
1671 *
1672 * Then we sort the render lists based on their render order, to restore the
1673 * right order for rendering.
1674 */
1676{
1677 // Flag any element that is currently in the render lists, but which
1678 // is not in a batch. This happens when we have a partial rebuild
1679 // in one sub tree while we have a BuildBatches change in another
1680 // isolated subtree. So that batch-building takes into account
1681 // these "orphaned" nodes, we flag them now. The ones under tagged
1682 // roots will be cleared again. The remaining ones are added into the
1683 // render lists so that they contain all visual nodes after the
1684 // function completes.
1687
1688 // Take a copy now, as we will be adding to this while traversing..
1691 it != roots.constEnd(); ++it) {
1692 tagSubRoots(*it);
1693 }
1694
1695 for (int i=0; i<m_opaqueBatches.size(); ++i) {
1699
1700 }
1701 for (int i=0; i<m_alphaBatches.size(); ++i) {
1705 }
1706
1710 m_partialRebuild = true;
1711 // Traverse each root, assigning it
1713 it != m_taggedRoots.constEnd(); ++it) {
1714 Node *root = *it;
1721 }
1722 }
1723 m_partialRebuild = false;
1724 m_partialRebuildRoot = nullptr;
1727
1728 // Add orphaned elements back into the list and then sort it..
1731
1734 if (m_alphaRenderList.size())
1736
1737}
1738
1740{
1743
1744 for (int i=0; i<m_opaqueBatches.size(); ++i)
1746 for (int i=0; i<m_alphaBatches.size(); ++i)
1750
1752
1754}
1755
1757{
1758 Q_ASSERT(batch);
1760
1761#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES)
1766
1769#else
1770 int first = batch->first->order;
1772#endif
1773
1774 batch->invalidate();
1775
1776 for (int i=0; i<m_alphaBatches.size(); ++i) {
1778 if (b->first) {
1779 int bf = b->first->order;
1780 int bl = b->lastOrderInBatch;
1781 if (bl > first && bf < last)
1782 b->invalidate();
1783 }
1784 }
1785
1787}
1788
1789/* Clean up batches by making it a consecutive list of "valid"
1790 * batches and moving all invalidated batches to the batches pool.
1791 */
1793 qsizetype n = batches->size();
1794 if (n == 0)
1795 return;
1796
1798 for (qsizetype i = 0; i < n; ++i) {
1799 Batch *b = batches->at(i);
1800 if (b->first)
1801 (*batches).data()[writeIndex++] = b;
1802 else
1804 }
1806}
1807
1809{
1810 for (int i=m_opaqueRenderList.size() - 1; i >= 0; --i) {
1812 if (!ei || ei->batch || ei->node->geometry()->vertexCount() == 0)
1813 continue;
1814 Batch *batch = newBatch();
1815 batch->first = ei;
1816 batch->root = ei->root;
1817 batch->isOpaque = true;
1818 batch->needsUpload = true;
1820
1822
1823 ei->batch = batch;
1824 Element *next = ei;
1825
1827
1828 for (int j = i - 1; j >= 0; --j) {
1830 if (!ej)
1831 continue;
1832 if (ej->root != ei->root)
1833 break;
1834 if (ej->batch || ej->node->geometry()->vertexCount() == 0)
1835 continue;
1836
1838
1839 const QSGGeometry *gniGeometry = gni->geometry();
1841 const QSGGeometry *gnjGeometry = gnj->geometry();
1843 if (gni->clipList() == gnj->clipList()
1851 && gniMaterial->type() == gnjMaterial->type()
1855 {
1856 ej->batch = batch;
1857 next->nextInBatch = ej;
1858 next = ej;
1859 }
1860 }
1861
1863 }
1864}
1865
1866bool Renderer::checkOverlap(int first, int last, const Rect &bounds)
1867{
1868 for (int i=first; i<=last; ++i) {
1870#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES)
1871 if (!e || e->batch)
1872#else
1873 if (!e)
1874#endif
1875 continue;
1877 if (e->bounds.intersects(bounds))
1878 return true;
1879 }
1880 return false;
1881}
1882
1883/*
1884 *
1885 * To avoid the O(n^2) checkOverlap check in most cases, we have the
1886 * overlapBounds which is the union of all bounding rects to check overlap
1887 * for. We know that if it does not overlap, then none of the individual
1888 * ones will either. For the typical list case, this results in no calls
1889 * to checkOverlap what-so-ever. This also ensures that when all consecutive
1890 * items are matching (such as a table of text), we don't build up an
1891 * overlap bounds and thus do not require full overlap checks.
1892 */
1893
1895{
1896 for (int i=0; i<m_alphaRenderList.size(); ++i) {
1898 if (!e || e->isRenderNode)
1899 continue;
1900 Q_ASSERT(!e->removed);
1902 }
1903
1904 for (int i=0; i<m_alphaRenderList.size(); ++i) {
1906 if (!ei || ei->batch)
1907 continue;
1908
1909 if (ei->isRenderNode) {
1910 Batch *rnb = newBatch();
1911 rnb->first = ei;
1912 rnb->root = ei->root;
1913 rnb->isOpaque = false;
1914 rnb->isRenderNode = true;
1915 ei->batch = rnb;
1917 continue;
1918 }
1919
1920 if (ei->node->geometry()->vertexCount() == 0)
1921 continue;
1922
1923 Batch *batch = newBatch();
1924 batch->first = ei;
1925 batch->root = ei->root;
1926 batch->isOpaque = false;
1927 batch->needsUpload = true;
1929 ei->batch = batch;
1930
1933
1936
1937 Element *next = ei;
1938
1939 for (int j = i + 1; j < m_alphaRenderList.size(); ++j) {
1941 if (!ej)
1942 continue;
1943 if (ej->root != ei->root || ej->isRenderNode)
1944 break;
1945 if (ej->batch) {
1946#if !defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES)
1948#endif
1949 continue;
1950 }
1951
1953 if (gnj->geometry()->vertexCount() == 0)
1954 continue;
1955
1956 const QSGGeometry *gniGeometry = gni->geometry();
1958 const QSGGeometry *gnjGeometry = gnj->geometry();
1960 if (gni->clipList() == gnj->clipList()
1964 // Must not do overlap checks when the line width is not 1,
1965 // we have no knowledge how such lines are rasterized.
1966 && gniGeometry->lineWidth() == 1.0f))
1970 && gniMaterial->type() == gnjMaterial->type()
1974 {
1975 if (!overlapBounds.intersects(ej->bounds) || !checkOverlap(i+1, j - 1, ej->bounds)) {
1976 ej->batch = batch;
1977 next->nextInBatch = ej;
1978 next = ej;
1979 } else {
1980 /* When we come across a compatible element which hits an overlap, we
1981 * need to stop the batch right away. We cannot add more elements
1982 * to the current batch as they will be rendered before the batch that the
1983 * current 'ej' will be added to.
1984 */
1985 break;
1986 }
1987 } else {
1989 }
1990 }
1991
1993 }
1994
1995
1996}
1997
1998static inline int qsg_fixIndexCount(int iCount, int drawMode)
1999{
2000 switch (drawMode) {
2001 case QSGGeometry::DrawTriangleStrip:
2002 // Merged triangle strips need to contain degenerate triangles at the beginning and end.
2003 // One could save 2 uploaded ushorts here by ditching the padding for the front of the
2004 // first and the end of the last, but for simplicity, we simply don't care.
2005 // Those extra triangles will be skipped while drawing to preserve the strip's parity
2006 // anyhow.
2007 return iCount + 2;
2008 case QSGGeometry::DrawLines:
2009 // For lines we drop the last vertex if the number of vertices is uneven.
2010 return iCount - (iCount % 2);
2011 case QSGGeometry::DrawTriangles:
2012 // For triangles we drop trailing vertices until the result is divisible by 3.
2013 return iCount - (iCount % 3);
2014 default:
2015 return iCount;
2016 }
2017}
2018
2019static inline float calculateElementZOrder(const Element *e, qreal zRange)
2020{
2021 // Clamp the zOrder to within the min and max depth of the viewport.
2022 return std::clamp(1.0f - float(e->order * zRange), VIEWPORT_MIN_DEPTH, VIEWPORT_MAX_DEPTH);
2023}
2024
2025/* These parameters warrant some explanation...
2026 *
2027 * vaOffset: The byte offset into the vertex data to the location of the
2028 * 2D float point vertex attributes.
2029 *
2030 * vertexData: destination where the geometry's vertex data should go
2031 *
2032 * zData: destination of geometries injected Z positioning
2033 *
2034 * indexData: destination of the indices for this element
2035 *
2036 * iBase: The starting index for this element in the batch
2037 */
2038
2039void Renderer::uploadMergedElement(Element *e, int vaOffset, char **vertexData, char **zData, char **indexData, void *iBasePtr, int *indexCount)
2040{
2041 if (Q_UNLIKELY(debug_upload())) qDebug() << " - uploading element:" << e << e->node << (void *) *vertexData << (qintptr) (*zData - *vertexData) << (qintptr) (*indexData - *vertexData);
2042 QSGGeometry *g = e->node->geometry();
2043
2044 const QMatrix4x4 &localx = *e->node->matrix();
2045 const float *localxdata = localx.constData();
2046
2047 const int vCount = g->vertexCount();
2048 const int vSize = g->sizeOfVertex();
2050
2051 // apply vertex transform..
2052 char *vdata = *vertexData + vaOffset;
2053 if (localx.flags() == QMatrix4x4::Translation) {
2054 for (int i=0; i<vCount; ++i) {
2055 Pt *p = (Pt *) vdata;
2056 p->x += localxdata[12];
2057 p->y += localxdata[13];
2058 vdata += vSize;
2059 }
2060 } else if (localx.flags() > QMatrix4x4::Translation) {
2061 for (int i=0; i<vCount; ++i) {
2062 ((Pt *) vdata)->map(localx);
2063 vdata += vSize;
2064 }
2065 }
2066
2067 if (useDepthBuffer()) {
2068 float *vzorder = (float *) *zData;
2070 for (int i=0; i<vCount; ++i)
2071 vzorder[i] = zorder;
2072 *zData += vCount * sizeof(float);
2073 }
2074
2075 int iCount = g->indexCount();
2076 if (m_uint32IndexForRhi) {
2077 // can only happen when using the rhi
2080 if (iCount == 0) {
2081 iCount = vCount;
2083 *indices++ = *iBase;
2084 else
2086
2087 for (int i=0; i<iCount; ++i)
2088 indices[i] = *iBase + i;
2089 } else {
2090 // source index data in QSGGeometry is always ushort (we would not merge otherwise)
2093 *indices++ = *iBase + srcIndices[0];
2094 else
2096
2097 for (int i=0; i<iCount; ++i)
2098 indices[i] = *iBase + srcIndices[i];
2099 }
2101 indices[iCount] = indices[iCount - 1];
2102 iCount += 2;
2103 }
2104 *iBase += vCount;
2105 } else {
2106 // normally batching is only done for ushort index data
2109 if (iCount == 0) {
2110 iCount = vCount;
2112 *indices++ = *iBase;
2113 else
2115
2116 for (int i=0; i<iCount; ++i)
2117 indices[i] = *iBase + i;
2118 } else {
2121 *indices++ = *iBase + srcIndices[0];
2122 else
2124
2125 for (int i=0; i<iCount; ++i)
2126 indices[i] = *iBase + srcIndices[i];
2127 }
2129 indices[iCount] = indices[iCount - 1];
2130 iCount += 2;
2131 }
2132 *iBase += vCount;
2133 }
2134
2135 *vertexData += vCount * vSize;
2137 *indexCount += iCount;
2138}
2139
2141{
2142 if (node->type() == QSGNode::TransformNodeType)
2143 return static_cast<QSGTransformNode *>(node->sgNode)->combinedMatrix();
2144 Q_ASSERT(node->type() == QSGNode::ClipNodeType);
2145 QSGClipNode *c = static_cast<QSGClipNode *>(node->sgNode);
2146 return *c->matrix();
2147}
2148
2150{
2151 // Early out if nothing has changed in this batch..
2152 if (!b->needsUpload) {
2153 if (Q_UNLIKELY(debug_upload())) qDebug() << " Batch:" << b << "already uploaded...";
2154 return;
2155 }
2156
2157 if (!b->first) {
2158 if (Q_UNLIKELY(debug_upload())) qDebug() << " Batch:" << b << "is invalid...";
2159 return;
2160 }
2161
2162 if (b->isRenderNode) {
2163 if (Q_UNLIKELY(debug_upload())) qDebug() << " Batch: " << b << "is a render node...";
2164 return;
2165 }
2166
2167 // Figure out if we can merge or not, if not, then just render the batch as is..
2168 Q_ASSERT(b->first);
2169 Q_ASSERT(b->first->node);
2170
2172 QSGGeometry *g = gn->geometry();
2176 && b->positionAttribute >= 0
2180 && b->isSafeToBatch();
2181
2182 b->merged = canMerge;
2183
2184 // Figure out how much memory we need...
2185 b->vertexCount = 0;
2186 b->indexCount = 0;
2187 int unmergedIndexSize = 0;
2188 Element *e = b->first;
2189
2190 // Merged batches always do indexed draw calls. Non-indexed geometry gets
2191 // indices generated automatically, when merged.
2192 while (e) {
2193 QSGGeometry *eg = e->node->geometry();
2194 b->vertexCount += eg->vertexCount();
2195 int iCount = eg->indexCount();
2196 if (b->merged) {
2197 if (iCount == 0)
2198 iCount = eg->vertexCount();
2200 } else {
2201 const int effectiveIndexSize = m_uint32IndexForRhi ? sizeof(quint32) : eg->sizeOfIndex();
2203 }
2204 b->indexCount += iCount;
2205 e = e->nextInBatch;
2206 }
2207
2208 // Abort if there are no vertices in this batch.. We abort this late as
2209 // this is a broken usecase which we do not care to optimize for...
2210 if (b->vertexCount == 0 || (b->merged && b->indexCount == 0))
2211 return;
2212
2213 /* Allocate memory for this batch. Merged batches are divided into three separate blocks
2214 1. Vertex data for all elements, as they were in the QSGGeometry object, but
2215 with the tranform relative to this batch's root applied. The vertex data
2216 is otherwise unmodified.
2217 2. Z data for all elements, derived from each elements "render order".
2218 This is present for merged data only.
2219 3. Indices for all elements, as they were in the QSGGeometry object, but
2220 adjusted so that each index matches its.
2221 And for TRIANGLE_STRIPs, we need to insert degenerate between each
2222 primitive. These are unsigned shorts for merged and arbitrary for
2223 non-merged.
2224 */
2226 int ibufferSize = 0;
2227 if (b->merged) {
2229 if (useDepthBuffer())
2230 bufferSize += b->vertexCount * sizeof(float);
2231 } else {
2233 }
2234
2235 map(&b->ibo, ibufferSize, true);
2236 map(&b->vbo, bufferSize);
2237
2238 if (Q_UNLIKELY(debug_upload())) qDebug() << " - batch" << b << " first:" << b->first << " root:"
2239 << b->root << " merged:" << b->merged << " positionAttribute" << b->positionAttribute
2240 << " vbo:" << b->vbo.buf << ":" << b->vbo.size;
2241
2242 if (b->merged) {
2243 char *vertexData = b->vbo.data;
2244 char *zData = vertexData + b->vertexCount * g->sizeOfVertex();
2245 char *indexData = b->ibo.data;
2246
2247 quint16 iOffset16 = 0;
2248 quint32 iOffset32 = 0;
2249 e = b->first;
2250 uint verticesInSet = 0;
2251 // Start a new set already after 65534 vertices because 0xFFFF may be
2252 // used for an always-on primitive restart with some apis (adapt for
2253 // uint32 indices as appropriate).
2254 const uint verticesInSetLimit = m_uint32IndexForRhi ? 0xfffffffe : 0xfffe;
2255 int indicesInSet = 0;
2256 b->drawSets.reset();
2257 int drawSetIndices = 0;
2258 const char *indexBase = b->ibo.data;
2260 while (e) {
2266 b->drawSets.last().indexCount -= 2;
2267 }
2270 zData - b->vbo.data,
2272 iOffset16 = 0;
2273 iOffset32 = 0;
2275 indicesInSet = 0;
2276 }
2277 void *iBasePtr = &iOffset16;
2281 e = e->nextInBatch;
2282 }
2284 // We skip the very first and very last degenerate triangles since they aren't needed
2285 // and the first one would reverse the vertex ordering of the merged strips.
2288 b->drawSets.last().indexCount -= 2;
2289 }
2290 } else {
2291 char *vboData = b->vbo.data;
2292 char *iboData = b->ibo.data;
2293 Element *e = b->first;
2294 while (e) {
2295 QSGGeometry *g = e->node->geometry();
2296 int vbs = g->vertexCount() * g->sizeOfVertex();
2298 vboData = vboData + vbs;
2299 const int indexCount = g->indexCount();
2300 if (indexCount) {
2301 const int effectiveIndexSize = m_uint32IndexForRhi ? sizeof(quint32) : g->sizeOfIndex();
2302 const int ibs = indexCount * effectiveIndexSize;
2303 if (g->sizeOfIndex() == effectiveIndexSize) {
2305 } else {
2306 if (g->sizeOfIndex() == sizeof(quint16) && effectiveIndexSize == sizeof(quint32)) {
2308 quint32 *dst = (quint32 *) iboData;
2309 for (int i = 0; i < indexCount; ++i)
2310 dst[i] = src[i];
2311 } else {
2312 Q_ASSERT_X(false, "uploadBatch (unmerged)", "uint index with ushort effective index - cannot happen");
2313 }
2314 }
2315 iboData += ibs;
2316 }
2317 e = e->nextInBatch;
2318 }
2319 }
2320#ifndef QT_NO_DEBUG_OUTPUT
2321 if (Q_UNLIKELY(debug_upload())) {
2322 const char *vd = b->vbo.data;
2323 qDebug() << " -- Vertex Data, count:" << b->vertexCount << " - " << g->sizeOfVertex() << "bytes/vertex";
2324 for (int i=0; i<b->vertexCount; ++i) {
2325 QDebug dump = qDebug().nospace();
2326 dump << " --- " << i << ": ";
2327 int offset = 0;
2328 for (int a=0; a<g->attributeCount(); ++a) {
2329 const QSGGeometry::Attribute &attr = g->attributes()[a];
2330 dump << attr.position << ":(" << attr.tupleSize << ",";
2331 if (attr.type == QSGGeometry::FloatType) {
2332 dump << "float ";
2334 dump << "* ";
2335 for (int t=0; t<attr.tupleSize; ++t)
2336 dump << *(const float *)(vd + offset + t * sizeof(float)) << " ";
2337 } else if (attr.type == QSGGeometry::UnsignedByteType) {
2338 dump << "ubyte ";
2339 for (int t=0; t<attr.tupleSize; ++t)
2340 dump << *(const unsigned char *)(vd + offset + t * sizeof(unsigned char)) << " ";
2341 }
2342 dump << ") ";
2344 }
2345 if (b->merged && useDepthBuffer()) {
2346 float zorder = ((float*)(b->vbo.data + b->vertexCount * g->sizeOfVertex()))[i];
2347 dump << " Z:(" << zorder << ")";
2348 }
2349 vd += g->sizeOfVertex();
2350 }
2351
2352 if (!b->drawSets.isEmpty()) {
2353 if (m_uint32IndexForRhi) {
2354 const quint32 *id = (const quint32 *) b->ibo.data;
2355 {
2356 QDebug iDump = qDebug();
2357 iDump << " -- Index Data, count:" << b->indexCount;
2358 for (int i=0; i<b->indexCount; ++i) {
2359 if ((i % 24) == 0)
2360 iDump << Qt::endl << " --- ";
2361 iDump << id[i];
2362 }
2363 }
2364 } else {
2365 const quint16 *id = (const quint16 *) b->ibo.data;
2366 {
2367 QDebug iDump = qDebug();
2368 iDump << " -- Index Data, count:" << b->indexCount;
2369 for (int i=0; i<b->indexCount; ++i) {
2370 if ((i % 24) == 0)
2371 iDump << Qt::endl << " --- ";
2372 iDump << id[i];
2373 }
2374 }
2375 }
2376
2377 for (int i=0; i<b->drawSets.size(); ++i) {
2378 const DrawSet &s = b->drawSets.at(i);
2379 qDebug() << " -- DrawSet: indexCount:" << s.indexCount << " vertices:" << s.vertices << " z:" << s.zorders << " indices:" << s.indices;
2380 }
2381 }
2382 }
2383#endif // QT_NO_DEBUG_OUTPUT
2384
2385 unmap(&b->vbo);
2386 unmap(&b->ibo, true);
2387
2389 qDebug() << " --- vertex/index buffers unmapped, batch upload completed... vbo pool size" << m_vboPoolCost << "ibo pool size" << m_iboPoolCost;
2390
2391 b->needsUpload = false;
2392
2393 if (Q_UNLIKELY(debug_render()))
2394 b->uploadedThisFrame = true;
2395}
2396
2398{
2401}
2402
2404{
2408 blend.colorWrite = {};
2409 ps->setTargetBlends({ blend });
2411 ps->setStencilTest(true);
2418 } else {
2423 }
2426
2428
2430
2434 ps->setShaderResourceBindings(batch->stencilClipState.srb); // use something, it just needs to be layout-compatible
2436
2437 if (!ps->create()) {
2438 qWarning("Failed to build stencil clip pipeline");
2439 delete ps;
2440 return nullptr;
2441 }
2442
2443 return ps;
2444}
2445
2447{
2448 // Note: No use of the clip-related speparate m_current* vars is allowed
2449 // here. All stored in batch->clipState instead. To collect state during
2450 // the prepare steps, m_currentClipState is used. It should not be used in
2451 // the render steps afterwards.
2452
2453 // The stenciling logic is slightly different from Qt 5's direct OpenGL version
2454 // as we cannot just randomly clear the stencil buffer. We now put all clip
2455 // shapes into the stencil buffer for all batches in the frame. This means
2456 // that the number of total clips in a scene is reduced (since the stencil
2457 // value cannot exceed 255) but we do not need any clears inbetween.
2458
2459 Q_ASSERT(m_rhi);
2464 return;
2465 }
2466
2470 const QSGClipNode *clip = clipList;
2471
2473 quint32 totalVSize = 0;
2474 quint32 totalISize = 0;
2475 quint32 totalUSize = 0;
2476 const quint32 StencilClipUbufSize = 64;
2477
2478 while (clip) {
2479 QMatrix4x4 m = m_current_projection_matrix_native_ndc[0]; // never hit for 3D and so multiview
2480 if (clip->matrix())
2481 m *= *clip->matrix();
2482
2484 && qFuzzyIsNull(m(3, 0)) && qFuzzyIsNull(m(3, 1));
2485 bool noRotate = qFuzzyIsNull(m(0, 1)) && qFuzzyIsNull(m(1, 0));
2486 bool isRotate90 = qFuzzyIsNull(m(0, 0)) && qFuzzyIsNull(m(1, 1));
2487
2489 QRectF bbox = clip->clipRect();
2490 qreal invW = 1 / m(3, 3);
2491 qreal fx1, fy1, fx2, fy2;
2492 if (noRotate) {
2493 fx1 = (bbox.left() * m(0, 0) + m(0, 3)) * invW;
2494 fy1 = (bbox.bottom() * m(1, 1) + m(1, 3)) * invW;
2495 fx2 = (bbox.right() * m(0, 0) + m(0, 3)) * invW;
2496 fy2 = (bbox.top() * m(1, 1) + m(1, 3)) * invW;
2497 } else {
2499 fx1 = (bbox.bottom() * m(0, 1) + m(0, 3)) * invW;
2500 fy1 = (bbox.left() * m(1, 0) + m(1, 3)) * invW;
2501 fx2 = (bbox.top() * m(0, 1) + m(0, 3)) * invW;
2502 fy2 = (bbox.right() * m(1, 0) + m(1, 3)) * invW;
2503 }
2504
2505 if (fx1 > fx2)
2506 qSwap(fx1, fx2);
2507 if (fy1 > fy2)
2508 qSwap(fy1, fy2);
2509
2510 QRect deviceRect = this->deviceRect();
2511
2512 qint32 ix1 = qRound((fx1 + 1) * deviceRect.width() * qreal(0.5));
2513 qint32 iy1 = qRound((fy1 + 1) * deviceRect.height() * qreal(0.5));
2514 qint32 ix2 = qRound((fx2 + 1) * deviceRect.width() * qreal(0.5));
2515 qint32 iy2 = qRound((fy2 + 1) * deviceRect.height() * qreal(0.5));
2516
2517 if (!(clipType & ClipState::ScissorClip)) {
2519 scissorRect = QRect(ix1, iy1, ix2 - ix1, iy2 - iy1);
2520 } else {
2521 scissorRect &= QRect(ix1, iy1, ix2 - ix1, iy2 - iy1);
2522 }
2523 } else {
2525
2526 const QSGGeometry *g = clip->geometry();
2527 Q_ASSERT(g->attributeCount() > 0);
2528
2529 const int vertexByteSize = g->sizeOfVertex() * g->vertexCount();
2530 // the 4 byte alignment may not actually be needed here
2532 if (g->indexCount()) {
2533 const int indexByteSize = g->sizeOfIndex() * g->indexCount();
2534 // so no need to worry about NonFourAlignedEffectiveIndexBufferOffset
2536 }
2537 // ubuf start offsets must be aligned (typically to 256 bytes)
2539
2541 }
2542
2543 clip = clip->clipList();
2544 }
2545
2547 bool rebuildVBuf = false;
2548 if (!batch->stencilClipState.vbuf) {
2550 rebuildVBuf = true;
2551 } else if (batch->stencilClipState.vbuf->size() < totalVSize) {
2553 rebuildVBuf = true;
2554 }
2555 if (rebuildVBuf) {
2556 if (!batch->stencilClipState.vbuf->create()) {
2557 qWarning("Failed to build stencil clip vertex buffer");
2558 delete batch->stencilClipState.vbuf;
2559 batch->stencilClipState.vbuf = nullptr;
2560 return;
2561 }
2562 }
2563
2564 if (totalISize) {
2565 bool rebuildIBuf = false;
2566 if (!batch->stencilClipState.ibuf) {
2568 rebuildIBuf = true;
2569 } else if (batch->stencilClipState.ibuf->size() < totalISize) {
2571 rebuildIBuf = true;
2572 }
2573 if (rebuildIBuf) {
2574 if (!batch->stencilClipState.ibuf->create()) {
2575 qWarning("Failed to build stencil clip index buffer");
2576 delete batch->stencilClipState.ibuf;
2577 batch->stencilClipState.ibuf = nullptr;
2578 return;
2579 }
2580 }
2581 }
2582
2583 bool rebuildUBuf = false;
2584 if (!batch->stencilClipState.ubuf) {
2586 rebuildUBuf = true;
2587 } else if (batch->stencilClipState.ubuf->size() < totalUSize) {
2589 rebuildUBuf = true;
2590 }
2591 if (rebuildUBuf) {
2592 if (!batch->stencilClipState.ubuf->create()) {
2593 qWarning("Failed to build stencil clip uniform buffer");
2594 delete batch->stencilClipState.ubuf;
2595 batch->stencilClipState.ubuf = nullptr;
2596 return;
2597 }
2598 }
2599
2600 if (!batch->stencilClipState.srb) {
2605 if (!batch->stencilClipState.srb->create()) {
2606 qWarning("Failed to build stencil clip srb");
2607 delete batch->stencilClipState.srb;
2608 batch->stencilClipState.srb = nullptr;
2609 return;
2610 }
2611 }
2612
2613 quint32 vOffset = 0;
2614 quint32 iOffset = 0;
2615 quint32 uOffset = 0;
2616 for (const QSGClipNode *clip : stencilClipNodes) {
2617 const QSGGeometry *g = clip->geometry();
2618 const QSGGeometry::Attribute *a = g->attributes();
2621
2626 }
2627#ifndef QT_NO_DEBUG
2628 else {
2630 qWarning("updateClipState: Clip list entries have different primitive topologies, this is not currently supported.");
2632 qWarning("updateClipState: Clip list entries have different vertex input layouts, this is must not happen.");
2633 }
2634#endif
2635
2637 const int vertexByteSize = g->sizeOfVertex() * g->vertexCount();
2639
2640 int indexByteSize = 0;
2641 if (g->indexCount()) {
2645 }
2646
2649
2651 if (clip->matrix())
2652 matrixYUpNDC *= *clip->matrix();
2653
2656 if (indexByteSize)
2658
2659 // stencil ref goes 1, 1, 2, 3, 4, ..., N for the clips in the first batch,
2660 // then N+1, N+1, N+2, N+3, ... for the next batch,
2661 // and so on.
2662 // Note the different stencilOp for the first and the subsequent clips.
2665
2670 }
2671
2673 m_stencilClipCommon.vs = QSGMaterialShaderPrivate::loadShader(QLatin1String(":/qt-project.org/scenegraph/shaders_ng/stencilclip.vert.qsb"));
2674
2676 m_stencilClipCommon.fs = QSGMaterialShaderPrivate::loadShader(QLatin1String(":/qt-project.org/scenegraph/shaders_ng/stencilclip.frag.qsb"));
2677
2680
2683
2685 }
2686
2691
2694}
2695
2697{
2698 // cliptype stencil + updateStencilBuffer==false means the batch uses
2699 // stenciling but relies on the stencil data generated by a previous batch
2700 // (due to the having the same clip node). Do not enqueue draw calls for
2701 // stencil in this case as the stencil buffer is already up-to-date.
2703 return;
2704
2706 const int count = batch->stencilClipState.drawCalls.size();
2707 for (int i = 0; i < count; ++i) {
2711 if (i == 0) {
2714 } else if (i == 1) {
2717 }
2718 // else incrPs is already bound
2722 if (drawCall.indexCount) {
2726 } else {
2727 cb->setVertexInput(0, 1, &vbufBinding);
2729 }
2730 }
2731}
2732
2734{
2735 Q_ASSERT(m_rhi);
2738 m_currentMaterial = nullptr;
2739}
2740
2741static inline bool needsBlendConstant(QRhiGraphicsPipeline::BlendFactor f)
2742{
2743 return f == QRhiGraphicsPipeline::ConstantColor
2744 || f == QRhiGraphicsPipeline::OneMinusConstantColor
2745 || f == QRhiGraphicsPipeline::ConstantAlpha
2746 || f == QRhiGraphicsPipeline::OneMinusConstantAlpha;
2747}
2748
2749// With QRhi renderBatches() is split to two steps: prepare and render.
2750//
2751// Prepare goes through the batches and elements, and set up a graphics
2752// pipeline, srb, uniform buffer, calculates clipping, based on m_gstate, the
2753// material (shaders), and the batches. This step does not touch the command
2754// buffer or renderpass-related state (m_pstate).
2755//
2756// The render step then starts a renderpass, and goes through all
2757// batches/elements again and records setGraphicsPipeline, drawIndexed, etc. on
2758// the command buffer. The prepare step's accumulated global state like
2759// m_gstate must not be used here. Rather, all data needed for rendering is
2760// available from Batch/Element at this stage. Bookkeeping of state in the
2761// renderpass is done via m_pstate.
2762
2764{
2765 // Note the key's == and qHash implementations: the renderpass descriptor
2766 // and srb are tested for compatibility, not pointer equality.
2767 //
2768 // We do not store the srb pointer itself because the ownership stays with
2769 // the Element and that can go away more often that we would like it
2770 // to. (think scrolling a list view, constantly dropping and creating new
2771 // nodes) Rather, use an opaque blob of a few uints and store and compare
2772 // that. This works because once the pipeline is built, we will always call
2773 // setShaderResources with an explicitly specified srb which is fine even if
2774 // e->srb we used here to bake the pipeline is already gone by that point.
2775 //
2776 // A typical QSGMaterial's serialized srb layout is 8 uints. (uniform buffer
2777 // + texture, 4 fields each) Regardless, using an implicitly shared
2778 // container is essential here. (won't detach so no more allocs and copies
2779 // are done, unless the Element decides to rebake the srb with a different
2780 // layout - but then the detach is exactly what we need)
2781 //
2782 // Same story for the renderpass descriptor: the object can go away but
2783 // that's fine because that has no effect on an already built pipeline, and
2784 // for comparison we only rely on the serialized blob in order decide if the
2785 // render target is compatible with the pipeline.
2786
2789 && prepared->psSms == sms && prepared->psState == m_gstate)
2790 {
2791 return true;
2792 }
2793
2795
2796 // Note: dynamic state (viewport rect, scissor rect, stencil ref, blend
2797 // constant) is never a part of GraphicsState/QRhiGraphicsPipeline.
2798
2799 auto remember = [this, prepared, sms] {
2800 if (prepared) {
2802 prepared->psSms = sms;
2804 }
2805 };
2806
2807 // See if there is an existing, matching pipeline state object.
2810 if (depthPostPass)
2811 e->depthPostPassPs = *it;
2812 else
2813 e->ps = *it;
2814 remember();
2815 return true;
2816 }
2817
2818 // Build a new one. This is potentially expensive.
2824
2828 {
2830 }
2835
2836 ps->setFlags(flags);
2842
2852 ps->setTargetBlends({ blend });
2853
2857
2858 if (m_gstate.stencilTest) {
2859 ps->setStencilTest(true);
2867 }
2868
2870
2872
2873 if (!ps->create()) {
2874 qWarning("Failed to build graphics pipeline state");
2875 delete ps;
2876 return false;
2877 }
2878
2880 if (depthPostPass)
2881 e->depthPostPassPs = ps;
2882 else
2883 e->ps = ps;
2884 remember();
2885 return true;
2886}
2887
2889{
2890 // the descriptor may have been recreated at the same address
2893 if (rpDesc != m_lastRpDesc) {
2894 changed = true;
2897 } else if (rpDesc) {
2899 if (format != m_lastRpDescFormat) {
2900 changed = true;
2902 }
2903 }
2904 if (changed) {
2906 if (++m_pipelineGeneration == 0)
2908 }
2909}
2910
2911static QRhiSampler *newSampler(QRhi *rhi, const QSGSamplerDescription &desc)
2912{
2913 QRhiSampler::Filter magFilter;
2914 QRhiSampler::Filter minFilter;
2915 QRhiSampler::Filter mipmapMode;
2916 QRhiSampler::AddressMode u;
2917 QRhiSampler::AddressMode v;
2918
2919 switch (desc.filtering) {
2920 case QSGTexture::None:
2921 Q_FALLTHROUGH();
2922 case QSGTexture::Nearest:
2923 magFilter = minFilter = QRhiSampler::Nearest;
2924 break;
2925 case QSGTexture::Linear:
2926 magFilter = minFilter = QRhiSampler::Linear;
2927 break;
2928 default:
2929 Q_UNREACHABLE();
2930 magFilter = minFilter = QRhiSampler::Nearest;
2931 break;
2932 }
2933
2934 switch (desc.mipmapFiltering) {
2935 case QSGTexture::None:
2936 mipmapMode = QRhiSampler::None;
2937 break;
2938 case QSGTexture::Nearest:
2939 mipmapMode = QRhiSampler::Nearest;
2940 break;
2941 case QSGTexture::Linear:
2942 mipmapMode = QRhiSampler::Linear;
2943 break;
2944 default:
2945 Q_UNREACHABLE();
2946 mipmapMode = QRhiSampler::None;
2947 break;
2948 }
2949
2950 switch (desc.horizontalWrap) {
2951 case QSGTexture::Repeat:
2952 u = QRhiSampler::Repeat;
2953 break;
2954 case QSGTexture::ClampToEdge:
2955 u = QRhiSampler::ClampToEdge;
2956 break;
2957 case QSGTexture::MirroredRepeat:
2958 u = QRhiSampler::Mirror;
2959 break;
2960 default:
2961 Q_UNREACHABLE();
2962 u = QRhiSampler::ClampToEdge;
2963 break;
2964 }
2965
2966 switch (desc.verticalWrap) {
2967 case QSGTexture::Repeat:
2968 v = QRhiSampler::Repeat;
2969 break;
2970 case QSGTexture::ClampToEdge:
2971 v = QRhiSampler::ClampToEdge;
2972 break;
2973 case QSGTexture::MirroredRepeat:
2974 v = QRhiSampler::Mirror;
2975 break;
2976 default:
2977 Q_UNREACHABLE();
2978 v = QRhiSampler::ClampToEdge;
2979 break;
2980 }
2981
2982 return rhi->newSampler(magFilter, minFilter, mipmapMode, u, v);
2983}
2984
2986{
2987 if (!m_dummyTexture) {
2989 if (m_dummyTexture->create()) {
2990 if (m_resourceUpdates) {
2992 img.fill(0);
2994 }
2995 }
2996 }
2997 return m_dummyTexture;
2998}
2999
3000static void rendererToMaterialGraphicsState(QSGMaterialShader::GraphicsPipelineState *dst,
3001 GraphicsState *src)
3002{
3003 dst->blendEnable = src->blending;
3004
3005 // the enum values should match, sanity check it
3006 Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::OneMinusSrc1Alpha) == int(QRhiGraphicsPipeline::OneMinusSrc1Alpha));
3007 Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::BlendOp::Max) == int(QRhiGraphicsPipeline::Max));
3008 Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::A) == int(QRhiGraphicsPipeline::A));
3009 Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::CullBack) == int(QRhiGraphicsPipeline::Back));
3010 Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::Line) == int(QRhiGraphicsPipeline::Line));
3011 dst->srcColor = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->srcColor);
3012 dst->dstColor = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->dstColor);
3013
3014 // For compatibility with any existing code, separateBlendFactors defaults
3015 // to _false_ which means that materials that do not touch srcAlpha and
3016 // dstAlpha will continue to use srcColor and dstColor as the alpha
3017 // blending factors. New code that needs different values for color/alpha,
3018 // can explicitly set separateBlendFactors to true and then set srcAlpha
3019 // and dstAlpha as well.
3020 dst->separateBlendFactors = false;
3021
3022 dst->srcAlpha = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->srcAlpha);
3023 dst->dstAlpha = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->dstAlpha);
3024
3025 dst->opColor = QSGMaterialShader::GraphicsPipelineState::BlendOp(src->opColor);
3026 dst->opAlpha = QSGMaterialShader::GraphicsPipelineState::BlendOp(src->opAlpha);
3027
3028 dst->colorWrite = QSGMaterialShader::GraphicsPipelineState::ColorMask(int(src->colorWrite));
3029
3030 dst->cullMode = QSGMaterialShader::GraphicsPipelineState::CullMode(src->cullMode);
3031 dst->polygonMode = QSGMaterialShader::GraphicsPipelineState::PolygonMode(src->polygonMode);
3032}
3033
3035 QSGMaterialShader::GraphicsPipelineState *src)
3036{
3037 dst->blending = src->blendEnable;
3038 dst->srcColor = QRhiGraphicsPipeline::BlendFactor(src->srcColor);
3039 dst->dstColor = QRhiGraphicsPipeline::BlendFactor(src->dstColor);
3040 if (src->separateBlendFactors) {
3041 dst->srcAlpha = QRhiGraphicsPipeline::BlendFactor(src->srcAlpha);
3042 dst->dstAlpha = QRhiGraphicsPipeline::BlendFactor(src->dstAlpha);
3043 } else {
3044 dst->srcAlpha = dst->srcColor;
3045 dst->dstAlpha = dst->dstColor;
3046 }
3047 dst->opColor = QRhiGraphicsPipeline::BlendOp(src->opColor);
3048 dst->opAlpha = QRhiGraphicsPipeline::BlendOp(src->opAlpha);
3049 dst->colorWrite = QRhiGraphicsPipeline::ColorMask(int(src->colorWrite));
3050 dst->cullMode = QRhiGraphicsPipeline::CullMode(src->cullMode);
3051 dst->polygonMode = QRhiGraphicsPipeline::PolygonMode(src->polygonMode);
3052}
3053
3055{
3057 return false;
3058
3061 if (end > quint32(m_uniformData.size()))
3063
3064 if (!m_uniformBuffer || m_uniformBuffer->size() < end) {
3066 if (m_uniformBuffer)
3068 else
3070 if (!m_uniformBuffer->create()) {
3071 qWarning("Failed to build uniform buffer of size %u bytes", bufferSize);
3072 // The batches prepared so far in this frame refer to the buffer as
3073 // well, prepareRenderPass() drops them. Retried in the next frame.
3074 delete m_uniformBuffer;
3075 m_uniformBuffer = nullptr;
3076 m_uniformBufferFailed = true;
3077 return false;
3078 }
3079 }
3080
3081 *offset = start;
3083 return true;
3084}
3085
3086// Not to be called between prepareRenderPass() and recordRenderPass(), the
3087// contents is lost.
3089{
3091 return;
3092
3094 if (!m_uniformBuffer->create()) {
3095 // recreated on the next allocateUniformData()
3096 delete m_uniformBuffer;
3097 m_uniformBuffer = nullptr;
3098 }
3099}
3100
3104 Element *e)
3105{
3107
3110
3111 if (pd->ubufBinding >= 0) {
3114 return false;
3115
3117 // The return value ('changed') is no longer used, and did not have much value to
3118 // begin with due to mostly being true (due to the matrix being dirty).
3120 m_current_uniform_data = nullptr;
3121
3123 }
3124
3126
3128 const int binding = qCountTrailingZeroBits(mask);
3129
3132
3135
3138
3139 if (nextTex.contains(nullptr)) {
3140 qWarning("No QSGTexture provided from updateSampledImage(). This is wrong.");
3141 continue;
3142 }
3143
3144 bool hasDirtySamplerOptions = false;
3145 bool isAnisotropic = false;
3146 for (QSGTexture *t : nextTex) {
3151 }
3152
3153 // prevTex may be invalid at this point, avoid dereferencing it
3155
3156 // The QSGTexture, and so the sampler parameters, may have changed.
3157 // The rhiTexture is not relevant here.
3158 pd->textureBindingTable[binding] = nextTex; // does not own
3159
3160 if (isAnisotropic) // ###
3161 qWarning("QSGTexture anisotropy levels are not currently supported");
3162
3165 int n = 0;
3166 for (QSGTexture *t : nextTex) {
3168 if (n < samplers.size() && descs[n] == samplerDesc) {
3169 ++n;
3170 continue;
3171 }
3172
3174
3175 if (!sampler) {
3177 if (!sampler->create()) {
3178 qWarning("Failed to build sampler");
3179 delete sampler;
3180 continue;
3181 }
3183 }
3184 if (n >= samplers.size()) {
3185 descs.resize(n + 1);
3186 samplers.resize(n + 1);
3187 }
3188 descs[n] = samplerDesc;
3189 samplers[n] = sampler; // does not own
3190 ++n;
3191 }
3192 descs.resize(n);
3193 samplers.resize(n);
3194 }
3195
3198 }
3199
3200 auto textureAt = [this, pd](int binding, int i) {
3201 // texture may be null if the update above failed for any reason,
3202 // or if the QSGTexture chose to return null intentionally. This is
3203 // valid and we still need to provide something to the shader.
3205 return texture ? texture : dummyTexture();
3206 };
3207
3210 QRhiTexture *singleTex = nullptr;
3211 QRhiSampler *singleSampler = nullptr;
3216 }
3217 QRhiBuffer *ubuf = pd->ubufBinding >= 0 ? m_uniformBuffer : nullptr;
3222 && prepared->ubuf == ubuf
3225 {
3226 return true;
3227 }
3228
3230
3231 if (pd->ubufBinding >= 0) {
3233 pd->ubufStages,
3236 }
3237
3238 for (quint32 mask = validSamplerBindings; mask; mask &= mask - 1) {
3239 const int binding = qCountTrailingZeroBits(mask);
3242
3243 for (int i = 0; i < pd->textureBindingTable[binding].size(); ++i) {
3247 }
3248
3249 if (!textureSamplers.isEmpty())
3253 }
3254
3255 if (!prepared)
3260 prepared->ubuf = ubuf;
3263
3264#ifndef QT_NO_DEBUG
3265 if (bindings.isEmpty())
3266 qWarning("No shader resources for material %p, this is odd.", material);
3267#endif
3268
3269 enum class SrbAction {
3270 Unknown,
3271 DoNothing,
3273 Rebake
3275
3276 // First, if the Element has no srb created at all, then try to find an existing,
3277 // currently unused srb that is layout-compatible with our binding list.
3278 if (!e->srb) {
3279 // reuse a QVector as our work area, thus possibly reusing the underlying allocation too
3281 layoutDesc.clear();
3285 if (e->srb) {
3286 // Here we know layout compatibility is satisfied, but do not spend time on full
3287 // comparison. The chance of getting an srb that refers to the same resources
3288 // (buffer, textures) is low in practice. So reuse, but write new resources.
3290 }
3291 }
3292
3293 // If the Element had an existing srb, investigate:
3294 // - It may be used as-is (when nothing changed in the scene regarding this node compared to the previous frame).
3295 // - Otherwise it may be able to go with a lightweight update (replace resources, binding list layout is the same).
3296 // - If all else fails rebake the full thing, meaning we reuse the memory allocation but will recreate everything underneath.
3297 if (srbAction == SrbAction::Unknown && e->srb) {
3301 [](const auto &a, const auto &b) { return a.isLayoutCompatible(b); }))
3302 {
3304 } else {
3306 }
3307 }
3308
3309 // If the Element had no srb associated at all and could not find a layout-compatible
3310 // one from the pool, then create a whole new object.
3311 if (!e->srb) {
3314 }
3315
3317
3318 switch (srbAction) {
3319 case SrbAction::DoNothing:
3320 break;
3322 {
3325 // Due to the way the binding list is built up above, if we have a uniform buffer
3326 // at binding point 0 (or none at all) then the sampledTexture bindings are added
3327 // with increasing binding points afterwards, so the list is already sorted based
3328 // on the binding points, thus we can save some time by telling the QRhi backend
3329 // not to sort again.
3330 if (pd->ubufBinding <= 0 || bindings.size() <= 1)
3332
3334 }
3335 break;
3336 case SrbAction::Rebake:
3339 if (!e->srb->create())
3340 qWarning("Failed to build srb");
3341 break;
3342 default:
3343 Q_ASSERT_X(false, "updateMaterialDynamicData", "No srb action set, this cannot happen");
3344 }
3345
3346 return true;
3347}
3348
3352 Batch *batch,
3353 bool *gstateChanged)
3354{
3356 *gstateChanged = false;
3358 // generate the public mini-state from m_gstate, invoke the material,
3359 // write the changes, if any, back to m_gstate, together with a way to
3360 // roll those back.
3364 if (changed) {
3369 {
3371 }
3372 *gstateChanged = true;
3373 }
3374 }
3375}
3376
3378{
3379 if (batch->vertexCount == 0 || batch->indexCount == 0)
3380 return false;
3381
3382 Element *e = batch->first;
3383 Q_ASSERT(e);
3384
3385#ifndef QT_NO_DEBUG_OUTPUT
3386 if (Q_UNLIKELY(debug_render())) {
3387 QDebug debug = qDebug();
3388 debug << " -"
3389 << batch
3390 << (batch->uploadedThisFrame ? "[ upload]" : "[retained]")
3391 << (e->node->clipList() ? "[ clip]" : "[noclip]")
3392 << (batch->isOpaque ? "[opaque]" : "[ alpha]")
3393 << "[ merged]"
3394 << " Nodes:" << QString::fromLatin1("%1").arg(qsg_countNodesInBatch(batch), 4).toLatin1().constData()
3395 << " Vertices:" << QString::fromLatin1("%1").arg(batch->vertexCount, 5).toLatin1().constData()
3396 << " Indices:" << QString::fromLatin1("%1").arg(batch->indexCount, 5).toLatin1().constData()
3397 << " root:" << batch->root
3398 << " mutability group: " << e->mutabilityGroup;
3399 if (batch->drawSets.size() > 1)
3400 debug << "sets:" << batch->drawSets.size();
3401 if (!batch->isOpaque)
3402 debug << "opacity:" << e->node->inheritedOpacity();
3403 batch->uploadedThisFrame = false;
3404 }
3405#endif
3406
3408
3409 // We always have dirty matrix as all batches are at a unique z range.
3411 if (batch->root)
3413 else
3416
3417 const int viewCount = projectionMatrixCount();
3419 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
3421
3425
3429
3430 const QSGGeometry *g = gn->geometry();
3434 if (!sms)
3435 return false;
3436
3438 if (m_currentShader != sms)
3440
3445 }
3446
3448
3449 bool pendingGStatePop = false;
3451
3453 if (pendingGStatePop)
3455 return false;
3456 }
3457
3460
3461 const bool hasPipeline = ensurePipelineState(e, sms);
3462
3463 if (pendingGStatePop)
3465
3466 if (!hasPipeline)
3467 return false;
3468
3472 ensurePipelineState(e, sms, true);
3474 }
3475
3477
3479 renderBatch->sms = sms;
3480
3481 return true;
3482}
3483
3485{
3488 {
3489 if (g->lineWidth() != 1.0f) {
3490 static bool checkedWideLineSupport = false;
3494 qWarning("Line widths other than 1 are not supported by the graphics API");
3495 }
3496 }
3497 } else if (g->drawingMode() == QSGGeometry::DrawPoints) {
3498 if (g->lineWidth() != 1.0f) {
3499 static bool warnedPointSize = false;
3500 if (!warnedPointSize) {
3501 warnedPointSize = true;
3502 qWarning("Point size is not controllable by QSGGeometry. "
3503 "Set gl_PointSize from the vertex shader instead.");
3504 }
3505 }
3506 }
3507}
3508
3510{
3511 const Batch *batch = renderBatch->batch;
3512 if (!batch->vbo.buf || !batch->ibo.buf)
3513 return;
3514
3515 Element *e = batch->first;
3517 QSGGeometry *g = gn->geometry();
3519
3522
3525
3526 for (int i = 0, ie = batch->drawSets.size(); i != ie; ++i) {
3527 const DrawSet &draw = batch->drawSets.at(i);
3531 };
3536 }
3537}
3538
3540{
3541 if (batch->vertexCount == 0)
3542 return false;
3543
3544 Element *e = batch->first;
3545 Q_ASSERT(e);
3546
3547 if (Q_UNLIKELY(debug_render())) {
3548 qDebug() << " -"
3549 << batch
3550 << (batch->uploadedThisFrame ? "[ upload]" : "[retained]")
3551 << (e->node->clipList() ? "[ clip]" : "[noclip]")
3552 << (batch->isOpaque ? "[opaque]" : "[ alpha]")
3553 << "[unmerged]"
3554 << " Nodes:" << QString::fromLatin1("%1").arg(qsg_countNodesInBatch(batch), 4).toLatin1().constData()
3555 << " Vertices:" << QString::fromLatin1("%1").arg(batch->vertexCount, 5).toLatin1().constData()
3556 << " Indices:" << QString::fromLatin1("%1").arg(batch->indexCount, 5).toLatin1().constData()
3557 << " root:" << batch->root
3558 << " mutability group: " << e->mutabilityGroup;
3559
3560
3561 batch->uploadedThisFrame = false;
3562 }
3563
3564 const int viewCount = projectionMatrixCount();
3566 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
3568
3572
3576
3577 // We always have dirty matrix as all batches are at a unique z range.
3579
3580 // The vertex attributes are assumed to be the same for all elements in the
3581 // unmerged batch since the material (and so the shaders) is the same.
3582 QSGGeometry *g = gn->geometry();
3585 if (!sms)
3586 return false;
3587
3589 if (m_currentShader != sms)
3591
3596 }
3597
3599
3601 bool pendingGStatePop = false;
3604
3605 QRhiGraphicsPipeline *ps = nullptr;
3607 e = batch->first;
3608
3609 while (e) {
3610 gn = e->node;
3611
3614
3615 const int viewCount = projectionMatrixCount();
3617 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
3619
3623
3624 if (useDepthBuffer()) {
3625 // this cannot be multiview
3628 }
3629
3632 if (pendingGStatePop)
3634 return false;
3635 }
3636
3638 const float prevLineWidth = m_gstate.lineWidth;
3641
3642 // Do not bother even looking up the ps if the topology has not changed
3643 // since everything else is the same for all elements in the batch.
3644 // (except if the material modified blend state)
3646 if (!ensurePipelineState(e, sms)) {
3647 if (pendingGStatePop)
3649 return false;
3650 }
3651 ps = e->ps;
3655 ensurePipelineState(e, sms, true);
3658 }
3659 } else {
3660 e->ps = ps;
3663 prepared->psSms = sms;
3665 }
3668 }
3669
3670 // We don't need to bother with asking each node for its material as they
3671 // are all identical (compare==0) since they are in the same batch.
3673
3674 // We only need to push this on the very first iteration...
3676
3677 e = e->nextInBatch;
3678 }
3679
3680 if (pendingGStatePop)
3682
3684 renderBatch->sms = sms;
3685
3686 return true;
3687}
3688
3690{
3691 const Batch *batch = renderBatch->batch;
3692 if (!batch->vbo.buf)
3693 return;
3694
3695 Element *e = batch->first;
3696
3699
3700 quint32 vOffset = 0;
3701 quint32 iOffset = 0;
3703
3704 while (e) {
3705 QSGGeometry *g = e->node->geometry();
3707 const int effectiveIndexSize = m_uint32IndexForRhi ? sizeof(quint32) : g->sizeOfIndex();
3708
3710
3712 if (g->indexCount()) {
3713 if (batch->ibo.buf) {
3715 batch->ibo.buf, iOffset,
3719 }
3720 } else {
3722 cb->draw(g->vertexCount());
3723 }
3724
3725 vOffset += g->sizeOfVertex() * g->vertexCount();
3727
3728 e = e->nextInBatch;
3729 }
3730}
3731
3733{
3734 if (!m_pstate.viewportSet) {
3735 m_pstate.viewportSet = true;
3737 }
3739 m_pstate.scissorSet = true;
3741 } else {
3742 // Regardless of the ps not using scissor, the scissor may need to be
3743 // reset, depending on the backend. So set the viewport again, which in
3744 // turn also sets the scissor on backends where a scissor rect is
3745 // always-on (Vulkan).
3746 if (m_pstate.scissorSet) {
3747 m_pstate.scissorSet = false;
3749 }
3750 }
3751}
3752
3753
3755 const ShaderManager::Shader *sms, bool depthPostPass)
3756{
3758
3760
3764 }
3767
3769 if (ubufBinding >= 0) {
3772 } else {
3774 }
3775}
3776
3778{
3779 if (e->isRenderNode) {
3780 delete static_cast<RenderNodeElement *>(e);
3781 } else {
3782 if (e->srb) {
3783 if (!inDestructor) {
3786 else
3787 delete e->srb;
3788 } else {
3789 delete e->srb;
3790 }
3791 e->srb = nullptr;
3792 }
3793 delete e->prepared;
3794 e->prepared = nullptr;
3796 }
3797}
3798
3800{
3801 if (!m_elementsToDelete.size())
3802 return;
3803
3804 for (int i=0; i<m_opaqueRenderList.size(); ++i) {
3806 if (*e && (*e)->removed)
3807 *e = nullptr;
3808 }
3809 for (int i=0; i<m_alphaRenderList.size(); ++i) {
3811 if (*e && (*e)->removed)
3812 *e = nullptr;
3813 }
3814
3815 for (int i=0; i<m_elementsToDelete.size(); ++i)
3817
3819}
3820
3821/*
3822 * Unlinks removed elements from their batches and from the render lists,
3823 * then releases them.
3824 */
3826{
3827 for (int i=0; i<m_opaqueBatches.size(); ++i)
3829 for (int i=0; i<m_alphaBatches.size(); ++i)
3832}
3833
3835{
3836 // Gracefully handle the lack of a render target - some autotests may rely
3837 // on this in odd cases.
3838 if (!renderTarget().rt)
3839 return;
3840
3845}
3846
3847// An alternative to render() is to call prepareInline() and renderInline() at
3848// the appropriate times (i.e. outside of a QRhi::beginPass() and then inside,
3849// respectively) These allow rendering within a render pass that is started by
3850// another component. In contrast, render() records a full render pass on its
3851// own.
3852
3857
3862
3864{
3865 if (ctx->valid)
3866 qWarning("prepareRenderPass() called with an already prepared render pass context");
3867
3868 ctx->valid = true;
3869
3870 if (Q_UNLIKELY(debug_dump())) {
3871 qDebug("\n");
3873 }
3874
3875 ctx->timeRenderLists = 0;
3877 ctx->timePrepareAlpha = 0;
3878 ctx->timeSorting = 0;
3879 ctx->timeUploadOpaque = 0;
3880 ctx->timeUploadAlpha = 0;
3881
3882 if (Q_UNLIKELY(debug_render() || debug_build())) {
3883 QByteArray type("rebuild:");
3884 if (m_rebuild == 0)
3885 type += " none";
3886 if (m_rebuild == FullRebuild)
3887 type += " full";
3888 else {
3890 type += " renderlists";
3892 type += " partial";
3893 else if (m_rebuild & BuildBatches)
3894 type += " batches";
3895 }
3896
3897 qDebug() << "Renderer::render()" << this << type;
3898 ctx->timer.start();
3899 }
3900
3903
3905 bool complete = (m_rebuild & BuildRenderLists) != 0;
3906 if (complete)
3908 else
3911
3912 if (Q_UNLIKELY(debug_build())) {
3913 qDebug("Opaque render lists %s:", (complete ? "(complete)" : "(partial)"));
3914 for (int i=0; i<m_opaqueRenderList.size(); ++i) {
3916 qDebug() << " - element:" << e << " batch:" << e->batch << " node:" << e->node << " order:" << e->order;
3917 }
3918 qDebug("Alpha render list %s:", complete ? "(complete)" : "(partial)");
3919 for (int i=0; i<m_alphaRenderList.size(); ++i) {
3921 qDebug() << " - element:" << e << " batch:" << e->batch << " node:" << e->node << " order:" << e->order;
3922 }
3923 }
3924 }
3926
3928
3931
3932 if (m_rebuild & BuildBatches) {
3937
3938 if (Q_UNLIKELY(debug_build())) {
3939 qDebug("Opaque Batches:");
3940 for (int i=0; i<m_opaqueBatches.size(); ++i) {
3942 qDebug() << " - Batch " << i << b << (b->needsUpload ? "upload" : "") << " root:" << b->root;
3943 for (Element *e = b->first; e; e = e->nextInBatch) {
3944 qDebug() << " - element:" << e << " node:" << e->node << e->order;
3945 }
3946 }
3947 qDebug("Alpha Batches:");
3948 for (int i=0; i<m_alphaBatches.size(); ++i) {
3950 qDebug() << " - Batch " << i << b << (b->needsUpload ? "upload" : "") << " root:" << b->root;
3951 for (Element *e = b->first; e; e = e->nextInBatch) {
3952 qDebug() << " - element:" << e << e->bounds << " node:" << e->node << " order:" << e->order;
3953 }
3954 }
3955 }
3956 } else {
3958 }
3959
3960
3962
3963 if (m_rebuild != 0) {
3964 // Then sort opaque batches so that we're drawing the batches with the highest
3965 // order first, maximizing the benefit of front-to-back z-ordering.
3966 if (m_opaqueBatches.size())
3968
3969 // Sort alpha batches back to front so that they render correctly.
3970 if (m_alphaBatches.size())
3972
3974 ? 1.0 / (m_nextRenderOrder)
3975 : 0;
3976 }
3977
3979
3980 // Set size to 0, nothing is deallocated, they will "grow" again
3981 // as part of uploadBatch.
3984
3985 if (Q_UNLIKELY(debug_upload())) qDebug("Uploading Opaque Batches:");
3986 for (int i=0; i<m_opaqueBatches.size(); ++i) {
3988 uploadBatch(b);
3989 }
3991
3992 if (Q_UNLIKELY(debug_upload())) qDebug("Uploading Alpha Batches:");
3993 for (int i=0; i<m_alphaBatches.size(); ++i) {
3995 uploadBatch(b);
3996 }
3998
3999 if (Q_UNLIKELY(debug_render())) {
4000 qDebug().nospace() << "Rendering:" << Qt::endl
4001 << " -> Opaque: " << qsg_countNodesInBatches(m_opaqueBatches) << " nodes in " << m_opaqueBatches.size() << " batches..." << Qt::endl
4002 << " -> Alpha: " << qsg_countNodesInBatches(m_alphaBatches) << " nodes in " << m_alphaBatches.size() << " batches...";
4003 }
4004
4006 m_currentMaterial = nullptr;
4007 m_currentShader = nullptr;
4008 m_currentProgram = nullptr;
4010
4011 const QRect viewport = viewportRect();
4012
4013 bool renderOpaque = !debug_noopaque();
4014 bool renderAlpha = !debug_noalpha();
4015
4021 m_pstate.viewportSet = false;
4022 m_pstate.scissorSet = false;
4023
4027 m_gstate.blending = false;
4028
4035 m_gstate.usesScissor = false;
4036 m_gstate.stencilTest = false;
4037
4040
4041 // Give back memory when the scene has become much smaller: if the peak
4042 // usage in the last UNIFORM_BUFFER_SHRINK_FRAMES frames is less than a
4043 // quarter of the uniform buffer size, shrink to twice the peak. Done
4044 // before anything refers to the buffer in this frame.
4048 if (m_uniformBuffer && m_uniformBuffer->size() > 2 * size)
4050 if (quint32(m_uniformData.size()) > 2 * size) {
4053 }
4056 }
4057
4059 m_uniformBufferFailed = false;
4060
4062 if (Q_LIKELY(renderOpaque)) {
4063 for (int i = 0, ie = m_opaqueBatches.size(); i != ie; ++i) {
4066 bool ok;
4067 if (b->merged)
4069 else
4071 if (ok)
4073 }
4074 }
4075
4076 m_gstate.blending = true;
4077 // factors never change, always set for premultiplied alpha based blending
4078
4079 // depth test stays enabled (if useDepthBuffer(), that is) but no need
4080 // to write out depth from the transparent (back-to-front) pass
4081 m_gstate.depthWrite = false;
4082
4083 // special case: the 3D plane mode tests against the depth buffer, but does
4084 // not write (and all batches are alpha because this render mode evaluates
4085 // to useDepthBuffer()==false)
4088 m_gstate.depthTest = true;
4089 }
4090
4092 if (Q_LIKELY(renderAlpha)) {
4093 for (int i = 0, ie = m_alphaBatches.size(); i != ie; ++i) {
4096 bool ok;
4097 if (b->merged)
4099 else if (b->isRenderNode)
4101 else
4103 if (ok)
4105 }
4106 }
4107
4108 m_rebuild = 0;
4109
4110#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES)
4113#endif
4114
4117
4119 // the batches prepared before the failure refer to the uniform buffer too
4122 } else if (m_uniformDataSize) {
4123 // All regions read by this frame's draws are written here, every
4124 // frame, so the direct update of the current frame slot is sufficient.
4126 }
4127
4129 m_resourceUpdates = nullptr;
4130}
4131
4133{
4136 // we cannot tell if the application will have
4137 // native rendering thrown in to this pass
4138 // (QQuickWindow::beginExternalCommands()), so
4139 // we have no choice but to set the flag always
4140 // (thus triggering using secondary command
4141 // buffers with Vulkan)
4143 // We do not use GPU compute at all at the moment, this means we can
4144 // get a small performance gain with OpenGL by declaring this.
4146
4149}
4150
4152{
4153 // prepareRenderPass and recordRenderPass must always be called together.
4154 // They are separate because beginRenderPass and endRenderPass are optional.
4155 //
4156 // The valid call sequence are therefore:
4157 // prepare, begin, record, end
4158 // or
4159 // prepare, record
4160
4161 if (!ctx->valid)
4162 qWarning("recordRenderPass() called without a prepared render pass context");
4163
4164 ctx->valid = false;
4165
4167 cb->debugMarkBegin(QByteArrayLiteral("Qt Quick scene render"));
4168
4169 for (int i = 0, ie = ctx->opaqueRenderBatches.size(); i != ie; ++i) {
4170 if (i == 0)
4171 cb->debugMarkMsg(QByteArrayLiteral("Qt Quick opaque batches"));
4173 if (renderBatch->batch->merged)
4175 else
4177 }
4178
4179 for (int i = 0, ie = ctx->alphaRenderBatches.size(); i != ie; ++i) {
4180 if (i == 0) {
4182 cb->debugMarkMsg(QByteArrayLiteral("Qt Quick 2D-in-3D batches"));
4183 else
4184 cb->debugMarkMsg(QByteArrayLiteral("Qt Quick alpha batches"));
4185 }
4187 if (renderBatch->batch->merged)
4189 else if (renderBatch->batch->isRenderNode)
4191 else
4193 }
4194
4196 // Depth post-pass to fill up the depth buffer in a way that it
4197 // corresponds to what got rendered to the color buffer in the previous
4198 // (alpha) pass. The previous pass cannot enable depth write due to Z
4199 // fighting. Rather, do it separately in a dedicated color-write-off,
4200 // depth-write-on pass. This enables the 3D content drawn afterwards to
4201 // depth test against the 2D items' rendering.
4202 for (int i = 0, ie = ctx->alphaRenderBatches.size(); i != ie; ++i) {
4203 if (i == 0)
4204 cb->debugMarkMsg(QByteArrayLiteral("Qt Quick 2D-in-3D depth post-pass"));
4206 if (renderBatch->batch->merged)
4208 else if (!renderBatch->batch->isRenderNode) // rendernodes are skipped here for now
4210 }
4211 }
4212
4213 if (m_currentShader)
4214 setActiveRhiShader(nullptr, nullptr);
4215
4216 cb->debugMarkEnd();
4217
4218 if (Q_UNLIKELY(debug_render())) {
4219 qDebug(" -> times: build: %d, prepare(opaque/alpha): %d/%d, sorting: %d, upload(opaque/alpha): %d/%d, record rendering: %d",
4220 (int) ctx->timeRenderLists,
4222 (int) ctx->timeSorting,
4223 (int) ctx->timeUploadOpaque, (int) ctx->timeUploadAlpha,
4224 (int) ctx->timer.elapsed());
4225 }
4226}
4227
4238
4240{
4241 const QMatrix4x4 *projectionMatrix() const override { return m_projectionMatrix; }
4242 QRect scissorRect() const override { return m_scissorRect; }
4244 int stencilValue() const override { return m_stencilValue; }
4246 const QRegion *clipRegion() const override { return nullptr; }
4247
4253};
4254
4256{
4257 if (Q_UNLIKELY(debug_render()))
4258 qDebug() << " -" << batch << "rendernode";
4259
4260 const int viewCount = projectionMatrixCount();
4262 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
4267
4269 RenderNodeElement *e = static_cast<RenderNodeElement *>(batch->first);
4270
4271 setActiveRhiShader(nullptr, nullptr);
4272
4274 rd->m_clip_list = nullptr;
4277 while (clip != rootNode()) {
4278 if (clip->type() == QSGNode::ClipNodeType) {
4279 rd->m_clip_list = static_cast<QSGClipNode *>(clip);
4280 break;
4281 }
4282 clip = clip->parent();
4283 }
4285 }
4286
4289 QSGNode *root = rootNode();
4290 if (e->root) {
4292 root = e->root->sgNode;
4293 }
4294 while (xform != root) {
4295 if (xform->type() == QSGNode::TransformNodeType) {
4296 matrix = matrix * static_cast<QSGTransformNode *>(xform)->combinedMatrix();
4297 break;
4298 }
4299 xform = xform->parent();
4300 }
4303
4305 rd->m_opacity = 1.0;
4306 while (opacity != rootNode()) {
4307 if (opacity->type() == QSGNode::OpacityNodeType) {
4308 rd->m_opacity = static_cast<QSGOpacityNode *>(opacity)->combinedOpacity();
4309 break;
4310 }
4311 opacity = opacity->parent();
4312 }
4313
4314 rd->m_rt = renderTarget();
4315
4317 for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
4319
4320 if (useDepthBuffer()) {
4321 // this cannot be multiview
4322 rd->m_projectionMatrix[0](2, 2) = m_zRange;
4324 }
4325
4326 e->renderNode->prepare();
4327
4329 renderBatch->sms = nullptr;
4330
4331 return true;
4332}
4333
4335{
4338
4339 RenderNodeElement *e = static_cast<RenderNodeElement *>(batch->first);
4341
4343 // Expose only the first matrix through the state object, the rest are
4344 // queriable through the QSGRenderNode getters anyway.
4346 const std::array<int, 4> scissor = batch->clipState.scissor.scissor();
4351
4353
4357 if (needsExternal)
4358 cb->beginExternal();
4360 if (needsExternal)
4361 cb->endExternal();
4362
4363 rd->m_matrix = nullptr;
4364 rd->m_clip_list = nullptr;
4365
4368 {
4369 // Reset both flags if either is reported as changed, since with the rhi
4370 // it could be setViewport() that will record the resetting of the scissor.
4371 m_pstate.viewportSet = false;
4372 m_pstate.scissorSet = false;
4373 }
4374
4375 // Do not bother with RenderTargetState. Where applicable, endExternal()
4376 // ensures the correct target is rebound. For others (like Vulkan) it makes
4377 // no sense since render() could not possibly do that on our command buffer
4378 // which is in renderpass recording state.
4379}
4380
4382{
4383 if (mode.isEmpty())
4385 else if (mode == "clip")
4387 else if (mode == "overdraw")
4389 else if (mode == "batches")
4391 else if (mode == "changes")
4393}
4394
4399
4400bool operator==(const GraphicsState &a, const GraphicsState &b) noexcept
4401{
4402 return a.depthTest == b.depthTest
4403 && a.depthWrite == b.depthWrite
4404 && a.depthFunc == b.depthFunc
4405 && a.blending == b.blending
4406 && a.srcColor == b.srcColor
4407 && a.dstColor == b.dstColor
4408 && a.srcAlpha == b.srcAlpha
4409 && a.dstAlpha == b.dstAlpha
4410 && a.opColor == b.opColor
4411 && a.opAlpha == b.opAlpha
4412 && a.colorWrite == b.colorWrite
4413 && a.cullMode == b.cullMode
4417 && a.drawMode == b.drawMode
4418 && a.lineWidth == b.lineWidth
4419 && a.polygonMode == b.polygonMode
4421}
4422
4423bool operator!=(const GraphicsState &a, const GraphicsState &b) noexcept
4424{
4425 return !(a == b);
4426}
4427
4428size_t qHash(const GraphicsState &s, size_t seed) noexcept
4429{
4430 // do not bother with all fields
4431 return seed
4432 + s.depthTest * 1000
4433 + s.depthWrite * 100
4434 + s.depthFunc
4435 + s.blending * 10
4436 + s.srcColor
4437 + s.cullMode
4438 + s.usesScissor
4439 + s.stencilTest
4440 + s.sampleCount
4441 + s.multiViewCount;
4442}
4443
4445{
4446 return a.state == b.state
4447 && a.sms->materialShader == b.sms->materialShader
4448 && a.renderTargetDescription == b.renderTargetDescription
4449 && a.srbLayoutDescription == b.srbLayoutDescription;
4450}
4451
4453{
4454 return !(a == b);
4455}
4456
4457size_t qHash(const GraphicsPipelineStateKey &k, size_t seed) noexcept
4458{
4459 return qHash(k.state, seed)
4460 ^ qHash(k.sms->materialShader)
4461 ^ k.extra.renderTargetDescriptionHash
4462 ^ k.extra.srbLayoutDescriptionHash;
4463}
4464
4465bool operator==(const ShaderKey &a, const ShaderKey &b) noexcept
4466{
4467 return a.type == b.type
4468 && a.renderMode == b.renderMode
4470}
4471
4472bool operator!=(const ShaderKey &a, const ShaderKey &b) noexcept
4473{
4474 return !(a == b);
4475}
4476
4477size_t qHash(const ShaderKey &k, size_t seed) noexcept
4478{
4479 return qHash(k.type, seed) ^ int(k.renderMode) ^ k.multiViewCount;
4480}
4481
4482Visualizer::Visualizer(Renderer *renderer)
4483 : m_renderer(renderer),
4485{
4486}
4487
4489{
4490}
4491
4492#define QSGNODE_DIRTY_PARENT (QSGNode::DirtyNodeAdded
4493 | QSGNode::DirtyOpacity
4494 | QSGNode::DirtyMatrix
4495 | QSGNode::DirtyNodeRemoved)
4496
4497void Visualizer::visualizeChangesPrepare(Node *n, uint parentChanges)
4498{
4499 uint childDirty = (parentChanges | n->dirtyState) & QSGNODE_DIRTY_PARENT;
4500 uint selfDirty = n->dirtyState | parentChanges;
4501 if (n->type() == QSGNode::GeometryNodeType && selfDirty != 0)
4502 m_visualizeChangeSet.insert(n, selfDirty);
4504 visualizeChangesPrepare(child, childDirty);
4505 }
4506}
4507
4508} // namespace QSGBatchRenderer
4509
4510QT_END_NAMESPACE
4511
4512#include "moc_qsgbatchrenderer_p.cpp"
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:326
void updateRootTransforms(Node *n, Node *root, const QMatrix4x4 &combined)
void updateStates(QSGNode *n) override
void updateRootTransforms(Node *n)
const int ZORDER_BUFFER_BINDING
static void qsg_wipeBuffer(Buffer *buffer)
static void rendererToMaterialGraphicsState(QSGMaterialShader::GraphicsPipelineState *dst, GraphicsState *src)
size_t qHash(const GraphicsState &s, size_t seed) noexcept
static QRhiVertexInputLayout calculateVertexInputLayout(const QSGMaterialShader *s, const QSGGeometry *geometry, bool batchable)
static void qsg_addBackOrphanedElements(QDataBuffer< Element * > &orphans, QDataBuffer< Element * > &renderList)
bool operator!=(const GraphicsPipelineStateKey &a, const GraphicsPipelineStateKey &b) noexcept
const float VIEWPORT_MIN_DEPTH
QSGMaterial::Flag QSGMaterial_FullMatrix
bool qsg_sort_batch_decreasing_order(Batch *a, Batch *b)
bool operator==(const ShaderKey &a, const ShaderKey &b) noexcept
bool operator==(const GraphicsPipelineStateKey &a, const GraphicsPipelineStateKey &b) noexcept
bool operator!=(const ShaderKey &a, const ShaderKey &b) noexcept
static void qsg_wipeBatch(Batch *batch)
static QRhiSampler * newSampler(QRhi *rhi, const QSGSamplerDescription &desc)
QRhiVertexInputAttribute::Format qsg_vertexInputFormat(const QSGGeometry::Attribute &a)
QRhiGraphicsPipeline::Topology qsg_topology(int geomDrawMode, QRhi *rhi)
QMatrix4x4 qsg_matrixForRoot(Node *node)
bool qsg_sort_batch_increasing_order(Batch *a, Batch *b)
static void qsg_addOrphanedElements(QDataBuffer< Element * > &orphans, const QDataBuffer< Element * > &renderList)
void qsg_setMultiViewFlagsOnMaterial(QSGMaterial *material, int multiViewCount)
const float VIEWPORT_MAX_DEPTH
int qsg_positionAttribute(QSGGeometry *g)
const quint32 MIN_UNIFORM_BUFFER_SIZE
static int size_of_type(int type)
static bool isTranslate(const QMatrix4x4 &m)
static int qsg_countNodesInBatches(const QDataBuffer< Batch * > &batches)
static float calculateElementZOrder(const Element *e, qreal zRange)
static int qsg_fixIndexCount(int iCount, int drawMode)
bool qsg_sort_element_increasing_order(Element *a, Element *b)
static void materialToRendererGraphicsState(GraphicsState *dst, QSGMaterialShader::GraphicsPipelineState *src)
static bool needsBlendConstant(QRhiGraphicsPipeline::BlendFactor f)
const int VERTEX_BUFFER_BINDING
const uint DYNAMIC_VERTEX_INDEX_BUFFER_THRESHOLD
static int qsg_countNodesInBatch(const Batch *batch)
const int UNIFORM_BUFFER_SHRINK_FRAMES
bool operator==(const GraphicsState &a, const GraphicsState &b) noexcept
QRhiCommandBuffer::IndexFormat qsg_indexFormat(const QSGGeometry *geometry)
bool operator!=(const GraphicsState &a, const GraphicsState &b) noexcept
bool qsg_sort_element_decreasing_order(Element *a, Element *b)
size_t qHash(const ShaderKey &k, size_t seed) noexcept
void qsg_dumpShadowRoots(BatchRootInfo *i, int indent)
void qsg_dumpShadowRoots(Node *n)
static bool isScale(const QMatrix4x4 &m)
static bool is2DSafe(const QMatrix4x4 &m)
size_t qHash(const GraphicsPipelineStateKey &k, size_t seed) noexcept
Int aligned(Int v, Int byteAlign)
const quint32 DEFAULT_BUFFER_POOL_SIZE_LIMIT
Q_CORE_EXPORT QDebug operator<<(QDebug debug, QDir::Filters filters)
Definition qdir.cpp:2620
#define DECLARE_DEBUG_VAR(variable)
#define QSGNODE_DIRTY_PARENT
QT_BEGIN_NAMESPACE int qt_sg_envInt(const char *name, int defaultValue)
#define SHADOWNODE_TRAVERSE(NODE)
#define QSGNODE_TRAVERSE(NODE)
bool geometryWasChanged(QSGGeometryNode *gn)
BatchCompatibility isMaterialCompatible(Element *e) const
BatchRootInfo * rootInfo() const
ClipBatchRootInfo * clipInfo() const
RenderNodeElement * renderNodeElement() const
void operator|=(const Pt &pt)
void set(float left, float top, float right, float bottom)
void map(const QMatrix4x4 &m)
const QMatrix4x4 * projectionMatrix() const override
const QRegion * clipRegion() const override