36#include "moc_qgstracer.cpp"
38using namespace Qt::StringLiterals;
47 return a.second > b.second;
55 int np = coords.count();
59 double x0 = coords[0].x(), y0 = coords[0].y();
62 for (
int i = 1; i < np; ++i )
77 double sqrDist = std::numeric_limits<double>::max();
79 int plcount = pl.count();
80 double prevX = pldata[0].
x(), prevY = pldata[0].
y();
81 double segmentPtX, segmentPtY;
82 for (
int i = 1; i < plcount; ++i )
84 double currentX = pldata[i].
x();
85 double currentY = pldata[i].
y();
87 if ( testDist < sqrDist )
142 const auto constEdges = edges;
148 int v1 = -1, v2 = -1;
181 int eIdx = g->
e.count() - 1;
182 g->
v[v1].edges << eIdx;
183 g->
v[v2].edges << eIdx;
192 if ( v1 == -1 || v2 == -1 )
193 return QVector<QgsPointXY>();
197 std::priority_queue< DijkstraQueueItem, std::vector< DijkstraQueueItem >,
comp > Q;
200 QVector<double> D( g.
v.count(), std::numeric_limits<double>::max() );
204 QVector<bool> F( g.
v.count() );
207 QVector<int> S( g.
v.count(), -1 );
224 const int *vuEdges = vu.
edges.constData();
225 int count = vu.
edges.count();
226 for (
int i = 0; i < count; ++i )
231 if ( !F[v] && D[u] + w < D[v] )
243 return QVector<QgsPointXY>();
247 QVector<QgsPointXY> points;
253 QVector<QgsPointXY> edgePoints = e.
coords;
254 if ( edgePoints[0] != g.
v[u].pt )
255 std::reverse( edgePoints.begin(), edgePoints.end() );
256 if ( !points.isEmpty() )
257 points.remove( points.count() - 1 );
258 points << edgePoints;
262 std::reverse( path.begin(), path.end() );
263 std::reverse( points.begin(), points.end() );
272 for (
int i = 0; i < g.
v.count(); ++i )
275 if ( v.
pt == pt || ( std::fabs( v.
pt.
x() - pt.
x() ) < epsilon && std::fabs( v.
pt.
y() - pt.
y() ) < epsilon ) )
285 for (
int i = 0; i < g.
e.count(); ++i )
291 int vertexAfter = -1;
295 lineVertexAfter = vertexAfter;
305 int count1 = lineVertexAfter;
306 int count2 = points.count() - lineVertexAfter;
308 for (
int i = 0; i < count1; ++i )
310 if ( points[lineVertexAfter - 1] != pt )
313 if ( pt != points[lineVertexAfter] )
315 for (
int i = 0; i < count2; ++i )
316 pts2 << points[i + lineVertexAfter];
324 int eIdx =
point2edge( g, pt, lineVertexAfter );
338 int vIdx = g.
v.count();
339 int e1Idx = g.
e.count();
340 int e2Idx = e1Idx + 1;
346 v.
edges << e1Idx << e2Idx;
359 v1.
edges.replace( v1.
edges.indexOf( eIdx ), e1Idx );
360 v2.
edges.replace( v2.
edges.indexOf( eIdx ), e2Idx );
395 if ( eIdx >= g.
e.count() )
399 for (
int i = 0; i < v1.
edges.count(); ++i )
401 if ( v1.
edges[i] >= g.
e.count() )
402 v1.
edges.remove( i-- );
407 for (
int i = 0; i < v2.
edges.count(); ++i )
409 if ( v2.
edges[i] >= g.
e.count() )
410 v2.
edges.remove( i-- );
427 if ( !segmentizedGeomV2 )
476bool QgsTracer::initGraph()
481 mHasTopologyProblem =
false;
490 QElapsedTimer t1, t2, t2a, t3;
493 int featuresCounted = 0;
494 for (
const QgsVectorLayer *vl : std::as_const( mLayers ) )
496 QgsFeatureRequest request;
498 std::unique_ptr< QgsFeatureRenderer > renderer;
499 std::unique_ptr<QgsRenderContext> ctx;
502 if ( !enableInvisibleFeature && mRenderContext && vl->renderer() )
504 renderer.reset( vl->renderer()->clone() );
505 ctx = std::make_unique<QgsRenderContext>( *mRenderContext.get() );
509 renderer->startRender( *ctx.get(), vl->fields() );
519 if ( !mExtent.isEmpty() )
522 QgsFeatureIterator fi = vl->getFeatures( request );
530 ctx->expressionContext().setFeature( f );
531 if ( !renderer->willRenderFeature( f, *ctx.get() ) )
540 if ( mMaxFeatureCount != 0 && featuresCounted >= mMaxFeatureCount )
546 renderer->stopRender( *ctx.get() );
549 int timeExtract = t1.elapsed();
555 int timeNodingCall = 0;
569 if ( mAddPointsOnIntersections )
571 mIntersections = QgsGeometry();
581 timeNodingCall = t2a.elapsed();
587 catch ( QgsGeosException &e )
592 mHasTopologyProblem =
true;
594 QgsDebugError( u
"Tracer Noding Exception: %1"_s.arg( e.what() ) );
598 int timeNoding = t2.elapsed();
604 int timeMake = t3.elapsed();
606 Q_UNUSED( timeExtract )
607 Q_UNUSED( timeNoding )
608 Q_UNUSED( timeNodingCall )
610 QgsDebugMsgLevel( u
"tracer extract %1 ms, noding %2 ms (call %3 ms), make %4 ms"_s
611 .arg( timeExtract ).arg( timeNoding ).arg( timeNodingCall ).arg( timeMake ), 2 );
634 disconnect( layer, &QObject::destroyed,
this, &QgsTracer::onLayerDestroyed );
647 connect( layer, &QObject::destroyed,
this, &QgsTracer::onLayerDestroyed );
656 mTransformContext = context;
662 mRenderContext = std::make_unique<QgsRenderContext>( *renderContext );
682 quadSegments = mOffsetSegments;
683 joinStyle =
static_cast< int >( mOffsetJoinStyle );
684 miterLimit = mOffsetMiterLimit;
689 mOffsetSegments = quadSegments;
691 mOffsetMiterLimit = miterLimit;
708 mGraph.reset(
nullptr );
730void QgsTracer::onAttributeValueChanged(
QgsFeatureId fid,
int idx,
const QVariant &value )
738void QgsTracer::onDataChanged( )
743void QgsTracer::onStyleChanged( )
748void QgsTracer::onLayerDestroyed( QObject *obj )
751 mLayers.removeAll(
static_cast<QgsVectorLayer *
>( obj ) );
761 return QVector<QgsPointXY>();
768 int tPrep = t.elapsed();
773 return QVector<QgsPointXY>();
778 return QVector<QgsPointXY>();
784 int tPath = t2.elapsed();
788 QgsDebugMsgLevel( u
"path timing: prep %1 ms, path %2 ms"_s.arg( tPrep ).arg( tPath ), 2 );
790 if ( points.size() > 2 && !mIntersections.isEmpty() )
792 QVector<QgsPointXY> noInts;
793 noInts.reserve( points.size() );
794 noInts.append( points.first() );
795 for (
auto it = std::next( points.begin() ), end = std::prev( points.end() ); it != end; ++it )
797 if ( mIntersections.contains( it->x(), it->y() ) )
801 if ( 0 == it->sqrDistToSegment( std::prev( it )->x(),
802 std::prev( it )->y(),
803 std::next( it )->x(),
804 std::next( it )->y(),
812 noInts.append( points.last() );
814 QgsDebugMsgLevel( u
"intersection point removal timing: %1 ms"_s.arg( t2.elapsed() - tPath ), 2 );
819 if ( !points.isEmpty() && mOffset != 0 )
821 QVector<QgsPointXY> pointsInput( points );
824 std::unique_ptr<QgsAbstractGeometry> linestringOffset( linestringEngine->offsetCurve( mOffset, mOffsetSegments, mOffsetJoinStyle, mOffsetMiterLimit ) );
828 for (
int i = 0; i < ls2->numPoints(); ++i )
832 if ( points.count() >= 2 )
834 QgsPointXY res1 = points.first(), res2 = points.last();
835 double diffNormal = res1.
distance( p1 ) + res2.distance( p2 );
836 double diffReversed = res1.
distance( p2 ) + res2.distance( p1 );
837 if ( diffReversed < diffNormal )
838 std::reverse( points.begin(), points.end() );
859 int e =
point2edge( *mGraph, pt, lineVertexAfter );
865 if ( enable == mAddPointsOnIntersections )
868 mAddPointsOnIntersections = enable;
JoinStyle
Join styles for buffers.
@ MultiPolygon
MultiPolygon.
@ MultiLineString
MultiLineString.
Abstract base class for all geometries.
virtual QgsAbstractGeometry * segmentize(double tolerance=M_PI/180., SegmentationToleranceType toleranceType=MaximumAngle) const
Returns a version of the geometry without curves.
Represents a coordinate reference system (CRS).
Contains information about the context in which a coordinate transform is executed.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
@ Filter
Features may be filtered, i.e. some features may not be rendered (categorized, rule based ....
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
static double distance2D(double x1, double y1, double x2, double y2)
Returns the 2D distance between (x1, y1) and (x2, y2).
static double sqrDistToLine(double ptX, double ptY, double x1, double y1, double x2, double y2, double &minDistX, double &minDistY, double epsilon)
Returns the squared distance between a point and a line.
A geometry is the spatial representation of a feature.
QgsMultiPolygonXY asMultiPolygon() const
Returns the contents of the geometry as a multi-polygon.
static QgsGeometry fromMultiPolylineXY(const QgsMultiPolylineXY &multiline)
Creates a new geometry from a QgsMultiPolylineXY object.
QgsPolygonXY asPolygon() const
Returns the contents of the geometry as a polygon.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsPolylineXY asPolyline() const
Returns the contents of the geometry as a polyline.
QgsMultiPolylineXY asMultiPolyline() const
Returns the contents of the geometry as a multi-linestring.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
static GEOSContextHandle_t get()
Returns a thread local instance of a GEOS context, safe for use in the current thread.
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlags())
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
static QgsGeometry geometryFromGeos(GEOSGeometry *geos)
Creates a new QgsGeometry object, feeding in a geometry in GEOS format.
Line string geometry type, with support for z-dimension and m-values.
void styleChanged()
Signal emitted whenever a change affects the layer's style.
void dataChanged()
Data of layer changed.
double distance(double x, double y) const
Returns the distance between this point and a specified x, y coordinate.
A rectangle specified with double values.
Contains information about the context of a rendering operation.
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
static const QgsSettingsEntryBool * settingsDigitizingSnapInvisibleFeature
Settings entry digitizing snap invisible feature.
void setRenderContext(const QgsRenderContext *renderContext)
Sets the renderContext used for tracing only on visible features.
void setExtent(const QgsRectangle &extent)
Sets extent to which graph's features will be limited (empty extent means no limit).
bool isPointSnapped(const QgsPointXY &pt)
Find out whether the point is snapped to a vertex or edge (i.e. it can be used for tracing start/stop...
QVector< QgsPointXY > findShortestPath(const QgsPointXY &p1, const QgsPointXY &p2, PathError *error=nullptr)
Given two points, find the shortest path and return points on the way.
PathError
Possible errors that may happen when calling findShortestPath().
@ ErrNoPath
Points are not connected in the graph.
@ ErrPoint2
End point cannot be joined to the graph.
@ ErrPoint1
Start point cannot be joined to the graph.
@ ErrTooManyFeatures
Max feature count threshold was reached while reading features.
void setOffset(double offset)
Set offset in map units that should be applied to the traced paths returned from findShortestPath().
QgsTracer()
Constructor for QgsTracer.
QgsRectangle extent() const
Gets extent to which graph's features will be limited (empty extent means no limit).
void setLayers(const QList< QgsVectorLayer * > &layers)
Sets layers used for tracing.
double offset() const
Gets offset in map units that should be applied to the traced paths returned from findShortestPath().
void offsetParameters(int &quadSegments, int &joinStyle, double &miterLimit)
Gets extra parameters for offset curve algorithm (used when offset is non-zero).
bool init()
Build the internal data structures.
void setOffsetParameters(int quadSegments, int joinStyle, double miterLimit)
Set extra parameters for offset curve algorithm (used when offset is non-zero).
void invalidateGraph()
Destroy the existing graph structure if any (de-initialize).
QList< QgsVectorLayer * > layers() const
Gets layers used for tracing.
void setAddPointsOnIntersectionsEnabled(bool enable)
When enable is true, the shortest path's straight segments will include vertices where the input laye...
virtual void configure()
Allows derived classes to setup the settings just before the tracer is initialized.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the crs and transform context used for tracing.
Represents a vector layer which manages a vector based dataset.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &value)
Emitted whenever an attribute value change is done in the edit buffer.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.
void featureDeleted(QgsFeatureId fid)
Emitted when a feature has been deleted.
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geometry)
Emitted whenever a geometry change is done in the edit buffer.
static Q_INVOKABLE bool isCurvedType(Qgis::WkbType type)
Returns true if the WKB type is a curved type or can contain curved geometries.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
T qgsgeometry_cast(QgsAbstractGeometry *geom)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QVector< QgsPolylineXY > QgsPolygonXY
Polygon: first item of the list is outer ring, inner rings (if any) start from second item.
QVector< QgsPolylineXY > QgsMultiPolylineXY
A collection of QgsPolylines that share a common collection of attributes.
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
std::pair< int, double > DijkstraQueueItem
void splitLinestring(const QgsPolylineXY &points, const QgsPointXY &pt, int lineVertexAfter, QgsPolylineXY &pts1, QgsPolylineXY &pts2)
int pointInGraph(QgsTracerGraph &g, const QgsPointXY &pt)
void extractLinework(const QgsGeometry &g, QgsMultiPolylineXY &mpl)
int point2vertex(const QgsTracerGraph &g, const QgsPointXY &pt, double epsilon=1e-6)
int point2edge(const QgsTracerGraph &g, const QgsPointXY &pt, int &lineVertexAfter, double epsilon=1e-6)
void resetGraph(QgsTracerGraph &g)
double closestSegment(const QgsPolylineXY &pl, const QgsPointXY &pt, int &vertexAfter, double epsilon)
double distance2D(const QgsPolylineXY &coords)
int joinVertexToGraph(QgsTracerGraph &g, const QgsPointXY &pt)
QgsTracerGraph * makeGraph(const QVector< QgsPolylineXY > &edges)
QVector< QgsPointXY > shortestPath(const QgsTracerGraph &g, int v1, int v2)
int v1
vertices that the edge connects
int otherVertex(int v0) const
QVector< QgsPointXY > coords
coordinates of the edge (including endpoints)
QVector< int > edges
indices of adjacent edges (used in Dijkstra algorithm)
QgsPointXY pt
location of the vertex
Simple graph structure for shortest path search.
QSet< int > inactiveEdges
Temporarily removed edges.
int joinedVertices
Temporarily added vertices (for each there are two extra edges).
QVector< E > e
Edges of the graph.
QVector< V > v
Vertices of the graph.
bool operator()(DijkstraQueueItem a, DijkstraQueueItem b) const