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
305void QQuickShapeCurveRenderer::setFillGradient(int index, QQuickShapeGradient *gradient)
306{
307 PathData &pd(m_paths[index]);
308 const bool wasVisible = pd.isFillVisible();
309 pd.gradientType = QGradient::NoGradient;
310 if (QQuickShapeLinearGradient *g = qobject_cast<QQuickShapeLinearGradient *>(gradient)) {
311 pd.gradientType = QGradient::LinearGradient;
312 pd.gradient.stops = gradient->gradientStops();
313 pd.gradient.spread = QGradient::Spread(gradient->spread());
314 pd.gradient.a = QPointF(g->x1(), g->y1());
315 pd.gradient.b = QPointF(g->x2(), g->y2());
316 } else if (QQuickShapeRadialGradient *g = qobject_cast<QQuickShapeRadialGradient *>(gradient)) {
317 pd.gradientType = QGradient::RadialGradient;
318 pd.gradient.a = QPointF(g->centerX(), g->centerY());
319 pd.gradient.b = QPointF(g->focalX(), g->focalY());
320 pd.gradient.v0 = g->centerRadius();
321 pd.gradient.v1 = g->focalRadius();
322 } else if (QQuickShapeConicalGradient *g = qobject_cast<QQuickShapeConicalGradient *>(gradient)) {
323 pd.gradientType = QGradient::ConicalGradient;
324 pd.gradient.a = QPointF(g->centerX(), g->centerY());
325 pd.gradient.v0 = g->angle();
326 } else if (gradient != nullptr) {
327 static bool warned = false;
328 if (!warned) {
329 warned = true;
330 qCWarning(lcShapeCurveRenderer) << "Unsupported gradient fill";
331 }
332 }
333
334 if (pd.gradientType != QGradient::NoGradient) {
335 pd.gradient.stops = gradient->gradientStops();
336 pd.gradient.spread = QGradient::Spread(gradient->spread());
337 }
338
339 pd.m_dirty |= (pd.isFillVisible() != wasVisible) ? FillDirty : UniformsDirty;
340}
341
342void QQuickShapeCurveRenderer::setFillTransform(int index, const QSGTransform &transform)
343{
344 auto &pathData = m_paths[index];
345 pathData.fillTransform = transform;
346 pathData.m_dirty |= UniformsDirty;
347}
348
349void QQuickShapeCurveRenderer::setFillTextureProvider(int index, QQuickItem *textureProviderItem)
350{
351 auto &pathData = m_paths[index];
352 const bool wasVisible = pathData.isFillVisible();
353 if (pathData.fillTextureProviderItem != nullptr)
354 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->derefWindow();
355 pathData.fillTextureProviderItem = textureProviderItem;
356 if (pathData.fillTextureProviderItem != nullptr)
357 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->refWindow(m_item->window());
358 pathData.m_dirty |= (pathData.isFillVisible() != wasVisible) ? FillDirty : UniformsDirty;
359}
360
361void QQuickShapeCurveRenderer::handleSceneChange(QQuickWindow *window)
362{
363 for (auto &pathData : m_paths) {
364 if (pathData.fillTextureProviderItem != nullptr) {
365 if (window == nullptr)
366 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->derefWindow();
367 else
368 QQuickItemPrivate::get(pathData.fillTextureProviderItem)->refWindow(window);
369 }
370 }
371}
372
373void QQuickShapeCurveRenderer::setAsyncCallback(void (*callback)(void *), void *data)
374{
375 m_asyncCallback = callback;
376 m_asyncCallbackData = data;
377}
378
379void QQuickShapeCurveRenderer::endSync(bool async)
380{
381 bool asyncThreadsRunning = false;
382
383 for (PathData &pathData : m_paths) {
384 if (!pathData.m_dirty)
385 continue;
386
387 if (pathData.m_dirty == UniformsDirty) {
388 // Requires no curve node computation, gets handled directly in updateNode()
389 continue;
390 }
391
392 if (pathData.currentRunner) {
393 // We are in a new sync round before updateNode() has been called to commit the results
394 // of the previous sync and processing round
395 if (pathData.currentRunner->isAsync) {
396 // Already performing async processing. A new run of the runner will be started in
397 // updateNode() to take care of the new dirty flags
398 asyncThreadsRunning = true;
399 continue;
400 } else {
401 // Throw away outdated results and start a new processing
402 delete pathData.currentRunner;
403 pathData.currentRunner = nullptr;
404 }
405 }
406
407 pathData.currentRunner = new QQuickShapeCurveRunnable;
408 setUpRunner(&pathData);
409
410#if QT_CONFIG(thread)
411 if (async) {
412 pathData.currentRunner->isAsync = true;
413 QThreadPool::globalInstance()->start(pathData.currentRunner);
414 asyncThreadsRunning = true;
415 } else
416#endif
417 {
418 pathData.currentRunner->run();
419 }
420 }
421
422 if (async && !asyncThreadsRunning && m_asyncCallback)
423 m_asyncCallback(m_asyncCallbackData);
424}
425
426void QQuickShapeCurveRenderer::setUpRunner(PathData *pathData)
427{
428 Q_ASSERT(pathData->currentRunner);
429 QQuickShapeCurveRunnable *runner = pathData->currentRunner;
430 runner->isDone = false;
431 runner->pathData = *pathData;
432 runner->pathData.fillNodes.clear();
433 runner->pathData.strokeNodes.clear();
434 runner->pathData.currentRunner = nullptr;
435 pathData->m_dirty = 0;
436 if (!runner->isInitialized) {
437 runner->isInitialized = true;
438 runner->setAutoDelete(false);
439 QObject::connect(runner, &QQuickShapeCurveRunnable::done, qApp,
440 [this](QQuickShapeCurveRunnable *r) {
441 r->isDone = true;
442 if (r->orphaned) {
443 delete r; // Renderer was destroyed
444 } else if (r->isAsync) {
445 maybeUpdateAsyncItem();
446 }
447 });
448 }
449}
450
451void QQuickShapeCurveRenderer::maybeUpdateAsyncItem()
452{
453 for (const PathData &pd : std::as_const(m_paths)) {
454 if (pd.currentRunner && !pd.currentRunner->isDone)
455 return;
456 }
457 if (m_item)
458 m_item->update();
459 if (m_asyncCallback)
460 m_asyncCallback(m_asyncCallbackData);
461}
462
463QQuickShapeCurveRunnable::~QQuickShapeCurveRunnable()
464{
465 qDeleteAll(pathData.fillNodes);
466 qDeleteAll(pathData.strokeNodes);
467}
468
470{
471 QQuickShapeCurveRenderer::processPath(&pathData);
472 emit done(this);
473}
474
476{
477 static bool d = qEnvironmentVariableIntValue("QT_QUICKSHAPES_DISABLE_STANDARD_DERIVATIVES") != 0;
478 return d;
479}
480
481void QQuickShapeCurveRenderer::updateNode()
482{
483 if (!m_rootNode)
484 return;
485
486 auto updateUniforms = [](const PathData &pathData) {
487 for (auto &pathNode : std::as_const(pathData.fillNodes)) {
488 if (pathNode->isDebugNode)
489 continue;
490 QSGCurveFillNode *fillNode = static_cast<QSGCurveFillNode *>(pathNode);
491 fillNode->setColor(pathData.fillColor);
492 fillNode->setGradientType(pathData.gradientType);
493 fillNode->setFillGradient(pathData.gradient);
494 fillNode->setFillTransform(pathData.fillTransform);
495 fillNode->setFillTextureProvider(pathData.fillTextureProviderItem != nullptr
496 ? pathData.fillTextureProviderItem->textureProvider()
497 : nullptr);
498 }
499 for (QSGCurveAbstractNode *pathNode : std::as_const(pathData.strokeNodes)) {
500 pathNode->setColor(pathData.pen.color());
501 if (pathNode->isDebugNode) {
502 auto *wfNode = static_cast<QQuickShapeWireFrameNode<StrokeWFT> *>(pathNode);
503 wfNode->setStrokeWidth(pathData.pen.widthF());
504 wfNode->setCosmeticStroke(pathData.pen.isCosmetic());
505 } else {
506 auto *strokeNode = static_cast<QSGCurveStrokeNode *>(pathNode);
507 strokeNode->setStrokeWidth(pathData.pen.widthF());
508 strokeNode->setCosmeticStroke(pathData.pen.isCosmetic());
509 }
510 }
511 };
512
513 NodeList toBeDeleted;
514
515 for (const PathData &pathData : std::as_const(m_removedPaths)) {
516 toBeDeleted += pathData.fillNodes;
517 toBeDeleted += pathData.strokeNodes;
518 }
519 m_removedPaths.clear();
520
521 const bool supportsDerivatives = m_item != nullptr
522 && m_item->window() != nullptr
523 && m_item->window()->rhi() != nullptr
524 && !disableScreenSpaceDerivativeShader()
525 ? m_item->window()->rhi()->isFeatureSupported(QRhi::ScreenSpaceDerivatives)
526 : false;
527
528 for (int i = 0; i < m_paths.size(); i++) {
529 PathData &pathData = m_paths[i];
530 if (pathData.currentRunner) {
531 if (!pathData.currentRunner->isDone)
532 continue;
533 // Find insertion point for new nodes. Default is the first stroke node of this path
534 QSGNode *nextNode = pathData.strokeNodes.value(0);
535 // If that is 0, use the first node (stroke or fill) of later paths, if any
536 for (int j = i + 1; !nextNode && j < m_paths.size(); j++) {
537 const PathData &pd = m_paths[j];
538 nextNode = pd.fillNodes.isEmpty() ? pd.strokeNodes.value(0) : pd.fillNodes.value(0);
539 }
540
541 PathData &newData = pathData.currentRunner->pathData;
542 if (newData.m_dirty & PathDirty)
543 pathData.path = newData.path;
544 if (newData.m_dirty & FillDirty) {
545 pathData.fillPath = newData.fillPath;
546 for (auto *node : std::as_const(newData.fillNodes)) {
547 node->setUseStandardDerivatives(supportsDerivatives);
548 if (nextNode)
549 m_rootNode->insertChildNodeBefore(node, nextNode);
550 else
551 m_rootNode->appendChildNode(node);
552 }
553 toBeDeleted += pathData.fillNodes;
554 pathData.fillNodes = newData.fillNodes;
555 }
556 if (newData.m_dirty & StrokeDirty) {
557 for (auto *node : std::as_const(newData.strokeNodes)) {
558 node->setUseStandardDerivatives(supportsDerivatives);
559 if (nextNode)
560 m_rootNode->insertChildNodeBefore(node, nextNode);
561 else
562 m_rootNode->appendChildNode(node);
563 }
564 toBeDeleted += pathData.strokeNodes;
565 pathData.strokeNodes = newData.strokeNodes;
566 }
567 if (newData.m_dirty & UniformsDirty)
568 updateUniforms(newData);
569
570 // Ownership of new nodes have been transferred to root node
571 newData.fillNodes.clear();
572 newData.strokeNodes.clear();
573
574#if QT_CONFIG(thread)
575 if (pathData.currentRunner->isAsync && (pathData.m_dirty & ~UniformsDirty)) {
576 // New changes have arrived while runner was computing; restart it to handle them
577 setUpRunner(&pathData);
578 QThreadPool::globalInstance()->start(pathData.currentRunner);
579 } else
580#endif
581 {
582 pathData.currentRunner->deleteLater();
583 pathData.currentRunner = nullptr;
584 }
585 }
586
587 if (pathData.m_dirty == UniformsDirty && !pathData.currentRunner) {
588 // Simple case so no runner was created in endSync(); handle it directly here
589 updateUniforms(pathData);
590 pathData.m_dirty = 0;
591 }
592 }
593 qDeleteAll(toBeDeleted); // also removes them from m_rootNode's child list
594}
595
596void QQuickShapeCurveRenderer::processPath(PathData *pathData)
597{
598 static const bool doOverlapSolving = !qEnvironmentVariableIntValue("QT_QUICKSHAPES_DISABLE_OVERLAP_SOLVER");
599 static const bool doIntersetionSolving = !qEnvironmentVariableIntValue("QT_QUICKSHAPES_DISABLE_INTERSECTION_SOLVER");
600 static const bool useTriangulatingStroker = qEnvironmentVariableIntValue("QT_QUICKSHAPES_TRIANGULATING_STROKER");
601 static const bool simplifyPath = qEnvironmentVariableIntValue("QT_QUICKSHAPES_SIMPLIFY_PATHS");
602
603 int &dirtyFlags = pathData->m_dirty;
604
605 if (dirtyFlags & PathDirty) {
606 if (simplifyPath)
607 pathData->path = QQuadPath::fromPainterPath(pathData->originalPath.simplified(), QQuadPath::PathLinear | QQuadPath::PathNonIntersecting | QQuadPath::PathNonOverlappingControlPointTriangles);
608 else
609 pathData->path = QQuadPath::fromPainterPath(pathData->originalPath, QQuadPath::PathHints(int(pathData->pathHints)));
610 pathData->path.setFillRule(pathData->fillRule);
611 pathData->fillPath = {};
612 dirtyFlags |= (FillDirty | StrokeDirty);
613 }
614
615 if (dirtyFlags & FillDirty) {
616 if (pathData->isFillVisible()) {
617 if (pathData->fillPath.isEmpty()) {
618 pathData->fillPath = pathData->path.subPathsClosed();
619 if (doIntersetionSolving)
620 QSGCurveProcessor::solveIntersections(pathData->fillPath);
621 pathData->fillPath.addCurvatureData();
622 if (doOverlapSolving)
623 QSGCurveProcessor::solveOverlaps(pathData->fillPath);
624 }
625 pathData->fillNodes = addFillNodes(pathData->fillPath);
626 dirtyFlags |= (StrokeDirty | UniformsDirty);
627 }
628 }
629
630 if (dirtyFlags & StrokeDirty) {
631 if (pathData->isStrokeVisible()) {
632 const QPen &pen = pathData->pen;
633 const bool solid = (pen.style() == Qt::SolidLine);
634 const QQuadPath &strokePath = solid ? pathData->path
635 : pathData->path.dashed(pen.widthF(),
636 pen.dashPattern(),
637 pen.dashOffset());
638 if (useTriangulatingStroker)
639 pathData->strokeNodes = addTriangulatingStrokerNodes(strokePath, pen);
640 else
641 pathData->strokeNodes = addCurveStrokeNodes(strokePath, pen);
642 }
643 }
644}
645
646QQuickShapeCurveRenderer::NodeList QQuickShapeCurveRenderer::addFillNodes(const QQuadPath &path)
647{
648 NodeList ret;
649 std::unique_ptr<QSGCurveFillNode> node(new QSGCurveFillNode);
650 std::unique_ptr<QQuickShapeWireFrameNode<SimpleWFT>> wfNode;
651
652 const qsizetype approxDataCount = 20 * path.elementCount();
653 node->reserve(approxDataCount);
654
655 const int debugFlags = debugVisualization();
656 const bool wireFrame = debugFlags & DebugWireframe;
657
658 if (Q_LIKELY(!wireFrame)) {
659 QSGCurveProcessor::processFill(path,
660 path.fillRule(),
661 [&node](const std::array<QVector2D, 3> &v,
662 const std::array<QVector2D, 3> &n,
663 QSGCurveProcessor::uvForPointCallback uvForPoint)
664 {
665 node->appendTriangle(v, n, uvForPoint);
666 });
667 } else {
668 QList<QQuickShapeWireFrameNode<SimpleWFT>::WireFrameVertex> wfVertices;
669 wfVertices.reserve(approxDataCount);
670 QSGCurveProcessor::processFill(path,
671 path.fillRule(),
672 [&wfVertices, &node](const std::array<QVector2D, 3> &v,
673 const std::array<QVector2D, 3> &n,
674 QSGCurveProcessor::uvForPointCallback uvForPoint)
675 {
676 node->appendTriangle(v, n, uvForPoint);
677
678 wfVertices.append({v.at(0).x(), v.at(0).y(), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }); // 0
679 wfVertices.append({v.at(1).x(), v.at(1).y(), 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }); // 1
680 wfVertices.append({v.at(2).x(), v.at(2).y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }); // 2
681 });
682
683 wfNode.reset(new QQuickShapeWireFrameNode<SimpleWFT>);
684 const QList<quint32> indices = node->uncookedIndexes();
685 QSGGeometry *wfg = new QSGGeometry(QQuickShapeWireFrameNode<SimpleWFT>::attributes(),
686 wfVertices.size(),
687 indices.size(),
688 QSGGeometry::UnsignedIntType);
689 wfNode->setGeometry(wfg);
690
691 wfg->setDrawingMode(QSGGeometry::DrawTriangles);
692 memcpy(wfg->indexData(),
693 indices.data(),
694 indices.size() * wfg->sizeOfIndex());
695 memcpy(wfg->vertexData(),
696 wfVertices.data(),
697 wfg->vertexCount() * wfg->sizeOfVertex());
698 }
699
700 if (Q_UNLIKELY(debugFlags & DebugCurves))
701 node->setDebug(0.5f);
702
703 if (node->uncookedIndexes().size() > 0) {
704 node->cookGeometry();
705 ret.append(node.release());
706 if (wireFrame)
707 ret.append(wfNode.release());
708 }
709
710 return ret;
711}
712
713QQuickShapeCurveRenderer::NodeList QQuickShapeCurveRenderer::addTriangulatingStrokerNodes(const QQuadPath &path, const QPen &pen)
714{
715 NodeList ret;
716 const QColor &color = pen.color();
717
718 QList<QQuickShapeWireFrameNode<StrokeWFT>::WireFrameVertex> wfVertices;
719
720 QTriangulatingStroker stroker;
721 const auto painterPath = path.toPainterPath();
722 const QVectorPath &vp = qtVectorPathForPath(painterPath);
723 stroker.process(vp, pen, {}, {});
724
725 auto *node = new QSGCurveFillNode;
726
727 auto uvForPoint = [](QVector2D v1, QVector2D v2, QVector2D p)
728 {
729 double divisor = v1.x() * v2.y() - v2.x() * v1.y();
730
731 float u = (p.x() * v2.y() - p.y() * v2.x()) / divisor;
732 float v = (p.y() * v1.x() - p.x() * v1.y()) / divisor;
733
734 return QVector2D(u, v);
735 };
736
737 // Find uv coordinates for the point p, for a quadratic curve from p0 to p2 with control point p1
738 // also works for a line from p0 to p2, where p1 is on the inside of the path relative to the line
739 auto curveUv = [uvForPoint](QVector2D p0, QVector2D p1, QVector2D p2, QVector2D p)
740 {
741 QVector2D v1 = 2 * (p1 - p0);
742 QVector2D v2 = p2 - v1 - p0;
743 return uvForPoint(v1, v2, p - p0);
744 };
745
746 auto findPointOtherSide = [](const QVector2D &startPoint, const QVector2D &endPoint, const QVector2D &referencePoint){
747
748 QVector2D baseLine = endPoint - startPoint;
749 QVector2D insideVector = referencePoint - startPoint;
750 QVector2D normal = QVector2D(-baseLine.y(), baseLine.x()); // TODO: limit size of triangle
751
752 bool swap = QVector2D::dotProduct(insideVector, normal) < 0;
753
754 return swap ? startPoint + normal : startPoint - normal;
755 };
756
757 static bool disableExtraTriangles = qEnvironmentVariableIntValue("QT_QUICKSHAPES_WIP_DISABLE_EXTRA_STROKE_TRIANGLES");
758
759 auto addStrokeTriangle = [&](const QVector2D &p1, const QVector2D &p2, const QVector2D &p3){
760 if (p1 == p2 || p2 == p3) {
761 return;
762 }
763
764 auto uvForPoint = [&p1, &p2, &p3, curveUv](QVector2D p) {
765 auto uv = curveUv(p1, p2, p3, p);
766 return QVector3D(uv.x(), uv.y(), 0.0f); // Line
767 };
768
769 node->appendTriangle(p1, p2, p3, uvForPoint);
770
771
772 wfVertices.append({p1.x(), p1.y(), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}); // 0
773 wfVertices.append({p2.x(), p2.y(), 0.0f, 0.1f, 0.0f, 0.0f, 0.0f, 1.0f}); // 1
774 wfVertices.append({p3.x(), p3.y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f}); // 2
775
776 if (!disableExtraTriangles) {
777 // Add a triangle on the outer side of the line to get some more AA
778 // The new point replaces p2 (currentVertex+1)
779 QVector2D op = findPointOtherSide(p1, p3, p2);
780 node->appendTriangle(p1, op, p3, uvForPoint);
781
782 wfVertices.append({p1.x(), p1.y(), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f});
783 wfVertices.append({op.x(), op.y(), 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}); // replacing p2
784 wfVertices.append({p3.x(), p3.y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f});
785 }
786 };
787
788 const int vertCount = stroker.vertexCount() / 2;
789 const float *verts = stroker.vertices();
790 for (int i = 0; i < vertCount - 2; ++i) {
791 QVector2D p[3];
792 for (int j = 0; j < 3; ++j) {
793 p[j] = QVector2D(verts[(i+j)*2], verts[(i+j)*2 + 1]);
794 }
795 addStrokeTriangle(p[0], p[1], p[2]);
796 }
797
798 QList<quint32> indices = node->uncookedIndexes();
799 if (indices.size() > 0) {
800 node->setColor(color);
801
802 node->cookGeometry();
803 ret.append(node);
804 }
805 const bool wireFrame = debugVisualization() & DebugWireframe;
806 if (wireFrame) {
807 QQuickShapeWireFrameNode<StrokeWFT> *wfNode = new QQuickShapeWireFrameNode<StrokeWFT>;
808 QSGGeometry *wfg = new QSGGeometry(QQuickShapeWireFrameNode<StrokeWFT>::attributes(),
809 wfVertices.size(),
810 indices.size(),
811 QSGGeometry::UnsignedIntType);
812 wfNode->setGeometry(wfg);
813
814 wfg->setDrawingMode(QSGGeometry::DrawTriangles);
815 memcpy(wfg->indexData(),
816 indices.data(),
817 indices.size() * wfg->sizeOfIndex());
818 memcpy(wfg->vertexData(),
819 wfVertices.data(),
820 wfg->vertexCount() * wfg->sizeOfVertex());
821
822 ret.append(wfNode);
823 }
824
825 return ret;
826}
827
828void QQuickShapeCurveRenderer::setRootNode(QSGNode *node)
829{
830 clearNodeReferences();
831 m_rootNode = node;
832}
833
834void QQuickShapeCurveRenderer::clearNodeReferences()
835{
836 for (PathData &pd : m_paths) {
837 pd.fillNodes.clear();
838 pd.strokeNodes.clear();
839 }
840}
841
842int QQuickShapeCurveRenderer::debugVisualizationFlags = QQuickShapeCurveRenderer::NoDebug;
843
844int QQuickShapeCurveRenderer::debugVisualization()
845{
846 static const int envFlags = qEnvironmentVariableIntValue("QT_QUICKSHAPES_DEBUG");
847 return debugVisualizationFlags | envFlags;
848}
849
850void QQuickShapeCurveRenderer::setDebugVisualization(int options)
851{
852 if (debugVisualizationFlags == options)
853 return;
854 debugVisualizationFlags = options;
855}
856
857/*! \internal
858 Convert \a path to QSGCurveAbstractNodes with vertices ready to send to the GPU.
859 The given \a path is assumed to be a stroke centerline: it may be continuous or dashed.
860 Also create the wireframe node if enabled.
861*/
862QQuickShapeCurveRenderer::NodeList QQuickShapeCurveRenderer::addCurveStrokeNodes(const QQuadPath &path, const QPen &pen)
863{
864 NodeList ret;
865
866 const bool debug = debugVisualization() & DebugCurves;
867 auto *node = new QSGCurveStrokeNode;
868 node->setDebug(0.2f * debug);
869 QList<QQuickShapeWireFrameNode<StrokeWFT>::WireFrameVertex> wfVertices;
870
871 const float penWidth = pen.widthF();
872
873 static const int subdivisions = qEnvironmentVariable("QT_QUICKSHAPES_STROKE_SUBDIVISIONS", QStringLiteral("3")).toInt();
874
875 const bool wireFrame = debugVisualization() & DebugWireframe;
876 QSGCurveProcessor::processStroke(path,
877 pen.miterLimit(),
878 penWidth, pen.isCosmetic(),
879 pen.joinStyle(),
880 pen.capStyle(),
881 // addStrokeTriangleCallback (see qsgcurveprocessor_p.h):
882 [&wfVertices, &node, &wireFrame](const std::array<QVector2D, 3> &vtx, // triangle corners
883 const std::array<QVector2D, 3> &ctl, // curve control points
884 const std::array<QVector2D, 3> &n, // normals
885 const std::array<float, 3> &ex, // extrusions
886 QSGCurveStrokeNode::TriangleFlags flags)
887 {
888 const QVector2D &v0 = vtx.at(0);
889 const QVector2D &v1 = vtx.at(1);
890 const QVector2D &v2 = vtx.at(2);
891 if (flags.testFlag(QSGCurveStrokeNode::TriangleFlag::Line))
892 node->appendTriangle(vtx, std::array<QVector2D, 2>{ctl.at(0), ctl.at(2)}, n, ex);
893 else
894 node->appendTriangle(vtx, ctl, n, ex);
895
896 if (Q_UNLIKELY(wireFrame)) {
897 wfVertices.append({v0.x(), v0.y(), 1.0f, 0.0f, 0.0f, n.at(0).x(), n.at(0).y(), ex.at(0)});
898 wfVertices.append({v1.x(), v1.y(), 0.0f, 1.0f, 0.0f, n.at(1).x(), n.at(1).y(), ex.at(1)});
899 wfVertices.append({v2.x(), v2.y(), 0.0f, 0.0f, 1.0f, n.at(2).x(), n.at(2).y(), ex.at(2)});
900 }
901 },
902 subdivisions);
903
904 auto indexCopy = node->uncookedIndexes(); // uncookedIndexes get deleted on cooking
905
906 node->setColor(pen.color());
907 node->setStrokeWidth(penWidth);
908 node->setCosmeticStroke(pen.isCosmetic());
909 node->cookGeometry();
910 ret.append(node);
911
912 if (Q_UNLIKELY(wireFrame)) {
913 QQuickShapeWireFrameNode<StrokeWFT> *wfNode = new QQuickShapeWireFrameNode<StrokeWFT>;
914
915 QSGGeometry *wfg = new QSGGeometry(QQuickShapeWireFrameNode<StrokeWFT>::attributes(),
916 wfVertices.size(),
917 indexCopy.size(),
918 QSGGeometry::UnsignedIntType);
919 wfNode->setGeometry(wfg);
920 wfNode->setCosmeticStroke(pen.isCosmetic());
921 wfNode->setStrokeWidth(penWidth);
922
923 wfg->setDrawingMode(QSGGeometry::DrawTriangles);
924 memcpy(wfg->indexData(),
925 indexCopy.data(),
926 indexCopy.size() * wfg->sizeOfIndex());
927 memcpy(wfg->vertexData(),
928 wfVertices.data(),
929 wfg->vertexCount() * wfg->sizeOfVertex());
930
931 ret.append(wfNode);
932 }
933
934 return ret;
935}
936
937QT_END_NAMESPACE
void run() override
Implement this pure virtual function in your subclass.
Combined button and popup list for selecting options.
static bool disableScreenSpaceDerivativeShader()