QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgsprofilerenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsprofilerenderer.cpp
3 ---------------
4 begin : March 2022
5 copyright : (C) 2022 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17#include "qgsprofilerenderer.h"
18
21#include "qgscurve.h"
22#include "qgslinesymbollayer.h"
23#include "qgsprofilesnapping.h"
24
25#include <QtConcurrentMap>
26
27#include "moc_qgsprofilerenderer.cpp"
28
29QgsProfilePlotRenderer::QgsProfilePlotRenderer( const QList< QgsAbstractProfileSource * > &sources, const QgsProfileRequest &request )
30 : mRequest( request )
31{
32 for ( QgsAbstractProfileSource *source : sources )
33 {
34 if ( source )
35 {
36 if ( std::unique_ptr< QgsAbstractProfileGenerator > generator { source->createProfileGenerator( mRequest ) } )
37 mGenerators.emplace_back( std::move( generator ) );
38 }
39 }
40}
41
42QgsProfilePlotRenderer::QgsProfilePlotRenderer( std::vector<std::unique_ptr<QgsAbstractProfileGenerator> > generators, const QgsProfileRequest &request )
43 : mGenerators( std::move( generators ) )
44 , mRequest( request )
45{}
46
54
56{
57 QStringList res;
58 res.reserve( mGenerators.size() );
59 for ( const auto &it : mGenerators )
60 {
61 res.append( it->sourceId() );
62 }
63 return res;
64}
65
67{
68 if ( isActive() )
69 return;
70
71 mStatus = Generating;
72
73 Q_ASSERT( mJobs.empty() );
74
75 mJobs.reserve( mGenerators.size() );
76 for ( const auto &it : mGenerators )
77 {
78 auto job = std::make_unique< ProfileJob >();
79 job->generator = it.get();
80 job->context = mContext;
81 mJobs.emplace_back( std::move( job ) );
82 }
83
84 connect( &mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsProfilePlotRenderer::onGeneratingFinished );
85
86 mFuture = QtConcurrent::map( mJobs, generateProfileStatic );
87 mFutureWatcher.setFuture( mFuture );
88}
89
91{
92 if ( isActive() )
93 return;
94
95 mStatus = Generating;
96
97 Q_ASSERT( mJobs.empty() );
98 mJobs.reserve( mGenerators.size() );
99
100 for ( const auto &it : mGenerators )
101 {
102 auto job = std::make_unique< ProfileJob >();
103 job->generator = it.get();
104 job->context = mContext;
105 it.get()->generateProfile( job->context );
106 job->results.reset( job->generator->takeResults() );
107 job->complete = true;
108 job->invalidatedResults.reset();
109 mJobs.emplace_back( std::move( job ) );
110 }
111
112 mStatus = Idle;
113}
114
116{
117 if ( !isActive() )
118 return;
119
120 disconnect( &mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsProfilePlotRenderer::onGeneratingFinished );
121
122 for ( const auto &job : mJobs )
123 {
124 if ( job->generator )
125 {
126 if ( QgsFeedback *feedback = job->generator->feedback() )
127 {
128 feedback->cancel();
129 }
130 }
131 }
132
133 mFutureWatcher.waitForFinished();
134
135 onGeneratingFinished();
136}
137
139{
140 if ( !isActive() )
141 return;
142
143 for ( const auto &job : mJobs )
144 {
145 if ( job->generator )
146 {
147 if ( QgsFeedback *feedback = job->generator->feedback() )
148 {
149 feedback->cancel();
150 }
151 }
152 }
153}
154
156{
157 if ( !isActive() )
158 return;
159
160 disconnect( &mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsProfilePlotRenderer::onGeneratingFinished );
161 mFutureWatcher.waitForFinished();
162
163 onGeneratingFinished();
164}
165
167{
168 return mStatus != Idle;
169}
170
172{
173 if ( mContext == context )
174 return;
175
176 const double maxErrorChanged = !qgsDoubleNear( context.maximumErrorMapUnits(), mContext.maximumErrorMapUnits() );
177 const double distanceRangeChanged = context.distanceRange() != mContext.distanceRange();
178 const double elevationRangeChanged = context.elevationRange() != mContext.elevationRange();
179 mContext = context;
180
181 for ( auto &job : mJobs )
182 {
183 // regenerate only those results which are refinable
184 const bool jobNeedsRegeneration = ( maxErrorChanged && ( job->generator->flags() & Qgis::ProfileGeneratorFlag::RespectsMaximumErrorMapUnit ) )
185 || ( distanceRangeChanged && ( job->generator->flags() & Qgis::ProfileGeneratorFlag::RespectsDistanceRange ) )
186 || ( elevationRangeChanged && ( job->generator->flags() & Qgis::ProfileGeneratorFlag::RespectsElevationRange ) );
187 if ( !jobNeedsRegeneration )
188 continue;
189
190 job->mutex.lock();
191 job->context = mContext;
192 if ( job->results && job->complete )
193 job->invalidatedResults = std::move( job->results );
194 job->results.reset();
195 job->complete = false;
196 job->mutex.unlock();
197 }
198}
199
201{
202 for ( auto &job : mJobs )
203 {
204 // regenerate only those results which are refinable
205 const bool jobNeedsRegeneration = ( job->generator->flags() & Qgis::ProfileGeneratorFlag::RespectsMaximumErrorMapUnit )
206 || ( job->generator->flags() & Qgis::ProfileGeneratorFlag::RespectsDistanceRange )
207 || ( job->generator->flags() & Qgis::ProfileGeneratorFlag::RespectsElevationRange );
208 if ( !jobNeedsRegeneration )
209 continue;
210
211 job->mutex.lock();
212 job->context = mContext;
213 if ( job->results && job->complete )
214 job->invalidatedResults = std::move( job->results );
215 job->results.reset();
216 job->complete = false;
217 job->mutex.unlock();
218 }
219}
220
222{
223 replaceSourceInternal( source, false );
224}
225
227{
228 return replaceSourceInternal( source, true );
229}
230
231bool QgsProfilePlotRenderer::replaceSourceInternal( QgsAbstractProfileSource *source, bool clearPreviousResults )
232{
233 if ( !source )
234 return false;
235
236 std::unique_ptr< QgsAbstractProfileGenerator > generator { source->createProfileGenerator( mRequest ) };
237 if ( !generator )
238 return false;
239
240 QString sourceId = generator->sourceId();
241 bool res = false;
242 for ( auto &job : mJobs )
243 {
244 if ( job->generator && job->generator->sourceId() == sourceId )
245 {
246 job->mutex.lock();
247 res = true;
248 if ( clearPreviousResults || job->generator->type() != generator->type() )
249 {
250 job->results.reset();
251 job->complete = false;
252 }
253 else if ( job->results )
254 {
255 job->results->copyPropertiesFromGenerator( generator.get() );
256 }
257 job->generator = generator.get();
258 job->mutex.unlock();
259
260 for ( auto it = mGenerators.begin(); it != mGenerators.end(); )
261 {
262 if ( ( *it )->sourceId() == sourceId )
263 it = mGenerators.erase( it );
264 else
265 it++;
266 }
267 mGenerators.emplace_back( std::move( generator ) );
268 }
269 }
270 return res;
271}
272
274{
275 if ( isActive() )
276 return;
277
278 mStatus = Generating;
279
280 connect( &mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsProfilePlotRenderer::onGeneratingFinished );
281
282 mFuture = QtConcurrent::map( mJobs, generateProfileStatic );
283 mFutureWatcher.setFuture( mFuture );
284}
285
287{
288 double min = std::numeric_limits< double >::max();
289 double max = std::numeric_limits< double >::lowest();
290 for ( const auto &job : mJobs )
291 {
292 if ( job->complete && job->results )
293 {
294 const QgsDoubleRange jobRange = job->results->zRange();
295 min = std::min( min, jobRange.lower() );
296 max = std::max( max, jobRange.upper() );
297 }
298 }
299 return QgsDoubleRange( min, max );
300}
301
302QImage QgsProfilePlotRenderer::renderToImage( int width, int height, double distanceMin, double distanceMax, double zMin, double zMax, const QString &sourceId, double devicePixelRatio )
303{
304 QImage res( width, height, QImage::Format_ARGB32_Premultiplied );
305 res.setDotsPerMeterX( 96 / 25.4 * 1000 );
306 res.setDotsPerMeterY( 96 / 25.4 * 1000 );
307 res.fill( Qt::transparent );
308
309 QPainter p( &res );
310
313 context.setPainterFlagsUsingContext( &p );
314 context.setDevicePixelRatio( devicePixelRatio );
315 const double mapUnitsPerPixel = ( distanceMax - distanceMin ) / width;
316 context.setMapToPixel( QgsMapToPixel( mapUnitsPerPixel ) );
317
318 render( context, width, height, distanceMin, distanceMax, zMin, zMax, sourceId );
319 p.end();
320
321 return res;
322}
323
324QTransform QgsProfilePlotRenderer::computeRenderTransform( double width, double height, double distanceMin, double distanceMax, double zMin, double zMax )
325{
326 QTransform transform;
327 transform.translate( 0, height );
328 transform.scale( width / ( distanceMax - distanceMin ), -height / ( zMax - zMin ) );
329 transform.translate( -distanceMin, -zMin );
330
331 return transform;
332}
333
334void QgsProfilePlotRenderer::render( QgsRenderContext &context, double width, double height, double distanceMin, double distanceMax, double zMin, double zMax, const QString &sourceId )
335{
336 QPainter *painter = context.painter();
337 if ( !painter )
338 return;
339
340 QgsProfileRenderContext profileRenderContext( context );
341 profileRenderContext.setWorldTransform( computeRenderTransform( width, height, distanceMin, distanceMax, zMin, zMax ) );
342
343 profileRenderContext.setDistanceRange( QgsDoubleRange( distanceMin, distanceMax ) );
344 profileRenderContext.setElevationRange( QgsDoubleRange( zMin, zMax ) );
345
346 for ( auto &job : mJobs )
347 {
348 if ( ( sourceId.isEmpty() || job->generator->sourceId() == sourceId ) )
349 {
350 job->mutex.lock();
351 if ( job->complete && job->results )
352 {
353 job->results->renderResults( profileRenderContext );
354 }
355 else if ( !job->complete && job->invalidatedResults )
356 {
357 // draw the outdated results while we wait for refinement to complete
358 job->invalidatedResults->renderResults( profileRenderContext );
359 }
360 job->mutex.unlock();
361 }
362 }
363
364 QRectF plotArea( QPointF( 0, 0 ), QPointF( width, height ) );
365 renderSubsectionsIndicator( context, plotArea, distanceMin, distanceMax, zMin, zMax );
366}
367
369{
370 auto subSections = std::make_unique< QgsSimpleLineSymbolLayer >( QColor( 255, 0, 0, 255 ), 0.5 );
371 subSections->setPenCapStyle( Qt::FlatCap );
372 return std::make_unique<QgsLineSymbol>( QgsSymbolLayerList() << subSections.release() );
373}
374
376{
377 mSubsectionsSymbol.reset( symbol );
378}
379
381{
382 return mSubsectionsSymbol.get();
383}
384
385void QgsProfilePlotRenderer::renderSubsectionsIndicator( QgsRenderContext &context, const QRectF &plotArea, double distanceMin, double distanceMax, double zMin, double zMax )
386{
387 QgsCurve *profileCurve = mRequest.profileCurve();
388 if ( !profileCurve || profileCurve->numPoints() < 3 || !mSubsectionsSymbol )
389 return;
390
391 QTransform transform = computeRenderTransform( plotArea.width(), plotArea.height(), distanceMin, distanceMax, zMin, zMax );
392
393 QgsPointSequence points;
394 profileCurve->points( points );
395 QgsPoint firstPoint = points.takeFirst();
396 points.removeLast();
397
398 mSubsectionsSymbol->startRender( context );
399 double accumulatedDistance = 0.;
400 for ( const QgsPoint &point : points )
401 {
402 accumulatedDistance += point.distance( firstPoint );
403 QPointF output = transform.map( QPointF( accumulatedDistance, 0. ) );
404 QPolygonF polyLine( QVector<QPointF> { QPointF( output.x() + plotArea.left(), plotArea.top() ), QPointF( output.x() + plotArea.left(), plotArea.bottom() ) } );
405 mSubsectionsSymbol->renderPolyline( polyLine, nullptr, context );
406 firstPoint = point;
407 }
408 mSubsectionsSymbol->stopRender( context );
409}
410
412{
413 QgsProfileSnapResult bestSnapResult;
414 if ( !mRequest.profileCurve() )
415 return bestSnapResult;
416
417 double bestSnapDistance = std::numeric_limits< double >::max();
418
419 for ( const auto &job : mJobs )
420 {
421 job->mutex.lock();
422 if ( job->complete && job->results )
423 {
424 const QgsProfileSnapResult jobSnapResult = job->results->snapPoint( point, context );
425 if ( jobSnapResult.isValid() )
426 {
427 const double snapDistance = std::pow( point.distance() - jobSnapResult.snappedPoint.distance(), 2 )
428 + std::pow( ( point.elevation() - jobSnapResult.snappedPoint.elevation() ) / context.displayRatioElevationVsDistance, 2 );
429
430 if ( snapDistance < bestSnapDistance )
431 {
432 bestSnapDistance = snapDistance;
433 bestSnapResult = jobSnapResult;
434 }
435 }
436 }
437 job->mutex.unlock();
438 }
439
440 return bestSnapResult;
441}
442
443QVector<QgsProfileIdentifyResults> QgsProfilePlotRenderer::identify( const QgsProfilePoint &point, const QgsProfileIdentifyContext &context )
444{
445 QVector<QgsProfileIdentifyResults> res;
446 if ( !mRequest.profileCurve() )
447 return res;
448
449 for ( const auto &job : mJobs )
450 {
451 job->mutex.lock();
452 if ( job->complete && job->results )
453 {
454 res.append( job->results->identify( point, context ) );
455 }
456 job->mutex.unlock();
457 }
458
459 return res;
460}
461
462QVector<QgsProfileIdentifyResults> QgsProfilePlotRenderer::identify( const QgsDoubleRange &distanceRange, const QgsDoubleRange &elevationRange, const QgsProfileIdentifyContext &context )
463{
464 QVector<QgsProfileIdentifyResults> res;
465 if ( !mRequest.profileCurve() )
466 return res;
467
468 for ( const auto &job : mJobs )
469 {
470 job->mutex.lock();
471 if ( job->complete && job->results )
472 {
473 res.append( job->results->identify( distanceRange, elevationRange, context ) );
474 }
475 job->mutex.unlock();
476 }
477
478 return res;
479}
480
481QVector<QgsAbstractProfileResults::Feature> QgsProfilePlotRenderer::asFeatures( Qgis::ProfileExportType type, QgsFeedback *feedback )
482{
483 QVector<QgsAbstractProfileResults::Feature > res;
484 for ( const auto &job : mJobs )
485 {
486 if ( feedback && feedback->isCanceled() )
487 break;
488
489 job->mutex.lock();
490 if ( job->complete && job->results )
491 {
492 res.append( job->results->asFeatures( type, feedback ) );
493 }
494 job->mutex.unlock();
495 }
496 return res;
497}
498
499void QgsProfilePlotRenderer::onGeneratingFinished()
500{
501 mStatus = Idle;
502 emit generationFinished();
503}
504
505void QgsProfilePlotRenderer::generateProfileStatic( std::unique_ptr< ProfileJob > &job )
506{
507 if ( job->results )
508 return;
509
510 Q_ASSERT( job->generator );
511
512 job->generator->generateProfile( job->context );
513 job->mutex.lock();
514 job->results.reset( job->generator->takeResults() );
515 job->complete = true;
516 job->invalidatedResults.reset();
517 job->mutex.unlock();
518}
@ RespectsMaximumErrorMapUnit
Generated profile respects the QgsProfileGenerationContext::maximumErrorMapUnits() property.
Definition qgis.h:4360
@ RespectsElevationRange
Generated profile respects the QgsProfileGenerationContext::elevationRange() property.
Definition qgis.h:4362
@ RespectsDistanceRange
Generated profile respects the QgsProfileGenerationContext::distanceRange() property.
Definition qgis.h:4361
@ Antialiasing
Use antialiasing while drawing.
Definition qgis.h:2853
ProfileExportType
Types of export for elevation profiles.
Definition qgis.h:4374
Interface for classes which can generate elevation profiles.
virtual QgsAbstractProfileGenerator * createProfileGenerator(const QgsProfileRequest &request)=0
Given a profile request, returns a new profile generator ready for generating elevation profiles.
Abstract base class for curved geometry type.
Definition qgscurve.h:36
virtual int numPoints() const =0
Returns the number of points in the curve.
virtual void points(QgsPointSequence &pt) const =0
Returns a list of points within the curve.
QgsRange which stores a range of double values.
Definition qgsrange.h:217
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
A line symbol type, for rendering LineString and MultiLineString geometries.
Perform transforms between map coordinates and device coordinates.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
Encapsulates the context in which an elevation profile is to be generated.
double maximumErrorMapUnits() const
Returns the maximum allowed error in the generated result, in profile curve map units.
QgsDoubleRange elevationRange() const
Returns the range of elevations to include in the generation.
QgsDoubleRange distanceRange() const
Returns the range of distances to include in the generation.
Encapsulates the context of identifying profile results.
void setSubsectionsSymbol(QgsLineSymbol *symbol)
Sets the symbol used to draw the subsections.
QgsProfileSnapResult snapPoint(const QgsProfilePoint &point, const QgsProfileSnapContext &context)
Snap a point to the results.
void render(QgsRenderContext &context, double width, double height, double distanceMin, double distanceMax, double zMin, double zMax, const QString &sourceId=QString())
Renders a portion of the profile using the specified render context.
void renderSubsectionsIndicator(QgsRenderContext &context, const QRectF &plotArea, double distanceMin, double distanceMax, double zMin, double zMax)
Renders the vertices of the profile curve as vertical lines using the specified render context.
void regenerateInvalidatedResults()
Starts a background regeneration of any invalidated results and immediately returns.
QVector< QgsAbstractProfileResults::Feature > asFeatures(Qgis::ProfileExportType type, QgsFeedback *feedback=nullptr)
Exports the profile results as a set of features.
QImage renderToImage(int width, int height, double distanceMin, double distanceMax, double zMin, double zMax, const QString &sourceId=QString(), double devicePixelRatio=1.0)
Renders a portion of the profile to an image with the given width and height.
void cancelGenerationWithoutBlocking()
Triggers cancellation of the generation job without blocking.
QgsLineSymbol * subsectionsSymbol()
Returns the line symbol used to draw the subsections.
void invalidateAllRefinableSources()
Invalidates previous results from all refinable sources.
void cancelGeneration()
Stop the generation job - does not return until the job has terminated.
QgsProfilePlotRenderer(const QList< QgsAbstractProfileSource * > &sources, const QgsProfileRequest &request)
Constructor for QgsProfilePlotRenderer, using the provided list of profile sources to generate the re...
void generateSynchronously()
Generate the profile results synchronously in this thread.
void startGeneration()
Start the generation job and immediately return.
QgsDoubleRange zRange() const
Returns the limits of the retrieved elevation values.
QVector< QgsProfileIdentifyResults > identify(const QgsProfilePoint &point, const QgsProfileIdentifyContext &context)
Identify results visible at the specified profile point.
void waitForFinished()
Block until the current job has finished.
bool isActive() const
Returns true if the generation job is currently running in background.
QStringList sourceIds() const
Returns the ordered list of source IDs for the sources used by the renderer.
bool invalidateResults(QgsAbstractProfileSource *source)
Invalidates the profile results from the source with matching ID.
void replaceSource(QgsAbstractProfileSource *source)
Replaces the existing source with matching ID.
void setContext(const QgsProfileGenerationContext &context)
Sets the context in which the profile generation will occur.
void generationFinished()
Emitted when the profile generation is finished (or canceled).
static std::unique_ptr< QgsLineSymbol > defaultSubSectionsSymbol()
Returns the default line symbol to use for subsections lines.
Encapsulates a point on a distance-elevation profile.
double elevation() const
Returns the elevation of the point.
double distance() const
Returns the distance of the point.
Abstract base class for storage of elevation profiles.
void setWorldTransform(const QTransform &transform)
Sets the transform from world coordinates to painter coordinates.
void setDistanceRange(const QgsDoubleRange &range)
Sets the range of distances to include in the render.
void setElevationRange(const QgsDoubleRange &range)
Sets the range of elevations to include in the render.
Encapsulates properties and constraints relating to fetching elevation profiles from different source...
Encapsulates the context of snapping a profile point.
double displayRatioElevationVsDistance
Display ratio of elevation vs distance units.
Encapsulates results of snapping a profile point.
bool isValid() const
Returns true if the result is a valid point.
QgsProfilePoint snappedPoint
Snapped point.
T lower() const
Returns the lower bound of the range.
Definition qgsrange.h:79
T upper() const
Returns the upper bound of the range.
Definition qgsrange.h:86
Contains information about the context of a rendering operation.
void setDevicePixelRatio(float ratio)
Sets the device pixel ratio.
QPainter * painter()
Returns the destination QPainter for the render operation.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
static QgsRenderContext fromQPainter(QPainter *painter)
Creates a default render context given a pixel based QPainter destination.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6975
QVector< QgsPoint > QgsPointSequence
QList< QgsSymbolLayer * > QgsSymbolLayerList
Definition qgssymbol.h:30