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
qquickshapecurverenderer.cpp
Go to the documentation of this file.
1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
7
8#if QT_CONFIG(thread)
9#include <QtCore/qthreadpool.h>
10#endif
11
12#include <QtGui/qvector2d.h>
13#include <QtGui/qvector4d.h>
14#include <QtGui/private/qtriangulator_p.h>
15#include <QtGui/private/qtriangulatingstroker_p.h>
16#include <QtGui/private/qrhi_p.h>
17
18#include <QtQuick/private/qsgcurvefillnode_p.h>
19#include <QtQuick/private/qsgcurvestrokenode_p.h>
20#include <QtQuick/private/qquadpath_p.h>
21#include <QtQuick/private/qsgcurveprocessor_p.h>
22#include <QtQuick/qsgmaterial.h>
23
25
26Q_LOGGING_CATEGORY(lcShapeCurveRenderer, "qt.shape.curverenderer");
27
28namespace {
29
30/*! \internal
31 Choice of vertex shader to use for the wireframe node:
32 * \c SimpleWFT is for when vertices are already in logical coordinates
33 * \c StrokeWFT chooses the stroke shader, which moves vertices according to the stroke width uniform
34*/
35enum WireFrameType { SimpleWFT, StrokeWFT };
36
37class QQuickShapeWireFrameMaterialShader : public QSGMaterialShader
38{
39public:
40 QQuickShapeWireFrameMaterialShader(WireFrameType wft, int viewCount) : m_wftype(wft)
41 {
42 setShaderFileName(VertexStage, wft == StrokeWFT ?
43 QStringLiteral(":/qt-project.org/scenegraph/shaders_ng/shapestroke_wireframe.vert.qsb") :
44 QStringLiteral(":/qt-project.org/shapes/shaders_ng/wireframe.vert.qsb"), viewCount);
45 setShaderFileName(FragmentStage,
46 wft == StrokeWFT ?
47 QStringLiteral(":/qt-project.org/scenegraph/shaders_ng/shapestroke_wireframe.frag.qsb") :
48 QStringLiteral(":/qt-project.org/shapes/shaders_ng/wireframe.frag.qsb"), viewCount);
49 }
50
51 bool updateUniformData(RenderState &state, QSGMaterial *newMaterial, QSGMaterial *) override;
52
53 WireFrameType m_wftype;
54};
55
56class QQuickShapeWireFrameMaterial : public QSGMaterial
57{
58public:
59 QQuickShapeWireFrameMaterial(WireFrameType wft) : m_wftype(wft)
60 {
61 setFlag(Blending, true);
62 }
63
64 int compare(const QSGMaterial *other) const override
65 {
66 return (type() - other->type());
67 }
68
69 void setCosmeticStroke(bool c)
70 {
71 m_cosmeticStroke = c;
72 }
73
74 void setStrokeWidth(float width)
75 {
76 m_strokeWidth = width;
77 }
78
79 float strokeWidth()
80 {
81 return (m_cosmeticStroke ? -1.0 : 1.0) * qAbs(m_strokeWidth);
82 }
83
84protected:
85 QSGMaterialType *type() const override
86 {
87 static QSGMaterialType t;
88 return &t;
89 }
90 QSGMaterialShader *createShader(QSGRendererInterface::RenderMode) const override
91 {
92 return new QQuickShapeWireFrameMaterialShader(m_wftype, viewCount());
93 }
94
95 WireFrameType m_wftype;
96 bool m_cosmeticStroke = false;
97 float m_strokeWidth = 1.0f;
98};
99
100bool QQuickShapeWireFrameMaterialShader::updateUniformData(RenderState &state, QSGMaterial *newMaterial, QSGMaterial *)
101{
102 QByteArray *buf = state.uniformData();
103 Q_ASSERT(buf->size() >= 64);
104 const int matrixCount = qMin(state.projectionMatrixCount(), newMaterial->viewCount());
105 bool changed = false;
106 float localScale = /* newNode != nullptr ? newNode->localScale() : */ 1.0f;
107
108 for (int viewIndex = 0; viewIndex < matrixCount; ++viewIndex) {
109 if (state.isMatrixDirty()) {
110 QMatrix4x4 m = state.combinedMatrix(viewIndex);
111 if (m_wftype == StrokeWFT)
112 m.scale(localScale);
113 memcpy(buf->data() + 64 * viewIndex, m.constData(), 64);
114 changed = true;
115 }
116 }
117 // determinant is xscale * yscale, as long as Item.transform does not include shearing or rotation
118 const float matrixScale = qSqrt(qAbs(state.determinant())) * state.devicePixelRatio() * localScale;
119 memcpy(buf->data() + matrixCount * 64, &matrixScale, 4);
120 const float dpr = state.devicePixelRatio();
121 memcpy(buf->data() + matrixCount * 64 + 8, &dpr, 4);
122 const float opacity = 1.0; // don't fade the wireframe
123 memcpy(buf->data() + matrixCount * 64 + 4, &opacity, 4);
124 const float strokeWidth = static_cast<QQuickShapeWireFrameMaterial *>(newMaterial)->strokeWidth();
125 memcpy(buf->data() + matrixCount * 64 + 12, &strokeWidth, 4);
126 changed = true;
127 // shapestroke_wireframe.vert doesn't use the strokeColor and debug uniforms, so we don't bother setting them
128
129 return changed;
130}
131
132template <WireFrameType wftype>
133class QQuickShapeWireFrameNode : public QSGCurveAbstractNode
134{
135public:
136 struct WireFrameVertex
137 {
138 float x, y, u, v, w, nx, ny, sw;
139 };
140
141 QQuickShapeWireFrameNode()
142 {
143 isDebugNode = true;
144 setFlag(OwnsGeometry, true);
145 setGeometry(new QSGGeometry(attributes(), 0, 0));
146 activateMaterial();
147 }
148
149 void setColor(QColor col) override
150 {
151 Q_UNUSED(col);
152 }
153
154 void setUseStandardDerivatives(bool useStandardDerivatives) override
155 {
156 Q_UNUSED(useStandardDerivatives);
157 }
158
159 void setCosmeticStroke(bool c)
160 {
161 m_material->setCosmeticStroke(c);
162 }
163
164 void setStrokeWidth(float width)
165 {
166 m_material->setStrokeWidth(width);
167 }
168
169 void activateMaterial()
170 {
171 m_material.reset(new QQuickShapeWireFrameMaterial(wftype));
172 setMaterial(m_material.data());
173 }
174
175 static const QSGGeometry::AttributeSet &attributes()
176 {
177 static QSGGeometry::Attribute data[] = {
178 QSGGeometry::Attribute::createWithAttributeType(0, 2, QSGGeometry::FloatType, QSGGeometry::PositionAttribute),
179 QSGGeometry::Attribute::createWithAttributeType(1, 3, QSGGeometry::FloatType, QSGGeometry::TexCoordAttribute),
180 QSGGeometry::Attribute::createWithAttributeType(2, 3, QSGGeometry::FloatType, QSGGeometry::TexCoordAttribute),
181 };
182 static QSGGeometry::AttributeSet attrs = { 3, sizeof(WireFrameVertex), data };
183 return attrs;
184 }
185
186 void cookGeometry() override
187 {
188 // Intentionally empty
189 }
190
191protected:
192 QScopedPointer<QQuickShapeWireFrameMaterial> m_material;
193};
194}
195
196QQuickShapeCurveRenderer::~QQuickShapeCurveRenderer()
197{
198 for (const PathData &pd : std::as_const(m_paths)) {
199 if (pd.currentRunner) {
200 pd.currentRunner->orphaned = true;
201 if (!pd.currentRunner->isAsync || pd.currentRunner->isDone)
202 delete pd.currentRunner;
203 }
204 }
205}
206
207void QQuickShapeCurveRenderer::beginSync(int totalCount, bool *countChanged)
208{
209 if (countChanged != nullptr && totalCount != m_paths.size())
210 *countChanged = true;
211 for (int i = totalCount; i < m_paths.size(); i++) { // Handle removal of paths
212 setFillTextureProvider(i, nullptr); // deref window
213 m_removedPaths.append(m_paths.at(i));
214 }
215 m_paths.resize(totalCount);
216}
217
218void QQuickShapeCurveRenderer::setPath(int index, const QPainterPath &path, QQuickShapePath::PathHints pathHints)
219{
220 auto &pathData = m_paths[index];
221 pathData.originalPath = path;
222 pathData.pathHints = pathHints;
223 pathData.m_dirty |= PathDirty;
224}
225
226void QQuickShapeCurveRenderer::setStrokeColor(int index, const QColor &color)
227{
228 auto &pathData = m_paths[index];
229 const bool wasVisible = pathData.isStrokeVisible();
230 pathData.pen.setColor(color);
231 if (pathData.isStrokeVisible() != wasVisible)
232 pathData.m_dirty |= StrokeDirty;
233 else
234 pathData.m_dirty |= UniformsDirty;
235}
236
237void QQuickShapeCurveRenderer::setStrokeWidth(int index, qreal w)
238{
239 auto &pathData = m_paths[index];
240 if (w > 0) {
241 pathData.validPenWidth = true;
242 pathData.pen.setWidthF(w);
243 } else {
244 pathData.validPenWidth = false;
245 }
246 pathData.m_dirty |= StrokeDirty;
247}
248
249void QQuickShapeCurveRenderer::setCosmeticStroke(int index, bool c)
250{
251 auto &pathData = m_paths[index];
252 pathData.pen.setCosmetic(c);
253 pathData.m_dirty |= StrokeDirty;
254}
255
256void QQuickShapeCurveRenderer::setFillColor(int index, const QColor &color)
257{
258 auto &pathData = m_paths[index];
259 const bool wasVisible = pathData.isFillVisible();
260 pathData.fillColor = color;
261 if (pathData.isFillVisible() != wasVisible)
262 pathData.m_dirty |= FillDirty;
263 else
264 pathData.m_dirty |= UniformsDirty;
265}
266
267void QQuickShapeCurveRenderer::setFillRule(int index, QQuickShapePath::FillRule fillRule)
268{
269 auto &pathData = m_paths[index];
270 pathData.fillRule = Qt::FillRule(fillRule);
271 pathData.m_dirty |= PathDirty;
272}
273
274void QQuickShapeCurveRenderer::setJoinStyle(int index,
275 QQuickShapePath::JoinStyle joinStyle,
276 int miterLimit)
277{
278 auto &pathData = m_paths[index];
279 pathData.pen.setJoinStyle(Qt::PenJoinStyle(joinStyle));
280 pathData.pen.setMiterLimit(miterLimit);
281 pathData.m_dirty |= StrokeDirty;
282}
283
284void QQuickShapeCurveRenderer::setCapStyle(int index, QQuickShapePath::CapStyle capStyle)
285{
286 auto &pathData = m_paths[index];
287 pathData.pen.setCapStyle(Qt::PenCapStyle(capStyle));
288 pathData.m_dirty |= StrokeDirty;
289}
290
291void QQuickShapeCurveRenderer::setStrokeStyle(int index,
292 QQuickShapePath::StrokeStyle strokeStyle,
293 qreal dashOffset,
294 const QList<qreal> &dashPattern)
295{
296 auto &pathData = m_paths[index];
297 pathData.pen.setStyle(Qt::PenStyle(strokeStyle));
298 if (strokeStyle == QQuickShapePath::DashLine) {
299 pathData.pen.setDashPattern(dashPattern);
300 pathData.pen.setDashOffset(dashOffset);
301 }
302 pathData.m_dirty |= StrokeDirty;
303}
304
305static QGradient::Type copyCurveGradient(const QQuickShapeGradient *gradient,
306 QSGGradientCache::GradientDesc *dst)
307{
308 QGradient::Type gradientType = QGradient::NoGradient;
309 if (const QQuickShapeLinearGradient *g = qobject_cast<const QQuickShapeLinearGradient *>(gradient)) {
310 gradientType = QGradient::LinearGradient;
311 dst->a = QPointF(g->x1(), g->y1());
312 dst->b = QPointF(g->x2(), g->y2());
313 } else if (const QQuickShapeRadialGradient *g = qobject_cast<const QQuickShapeRadialGradient *>(gradient)) {
314 gradientType = QGradient::RadialGradient;
315 dst->a = QPointF(g->centerX(), g->centerY());
316 dst->b = QPointF(g->focalX(), g->focalY());
317 dst->v0 = g->centerRadius();
318 dst->v1 = g->focalRadius();
319 } else if (const QQuickShapeConicalGradient *g = qobject_cast<const QQuickShapeConicalGradient *>(gradient)) {
320 gradientType = QGradient::ConicalGradient;
321 dst->a = QPointF(g->centerX(), g->centerY());
322 dst->v0 = g->angle();
323 } else if (gradient != nullptr) {
324 static bool warned = false;
325 if (!warned) {
326 warned = true;
327 qCWarning(lcShapeCurveRenderer) << "Unsupported gradient";
328 }
329 }
330
331 if (gradientType != QGradient::NoGradient) {
332 dst->stops = gradient->gradientStops();
333 dst->spread = QGradient::Spread(gradient->spread());
334 }
335
336 return gradientType;
337}
338
339void QQuickShapeCurveRenderer::setFillGradient(int index, QQuickShapeGradient *gradient)
340{
341 PathData &pd(m_paths[index]);
342 const bool wasVisible = pd.isFillVisible();
343 pd.gradientType = copyCurveGradient(gradient, &pd.gradient);
344 pd.m_dirty |= (pd.isFillVisible() != wasVisible) ? FillDirty : UniformsDirty;
345}
346
347void QQuickShapeCurveRenderer::setStrokeGradient(int index, QQuickShapeGradient *gradient)
348{
349 PathData &pd(m_paths[index]);
350 const bool wasVisible = pd.isStrokeVisible();
351 pd.strokeGradientType = copyCurveGradient(gradient, &pd.strokeGradient);
352 pd.m_dirty |= (pd.isStrokeVisible() != wasVisible) ? StrokeDirty : UniformsDirty;
353}
354
355void QQuickShapeCurveRenderer::setFillTransform(int index, const QSGTransform &transform)
356{
357 auto &pathData = m_paths[index];
358 pathData.fillTransform = transform;
359 pathData.m_dirty |= UniformsDirty;
360}
361
362void QQuickShapeCurveRenderer::setFillTextureProvider(int index, QQuickItem *textureProviderItem)
363{
364 auto &pathData = m_paths[index];
365 const bool wasVisible = pathData.isFillVisible();
366 if (pathData.fillTextureProviderItem != nullptr)
367 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->derefWindow();
368 pathData.fillTextureProviderItem = textureProviderItem;
369 if (pathData.fillTextureProviderItem != nullptr)
370 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->refWindow(m_item->window());
371 pathData.m_dirty |= (pathData.isFillVisible() != wasVisible) ? FillDirty : UniformsDirty;
372}
373
374void QQuickShapeCurveRenderer::setVisible(int index, bool visible)
375{
376 auto &pathData = m_paths[index];
377 if (pathData.visible == visible)
378 return;
379 const bool wasFillVisible = pathData.isFillVisible();
380 const bool wasStrokeVisible = pathData.isStrokeVisible();
381 pathData.visible = visible;
382 if (pathData.isFillVisible() != wasFillVisible)
383 pathData.m_dirty |= FillDirty;
384 if (pathData.isStrokeVisible() != wasStrokeVisible)
385 pathData.m_dirty |= StrokeDirty;
386}
387
388void QQuickShapeCurveRenderer::handleSceneChange(QQuickWindow *window)
389{
390 for (auto &pathData : m_paths) {
391 if (pathData.fillTextureProviderItem != nullptr) {
392 if (window == nullptr)
393 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->derefWindow();
394 else
395 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->refWindow(window);
396 }
397 }
398
399 if (!window)
400 clearNodeReferences(); // Nodes are owned by the window, drop our pointers to them
401}
402
403void QQuickShapeCurveRenderer::setAsyncCallback(void (*callback)(void *), void *data)
404{
405 m_asyncCallback = callback;
406 m_asyncCallbackData = data;
407}
408
409void QQuickShapeCurveRenderer::endSync(bool async)
410{
411 bool asyncThreadsRunning = false;
412
413 for (PathData &pathData : m_paths) {
414 if (!pathData.m_dirty)
415 continue;
416
417 if (pathData.m_dirty == UniformsDirty) {
418 // Requires no curve node computation, gets handled directly in updateNode()
419 continue;
420 }
421
422 if (pathData.currentRunner) {
423 // We are in a new sync round before updateNode() has been called to commit the results
424 // of the previous sync and processing round
425 if (pathData.currentRunner->isAsync) {
426 // Already performing async processing. A new run of the runner will be started in
427 // updateNode() to take care of the new dirty flags
428 asyncThreadsRunning = true;
429 continue;
430 } else {
431 // Throw away outdated results and start a new processing
432 delete pathData.currentRunner;
433 pathData.currentRunner = nullptr;
434 }
435 }
436
437 pathData.currentRunner = new QQuickShapeCurveRunnable;
438 setUpRunner(&pathData);
439
440#if QT_CONFIG(thread)
441 if (async) {
442 pathData.currentRunner->isAsync = true;
443 QThreadPool::globalInstance()->start(pathData.currentRunner);
444 asyncThreadsRunning = true;
445 } else
446#endif
447 {
448 pathData.currentRunner->run();
449 }
450 }
451
452 if (async && !asyncThreadsRunning && m_asyncCallback)
453 m_asyncCallback(m_asyncCallbackData);
454}
455
456void QQuickShapeCurveRenderer::setUpRunner(PathData *pathData)
457{
458 Q_ASSERT(pathData->currentRunner);
459 QQuickShapeCurveRunnable *runner = pathData->currentRunner;
460 runner->isDone = false;
461 runner->pathData = *pathData;
462 runner->pathData.fillNodes.clear();
463 runner->pathData.strokeNodes.clear();
464 runner->pathData.currentRunner = nullptr;
465 pathData->m_dirty = 0;
466 if (!runner->isInitialized) {
467 runner->isInitialized = true;
468 runner->setAutoDelete(false);
469 QObject::connect(runner, &QQuickShapeCurveRunnable::done, qApp,
470 [this](QQuickShapeCurveRunnable *r) {
471 r->isDone = true;
472 if (r->orphaned) {
473 delete r; // Renderer was destroyed
474 } else if (r->isAsync) {
475 maybeUpdateAsyncItem();
476 }
477 });
478 }
479}
480
481void QQuickShapeCurveRenderer::maybeUpdateAsyncItem()
482{
483 for (const PathData &pd : std::as_const(m_paths)) {
484 if (pd.currentRunner && !pd.currentRunner->isDone)
485 return;
486 }
487 if (m_item)
488 m_item->update();
489 if (m_asyncCallback)
490 m_asyncCallback(m_asyncCallbackData);
491}
492
493QQuickShapeCurveRunnable::~QQuickShapeCurveRunnable()
494{
495 qDeleteAll(pathData.fillNodes);
496 qDeleteAll(pathData.strokeNodes);
497}
498
500{
501 QQuickShapeCurveRenderer::processPath(&pathData);
502 emit done(this);
503}
504
506{
507 static bool d = qEnvironmentVariableIntValue("QT_QUICKSHAPES_DISABLE_STANDARD_DERIVATIVES") != 0;
508 return d;
509}
510
511void QQuickShapeCurveRenderer::updateNode()
512{
513 if (!m_rootNode)
514 return;
515
516 auto updateUniforms = [](const PathData &pathData) {
517 for (auto &pathNode : std::as_const(pathData.fillNodes)) {
518 if (pathNode->isDebugNode)
519 continue;
520 QSGCurveFillNode *fillNode = static_cast<QSGCurveFillNode *>(pathNode);
521 fillNode->setColor(pathData.fillColor);
522 fillNode->setGradientType(pathData.gradientType);
523 fillNode->setFillGradient(pathData.gradient);
524 fillNode->setFillTransform(pathData.fillTransform);
525 fillNode->setFillTextureProvider(pathData.fillTextureProviderItem != nullptr
526 ? pathData.fillTextureProviderItem->textureProvider()
527 : nullptr);
528 }
529 for (QSGCurveAbstractNode *pathNode : std::as_const(pathData.strokeNodes)) {
530 pathNode->setColor(pathData.pen.color());
531 if (pathNode->isDebugNode) {
532 auto *wfNode = static_cast<QQuickShapeWireFrameNode<StrokeWFT> *>(pathNode);
533 wfNode->setStrokeWidth(pathData.pen.widthF());
534 wfNode->setCosmeticStroke(pathData.pen.isCosmetic());
535 } else {
536 auto *strokeNode = static_cast<QSGCurveStrokeNode *>(pathNode);
537 strokeNode->setStrokeWidth(pathData.pen.widthF());
538 strokeNode->setCosmeticStroke(pathData.pen.isCosmetic());
539 strokeNode->setStrokeGradient(pathData.strokeGradient);
540 strokeNode->setGradientType(pathData.strokeGradientType);
541 }
542 }
543 };
544
545 NodeList toBeDeleted;
546
547 for (const PathData &pathData : std::as_const(m_removedPaths)) {
548 toBeDeleted += pathData.fillNodes;
549 toBeDeleted += pathData.strokeNodes;
550 }
551 m_removedPaths.clear();
552
553 const bool supportsDerivatives = m_item != nullptr
554 && m_item->window() != nullptr
555 && m_item->window()->rhi() != nullptr
556 && !disableScreenSpaceDerivativeShader()
557 ? m_item->window()->rhi()->isFeatureSupported(QRhi::ScreenSpaceDerivatives)
558 : false;
559
560 for (int i = 0; i < m_paths.size(); i++) {
561 PathData &pathData = m_paths[i];
562 if (pathData.currentRunner) {
563 if (!pathData.currentRunner->isDone)
564 continue;
565 // Find insertion point for new nodes. Default is the first stroke node of this path
566 QSGNode *nextNode = pathData.strokeNodes.value(0);
567 // If that is 0, use the first node (stroke or fill) of later paths, if any
568 for (int j = i + 1; !nextNode && j < m_paths.size(); j++) {
569 const PathData &pd = m_paths[j];
570 nextNode = pd.fillNodes.isEmpty() ? pd.strokeNodes.value(0) : pd.fillNodes.value(0);
571 }
572
573 PathData &newData = pathData.currentRunner->pathData;
574 if (newData.m_dirty & PathDirty)
575 pathData.path = newData.path;
576 if (newData.m_dirty & FillDirty) {
577 pathData.fillPath = newData.fillPath;
578 for (auto *node : std::as_const(newData.fillNodes)) {
579 node->setUseStandardDerivatives(supportsDerivatives);
580 if (nextNode)
581 m_rootNode->insertChildNodeBefore(node, nextNode);
582 else
583 m_rootNode->appendChildNode(node);
584 }
585 toBeDeleted += pathData.fillNodes;
586 pathData.fillNodes = newData.fillNodes;
587 }
588 if (newData.m_dirty & StrokeDirty) {
589 for (auto *node : std::as_const(newData.strokeNodes)) {
590 node->setUseStandardDerivatives(supportsDerivatives);
591 if (nextNode)
592 m_rootNode->insertChildNodeBefore(node, nextNode);
593 else
594 m_rootNode->appendChildNode(node);
595 }
596 toBeDeleted += pathData.strokeNodes;
597 pathData.strokeNodes = newData.strokeNodes;
598 }
599 if (newData.m_dirty & UniformsDirty)
600 updateUniforms(pathData);
601
602 // Ownership of new nodes have been transferred to root node
603 newData.fillNodes.clear();
604 newData.strokeNodes.clear();
605
606#if QT_CONFIG(thread)
607 if (pathData.currentRunner->isAsync && (pathData.m_dirty & ~UniformsDirty)) {
608 // New changes have arrived while runner was computing; restart it to handle them
609 setUpRunner(&pathData);
610 QThreadPool::globalInstance()->start(pathData.currentRunner);
611 } else
612#endif
613 {
614 pathData.currentRunner->deleteLater();
615 pathData.currentRunner = nullptr;
616 }
617 }
618
619 if (pathData.m_dirty == UniformsDirty && !pathData.currentRunner) {
620 // Simple case so no runner was created in endSync(); handle it directly here
621 updateUniforms(pathData);
622 pathData.m_dirty = 0;
623 }
624 }
625 qDeleteAll(toBeDeleted); // also removes them from m_rootNode's child list
626}
627
628void QQuickShapeCurveRenderer::processPath(PathData *pathData)
629{
630 static const bool doOverlapSolving = !qEnvironmentVariableIntValue("QT_QUICKSHAPES_DISABLE_OVERLAP_SOLVER");
631 static const bool doIntersetionSolving = !qEnvironmentVariableIntValue("QT_QUICKSHAPES_DISABLE_INTERSECTION_SOLVER");
632 static const bool useTriangulatingStroker = qEnvironmentVariableIntValue("QT_QUICKSHAPES_TRIANGULATING_STROKER");
633 static const bool simplifyPath = qEnvironmentVariableIntValue("QT_QUICKSHAPES_SIMPLIFY_PATHS");
634
635 int &dirtyFlags = pathData->m_dirty;
636
637 if (dirtyFlags & PathDirty) {
638 if (simplifyPath)
639 pathData->path = QQuadPath::fromPainterPath(pathData->originalPath.simplified(), QQuadPath::PathLinear | QQuadPath::PathNonIntersecting | QQuadPath::PathNonOverlappingControlPointTriangles);
640 else
641 pathData->path = QQuadPath::fromPainterPath(pathData->originalPath, QQuadPath::PathHints(int(pathData->pathHints)));
642 pathData->path.setFillRule(pathData->fillRule);
643 pathData->fillPath = {};
644 dirtyFlags |= (FillDirty | StrokeDirty);
645 }
646
647 if (dirtyFlags & FillDirty) {
648 if (pathData->isFillVisible()) {
649 if (pathData->fillPath.isEmpty()) {
650 pathData->fillPath = pathData->path.subPathsClosed();
651 if (doIntersetionSolving)
652 QSGCurveProcessor::solveIntersections(pathData->fillPath);
653 pathData->fillPath.addCurvatureData();
654 if (doOverlapSolving)
655 QSGCurveProcessor::solveOverlaps(pathData->fillPath);
656 }
657 pathData->fillNodes = addFillNodes(pathData->fillPath);
658 dirtyFlags |= (StrokeDirty | UniformsDirty);
659 }
660 }
661
662 if (dirtyFlags & StrokeDirty) {
663 if (pathData->isStrokeVisible()) {
664 const QPen &pen = pathData->pen;
665 const bool solid = (pen.style() == Qt::SolidLine);
666 const QQuadPath &strokePath = solid ? pathData->path
667 : pathData->path.dashed(pen.widthF(),
668 pen.dashPattern(),
669 pen.dashOffset());
670 if (useTriangulatingStroker)
671 pathData->strokeNodes = addTriangulatingStrokerNodes(strokePath, pen);
672 else
673 pathData->strokeNodes = addCurveStrokeNodes(strokePath, pen);
674 dirtyFlags |= UniformsDirty;
675 }
676 }
677}
678
679QQuickShapeCurveRenderer::NodeList QQuickShapeCurveRenderer::addFillNodes(const QQuadPath &path)
680{
681 NodeList ret;
682 std::unique_ptr<QSGCurveFillNode> node(new QSGCurveFillNode);
683 std::unique_ptr<QQuickShapeWireFrameNode<SimpleWFT>> wfNode;
684
685 const qsizetype approxDataCount = 20 * path.elementCount();
686 node->reserve(approxDataCount);
687
688 const int debugFlags = debugVisualization();
689 const bool wireFrame = debugFlags & DebugWireframe;
690
691 if (Q_LIKELY(!wireFrame)) {
692 QSGCurveProcessor::processFill(path,
693 path.fillRule(),
694 [&node](const std::array<QVector2D, 3> &v,
695 const std::array<QVector2D, 3> &n,
696 QSGCurveProcessor::uvForPointCallback uvForPoint)
697 {
698 node->appendTriangle(v, n, uvForPoint);
699 });
700 } else {
701 QList<QQuickShapeWireFrameNode<SimpleWFT>::WireFrameVertex> wfVertices;
702 wfVertices.reserve(approxDataCount);
703 QSGCurveProcessor::processFill(path,
704 path.fillRule(),
705 [&wfVertices, &node](const std::array<QVector2D, 3> &v,
706 const std::array<QVector2D, 3> &n,
707 QSGCurveProcessor::uvForPointCallback uvForPoint)
708 {
709 node->appendTriangle(v, n, uvForPoint);
710
711 wfVertices.append({v.at(0).x(), v.at(0).y(), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }); // 0
712 wfVertices.append({v.at(1).x(), v.at(1).y(), 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }); // 1
713 wfVertices.append({v.at(2).x(), v.at(2).y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }); // 2
714 });
715
716 wfNode.reset(new QQuickShapeWireFrameNode<SimpleWFT>);
717 const QList<quint32> indices = node->uncookedIndexes();
718 QSGGeometry *wfg = new QSGGeometry(QQuickShapeWireFrameNode<SimpleWFT>::attributes(),
719 wfVertices.size(),
720 indices.size(),
721 QSGGeometry::UnsignedIntType);
722 wfNode->setGeometry(wfg);
723
724 wfg->setDrawingMode(QSGGeometry::DrawTriangles);
725 memcpy(wfg->indexData(),
726 indices.data(),
727 indices.size() * wfg->sizeOfIndex());
728 memcpy(wfg->vertexData(),
729 wfVertices.data(),
730 wfg->vertexCount() * wfg->sizeOfVertex());
731 }
732
733 if (Q_UNLIKELY(debugFlags & DebugCurves))
734 node->setDebug(0.5f);
735
736 if (node->uncookedIndexes().size() > 0) {
737 node->cookGeometry();
738 ret.append(node.release());
739 if (wireFrame)
740 ret.append(wfNode.release());
741 }
742
743 return ret;
744}
745
746QQuickShapeCurveRenderer::NodeList QQuickShapeCurveRenderer::addTriangulatingStrokerNodes(const QQuadPath &path, const QPen &pen)
747{
748 NodeList ret;
749 const QColor &color = pen.color();
750
751 QList<QQuickShapeWireFrameNode<StrokeWFT>::WireFrameVertex> wfVertices;
752
753 QTriangulatingStroker stroker;
754 const auto painterPath = path.toPainterPath();
755 const QVectorPath &vp = qtVectorPathForPath(painterPath);
756 stroker.process(vp, pen, {}, {});
757
758 auto *node = new QSGCurveFillNode;
759
760 auto uvForPoint = [](QVector2D v1, QVector2D v2, QVector2D p)
761 {
762 double divisor = v1.x() * v2.y() - v2.x() * v1.y();
763
764 float u = (p.x() * v2.y() - p.y() * v2.x()) / divisor;
765 float v = (p.y() * v1.x() - p.x() * v1.y()) / divisor;
766
767 return QVector2D(u, v);
768 };
769
770 // Find uv coordinates for the point p, for a quadratic curve from p0 to p2 with control point p1
771 // also works for a line from p0 to p2, where p1 is on the inside of the path relative to the line
772 auto curveUv = [uvForPoint](QVector2D p0, QVector2D p1, QVector2D p2, QVector2D p)
773 {
774 QVector2D v1 = 2 * (p1 - p0);
775 QVector2D v2 = p2 - v1 - p0;
776 return uvForPoint(v1, v2, p - p0);
777 };
778
779 auto findPointOtherSide = [](const QVector2D &startPoint, const QVector2D &endPoint, const QVector2D &referencePoint){
780
781 QVector2D baseLine = endPoint - startPoint;
782 QVector2D insideVector = referencePoint - startPoint;
783 QVector2D normal = QVector2D(-baseLine.y(), baseLine.x()); // TODO: limit size of triangle
784
785 bool swap = QVector2D::dotProduct(insideVector, normal) < 0;
786
787 return swap ? startPoint + normal : startPoint - normal;
788 };
789
790 static bool disableExtraTriangles = qEnvironmentVariableIntValue("QT_QUICKSHAPES_WIP_DISABLE_EXTRA_STROKE_TRIANGLES");
791
792 auto addStrokeTriangle = [&](const QVector2D &p1, const QVector2D &p2, const QVector2D &p3){
793 if (p1 == p2 || p2 == p3) {
794 return;
795 }
796
797 auto uvForPoint = [&p1, &p2, &p3, curveUv](QVector2D p) {
798 auto uv = curveUv(p1, p2, p3, p);
799 return QVector3D(uv.x(), uv.y(), 0.0f); // Line
800 };
801
802 node->appendTriangle(p1, p2, p3, uvForPoint);
803
804
805 wfVertices.append({p1.x(), p1.y(), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}); // 0
806 wfVertices.append({p2.x(), p2.y(), 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, 1.0f}); // 1
807 wfVertices.append({p3.x(), p3.y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f}); // 2
808
809 if (!disableExtraTriangles) {
810 // Add a triangle on the outer side of the line to get some more AA
811 // The new point replaces p2 (currentVertex+1)
812 QVector2D op = findPointOtherSide(p1, p3, p2);
813 node->appendTriangle(p1, op, p3, uvForPoint);
814
815 wfVertices.append({p1.x(), p1.y(), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f});
816 wfVertices.append({op.x(), op.y(), 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}); // replacing p2
817 wfVertices.append({p3.x(), p3.y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f});
818 }
819 };
820
821 const int vertCount = stroker.vertexCount() / 2;
822 const float *verts = stroker.vertices();
823 for (int i = 0; i < vertCount - 2; ++i) {
824 QVector2D p[3];
825 for (int j = 0; j < 3; ++j) {
826 p[j] = QVector2D(verts[(i+j)*2], verts[(i+j)*2 + 1]);
827 }
828 addStrokeTriangle(p[0], p[1], p[2]);
829 }
830
831 QList<quint32> indices = node->uncookedIndexes();
832 if (indices.size() > 0) {
833 node->setColor(color);
834
835 node->cookGeometry();
836 ret.append(node);
837 }
838 const bool wireFrame = debugVisualization() & DebugWireframe;
839 if (wireFrame) {
840 QQuickShapeWireFrameNode<StrokeWFT> *wfNode = new QQuickShapeWireFrameNode<StrokeWFT>;
841 QSGGeometry *wfg = new QSGGeometry(QQuickShapeWireFrameNode<StrokeWFT>::attributes(),
842 wfVertices.size(),
843 indices.size(),
844 QSGGeometry::UnsignedIntType);
845 wfNode->setGeometry(wfg);
846
847 wfg->setDrawingMode(QSGGeometry::DrawTriangles);
848 memcpy(wfg->indexData(),
849 indices.data(),
850 indices.size() * wfg->sizeOfIndex());
851 memcpy(wfg->vertexData(),
852 wfVertices.data(),
853 wfg->vertexCount() * wfg->sizeOfVertex());
854
855 ret.append(wfNode);
856 }
857
858 return ret;
859}
860
861void QQuickShapeCurveRenderer::setRootNode(QSGNode *node)
862{
863 clearNodeReferences();
864 m_rootNode = node;
865}
866
867void QQuickShapeCurveRenderer::clearNodeReferences()
868{
869 for (PathData &pd : m_paths) {
870 pd.fillNodes.clear();
871 pd.strokeNodes.clear();
872 }
873}
874
875int QQuickShapeCurveRenderer::debugVisualizationFlags = QQuickShapeCurveRenderer::NoDebug;
876
877int QQuickShapeCurveRenderer::debugVisualization()
878{
879 static const int envFlags = qEnvironmentVariableIntValue("QT_QUICKSHAPES_DEBUG");
880 return debugVisualizationFlags | envFlags;
881}
882
883void QQuickShapeCurveRenderer::setDebugVisualization(int options)
884{
885 if (debugVisualizationFlags == options)
886 return;
887 debugVisualizationFlags = options;
888}
889
890/*! \internal
891 Convert \a path to QSGCurveAbstractNodes with vertices ready to send to the GPU.
892 The given \a path is assumed to be a stroke centerline: it may be continuous or dashed.
893 Also create the wireframe node if enabled.
894*/
895QQuickShapeCurveRenderer::NodeList QQuickShapeCurveRenderer::addCurveStrokeNodes(const QQuadPath &path, const QPen &pen)
896{
897 NodeList ret;
898
899 const bool debug = debugVisualization() & DebugCurves;
900 auto *node = new QSGCurveStrokeNode;
901 node->setDebug(0.2f * debug);
902 QList<QQuickShapeWireFrameNode<StrokeWFT>::WireFrameVertex> wfVertices;
903
904 const float penWidth = pen.widthF();
905
906 static const int subdivisions = qEnvironmentVariable("QT_QUICKSHAPES_STROKE_SUBDIVISIONS", QStringLiteral("3")).toInt();
907
908 const bool wireFrame = debugVisualization() & DebugWireframe;
909 QSGCurveProcessor::processStroke(path,
910 pen.miterLimit(),
911 penWidth, pen.isCosmetic(),
912 pen.joinStyle(),
913 pen.capStyle(),
914 // addStrokeTriangleCallback (see qsgcurveprocessor_p.h):
915 [&wfVertices, &node, &wireFrame](const std::array<QVector2D, 3> &vtx, // triangle corners
916 const std::array<QVector2D, 3> &ctl, // curve control points
917 const std::array<QVector2D, 3> &n, // normals
918 const std::array<float, 3> &ex, // extrusions
919 QSGCurveStrokeNode::TriangleFlags flags)
920 {
921 const QVector2D &v0 = vtx.at(0);
922 const QVector2D &v1 = vtx.at(1);
923 const QVector2D &v2 = vtx.at(2);
924 if (flags.testFlag(QSGCurveStrokeNode::TriangleFlag::Line))
925 node->appendTriangle(vtx, std::array<QVector2D, 2>{ctl.at(0), ctl.at(2)}, n, ex);
926 else
927 node->appendTriangle(vtx, ctl, n, ex);
928
929 if (Q_UNLIKELY(wireFrame)) {
930 wfVertices.append({v0.x(), v0.y(), 1.0f, 0.0f, 0.0f, n.at(0).x(), n.at(0).y(), ex.at(0)});
931 wfVertices.append({v1.x(), v1.y(), 0.0f, 1.0f, 0.0f, n.at(1).x(), n.at(1).y(), ex.at(1)});
932 wfVertices.append({v2.x(), v2.y(), 0.0f, 0.0f, 1.0f, n.at(2).x(), n.at(2).y(), ex.at(2)});
933 }
934 },
935 subdivisions);
936
937 auto indexCopy = node->uncookedIndexes(); // uncookedIndexes get deleted on cooking
938
939 node->setColor(pen.color());
940 node->setStrokeWidth(penWidth);
941 node->setCosmeticStroke(pen.isCosmetic());
942 node->cookGeometry();
943 ret.append(node);
944
945 if (Q_UNLIKELY(wireFrame)) {
946 QQuickShapeWireFrameNode<StrokeWFT> *wfNode = new QQuickShapeWireFrameNode<StrokeWFT>;
947
948 QSGGeometry *wfg = new QSGGeometry(QQuickShapeWireFrameNode<StrokeWFT>::attributes(),
949 wfVertices.size(),
950 indexCopy.size(),
951 QSGGeometry::UnsignedIntType);
952 wfNode->setGeometry(wfg);
953 wfNode->setCosmeticStroke(pen.isCosmetic());
954 wfNode->setStrokeWidth(penWidth);
955
956 wfg->setDrawingMode(QSGGeometry::DrawTriangles);
957 memcpy(wfg->indexData(),
958 indexCopy.data(),
959 indexCopy.size() * wfg->sizeOfIndex());
960 memcpy(wfg->vertexData(),
961 wfVertices.data(),
962 wfg->vertexCount() * wfg->sizeOfVertex());
963
964 ret.append(wfNode);
965 }
966
967 return ret;
968}
969
970QT_END_NAMESPACE
void run() override
Implement this pure virtual function in your subclass.
Combined button and popup list for selecting options.
static bool disableScreenSpaceDerivativeShader()
static QGradient::Type copyCurveGradient(const QQuickShapeGradient *gradient, QSGGradientCache::GradientDesc *dst)