QGIS API Documentation 4.5.0-Master (3b5d115045b)
Loading...
Searching...
No Matches
qgstessellator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgstessellator.cpp
3 --------------------------------------
4 Date : July 2017
5 Copyright : (C) 2017 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgstessellator.h"
17
18#include <algorithm>
19#include <earcut.hpp>
20#include <unordered_set>
21
22#include "poly2tri.h"
23#include "qgis.h"
24#include "qgsabstractgeometry.h"
25#include "qgscurve.h"
26#include "qgsgeometry.h"
28#include "qgsmultipolygon.h"
29#include "qgspoint.h"
30#include "qgspolygon.h"
32#include "qgstriangle.h"
33
34#include <QMatrix4x4>
35#include <QVector3D>
36#include <QtDebug>
37#include <QtMath>
38
39void QgsTessellator::addExtrusionWallQuad( const QVector3D &pt1, const QVector3D &pt2, float height, float u1, float u2 )
40{
41 const float dx = pt2.x() - pt1.x();
42 const float dy = pt2.y() - pt1.y();
43
44 // perpendicular vector in plane to [x,y] is [-y,x]
45 QVector3D vn = QVector3D( -dy, dx, 0 );
46 vn.normalize();
47
48 QVector4D vt;
49 if ( mAddTangents )
50 {
51 // first make tangents following the walls horizontally
52 QVector3D tangentDir( dx, dy, 0 );
53 tangentDir.normalize();
54
55 // if we flipped the direction of U along the wall, then we'll need to adjust the tangent accordingly
56 // so that it's always pointing in the direction of increasing U
57 if ( u2 < u1 )
58 {
59 tangentDir = -tangentDir;
60 }
61
62 vt = QVector4D( tangentDir.x(), tangentDir.y(), tangentDir.z(), 1.0f );
63 }
64
65 // here, we have to flip the z coordinate from an "increasing vertically" axis
66 // to a "decreasing vertically" axis -- otherwise textures are rendered upside down.
67 // we align textures so that the bottom of the texture is aligned to the bottom of
68 // the wall (so eg doors in a facade texture are correctly placed at the bottom
69 // of the wall)
70 const float v0 = -height;
71 const float v1 = -height;
72 const float v2 = 0.0f;
73 const float v3 = 0.0f;
74
75 // triangle 1 vertex 1
76 mIndexBuffer << uniqueVertexCount();
77 mData << pt1.x() << pt1.y() << pt1.z() + height;
78 if ( mAddNormals )
79 mData << vn.x() << vn.y() << vn.z();
80 if ( mAddTangents )
81 mData << vt.x() << vt.y() << vt.z() << vt.w();
82 if ( mAddTextureCoords )
83 mData << u1 << v0;
84
85 // triangle 1 vertex 2
86 mIndexBuffer << uniqueVertexCount();
87 mData << pt2.x() << pt2.y() << pt2.z() + height;
88 if ( mAddNormals )
89 mData << vn.x() << vn.y() << vn.z();
90 if ( mAddTangents )
91 mData << vt.x() << vt.y() << vt.z() << vt.w();
92 if ( mAddTextureCoords )
93 mData << u2 << v1;
94
95 // triangle 1 vertex 3
96 mIndexBuffer << uniqueVertexCount();
97 mData << pt1.x() << pt1.y() << pt1.z();
98 if ( mAddNormals )
99 mData << vn.x() << vn.y() << vn.z();
100 if ( mAddTangents )
101 mData << vt.x() << vt.y() << vt.z() << vt.w();
102 if ( mAddTextureCoords )
103 mData << u1 << v2;
104
105 // triangle 2 vertex 1
106 mIndexBuffer << uniqueVertexCount() - 1;
107
108 // triangle 2 vertex 2
109 mIndexBuffer << uniqueVertexCount() - 2;
110
111 // triangle 2 vertex 3
112 mIndexBuffer << uniqueVertexCount();
113 mData << pt2.x() << pt2.y() << pt2.z();
114 if ( mAddNormals )
115 mData << vn.x() << vn.y() << vn.z();
116 if ( mAddTangents )
117 mData << vt.x() << vt.y() << vt.z() << vt.w();
118 if ( mAddTextureCoords )
119 mData << u2 << v3;
120}
121
123
124QgsTessellator::QgsTessellator( double originX, double originY, bool addNormals, bool invertNormals, bool addBackFaces, bool noZ, bool addTextureCoords, int facade, float )
125{
126 setOrigin( QgsVector3D( originX, originY, 0 ) );
127 setAddNormals( addNormals );
128 setInvertNormals( invertNormals );
129 setExtrusionFacesLegacy( facade );
130 setBackFacesEnabled( addBackFaces );
131 setAddTextureUVs( addTextureCoords );
133}
134
135QgsTessellator::QgsTessellator( const QgsRectangle &bounds, bool addNormals, bool invertNormals, bool addBackFaces, bool noZ, bool addTextureCoords, int facade, float )
136{
137 setAddTextureUVs( addTextureCoords );
138 setExtrusionFacesLegacy( facade );
139 setBounds( bounds );
140 setAddNormals( addNormals );
141 setInvertNormals( invertNormals );
142 setBackFacesEnabled( addBackFaces );
144}
145
147{
148 mOrigin = origin;
149}
150
152{
153 mOrigin = QgsVector3D( bounds.xMinimum(), bounds.yMinimum(), 0 );
154 mScale = bounds.isNull() ? 1.0 : std::max( 10000.0 / bounds.width(), 10000.0 / bounds.height() );
155}
156
158{
159 mInputZValueIgnored = ignore;
160}
161
163{
164 mExtrusionFaces = faces;
165}
166
167void QgsTessellator::setExtrusionFacesLegacy( int facade )
168{
169 switch ( facade )
170 {
171 case 0:
172 mExtrusionFaces = Qgis::ExtrusionFace::NoFace;
173 break;
174 case 1:
175 mExtrusionFaces = Qgis::ExtrusionFace::Walls;
176 break;
177 case 2:
178 mExtrusionFaces = Qgis::ExtrusionFace::Roof;
179 break;
180 case 3:
182 break;
183 case 7:
185 break;
186 default:
187 break;
188 }
189}
190
193
194void QgsTessellator::setBackFacesEnabled( bool addBackFaces )
195{
196 mAddBackFaces = addBackFaces;
197}
198
199void QgsTessellator::setInvertNormals( bool invertNormals )
200{
201 mInvertNormals = invertNormals;
202}
203
204void QgsTessellator::setAddNormals( bool addNormals )
205{
206 mAddNormals = addNormals;
207 updateStride();
208}
209
210void QgsTessellator::setAddTangents( bool addTangents )
211{
212 mAddTangents = addTangents;
213 updateStride();
214}
215
216void QgsTessellator::setAddTextureUVs( bool addTextureUVs )
217{
218 mAddTextureCoords = addTextureUVs;
219 updateStride();
220}
221
226
229
230void QgsTessellator::updateStride()
231{
232 mStride = 3 * sizeof( float );
233 if ( mAddNormals )
234 mStride += 3 * sizeof( float );
235 if ( mAddTangents )
236 mStride += 4 * sizeof( float );
237 if ( mAddTextureCoords )
238 mStride += 2 * sizeof( float );
239}
240
241void QgsTessellator::makeWalls( const QgsLineString &ring, bool ccw, float extrusionHeight )
242{
243 // we need to find out orientation of the ring so that the triangles we generate
244 // face the right direction
245 // (for exterior we want clockwise order, for holes we want counter-clockwise order)
247
248 QgsPoint pt;
249 QgsPoint ptPrev = ring.pointN( isCounterClockwise == ccw ? 0 : ring.numPoints() - 1 );
250
251 // accumulate texture U as we travel around the ring, so that texture seamless wraps
252 // around the walls
253 float accumulatedU = 0.0f;
254 for ( int i = 1; i < ring.numPoints(); ++i )
255 {
256 pt = ring.pointN( isCounterClockwise == ccw ? i : ring.numPoints() - i - 1 );
257
258 const QVector3D pt1( static_cast<float>( ptPrev.x() - mOrigin.x() ), static_cast<float>( ptPrev.y() - mOrigin.y() ), static_cast<float>( std::isnan( ptPrev.z() ) ? 0 : ptPrev.z() - mOrigin.z() ) );
259
260 const QVector3D pt2( static_cast<float>( pt.x() - mOrigin.x() ), static_cast<float>( pt.y() - mOrigin.y() ), static_cast<float>( std::isnan( pt.z() ) ? 0 : pt.z() - mOrigin.z() ) );
261
262 const float segmentLength = pt1.distanceToPoint( pt2 );
263
264 // make a quad
265 addExtrusionWallQuad( pt1, pt2, extrusionHeight, -accumulatedU, -( accumulatedU + segmentLength ) );
266
267 if ( mAddBackFaces )
268 {
269 // texture start/end u are reversed so that texture isn't flipped on the backface
270 addExtrusionWallQuad( pt2, pt1, extrusionHeight, accumulatedU + segmentLength, accumulatedU );
271 }
272
273 accumulatedU += segmentLength;
274 ptPrev = pt;
275 }
276}
277
278static QVector3D calculateNormal( const QgsLineString *curve, double originX, double originY, double originZ, bool invertNormal, float extrusionHeight )
279{
280 if ( !QgsWkbTypes::hasZ( curve->wkbType() ) )
281 {
282 // In case of extrusions, flat polygons always face up
283 if ( extrusionHeight != 0 )
284 return QVector3D( 0, 0, 1 );
285
286 // For non-extrusions, decide based on polygon winding order and invertNormal flag
287 float orientation = 1.f;
289 orientation = -orientation;
290 if ( invertNormal )
291 orientation = -orientation;
292 return QVector3D( 0, 0, orientation );
293 }
294
295 // often we have 3D coordinates, but Z is the same for all vertices
296 // if these flat polygons are extruded, we consider them up-facing regardless of winding order
297 bool sameZ = true;
298 QgsPoint pt1 = curve->pointN( 0 );
299 QgsPoint pt2;
300 for ( int i = 1; i < curve->numPoints(); i++ )
301 {
302 pt2 = curve->pointN( i );
303 if ( pt1.z() != pt2.z() )
304 {
305 sameZ = false;
306 break;
307 }
308 }
309 if ( sameZ && extrusionHeight != 0 )
310 return QVector3D( 0, 0, 1 );
311
312 // Calculate the polygon's normal vector, based on Newell's method
313 // https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal
314 //
315 // Order of vertices is important here as it determines the front/back face of the polygon
316
317 double nx = 0, ny = 0, nz = 0;
318
319 // shift points by the tessellator's origin - this does not affect normal calculation and it may save us from losing some precision
320 pt1.setX( pt1.x() - originX );
321 pt1.setY( pt1.y() - originY );
322 pt1.setZ( std::isnan( pt1.z() ) ? 0.0 : pt1.z() - originZ );
323 for ( int i = 1; i < curve->numPoints(); i++ )
324 {
325 pt2 = curve->pointN( i );
326 pt2.setX( pt2.x() - originX );
327 pt2.setY( pt2.y() - originY );
328 pt2.setZ( std::isnan( pt2.z() ) ? 0.0 : pt2.z() - originZ );
329
330 nx += ( pt1.y() - pt2.y() ) * ( pt1.z() + pt2.z() );
331 ny += ( pt1.z() - pt2.z() ) * ( pt1.x() + pt2.x() );
332 nz += ( pt1.x() - pt2.x() ) * ( pt1.y() + pt2.y() );
333
334 pt1 = pt2;
335 }
336
337 QVector3D normal( nx, ny, nz );
338 if ( invertNormal )
339 normal = -normal;
340 normal.normalize();
341 return normal;
342}
343
344
345static void normalVectorToXYVectors( const QVector3D &pNormal, QVector3D &pXVector, QVector3D &pYVector )
346{
347 // Here we define the two perpendicular vectors that define the local
348 // 2D space on the plane. They will act as axis for which we will
349 // calculate the projection coordinates of a 3D point to the plane.
350 if ( pNormal.z() > 0.001 || pNormal.z() < -0.001 )
351 {
352 pXVector = QVector3D( 1, 0, -pNormal.x() / pNormal.z() );
353 }
354 else if ( pNormal.y() > 0.001 || pNormal.y() < -0.001 )
355 {
356 pXVector = QVector3D( 1, -pNormal.x() / pNormal.y(), 0 );
357 }
358 else
359 {
360 pXVector = QVector3D( -pNormal.y() / pNormal.x(), 1, 0 );
361 }
362 pXVector.normalize();
363 pYVector = QVector3D::normal( pNormal, pXVector );
364}
365
367{
368 std::size_t operator()( const std::pair<float, float> pair ) const
369 {
370 const std::size_t h1 = std::hash<float>()( pair.first );
371 const std::size_t h2 = std::hash<float>()( pair.second );
372
373 return h1 ^ h2;
374 }
375};
376
377void ringToPoly2tri( const QgsLineString *ring, std::vector<p2t::Point *> &polyline, QHash<p2t::Point *, float> *zHash )
378{
379 const int pCount = ring->numPoints();
380
381 polyline.reserve( pCount );
382
383 const double *srcXData = ring->xData();
384 const double *srcYData = ring->yData();
385 const double *srcZData = ring->zData();
386 std::unordered_set<std::pair<float, float>, float_pair_hash> foundPoints;
387
388 for ( int i = 0; i < pCount - 1; ++i )
389 {
390 const float x = *srcXData++;
391 const float y = *srcYData++;
392
393 const auto res = foundPoints.insert( std::make_pair( x, y ) );
394 if ( !res.second )
395 {
396 // already used this point, don't add a second time
397 continue;
398 }
399
400 p2t::Point *pt2 = new p2t::Point( x, y );
401 polyline.push_back( pt2 );
402 if ( zHash )
403 {
404 ( *zHash )[pt2] = *srcZData++;
405 }
406 }
407}
408
409
410double roundCoord( double x )
411{
412 const double exp = 1e10; // round to 10 decimal digits
413 return round( x * exp ) / exp;
414}
415
416
417static QgsCurve *transformRingToNewBase( const QgsLineString &curve, const QgsPoint &pt0, const QMatrix4x4 *toNewBase, const float scale )
418{
419 const int count = curve.numPoints();
420 QVector<double> x;
421 QVector<double> y;
422 QVector<double> z;
423 x.resize( count );
424 y.resize( count );
425 z.resize( count );
426 double *xData = x.data();
427 double *yData = y.data();
428 double *zData = z.data();
429
430 const double *srcXData = curve.xData();
431 const double *srcYData = curve.yData();
432 const double *srcZData = curve.is3D() ? curve.zData() : nullptr;
433
434 for ( int i = 0; i < count; ++i )
435 {
436 QVector4D v( *srcXData++ - pt0.x(), *srcYData++ - pt0.y(), srcZData ? *srcZData++ - pt0.z() : 0, 0 );
437 if ( toNewBase )
438 v = toNewBase->map( v );
439
440 // scale coordinates
441 v.setX( v.x() * scale );
442 v.setY( v.y() * scale );
443
444 // we also round coordinates before passing them to poly2tri triangulation in order to fix possible numerical
445 // stability issues. We had crashes with nearly collinear points where one of the points was off by a tiny bit (e.g. by 1e-20).
446 // See TestQgsTessellator::testIssue17745().
447 //
448 // A hint for a similar issue: https://github.com/greenm01/poly2tri/issues/99
449 //
450 // The collinear tests uses epsilon 1e-12. Seems rounding to 12 places you still
451 // can get problems with this test when points are pretty much on a straight line.
452 // I suggest you round to 10 decimals for stability and you can live with that
453 // precision.
454 *xData++ = roundCoord( v.x() );
455 *yData++ = roundCoord( v.y() );
456 *zData++ = roundCoord( v.z() );
457 }
458 return new QgsLineString( x, y, z );
459}
460
461
462QgsPolygon *transformPolygonToNewBase( const QgsPolygon &polygon, const QgsPoint &pt0, const QMatrix4x4 *toNewBase, const float scale )
463{
464 QgsPolygon *p = new QgsPolygon;
465 p->setExteriorRing( transformRingToNewBase( *qgsgeometry_cast< const QgsLineString * >( polygon.exteriorRing() ), pt0, toNewBase, scale ) );
466 for ( int i = 0; i < polygon.numInteriorRings(); ++i )
467 p->addInteriorRing( transformRingToNewBase( *qgsgeometry_cast< const QgsLineString * >( polygon.interiorRing( i ) ), pt0, toNewBase, scale ) );
468 return p;
469}
470
471
473{
474 double min_d = 1e20;
475
476 std::vector< const QgsLineString * > rings;
477 rings.reserve( 1 + polygon.numInteriorRings() );
478 rings.emplace_back( qgsgeometry_cast< const QgsLineString * >( polygon.exteriorRing() ) );
479 for ( int i = 0; i < polygon.numInteriorRings(); ++i )
480 rings.emplace_back( qgsgeometry_cast< const QgsLineString * >( polygon.interiorRing( i ) ) );
481
482 for ( const QgsLineString *ring : rings )
483 {
484 const int numPoints = ring->numPoints();
485 if ( numPoints <= 1 )
486 continue;
487
488 const double *srcXData = ring->xData();
489 const double *srcYData = ring->yData();
490 double x0 = *srcXData++;
491 double y0 = *srcYData++;
492 for ( int i = 1; i < numPoints; ++i )
493 {
494 const double x1 = *srcXData++;
495 const double y1 = *srcYData++;
496 const double d = QgsGeometryUtilsBase::sqrDistance2D( x0, y0, x1, y1 );
497 if ( d < min_d )
498 min_d = d;
499 x0 = x1;
500 y0 = y1;
501 }
502 }
503
504 return min_d != 1e20 ? std::sqrt( min_d ) : 1e20;
505}
506
508{
509 return QByteArray( reinterpret_cast<const char *>( mData.constData() ), sizeof( float ) * mData.size() );
510}
511
513{
514 return QByteArray( reinterpret_cast<const char *>( mIndexBuffer.constData() ), sizeof( uint32_t ) * mIndexBuffer.size() );
515}
516
517void QgsTessellator::calculateBaseTransform( const QVector3D &pNormal, QMatrix4x4 *base ) const
518{
519 if ( !mInputZValueIgnored && pNormal != QVector3D( 0, 0, 1 ) )
520 {
521 // this is not a horizontal plane - need to reproject to a new base so that
522 // we can do the triangulation in a plane
523 QVector3D pXVector, pYVector;
524 normalVectorToXYVectors( pNormal, pXVector, pYVector );
525
526 // so now we have three orthogonal unit vectors defining new base
527 // let's build transform matrix. We actually need just a 3x3 matrix,
528 // but Qt does not have good support for it, so using 4x4 matrix instead.
529 *base = QMatrix4x4( pXVector.x(), pXVector.y(), pXVector.z(), 0, pYVector.x(), pYVector.y(), pYVector.z(), 0, pNormal.x(), pNormal.y(), pNormal.z(), 0, 0, 0, 0, 0 );
530 }
531 else
532 {
533 base->setToIdentity();
534 }
535}
536
537QVector3D QgsTessellator::applyTransformWithExtrusion( const QVector3D point, float extrusionHeight, QMatrix4x4 *transformMatrix, const QgsPoint *originOffset )
538{
539 const float z = mInputZValueIgnored ? 0.0f : point.z();
540 QVector4D pt( point.x(), point.y(), z, 0 );
541
542 pt = *transformMatrix * pt;
543
544 const double fx = pt.x() - mOrigin.x() + originOffset->x();
545 const double fy = pt.y() - mOrigin.y() + originOffset->y();
546 const double baseHeight = mInputZValueIgnored ? 0 : pt.z() - mOrigin.z() + originOffset->z();
547 const double fz = mInputZValueIgnored ? 0.0 : ( baseHeight + extrusionHeight );
548
549 if ( baseHeight < mZMin )
550 mZMin = static_cast<float>( baseHeight );
551 if ( baseHeight > mZMax )
552 mZMax = static_cast<float>( baseHeight );
553 if ( fz > mZMax )
554 mZMax = static_cast<float>( fz );
555
556 return QVector3D( static_cast<float>( fx ), static_cast<float>( fy ), static_cast<float>( fz ) );
557}
558
559
560void ringToEarcutPoints( const QgsLineString *ring, std::vector<std::array<double, 2>> &polyline, std::vector<double> *zValues )
561{
562 const int pCount = ring->numPoints();
563
564 polyline.reserve( pCount );
565
566 const double *srcXData = ring->xData();
567 const double *srcYData = ring->yData();
568 const double *srcZData = ring->zData();
569
570 // earcut handles duplicates, we do not need to remove them here
571 for ( int i = 0; i < pCount - 1; ++i )
572 {
573 const double x = *srcXData++;
574 const double y = *srcYData++;
575
576 std::array<double, 2> pt = { x, y };
577 polyline.push_back( pt );
578 }
579
580 if ( zValues && srcZData )
581 {
582 zValues->insert( zValues->end(), srcZData, srcZData + pCount - 1 );
583 }
584}
585
586std::vector<QVector3D> QgsTessellator::generateConstrainedDelaunayTriangles( const QgsPolygon *polygonNew )
587{
588 QList<std::vector<p2t::Point *>> polylinesToDelete;
589 QHash<p2t::Point *, float> z;
590
591 // polygon exterior
592 std::vector<p2t::Point *> polyline;
593 ringToPoly2tri( qgsgeometry_cast< const QgsLineString * >( polygonNew->exteriorRing() ), polyline, mInputZValueIgnored ? nullptr : &z );
594 polylinesToDelete << polyline;
595
596 p2t::CDT cdt = p2t::CDT( polyline );
597
598 // polygon holes
599 for ( int i = 0; i < polygonNew->numInteriorRings(); ++i )
600 {
601 std::vector<p2t::Point *> holePolyline;
602 const QgsLineString *hole = qgsgeometry_cast< const QgsLineString *>( polygonNew->interiorRing( i ) );
603
604 ringToPoly2tri( hole, holePolyline, mInputZValueIgnored ? nullptr : &z );
605
606 cdt.AddHole( holePolyline );
607 polylinesToDelete << holePolyline;
608 }
609
610 cdt.Triangulate();
611 std::vector<p2t::Triangle *> triangles = cdt.GetTriangles();
612
613 std::vector<QVector3D> trianglePoints;
614 trianglePoints.reserve( triangles.size() * 3 );
615
616 for ( p2t::Triangle *t : triangles )
617 {
618 trianglePoints.emplace_back( t->GetPoint( 0 )->x / mScale, t->GetPoint( 0 )->y / mScale, z.value( t->GetPoint( 0 ) ) );
619 trianglePoints.emplace_back( t->GetPoint( 1 )->x / mScale, t->GetPoint( 1 )->y / mScale, z.value( t->GetPoint( 1 ) ) );
620 trianglePoints.emplace_back( t->GetPoint( 2 )->x / mScale, t->GetPoint( 2 )->y / mScale, z.value( t->GetPoint( 2 ) ) );
621 }
622
623 for ( int i = 0; i < polylinesToDelete.count(); ++i )
624 qDeleteAll( polylinesToDelete[i] );
625
626 return trianglePoints;
627}
628
629std::vector<QVector3D> QgsTessellator::generateEarcutTriangles( const QgsPolygon *polygonNew )
630{
631 const bool useZValues = !mInputZValueIgnored && polygonNew->is3D();
632 const int allVerticesCount = polygonNew->nCoordinates();
633 std::vector<double> zValues;
634
635 if ( useZValues )
636 zValues.reserve( allVerticesCount );
637
638 std::vector<std::vector<std::array<double, 2>>> rings;
639 rings.reserve( polygonNew->numInteriorRings() + 1 );
640
641 {
642 std::vector<std::array<double, 2>> polyline;
643 ringToEarcutPoints( qgsgeometry_cast< const QgsLineString * >( polygonNew->exteriorRing() ), polyline, useZValues ? &zValues : nullptr );
644 rings.push_back( std::move( polyline ) );
645 }
646
647 for ( int i = 0; i < polygonNew->numInteriorRings(); ++i )
648 {
649 std::vector<std::array<double, 2>> holePolyline;
650 ringToEarcutPoints( qgsgeometry_cast<const QgsLineString *>( polygonNew->interiorRing( i ) ), holePolyline, useZValues ? &zValues : nullptr );
651 rings.push_back( std::move( holePolyline ) );
652 }
653
654 std::vector<std::array<double, 2>> points;
655 points.reserve( allVerticesCount );
656
657 for ( const auto &ring : rings )
658 {
659 points.insert( points.end(), ring.begin(), ring.end() );
660 }
661
662 std::vector<uint32_t> indices = mapbox::earcut<uint32_t>( rings );
663 std::vector<QVector3D> trianglePoints;
664 trianglePoints.reserve( indices.size() );
665
666 for ( size_t i = 0; i < indices.size(); i++ )
667 {
668 uint32_t vertexIndex = indices[i];
669
670 const float x = static_cast<float>( points[vertexIndex][0] );
671 const float y = static_cast<float>( points[vertexIndex][1] );
672 const float z = static_cast<float>( useZValues ? zValues[vertexIndex] : 0.0 );
673
674 trianglePoints.emplace_back( x / mScale, y / mScale, z );
675 }
676
677 return trianglePoints;
678}
679
680void QgsTessellator::addVertex(
681 const QVector3D &point,
682 const QVector3D &normal,
683 const QVector4D &tangent,
684 float extrusionHeight,
685 QMatrix4x4 *transformMatrix,
686 const QgsPoint *originOffset,
687 QHash<VertexPoint, unsigned int> *vertexBuffer,
688 const size_t &vertexBufferOffset,
689 bool isFloor
690)
691{
692 const QVector3D pt = applyTransformWithExtrusion( point, extrusionHeight, transformMatrix, originOffset );
693 const VertexPoint vertex( pt, normal, tangent );
694 if ( vertexBuffer->contains( vertex ) )
695 {
696 unsigned int index = vertexBuffer->value( vertex );
697 mIndexBuffer << vertexBufferOffset + index;
698 }
699 else
700 {
701 unsigned int index = vertexBuffer->size();
702 vertexBuffer->insert( vertex, index );
703 mIndexBuffer << vertexBufferOffset + index;
704
705 mData << pt.x() << pt.y() << pt.z();
706 if ( mAddNormals )
707 {
708 mData << normal.x() << normal.y() << normal.z();
709 }
710 if ( mAddTangents )
711 {
712 mData << tangent.x() << tangent.y() << tangent.z() << tangent.w();
713 }
714 if ( mAddTextureCoords )
715 {
716 // flip y coordinate -- source texture images will have increasing y from top-to-bottom,
717 // but 3d textures need to increase from bottom-to-top
718 float u = pt.x();
719 float v = -pt.y();
720
721 if ( isFloor )
722 {
723 u = -u;
724 }
725
726 mData << u << v;
727 }
728 }
729}
730
731void QgsTessellator::addVertex( const QVector3D &point, const QVector3D &normal, const QVector4D &tangent, float extrusionHeight, QMatrix4x4 *transformMatrix, const QgsPoint *originOffset, bool isFloor )
732{
733 const QVector3D pt = applyTransformWithExtrusion( point, extrusionHeight, transformMatrix, originOffset );
734 mIndexBuffer << uniqueVertexCount();
735 mData << pt.x() << pt.y() << pt.z();
736 if ( mAddNormals )
737 {
738 mData << normal.x() << normal.y() << normal.z();
739 }
740 if ( mAddTangents )
741 {
742 mData << tangent.x() << tangent.y() << tangent.z() << tangent.w();
743 }
744 if ( mAddTextureCoords )
745 {
746 // flip y coordinate -- source texture images will have increasing y from top-to-bottom,
747 // but 3d textures need to increase from bottom-to-top
748 float u = pt.x();
749 float v = -pt.y();
750
751 if ( isFloor )
752 {
753 u = -u;
754 }
755
756 mData << u << v;
757 }
758}
759
760void QgsTessellator::addPolygon( const QgsPolygon &polygon, float extrusionHeight )
761{
763 if ( !exterior )
764 return;
765
766 const QVector3D pNormal = !mInputZValueIgnored ? calculateNormal( exterior, mOrigin.x(), mOrigin.y(), mOrigin.z(), mInvertNormals, extrusionHeight ) : QVector3D();
767 // calculate the tangent for the flat polygon (roof and floor)
768 const QVector4D frontTangent( 1.0f, 0.0f, 0.0f, 1.0f );
769 const QVector4D floorFrontTangent( -1.0f, 0.0f, 0.0f, 1.0f );
770 // back face tangent
771 const QVector4D backTangent( frontTangent.x(), frontTangent.y(), frontTangent.z(), -1.0f );
772 const QVector4D floorBackTangent( floorFrontTangent.x(), floorFrontTangent.y(), floorFrontTangent.z(), -1.0f );
773
774 const int pCount = exterior->numPoints();
775 if ( pCount == 0 )
776 return;
777
778 QMatrix4x4 base; // identity matrix by default
779 const QgsPoint ptStart( exterior->startPoint() );
780 const QgsPoint extrusionOrigin( Qgis::WkbType::PointZ, ptStart.x(), ptStart.y(), std::isnan( ptStart.z() ) ? 0 : ptStart.z() );
781 std::unique_ptr<QgsPolygon> polygonNew;
782
783 if ( !mInputZValueIgnored && !qgsDoubleNear( pNormal.length(), 1, 0.001 ) )
784 return; // this should not happen - pNormal should be normalized to unit length
785
786 bool buildWalls = false;
787 bool buildFloor = false;
788 bool buildRoof = false;
789 if ( qgsDoubleNear( extrusionHeight, 0 ) )
790 {
791 // no extrusion -- if either floor or roof are enabled, we just build the roof. These two surfaces would otherwise
792 // be identical
793 buildRoof = mExtrusionFaces.testFlag( Qgis::ExtrusionFace::Floor ) || mExtrusionFaces.testFlag( Qgis::ExtrusionFace::Roof );
794 }
795 else
796 {
797 // extrusion
798 buildWalls = mExtrusionFaces.testFlag( Qgis::ExtrusionFace::Walls );
799 buildFloor = mExtrusionFaces.testFlag( Qgis::ExtrusionFace::Floor );
800 buildRoof = mExtrusionFaces.testFlag( Qgis::ExtrusionFace::Roof );
801 }
802
803 if ( buildFloor || buildRoof )
804 {
805 calculateBaseTransform( pNormal, &base );
806 polygonNew.reset( transformPolygonToNewBase( polygon, extrusionOrigin, &base, mScale ) );
807
808 QVector3D normal = pNormal;
809 // our 3x3 matrix is orthogonal, so for inverse we only need to transpose it
810 base = base.transposed();
811
812 if ( pCount == 4 && polygon.numInteriorRings() == 0 )
813 {
814 Q_ASSERT( polygonNew->exteriorRing()->numPoints() >= 3 );
815
816 const QgsLineString *triangle = qgsgeometry_cast< const QgsLineString * >( polygonNew->exteriorRing() );
817 const QVector3D p1( static_cast<float>( triangle->xAt( 0 ) ), static_cast<float>( triangle->yAt( 0 ) ), static_cast<float>( triangle->zAt( 0 ) ) );
818 const QVector3D p2( static_cast<float>( triangle->xAt( 1 ) ), static_cast<float>( triangle->yAt( 1 ) ), static_cast<float>( triangle->zAt( 1 ) ) );
819 const QVector3D p3( static_cast<float>( triangle->xAt( 2 ) ), static_cast<float>( triangle->yAt( 2 ) ), static_cast<float>( triangle->zAt( 2 ) ) );
820 std::array<QVector3D, 3> points = { p1, p2, p3 };
821
822 if ( buildRoof )
823 {
824 for ( const QVector3D &point : points )
825 {
826 addVertex( point, normal, frontTangent, extrusionHeight, &base, &extrusionOrigin );
827 }
828
829 if ( mAddBackFaces )
830 {
831 for ( size_t i = points.size(); i-- > 0; )
832 {
833 const QVector3D &point = points[i];
834 addVertex( point, -normal, backTangent, extrusionHeight, &base, &extrusionOrigin );
835 }
836 }
837 }
838
839 if ( buildFloor )
840 {
841 for ( const QVector3D &point : points )
842 {
843 addVertex( point, normal, floorFrontTangent, 0.0, &base, &extrusionOrigin, true );
844 }
845
846 if ( mAddBackFaces )
847 {
848 for ( size_t i = points.size(); i-- > 0; )
849 {
850 const QVector3D &point = points[i];
851 addVertex( point, -normal, floorBackTangent, 0.0, &base, &extrusionOrigin, true );
852 }
853 }
854 }
855 }
856 else // we need to triangulate the polygon
857 {
858 if ( minimumDistanceBetweenCoordinates( *polygonNew ) < 0.001 )
859 {
860 // when the distances between coordinates of input points are very small,
861 // the triangulation likes to crash on numerical errors - when the distances are ~ 1e-5
862 // Assuming that the coordinates should be in a projected CRS, we should be able
863 // to simplify geometries that may cause problems and avoid possible crashes
864 const QgsGeometry polygonSimplified = QgsGeometry( polygonNew->clone() ).simplify( 0.001 );
865 if ( polygonSimplified.isNull() )
866 {
867 mError = QObject::tr( "geometry simplification failed - skipping" );
868 return;
869 }
870 const QgsPolygon *polygonSimplifiedData = qgsgeometry_cast<const QgsPolygon *>( polygonSimplified.constGet() );
871 if ( !polygonSimplifiedData || minimumDistanceBetweenCoordinates( *polygonSimplifiedData ) < 0.001 )
872 {
873 // Failed to fix that. It could be a really tiny geometry... or maybe they gave us
874 // geometry in unprojected lat/lon coordinates
875 mError = QObject::tr( "geometry's coordinates are too close to each other and simplification failed - skipping" );
876 return;
877 }
878 else
879 {
880 polygonNew.reset( polygonSimplifiedData->clone() );
881 }
882 }
883
884 // run triangulation and write vertices to the output data array
885 try
886 {
887 std::vector<QVector3D> trianglePoints;
888 switch ( mTriangulationAlgorithm )
889 {
891 trianglePoints = generateConstrainedDelaunayTriangles( polygonNew.get() );
892 break;
894 trianglePoints = generateEarcutTriangles( polygonNew.get() );
895 break;
896 }
897
898 if ( trianglePoints.empty() )
899 {
900 mError = QObject::tr( "Failed to triangulate polygon." );
901 return;
902 }
903
904 Q_ASSERT( trianglePoints.size() % 3 == 0 );
905
906 mData.reserve( mData.size() + trianglePoints.size() * 3 * ( stride() / sizeof( float ) ) );
907
908 const size_t vertexBufferSize = uniqueVertexCount();
909 QHash<VertexPoint, unsigned int> vertexBuffer;
910 for ( size_t i = 0; i < trianglePoints.size(); i += 3 )
911 {
912 const std::array<QVector3D, 3> points = { trianglePoints[i + 0], trianglePoints[i + 1], trianglePoints[i + 2] };
913
914 // roof
915 if ( buildRoof )
916 {
917 for ( const QVector3D &point : points )
918 {
919 addVertex( point, normal, frontTangent, extrusionHeight, &base, &extrusionOrigin, &vertexBuffer, vertexBufferSize );
920 }
921
922 if ( mAddBackFaces )
923 {
924 for ( size_t i = points.size(); i-- > 0; )
925 {
926 const QVector3D &point = points[i];
927 addVertex( point, -normal, backTangent, extrusionHeight, &base, &extrusionOrigin, &vertexBuffer, vertexBufferSize );
928 }
929 }
930 }
931
932 if ( buildFloor )
933 {
934 for ( const QVector3D &point : points )
935 {
936 addVertex( point, normal, floorFrontTangent, 0.0, &base, &extrusionOrigin, &vertexBuffer, vertexBufferSize, true );
937 }
938
939 if ( mAddBackFaces )
940 {
941 for ( size_t i = points.size(); i-- > 0; )
942 {
943 const QVector3D &point = points[i];
944 addVertex( point, -normal, floorBackTangent, 0.0, &base, &extrusionOrigin, &vertexBuffer, vertexBufferSize, true );
945 }
946 }
947 }
948 }
949 }
950 catch ( std::runtime_error &err )
951 {
952 mError = err.what();
953 }
954 catch ( ... )
955 {
956 mError = QObject::tr( "An unknown error occurred" );
957 }
958 }
959 }
960
961 // add walls if extrusion is enabled
962 if ( buildWalls )
963 {
964 makeWalls( *exterior, false, extrusionHeight );
965 for ( int i = 0; i < polygon.numInteriorRings(); ++i )
966 makeWalls( *qgsgeometry_cast< const QgsLineString * >( polygon.interiorRing( i ) ), true, extrusionHeight );
967 }
968}
969
970void QgsTessellator::addGeometry( const QgsAbstractGeometry &geometry, float extrusionHeight )
971{
972 if ( const QgsPolygon *polygon = qgsgeometry_cast<const QgsPolygon *>( &geometry ) )
973 {
974 addPolygon( *polygon, extrusionHeight );
975 }
976 else if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast<const QgsCurvePolygon *>( &geometry ) )
977 {
978 std::unique_ptr<QgsPolygon> segmentized( qgsgeometry_cast<QgsPolygon *>( curvePolygon->segmentize() ) );
979 if ( segmentized )
980 {
981 addPolygon( *segmentized, extrusionHeight );
982 }
983 }
984 else if ( const QgsPolyhedralSurface *surface = qgsgeometry_cast<const QgsPolyhedralSurface *>( &geometry ) )
985 {
986 for ( int i = 0; i < surface->numPatches(); ++i )
987 {
988 addPolygon( *surface->patchN( i ), extrusionHeight );
989 }
990 }
991 else if ( const QgsGeometryCollection *collection = qgsgeometry_cast<const QgsGeometryCollection *>( &geometry ) )
992 {
993 for ( int i = 0; i < collection->numGeometries(); ++i )
994 {
995 addGeometry( *collection->geometryN( i ), extrusionHeight );
996 }
997 }
998 else
999 {
1000 mError = QObject::tr( "Unsupported geometry type %1" ).arg( QgsWkbTypes::displayString( geometry.wkbType() ) );
1001 }
1002}
1003
1005{
1006 return mIndexBuffer.size();
1007}
1008
1009std::unique_ptr<QgsMultiPolygon> QgsTessellator::asMultiPolygon() const
1010{
1011 auto mp = std::make_unique< QgsMultiPolygon >();
1012 const size_t nVals = mIndexBuffer.size();
1013
1014 Q_ASSERT( nVals % 3 == 0 );
1015
1016 mp->reserve( nVals / 3 );
1017 const size_t noOfElements = stride() / sizeof( float );
1018
1019 for ( size_t i = 0; i + 2 < nVals; i += 3 )
1020 {
1021 const uint32_t index1 = mIndexBuffer[i] * noOfElements;
1022 const uint32_t index2 = mIndexBuffer[i + 1] * noOfElements;
1023 const uint32_t index3 = mIndexBuffer[i + 2] * noOfElements;
1024
1025 const QgsPoint p1( mData[index1], mData[index1 + 1], mData[index1 + 2] );
1026 const QgsPoint p2( mData[index2], mData[index2 + 1], mData[index2 + 2] );
1027 const QgsPoint p3( mData[index3], mData[index3 + 1], mData[index3 + 2] );
1028 mp->addGeometry( new QgsTriangle( p1, p2, p3 ) );
1029 }
1030
1031 return mp;
1032}
1033
1034QVector<float> QgsTessellator::data() const
1035{
1036 const size_t n = mIndexBuffer.size();
1037 if ( n == 0 )
1038 return QVector<float>();
1039
1040 QVector<float> tData;
1041 size_t noOfElements = stride() / sizeof( float );
1042 tData.reserve( n * noOfElements );
1043
1044 for ( auto &index : mIndexBuffer )
1045 {
1046 for ( size_t i = 0; i < noOfElements; i++ )
1047 {
1048 tData << mData[index * noOfElements + i];
1049 }
1050 }
1051
1052 return tData;
1053}
1054
1056{
1057 if ( mData.size() == 0 )
1058 return 0;
1059
1060 return mData.size() / ( stride() / sizeof( float ) );
1061}
@ CounterClockwise
Counter-clockwise direction.
Definition qgis.h:3699
@ Clockwise
Clockwise direction.
Definition qgis.h:3698
TriangulationAlgorithm
Triangulation algorithms.
Definition qgis.h:7101
QFlags< ExtrusionFace > ExtrusionFaces
Tessellator extrusion face types.
Definition qgis.h:7093
@ PointZ
PointZ.
Definition qgis.h:333
Abstract base class for all geometries.
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
Curve polygon geometry type.
int numInteriorRings() const
Returns the number of interior rings contained with the curve polygon.
const QgsCurve * exteriorRing() const
Returns the curve polygon's exterior ring.
const QgsCurve * interiorRing(int i) const
Retrieves an interior ring from the curve polygon.
int nCoordinates() const override
Returns the number of nodes contained in the geometry.
Abstract base class for curved geometry type.
Definition qgscurve.h:36
Qgis::AngularDirection orientation() const
Returns the curve's orientation, e.g.
Definition qgscurve.cpp:291
static double sqrDistance2D(double x1, double y1, double x2, double y2)
Returns the squared 2D distance between (x1, y1) and (x2, y2).
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometry simplify(double tolerance, QgsFeedback *feedback=nullptr) const
Returns a simplified version of this geometry using a specified tolerance value.
Line string geometry type, with support for z-dimension and m-values.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
void setY(double y)
Sets the point's y-coordinate.
Definition qgspoint.h:387
void setX(double x)
Sets the point's x-coordinate.
Definition qgspoint.h:376
double z
Definition qgspoint.h:58
double x
Definition qgspoint.h:56
void setZ(double z)
Sets the point's z-coordinate.
Definition qgspoint.h:400
double y
Definition qgspoint.h:57
Polygon geometry type.
Definition qgspolygon.h:37
void setExteriorRing(QgsCurve *ring) override
Sets the exterior ring of the polygon.
void addInteriorRing(QgsCurve *ring) override
Adds an interior ring to the geometry (takes ownership).
QgsPolygon * clone() const override
Clones the geometry by performing a deep copy.
Polyhedral surface geometry type.
A rectangle specified with double values.
double xMinimum
double yMinimum
double yAt(int index) const override
Returns the y-coordinate of the specified node in the line string.
int numPoints() const override
Returns the number of points in the curve.
double xAt(int index) const override
Returns the x-coordinate of the specified node in the line string.
const double * yData() const
Returns a const pointer to the y vertex data.
double zAt(int index) const override
Returns the z-coordinate of the specified node in the simple curve.
QgsPoint startPoint() const override
Returns the starting point of the curve.
QgsPoint pointN(int i) const
Returns the specified point from inside the simple curve.
const double * xData() const
Returns a const pointer to the x vertex data.
const double * zData() const
Returns a const pointer to the z vertex data, or nullptr if the simple curve does not have z values.
std::unique_ptr< QgsMultiPolygon > asMultiPolygon() const
Returns the triangulation as a multipolygon geometry.
Q_DECL_DEPRECATED void setTextureRotation(float rotation)
Sets the rotation of texture UV coordinates (in degrees).
void addGeometry(const QgsAbstractGeometry &geometry, float extrusionHeight=0)
Tessellates a surface geometry and adds its vertex entries to the output data array.
void setOrigin(const QgsVector3D &origin)
Sets the origin point of the map.
void setTriangulationAlgorithm(Qgis::TriangulationAlgorithm algorithm)
Sets the triangulation algorithm.
Q_DECL_DEPRECATED QVector< float > data() const
Returns array of triangle vertex data.
QByteArray vertexBuffer() const
Returns vertex buffer for the generated points.
int stride() const
Returns size of one vertex entry in bytes.
void setBounds(const QgsRectangle &bounds)
Sets scaling and the bounds of the input geometry coordinates.
void addPolygon(const QgsPolygon &polygon, float extrusionHeight)
Tessellates a triangle and adds its vertex entries to the output data array.
QgsVector3D origin() const
Returns the origin point of the map.
int uniqueVertexCount() const
Returns unique vertex count.
QByteArray indexBuffer() const
Returns index buffer for the generated points.
void setInvertNormals(bool invertNormals)
Sets whether normals should be inverted.
void setBackFacesEnabled(bool addBackFaces)
Sets whether back faces should be added to the output data.
Q_DECL_DEPRECATED void setOutputZUp(bool zUp)
Sets whether the "up" direction should be the Z axis on output (true), otherwise the "up" direction w...
void setAddTangents(bool addTangents)
Sets whether tangents should be added to the output data.
int dataVerticesCount() const
Returns the number of vertices stored in the output data array.
void setExtrusionFaces(Qgis::ExtrusionFaces faces)
Sets which faces should be generated during extrusion.
void setInputZValueIgnored(bool ignore)
Sets whether Z values from the input geometries are ignored (true) or not (false).
void setAddTextureUVs(bool addTextureUVs)
Sets whether texture UV coordinates should be added to the output data.
void setAddNormals(bool addNormals)
Sets whether normals should be added to the output data.
Triangle geometry type.
Definition qgstriangle.h:33
A 3D vector (similar to QVector3D) with the difference that it uses double precision instead of singl...
Definition qgsvector3d.h:33
static Q_INVOKABLE QString displayString(Qgis::WkbType type)
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
static Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7826
T qgsgeometry_cast(QgsAbstractGeometry *geom)
bool isCounterClockwise(std::array< Direction, 4 > dirs)
Checks whether the 4 directions in dirs make up a counter-clockwise rectangle.
double minimumDistanceBetweenCoordinates(const QgsPolygon &polygon)
void ringToEarcutPoints(const QgsLineString *ring, std::vector< std::array< double, 2 > > &polyline, std::vector< double > *zValues)
void ringToPoly2tri(const QgsLineString *ring, std::vector< p2t::Point * > &polyline, QHash< p2t::Point *, float > *zHash)
QgsPolygon * transformPolygonToNewBase(const QgsPolygon &polygon, const QgsPoint &pt0, const QMatrix4x4 *toNewBase, const float scale)
double roundCoord(double x)
std::size_t operator()(const std::pair< float, float > pair) const