QGIS API Documentation 4.3.0-Master (91d4a333d5d)
Loading...
Searching...
No Matches
qgslinesymbollayer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgslinesymbollayer.cpp
3 ---------------------
4 begin : November 2009
5 copyright : (C) 2009 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 "qgslinesymbollayer.h"
17
18#include <algorithm>
19#include <cmath>
20#include <line_p.h>
21#include <memory>
22
23#include "qgsapplication.h"
24#include "qgscolorrampimpl.h"
25#include "qgscolorutils.h"
26#include "qgscurvepolygon.h"
27#include "qgsdatadefinedutils.h"
28#include "qgsdxfexport.h"
30#include "qgsfeedback.h"
31#include "qgsfillsymbol.h"
33#include "qgsgeometryutils.h"
34#include "qgsgeos.h"
35#include "qgsimagecache.h"
36#include "qgsimageoperation.h"
37#include "qgslinesymbol.h"
38#include "qgslogger.h"
39#include "qgsmarkersymbol.h"
40#include "qgsmultipolygon.h"
41#include "qgspainting.h"
42#include "qgspolygon.h"
43#include "qgsproperty.h"
44#include "qgsrendercontext.h"
45#include "qgssldexportcontext.h"
46#include "qgssymbollayerutils.h"
47#include "qgsunittypes.h"
48
49#include <QDomDocument>
50#include <QDomElement>
51#include <QPainter>
52#include <QString>
53
54using namespace Qt::StringLiterals;
55
57 : mPenStyle( penStyle )
58{
59 mColor = color;
60 mWidth = width;
61 mCustomDashVector << 5 << 2;
62}
63
65
67{
69 mWidthUnit = unit;
70 mOffsetUnit = unit;
71 mCustomDashPatternUnit = unit;
72 mDashPatternOffsetUnit = unit;
73 mTrimDistanceStartUnit = unit;
74 mTrimDistanceEndUnit = unit;
75}
76
78{
80 if ( mWidthUnit != unit || mOffsetUnit != unit || mCustomDashPatternUnit != unit )
81 {
83 }
84 return unit;
85}
86
91
93{
95 mWidthMapUnitScale = scale;
96 mOffsetMapUnitScale = scale;
97 mCustomDashPatternMapUnitScale = scale;
98}
99
108
109std::unique_ptr<QgsSymbolLayer> QgsSimpleLineSymbolLayer::create( const QVariantMap &props )
110{
114
115 if ( props.contains( u"line_color"_s ) )
116 {
117 color = QgsColorUtils::colorFromString( props[u"line_color"_s].toString() );
118 }
119 else if ( props.contains( u"outline_color"_s ) )
120 {
121 color = QgsColorUtils::colorFromString( props[u"outline_color"_s].toString() );
122 }
123 else if ( props.contains( u"color"_s ) )
124 {
125 //pre 2.5 projects used "color"
126 color = QgsColorUtils::colorFromString( props[u"color"_s].toString() );
127 }
128 if ( props.contains( u"line_width"_s ) )
129 {
130 width = props[u"line_width"_s].toDouble();
131 }
132 else if ( props.contains( u"outline_width"_s ) )
133 {
134 width = props[u"outline_width"_s].toDouble();
135 }
136 else if ( props.contains( u"width"_s ) )
137 {
138 //pre 2.5 projects used "width"
139 width = props[u"width"_s].toDouble();
140 }
141 if ( props.contains( u"line_style"_s ) )
142 {
143 penStyle = QgsSymbolLayerUtils::decodePenStyle( props[u"line_style"_s].toString() );
144 }
145 else if ( props.contains( u"outline_style"_s ) )
146 {
147 penStyle = QgsSymbolLayerUtils::decodePenStyle( props[u"outline_style"_s].toString() );
148 }
149 else if ( props.contains( u"penstyle"_s ) )
150 {
151 penStyle = QgsSymbolLayerUtils::decodePenStyle( props[u"penstyle"_s].toString() );
152 }
153
154 auto l = std::make_unique<QgsSimpleLineSymbolLayer>( color, width, penStyle );
155 if ( props.contains( u"line_width_unit"_s ) )
156 {
157 l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"line_width_unit"_s].toString() ) );
158 }
159 else if ( props.contains( u"outline_width_unit"_s ) )
160 {
161 l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"outline_width_unit"_s].toString() ) );
162 }
163 else if ( props.contains( u"width_unit"_s ) )
164 {
165 //pre 2.5 projects used "width_unit"
166 l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"width_unit"_s].toString() ) );
167 }
168 if ( props.contains( u"width_map_unit_scale"_s ) )
169 l->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"width_map_unit_scale"_s].toString() ) );
170 if ( props.contains( u"offset"_s ) )
171 l->setOffset( props[u"offset"_s].toDouble() );
172 if ( props.contains( u"offset_unit"_s ) )
173 l->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[u"offset_unit"_s].toString() ) );
174 if ( props.contains( u"offset_map_unit_scale"_s ) )
175 l->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"offset_map_unit_scale"_s].toString() ) );
176 if ( props.contains( u"joinstyle"_s ) )
177 l->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( props[u"joinstyle"_s].toString() ) );
178 if ( props.contains( u"capstyle"_s ) )
179 l->setPenCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( props[u"capstyle"_s].toString() ) );
180
181 if ( props.contains( u"use_custom_dash"_s ) )
182 {
183 l->setUseCustomDashPattern( props[u"use_custom_dash"_s].toInt() );
184 }
185 if ( props.contains( u"customdash"_s ) )
186 {
187 l->setCustomDashVector( QgsSymbolLayerUtils::decodeRealVector( props[u"customdash"_s].toString() ) );
188 }
189 if ( props.contains( u"customdash_unit"_s ) )
190 {
191 l->setCustomDashPatternUnit( QgsUnitTypes::decodeRenderUnit( props[u"customdash_unit"_s].toString() ) );
192 }
193 if ( props.contains( u"customdash_map_unit_scale"_s ) )
194 {
195 l->setCustomDashPatternMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"customdash_map_unit_scale"_s].toString() ) );
196 }
197
198 if ( props.contains( u"draw_inside_polygon"_s ) )
199 {
200 l->setDrawInsidePolygon( props[u"draw_inside_polygon"_s].toInt() );
201 }
202
203 if ( props.contains( u"ring_filter"_s ) )
204 {
205 l->setRingFilter( static_cast< RenderRingFilter>( props[u"ring_filter"_s].toInt() ) );
206 }
207
208 if ( props.contains( u"dash_pattern_offset"_s ) )
209 l->setDashPatternOffset( props[u"dash_pattern_offset"_s].toDouble() );
210 if ( props.contains( u"dash_pattern_offset_unit"_s ) )
211 l->setDashPatternOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[u"dash_pattern_offset_unit"_s].toString() ) );
212 if ( props.contains( u"dash_pattern_offset_map_unit_scale"_s ) )
213 l->setDashPatternOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"dash_pattern_offset_map_unit_scale"_s].toString() ) );
214
215 if ( props.contains( u"trim_distance_start"_s ) )
216 l->setTrimDistanceStart( props[u"trim_distance_start"_s].toDouble() );
217 if ( props.contains( u"trim_distance_start_unit"_s ) )
218 l->setTrimDistanceStartUnit( QgsUnitTypes::decodeRenderUnit( props[u"trim_distance_start_unit"_s].toString() ) );
219 if ( props.contains( u"trim_distance_start_map_unit_scale"_s ) )
220 l->setTrimDistanceStartMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"trim_distance_start_map_unit_scale"_s].toString() ) );
221 if ( props.contains( u"trim_distance_end"_s ) )
222 l->setTrimDistanceEnd( props[u"trim_distance_end"_s].toDouble() );
223 if ( props.contains( u"trim_distance_end_unit"_s ) )
224 l->setTrimDistanceEndUnit( QgsUnitTypes::decodeRenderUnit( props[u"trim_distance_end_unit"_s].toString() ) );
225 if ( props.contains( u"trim_distance_end_map_unit_scale"_s ) )
226 l->setTrimDistanceEndMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"trim_distance_end_map_unit_scale"_s].toString() ) );
227
228 if ( props.contains( u"align_dash_pattern"_s ) )
229 l->setAlignDashPattern( props[u"align_dash_pattern"_s].toInt() );
230
231 if ( props.contains( u"tweak_dash_pattern_on_corners"_s ) )
232 l->setTweakDashPatternOnCorners( props[u"tweak_dash_pattern_on_corners"_s].toInt() );
233
234 l->restoreOldDataDefinedProperties( props );
235
236 return l;
237}
238
240{
241 return u"SimpleLine"_s;
242}
243
248
250{
251 QColor penColor = mColor;
252 penColor.setAlphaF( mColor.alphaF() * context.opacity() );
253 mPen.setColor( penColor );
254 double scaledWidth = context.renderContext().convertToPainterUnits( mWidth, mWidthUnit, mWidthMapUnitScale );
255 mPen.setWidthF( scaledWidth );
256
257 //note that Qt seems to have issues with scaling dash patterns with very small pen widths.
258 //treating the pen as having no less than a 1 pixel size avoids the worst of these issues
259 const double dashWidthDiv = std::max( 1.0, scaledWidth );
260 if ( mUseCustomDashPattern )
261 {
262 mPen.setStyle( Qt::CustomDashLine );
263
264 //scale pattern vector
265
266 QVector<qreal> scaledVector;
267 QVector<qreal>::const_iterator it = mCustomDashVector.constBegin();
268 for ( ; it != mCustomDashVector.constEnd(); ++it )
269 {
270 //the dash is specified in terms of pen widths, therefore the division
271 scaledVector << context.renderContext().convertToPainterUnits( ( *it ), mCustomDashPatternUnit, mCustomDashPatternMapUnitScale ) / dashWidthDiv;
272 }
273 mPen.setDashPattern( scaledVector );
274 }
275 else
276 {
277 mPen.setStyle( mPenStyle );
278 }
279
280 if ( mDashPatternOffset && mPen.style() != Qt::SolidLine )
281 {
282 mPen.setDashOffset( context.renderContext().convertToPainterUnits( mDashPatternOffset, mDashPatternOffsetUnit, mDashPatternOffsetMapUnitScale ) / dashWidthDiv );
283 }
284
285 mPen.setJoinStyle( mPenJoinStyle );
286 mPen.setCapStyle( mPenCapStyle );
287
288 mSelPen = mPen;
289 QColor selColor = context.renderContext().selectionColor();
290 if ( !SELECTION_IS_OPAQUE )
291 selColor.setAlphaF( context.opacity() );
292 mSelPen.setColor( selColor );
293}
294
296{
297 Q_UNUSED( context )
298}
299
300void QgsSimpleLineSymbolLayer::renderPolygonStroke( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
301{
302 QPainter *p = context.renderContext().painter();
303 if ( !p )
304 {
305 return;
306 }
307
308 QgsExpressionContextScope *scope = nullptr;
309 std::unique_ptr< QgsExpressionContextScopePopper > scopePopper;
311 {
312 scope = new QgsExpressionContextScope();
313 scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.renderContext().expressionContext(), scope );
314 }
315
317 if ( mDrawInsidePolygon )
318 {
319 painterState.save();
320 }
321
322 switch ( mRingFilter )
323 {
324 case AllRings:
325 case ExteriorRingOnly:
326 {
327 if ( mDrawInsidePolygon )
328 {
329 //only drawing the line on the interior of the polygon, so set clip path for painter
330 QPainterPath clipPath;
331 clipPath.addPolygon( points );
332
333 if ( rings )
334 {
335 //add polygon rings
336 for ( auto it = rings->constBegin(); it != rings->constEnd(); ++it )
337 {
338 QPolygonF ring = *it;
339 clipPath.addPolygon( ring );
340 }
341 }
342
343 //use intersect mode, as a clip path may already exist (e.g., for composer maps)
344 p->setClipPath( clipPath, Qt::IntersectClip );
345 }
346
347 if ( scope )
349
350 renderPolyline( points, context );
351 }
352 break;
353
355 break;
356 }
357
358 if ( rings )
359 {
360 switch ( mRingFilter )
361 {
362 case AllRings:
364 {
365 mOffset = -mOffset; // invert the offset for rings!
366 int ringIndex = 1;
367 for ( const QPolygonF &ring : std::as_const( *rings ) )
368 {
369 if ( scope )
371
372 renderPolyline( ring, context );
373 ringIndex++;
374 }
375 mOffset = -mOffset;
376 }
377 break;
378 case ExteriorRingOnly:
379 break;
380 }
381 }
382}
383
389 QPolygonF &points,
390 double startTrim,
391 double endTrim,
392 Qgis::RenderUnit trimDistanceStartUnit,
393 Qgis::RenderUnit trimDistanceEndUnit,
394 const QgsMapUnitScale &trimDistanceStartMapUnitScale,
395 const QgsMapUnitScale &trimDistanceEndMapUnitScale,
396 const QgsPropertyCollection &mDataDefinedProperties,
398)
399{
400 if ( mDataDefinedProperties.isActive( QgsSymbolLayer::Property::TrimStart ) )
401 {
402 context.setOriginalValueVariable( startTrim );
403 startTrim = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::TrimStart, context.renderContext().expressionContext(), startTrim );
404 }
405
406 if ( mDataDefinedProperties.isActive( QgsSymbolLayer::Property::TrimEnd ) )
407 {
408 context.setOriginalValueVariable( endTrim );
409 endTrim = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::TrimEnd, context.renderContext().expressionContext(), endTrim );
410 }
411
412 double totalLength = -1;
413 if ( trimDistanceStartUnit == Qgis::RenderUnit::Percentage )
414 {
415 totalLength = QgsSymbolLayerUtils::polylineLength( points );
416 startTrim = startTrim * 0.01 * totalLength;
417 }
418 else
419 {
420 startTrim = context.renderContext().convertToPainterUnits( startTrim, trimDistanceStartUnit, trimDistanceStartMapUnitScale );
421 }
422 if ( trimDistanceEndUnit == Qgis::RenderUnit::Percentage )
423 {
424 if ( totalLength < 0 ) // only recalculate if we didn't already work this out for the start distance!
425 totalLength = QgsSymbolLayerUtils::polylineLength( points );
426 endTrim = endTrim * 0.01 * totalLength;
427 }
428 else
429 {
430 endTrim = context.renderContext().convertToPainterUnits( endTrim, trimDistanceEndUnit, trimDistanceEndMapUnitScale );
431 }
432 if ( !qgsDoubleNear( startTrim, 0 ) || !qgsDoubleNear( endTrim, 0 ) )
433 {
434 points = QgsSymbolLayerUtils::polylineSubstring( points, startTrim, -endTrim );
435 }
436}
437
438
440{
441 QPainter *p = context.renderContext().painter();
442 if ( !p )
443 {
444 return;
445 }
446
447 QPolygonF points = pts;
448 trimPoints( points, mTrimDistanceStart, mTrimDistanceEnd, mTrimDistanceStartUnit, mTrimDistanceEndUnit, mTrimDistanceStartMapUnitScale, mTrimDistanceEndMapUnitScale, mDataDefinedProperties, context );
449
450 QColor penColor = mColor;
451 penColor.setAlphaF( mColor.alphaF() * context.opacity() );
452 mPen.setColor( penColor );
453
454 double offset = mOffset;
455 applyDataDefinedSymbology( context, mPen, mSelPen, offset );
456
457 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
458 const QPen pen = useSelectedColor ? mSelPen : mPen;
459
460 if ( !pen.dashPattern().isEmpty() )
461 {
462 // check for a null (all 0) dash component, and shortcut out early if so -- these lines are rendered as "no pen"
463 const QVector<double> pattern = pen.dashPattern();
464 bool foundNonNull = false;
465 for ( int i = 0; i < pattern.size(); ++i )
466 {
467 if ( i % 2 == 0 && !qgsDoubleNear( pattern[i], 0 ) )
468 {
469 foundNonNull = true;
470 break;
471 }
472 }
473 if ( !foundNonNull )
474 return;
475 }
476
477 p->setBrush( Qt::NoBrush );
478
479 // Disable 'Antialiasing' if the geometry was generalized in the current RenderContext (We known that it must have least #2 points).
481 if ( points.size() <= 2
484 && ( p->renderHints() & QPainter::Antialiasing ) )
485 {
486 painterState.save();
487 p->setRenderHint( QPainter::Antialiasing, false );
488 }
489
490 const bool applyPatternTweaks = mAlignDashPattern && ( pen.style() != Qt::SolidLine || !pen.dashPattern().empty() ) && pen.dashOffset() == 0;
491
492 if ( qgsDoubleNear( offset, 0 ) )
493 {
494 if ( applyPatternTweaks )
495 {
496 drawPathWithDashPatternTweaks( p, points, pen );
497 }
498 else
499 {
500 p->setPen( pen );
501 QPainterPath path;
502 path.addPolygon( points );
503 p->drawPath( path );
504 }
505 }
506 else
507 {
508 double scaledOffset = context.renderContext().convertToPainterUnits( offset, mOffsetUnit, mOffsetMapUnitScale );
511 {
512 // rendering for symbol previews -- a size in meters in map units can't be calculated, so treat the size as millimeters
513 // and clamp it to a reasonable range. It's the best we can do in this situation!
514 scaledOffset = std::min( std::max( context.renderContext().convertToPainterUnits( offset, Qgis::RenderUnit::Millimeters ), 3.0 ), 100.0 );
515 }
516
517 QList<QPolygonF> mline = ::offsetLine( points, scaledOffset, context.originalGeometryType() != Qgis::GeometryType::Unknown ? context.originalGeometryType() : Qgis::GeometryType::Line );
518 for ( const QPolygonF &part : mline )
519 {
520 if ( applyPatternTweaks )
521 {
522 drawPathWithDashPatternTweaks( p, part, pen );
523 }
524 else
525 {
526 p->setPen( pen );
527 QPainterPath path;
528 path.addPolygon( part );
529 p->drawPath( path );
530 }
531 }
532 }
533}
534
536{
537 QVariantMap map;
538 map[u"line_color"_s] = QgsColorUtils::colorToString( mColor );
539 map[u"line_width"_s] = QString::number( mWidth );
540 map[u"line_width_unit"_s] = QgsUnitTypes::encodeUnit( mWidthUnit );
541 map[u"width_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale );
542 map[u"line_style"_s] = QgsSymbolLayerUtils::encodePenStyle( mPenStyle );
543 map[u"joinstyle"_s] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle );
544 map[u"capstyle"_s] = QgsSymbolLayerUtils::encodePenCapStyle( mPenCapStyle );
545 map[u"offset"_s] = QString::number( mOffset );
546 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
547 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
548 map[u"use_custom_dash"_s] = ( mUseCustomDashPattern ? u"1"_s : u"0"_s );
549 map[u"customdash"_s] = QgsSymbolLayerUtils::encodeRealVector( mCustomDashVector );
550 map[u"customdash_unit"_s] = QgsUnitTypes::encodeUnit( mCustomDashPatternUnit );
551 map[u"customdash_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mCustomDashPatternMapUnitScale );
552 map[u"dash_pattern_offset"_s] = QString::number( mDashPatternOffset );
553 map[u"dash_pattern_offset_unit"_s] = QgsUnitTypes::encodeUnit( mDashPatternOffsetUnit );
554 map[u"dash_pattern_offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mDashPatternOffsetMapUnitScale );
555 map[u"trim_distance_start"_s] = QString::number( mTrimDistanceStart );
556 map[u"trim_distance_start_unit"_s] = QgsUnitTypes::encodeUnit( mTrimDistanceStartUnit );
557 map[u"trim_distance_start_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mTrimDistanceStartMapUnitScale );
558 map[u"trim_distance_end"_s] = QString::number( mTrimDistanceEnd );
559 map[u"trim_distance_end_unit"_s] = QgsUnitTypes::encodeUnit( mTrimDistanceEndUnit );
560 map[u"trim_distance_end_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mTrimDistanceEndMapUnitScale );
561 map[u"draw_inside_polygon"_s] = ( mDrawInsidePolygon ? u"1"_s : u"0"_s );
562 map[u"ring_filter"_s] = QString::number( static_cast< int >( mRingFilter ) );
563 map[u"align_dash_pattern"_s] = mAlignDashPattern ? u"1"_s : u"0"_s;
564 map[u"tweak_dash_pattern_on_corners"_s] = mPatternCartographicTweakOnSharpCorners ? u"1"_s : u"0"_s;
565 return map;
566}
567
569{
575 l->setCustomDashPatternUnit( mCustomDashPatternUnit );
576 l->setCustomDashPatternMapUnitScale( mCustomDashPatternMapUnitScale );
577 l->setOffset( mOffset );
578 l->setPenJoinStyle( mPenJoinStyle );
579 l->setPenCapStyle( mPenCapStyle );
580 l->setUseCustomDashPattern( mUseCustomDashPattern );
581 l->setCustomDashVector( mCustomDashVector );
582 l->setDrawInsidePolygon( mDrawInsidePolygon );
584 l->setDashPatternOffset( mDashPatternOffset );
585 l->setDashPatternOffsetUnit( mDashPatternOffsetUnit );
586 l->setDashPatternOffsetMapUnitScale( mDashPatternOffsetMapUnitScale );
587 l->setTrimDistanceStart( mTrimDistanceStart );
588 l->setTrimDistanceStartUnit( mTrimDistanceStartUnit );
589 l->setTrimDistanceStartMapUnitScale( mTrimDistanceStartMapUnitScale );
590 l->setTrimDistanceEnd( mTrimDistanceEnd );
591 l->setTrimDistanceEndUnit( mTrimDistanceEndUnit );
592 l->setTrimDistanceEndMapUnitScale( mTrimDistanceEndMapUnitScale );
593 l->setAlignDashPattern( mAlignDashPattern );
594 l->setTweakDashPatternOnCorners( mPatternCartographicTweakOnSharpCorners );
595
597 return l;
598}
599
600void QgsSimpleLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
601{
602 QgsSldExportContext context;
603 context.setExtraProperties( props );
604 toSld( doc, element, context );
605}
606
607bool QgsSimpleLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
608{
609 if ( mPenStyle == Qt::NoPen )
610 return true;
611
612 const QVariantMap props = context.extraProperties();
613 QDomElement symbolizerElem = doc.createElement( u"se:LineSymbolizer"_s );
614 if ( !props.value( u"uom"_s, QString() ).toString().isEmpty() )
615 symbolizerElem.setAttribute( u"uom"_s, props.value( u"uom"_s, QString() ).toString() );
616 element.appendChild( symbolizerElem );
617
618 // <Geometry>
619 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( u"geom"_s, QString() ).toString(), context );
620
621 // <Stroke>
622 QDomElement strokeElem = doc.createElement( u"se:Stroke"_s );
623 symbolizerElem.appendChild( strokeElem );
624
625 Qt::PenStyle penStyle = mUseCustomDashPattern ? Qt::CustomDashLine : mPenStyle;
627 QVector<qreal> customDashVector = QgsSymbolLayerUtils::rescaleUom( mCustomDashVector, mCustomDashPatternUnit, props );
628 QgsSymbolLayerUtils::lineToSld( doc, strokeElem, penStyle, mColor, context, width, &mPenJoinStyle, &mPenCapStyle, &customDashVector );
629
630 // <se:PerpendicularOffset>
631 if ( !qgsDoubleNear( mOffset, 0.0 ) )
632 {
633 QDomElement perpOffsetElem = doc.createElement( u"se:PerpendicularOffset"_s );
635 perpOffsetElem.appendChild( doc.createTextNode( qgsDoubleToString( offset ) ) );
636 symbolizerElem.appendChild( perpOffsetElem );
637 }
638 return true;
639}
640
641QString QgsSimpleLineSymbolLayer::ogrFeatureStyle( double mmScaleFactor, double mapUnitScaleFactor ) const
642{
643 if ( mUseCustomDashPattern )
644 {
645 return QgsSymbolLayerUtils::ogrFeatureStylePen( mWidth, mmScaleFactor, mapUnitScaleFactor, mPen.color(), mPenJoinStyle, mPenCapStyle, mOffset, &mCustomDashVector );
646 }
647 else
648 {
649 return QgsSymbolLayerUtils::ogrFeatureStylePen( mWidth, mmScaleFactor, mapUnitScaleFactor, mPen.color(), mPenJoinStyle, mPenCapStyle, mOffset );
650 }
651}
652
653std::unique_ptr<QgsSymbolLayer> QgsSimpleLineSymbolLayer::createFromSld( QDomElement &element )
654{
655 QgsDebugMsgLevel( u"Entered."_s, 4 );
656
657 QDomElement strokeElem = element.firstChildElement( u"Stroke"_s );
658 if ( strokeElem.isNull() )
659 return nullptr;
660
661 Qt::PenStyle penStyle;
662 QColor color;
663 double width;
664 Qt::PenJoinStyle penJoinStyle;
665 Qt::PenCapStyle penCapStyle;
666 QVector<qreal> customDashVector;
667
669 return nullptr;
670
671 double offset = 0.0;
672 QDomElement perpOffsetElem = element.firstChildElement( u"PerpendicularOffset"_s );
673 if ( !perpOffsetElem.isNull() )
674 {
675 bool ok;
676 double d = perpOffsetElem.firstChild().nodeValue().toDouble( &ok );
677 if ( ok )
678 offset = d;
679 }
680
681 double scaleFactor = 1.0;
682 const QString uom = element.attribute( u"uom"_s );
683 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
684 width = width * scaleFactor;
685 offset = offset * scaleFactor;
686
687 auto l = std::make_unique<QgsSimpleLineSymbolLayer>( color, width, penStyle );
688 l->setOutputUnit( sldUnitSize );
689 l->setOffset( offset );
690 l->setPenJoinStyle( penJoinStyle );
691 l->setPenCapStyle( penCapStyle );
692 l->setUseCustomDashPattern( penStyle == Qt::CustomDashLine );
693 l->setCustomDashVector( customDashVector );
694 return l;
695}
696
697void QgsSimpleLineSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext &context, QPen &pen, QPen &selPen, double &offset )
698{
699 if ( !dataDefinedProperties().hasActiveProperties() )
700 return; // shortcut
701
702 //data defined properties
703 bool hasStrokeWidthExpression = false;
705 {
707 double scaledWidth
708 = context.renderContext()
710 pen.setWidthF( scaledWidth );
711 selPen.setWidthF( scaledWidth );
712 hasStrokeWidthExpression = true;
713 }
714
715 //color
717 {
719
721 penColor.setAlphaF( context.opacity() * penColor.alphaF() );
722 pen.setColor( penColor );
723 }
724
725 //offset
727 {
730 }
731
732 //dash dot vector
733
734 //note that Qt seems to have issues with scaling dash patterns with very small pen widths.
735 //treating the pen as having no less than a 1 pixel size avoids the worst of these issues
736 const double dashWidthDiv = std::max( hasStrokeWidthExpression ? pen.widthF() : mPen.widthF(), 1.0 );
737
739 {
740 const QString customDashString
742 const QStringList dashList = customDashString.split( ';' );
743 QVector<qreal> dashVector;
744 for ( const QString &dash : dashList )
745 {
746 dashVector.push_back( context.renderContext().convertToPainterUnits( dash.toDouble(), mCustomDashPatternUnit, mCustomDashPatternMapUnitScale ) / dashWidthDiv );
747 }
748 pen.setDashPattern( dashVector );
749 }
750 else if ( mDataDefinedProperties.isActive( QgsSymbolLayer::Property::StrokeWidth ) && mUseCustomDashPattern )
751 {
752 //re-scale pattern vector after data defined pen width was applied
753
754 QVector<qreal> scaledVector;
755 for ( double v : std::as_const( mCustomDashVector ) )
756 {
757 //the dash is specified in terms of pen widths, therefore the division
758 scaledVector << context.renderContext().convertToPainterUnits( v, mCustomDashPatternUnit, mCustomDashPatternMapUnitScale ) / dashWidthDiv;
759 }
760 mPen.setDashPattern( scaledVector );
761 }
762
763 // dash pattern offset
764 double patternOffset = mDashPatternOffset;
765 if ( mDataDefinedProperties.isActive( QgsSymbolLayer::Property::DashPatternOffset ) && pen.style() != Qt::SolidLine )
766 {
767 context.setOriginalValueVariable( patternOffset );
768 patternOffset = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::DashPatternOffset, context.renderContext().expressionContext(), mDashPatternOffset );
769 pen.setDashOffset( context.renderContext().convertToPainterUnits( patternOffset, mDashPatternOffsetUnit, mDashPatternOffsetMapUnitScale ) / dashWidthDiv );
770 }
771
772 //line style
774 {
776 const QString lineStyleString
778 pen.setStyle( QgsSymbolLayerUtils::decodePenStyle( lineStyleString ) );
779 }
780
781 //join style
783 {
785 const QString joinStyleString
787 pen.setJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( joinStyleString ) );
788 }
789
790 //cap style
792 {
794 const QString capStyleString
796 pen.setCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( capStyleString ) );
797 }
798}
799
800void QgsSimpleLineSymbolLayer::drawPathWithDashPatternTweaks( QPainter *painter, const QPolygonF &points, QPen pen ) const
801{
802 if ( pen.dashPattern().empty() || points.size() < 2 )
803 return;
804
805 if ( pen.widthF() <= 1.0 )
806 {
807 pen.setWidthF( 1.0001 );
808 }
809
810 QVector< qreal > sourcePattern = pen.dashPattern();
811 const double dashWidthDiv = pen.widthF();
812 // back to painter units
813 for ( int i = 0; i < sourcePattern.size(); ++i )
814 sourcePattern[i] *= pen.widthF();
815
816 QVector< qreal > buffer;
817 QPolygonF bufferedPoints;
818 QPolygonF previousSegmentBuffer;
819 // we iterate through the line points, building a custom dash pattern and adding it to the buffer
820 // as soon as we hit a sharp bend, we scale the buffered pattern in order to nicely place a dash component over the bend
821 // and then append the buffer to the output pattern.
822
823 auto ptIt = points.constBegin();
824 double totalBufferLength = 0;
825 int patternIndex = 0;
826 double currentRemainingDashLength = 0;
827 double currentRemainingGapLength = 0;
828
829 auto compressPattern = []( const QVector< qreal > &buffer ) -> QVector< qreal > {
830 QVector< qreal > result;
831 result.reserve( buffer.size() );
832 for ( auto it = buffer.begin(); it != buffer.end(); )
833 {
834 qreal dash = *it++;
835 qreal gap = *it++;
836 while ( dash == 0 && !result.empty() )
837 {
838 result.last() += gap;
839
840 if ( it == buffer.end() )
841 return result;
842 dash = *it++;
843 gap = *it++;
844 }
845 while ( gap == 0 && it != buffer.end() )
846 {
847 dash += *it++;
848 gap = *it++;
849 }
850 result << dash << gap;
851 }
852 return result;
853 };
854
855 double currentBufferLineLength = 0;
856 auto flushBuffer =
857 [pen, painter, &buffer, &bufferedPoints, &previousSegmentBuffer, &currentRemainingDashLength, &currentRemainingGapLength, &currentBufferLineLength, &totalBufferLength, dashWidthDiv, &compressPattern](
858 QPointF *nextPoint
859 ) {
860 if ( buffer.empty() || bufferedPoints.size() < 2 )
861 {
862 return;
863 }
864
865 if ( currentRemainingDashLength )
866 {
867 // ended midway through a dash -- we want to finish this off
868 buffer << currentRemainingDashLength << 0.0;
869 totalBufferLength += currentRemainingDashLength;
870 }
871 QVector< qreal > compressed = compressPattern( buffer );
872 if ( !currentRemainingDashLength )
873 {
874 // ended midway through a gap -- we don't want this, we want to end at previous dash
875 totalBufferLength -= compressed.last();
876 compressed.last() = 0;
877 }
878
879 // rescale buffer for final bit of line -- we want to end at the end of a dash, not a gap
880 const double scaleFactor = currentBufferLineLength / totalBufferLength;
881
882 bool shouldFlushPreviousSegmentBuffer = false;
883
884 if ( !previousSegmentBuffer.empty() )
885 {
886 // add first dash from current buffer
887 QPolygonF firstDashSubstring = QgsSymbolLayerUtils::polylineSubstring( bufferedPoints, 0, compressed.first() * scaleFactor );
888 if ( !firstDashSubstring.empty() )
889 QgsSymbolLayerUtils::appendPolyline( previousSegmentBuffer, firstDashSubstring );
890
891 // then we skip over the first dash and gap for this segment
892 bufferedPoints = QgsSymbolLayerUtils::polylineSubstring( bufferedPoints, ( compressed.first() + compressed.at( 1 ) ) * scaleFactor, 0 );
893
894 compressed = compressed.mid( 2 );
895 shouldFlushPreviousSegmentBuffer = !compressed.empty();
896 }
897
898 if ( !previousSegmentBuffer.empty() && ( shouldFlushPreviousSegmentBuffer || !nextPoint ) )
899 {
900 QPen adjustedPen = pen;
901 adjustedPen.setStyle( Qt::SolidLine );
902 painter->setPen( adjustedPen );
903 QPainterPath path;
904 path.addPolygon( previousSegmentBuffer );
905 painter->drawPath( path );
906 previousSegmentBuffer.clear();
907 }
908
909 double finalDash = 0;
910 if ( nextPoint )
911 {
912 // sharp bend:
913 // 1. rewind buffered points line by final dash and gap length
914 // (later) 2. draw the bend with a solid line of length 2 * final dash size
915
916 if ( !compressed.empty() )
917 {
918 finalDash = compressed.at( compressed.size() - 2 );
919 const double finalGap = compressed.size() > 2 ? compressed.at( compressed.size() - 3 ) : 0;
920
921 const QPolygonF thisPoints = bufferedPoints;
922 bufferedPoints = QgsSymbolLayerUtils::polylineSubstring( thisPoints, 0, -( finalDash + finalGap ) * scaleFactor );
923 previousSegmentBuffer = QgsSymbolLayerUtils::polylineSubstring( thisPoints, -finalDash * scaleFactor, 0 );
924 }
925 else
926 {
927 previousSegmentBuffer << bufferedPoints;
928 }
929 }
930
931 currentBufferLineLength = 0;
932 currentRemainingDashLength = 0;
933 currentRemainingGapLength = 0;
934 totalBufferLength = 0;
935 buffer.clear();
936
937 if ( !bufferedPoints.empty() && ( !compressed.empty() || !nextPoint ) )
938 {
939 QPen adjustedPen = pen;
940 if ( !compressed.empty() )
941 {
942 // maximum size of dash pattern is 32 elements
943 compressed = compressed.mid( 0, 32 );
944 std::for_each( compressed.begin(), compressed.end(), [scaleFactor, dashWidthDiv]( qreal &element ) { element *= scaleFactor / dashWidthDiv; } );
945 adjustedPen.setDashPattern( compressed );
946 }
947 else
948 {
949 adjustedPen.setStyle( Qt::SolidLine );
950 }
951
952 painter->setPen( adjustedPen );
953 QPainterPath path;
954 path.addPolygon( bufferedPoints );
955 painter->drawPath( path );
956 }
957
958 bufferedPoints.clear();
959 };
960
961 QPointF p1;
962 QPointF p2 = *ptIt;
963 ptIt++;
964 bufferedPoints << p2;
965 for ( ; ptIt != points.constEnd(); ++ptIt )
966 {
967 p1 = *ptIt;
968 if ( qgsDoubleNear( p1.y(), p2.y() ) && qgsDoubleNear( p1.x(), p2.x() ) )
969 {
970 continue;
971 }
972
973 double remainingSegmentDistance = std::sqrt( std::pow( p2.x() - p1.x(), 2.0 ) + std::pow( p2.y() - p1.y(), 2.0 ) );
974 currentBufferLineLength += remainingSegmentDistance;
975 while ( true )
976 {
977 // handle currentRemainingDashLength/currentRemainingGapLength
978 if ( currentRemainingDashLength > 0 )
979 {
980 // bit more of dash to insert
981 if ( remainingSegmentDistance >= currentRemainingDashLength )
982 {
983 // all of dash fits in
984 buffer << currentRemainingDashLength << 0.0;
985 totalBufferLength += currentRemainingDashLength;
986 remainingSegmentDistance -= currentRemainingDashLength;
987 patternIndex++;
988 currentRemainingDashLength = 0.0;
989 currentRemainingGapLength = sourcePattern.at( patternIndex );
990 if ( currentRemainingGapLength == 0.0 )
991 {
992 patternIndex++;
993 }
994 }
995 else
996 {
997 // only part of remaining dash fits in
998 buffer << remainingSegmentDistance << 0.0;
999 totalBufferLength += remainingSegmentDistance;
1000 currentRemainingDashLength -= remainingSegmentDistance;
1001 break;
1002 }
1003 }
1004 if ( currentRemainingGapLength > 0 )
1005 {
1006 // bit more of gap to insert
1007 if ( remainingSegmentDistance >= currentRemainingGapLength )
1008 {
1009 // all of gap fits in
1010 buffer << 0.0 << currentRemainingGapLength;
1011 totalBufferLength += currentRemainingGapLength;
1012 remainingSegmentDistance -= currentRemainingGapLength;
1013 currentRemainingGapLength = 0.0;
1014 patternIndex++;
1015 }
1016 else
1017 {
1018 // only part of remaining gap fits in
1019 buffer << 0.0 << remainingSegmentDistance;
1020 totalBufferLength += remainingSegmentDistance;
1021 currentRemainingGapLength -= remainingSegmentDistance;
1022 break;
1023 }
1024 }
1025
1026 if ( patternIndex + 1 >= sourcePattern.size() )
1027 {
1028 patternIndex = 0;
1029 }
1030
1031 const double nextPatternDashLength = sourcePattern.at( patternIndex );
1032 const double nextPatternGapLength = sourcePattern.at( patternIndex + 1 );
1033 if ( nextPatternDashLength + nextPatternGapLength <= remainingSegmentDistance )
1034 {
1035 buffer << nextPatternDashLength << nextPatternGapLength;
1036 remainingSegmentDistance -= nextPatternDashLength + nextPatternGapLength;
1037 totalBufferLength += nextPatternDashLength + nextPatternGapLength;
1038 patternIndex += 2;
1039 }
1040 else if ( nextPatternDashLength <= remainingSegmentDistance )
1041 {
1042 // can fit in "dash", but not "gap"
1043 buffer << nextPatternDashLength << remainingSegmentDistance - nextPatternDashLength;
1044 totalBufferLength += remainingSegmentDistance;
1045 currentRemainingGapLength = nextPatternGapLength - ( remainingSegmentDistance - nextPatternDashLength );
1046 currentRemainingDashLength = 0;
1047 patternIndex++;
1048 break;
1049 }
1050 else
1051 {
1052 // can't fit in "dash"
1053 buffer << remainingSegmentDistance << 0.0;
1054 totalBufferLength += remainingSegmentDistance;
1055 currentRemainingGapLength = 0;
1056 currentRemainingDashLength = nextPatternDashLength - remainingSegmentDistance;
1057 break;
1058 }
1059 }
1060
1061 bufferedPoints << p1;
1062 if ( mPatternCartographicTweakOnSharpCorners && ptIt + 1 != points.constEnd() )
1063 {
1064 QPointF nextPoint = *( ptIt + 1 );
1065
1066 // extreme angles form more than 45 degree angle at a node
1067 if ( QgsSymbolLayerUtils::isSharpCorner( p2, p1, nextPoint ) )
1068 {
1069 // extreme angle. Rescale buffer and flush
1070 flushBuffer( &nextPoint );
1071 bufferedPoints << p1;
1072 // restart the line with the full length of the most recent dash element -- see
1073 // "Cartographic Generalization" (Swiss Society of Cartography) p33, example #8
1074 if ( patternIndex % 2 == 1 )
1075 {
1076 patternIndex--;
1077 }
1078 currentRemainingDashLength = sourcePattern.at( patternIndex );
1079 }
1080 }
1081
1082 p2 = p1;
1083 }
1084
1085 flushBuffer( nullptr );
1086 if ( !previousSegmentBuffer.empty() )
1087 {
1088 QPen adjustedPen = pen;
1089 adjustedPen.setStyle( Qt::SolidLine );
1090 painter->setPen( adjustedPen );
1091 QPainterPath path;
1092 path.addPolygon( previousSegmentBuffer );
1093 painter->drawPath( path );
1094 previousSegmentBuffer.clear();
1095 }
1096}
1097
1099{
1100 if ( mDrawInsidePolygon )
1101 {
1102 //set to clip line to the interior of polygon, so we expect no bleed
1103 return 0;
1104 }
1105 else
1106 {
1108 }
1109}
1110
1112{
1113 unit = mCustomDashPatternUnit;
1114 return mUseCustomDashPattern ? mCustomDashVector : QVector<qreal>();
1115}
1116
1118{
1119 return mPenStyle;
1120}
1121
1133
1143
1145{
1146 return mPenStyle != Qt::SolidLine || mUseCustomDashPattern;
1147}
1148
1150{
1151 return mAlignDashPattern;
1152}
1153
1155{
1156 mAlignDashPattern = enabled;
1157}
1158
1160{
1161 return mPatternCartographicTweakOnSharpCorners;
1162}
1163
1165{
1166 mPatternCartographicTweakOnSharpCorners = enabled;
1167}
1168
1170{
1171 double offset = mOffset;
1172
1174 {
1177 }
1178
1180 return -offset; //direction seems to be inverse to symbology offset
1181}
1182
1183//
1184// QgsTemplatedLineSymbolLayerBase
1185//
1187 : mRotateSymbols( rotateSymbol )
1188 , mInterval( interval )
1189{}
1190
1212
1217
1219
1221{
1222 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
1223 if ( mRenderingFeature )
1224 {
1225 // in the middle of rendering a possibly multi-part feature, so we collect all the parts and defer the actual rendering
1226 // until after we've received the final part
1227 mFeatureSymbolOpacity = context.opacity();
1228 mCurrentFeatureIsSelected = useSelectedColor;
1229 }
1230
1231 double offset = mOffset;
1232
1234 {
1237 }
1238
1240
1242 {
1244 if ( !QgsVariantUtils::isNull( exprVal ) )
1245 {
1246 QString placementString = exprVal.toString();
1247
1248 static constexpr auto PLACEMENT_MAP = makeDataDefinedStringDecoder<Qgis::MarkerLinePlacements>( {
1249 { u"interval", Qgis::MarkerLinePlacement::Interval },
1250 { u"vertex", Qgis::MarkerLinePlacement::Vertex },
1251 { u"innervertices", Qgis::MarkerLinePlacement::InnerVertices },
1252 { u"lastvertex", Qgis::MarkerLinePlacement::LastVertex },
1253 { u"firstvertex", Qgis::MarkerLinePlacement::FirstVertex },
1254 { u"centerpoint", Qgis::MarkerLinePlacement::CentralPoint },
1255 { u"curvepoint", Qgis::MarkerLinePlacement::CurvePoint },
1256 { u"segmentcenter", Qgis::MarkerLinePlacement::SegmentCenter },
1257 } );
1258
1259 auto evaluatedPlacement = PLACEMENT_MAP.lookup( placementString );
1260 if ( evaluatedPlacement )
1261 {
1262 placements = *evaluatedPlacement;
1263 }
1264 else
1265 {
1267 }
1268 }
1269 }
1270
1271 QgsScopedQPainterState painterState( context.renderContext().painter() );
1272
1273 double averageOver = mAverageAngleLength;
1275 {
1276 context.setOriginalValueVariable( mAverageAngleLength );
1277 averageOver = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::AverageAngleLength, context.renderContext().expressionContext(), mAverageAngleLength );
1278 }
1279 averageOver = context.renderContext().convertToPainterUnits( averageOver, mAverageAngleLengthUnit, mAverageAngleLengthMapUnitScale ) / 2.0;
1280
1281 QgsSymbolLayerUtils::BlankSegments blankSegments;
1283 {
1284 const QString strBlankSegments = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::BlankSegments, context.renderContext().expressionContext() );
1285 QString error;
1286 QList<QList<QgsSymbolLayerUtils::BlankSegments>> allBlankSegments = QgsSymbolLayerUtils::parseBlankSegments( strBlankSegments, context.renderContext(), blankSegmentsUnit(), error );
1287
1288 if ( !error.isEmpty() )
1289 {
1290 QgsDebugError( u"Badly formatted blank segment '%1', skip it: %2"_s.arg( strBlankSegments ).arg( error ) );
1291 }
1292 else
1293 {
1294 // keep only the part/ring we are currently rendering
1295 const int iPart = context.geometryPartNum() - 1;
1296 if ( iPart >= 0 && mRingIndex >= 0 && iPart < allBlankSegments.count() && mRingIndex < allBlankSegments.at( iPart ).count() )
1297 {
1298 blankSegments = allBlankSegments.at( iPart ).at( mRingIndex );
1299 }
1300 }
1301 }
1302
1303 QPolygonF points = pts;
1304 trimPoints( points, mTrimDistanceStart, mTrimDistanceEnd, mTrimDistanceStartUnit, mTrimDistanceEndUnit, mTrimDistanceStartMapUnitScale, mTrimDistanceEndMapUnitScale, mDataDefinedProperties, context );
1305
1306 if ( qgsDoubleNear( offset, 0.0 ) )
1307 {
1309 renderPolylineInterval( points, context, averageOver, blankSegments );
1311 renderPolylineCentral( points, context, averageOver, blankSegments );
1313 renderPolylineVertex( points, context, Qgis::MarkerLinePlacement::Vertex, blankSegments );
1314 if ( placements & Qgis::MarkerLinePlacement::FirstVertex && ( mPlaceOnEveryPart || !mHasRenderedFirstPart ) )
1315 {
1316 renderPolylineVertex( points, context, Qgis::MarkerLinePlacement::FirstVertex, blankSegments );
1317 mHasRenderedFirstPart = mRenderingFeature;
1318 }
1320 renderPolylineVertex( points, context, Qgis::MarkerLinePlacement::InnerVertices, blankSegments );
1322 renderPolylineVertex( points, context, Qgis::MarkerLinePlacement::CurvePoint, blankSegments );
1324 renderPolylineVertex( points, context, Qgis::MarkerLinePlacement::SegmentCenter, blankSegments );
1326 renderPolylineVertex( points, context, Qgis::MarkerLinePlacement::LastVertex, blankSegments );
1327 }
1328 else
1329 {
1330 context.renderContext().setGeometry( nullptr ); //always use segmented geometry with offset
1331 QList<QPolygonF> mline = ::
1333
1334 for ( int part = 0; part < mline.count(); ++part )
1335 {
1336 const QPolygonF &points2 = mline[part];
1337
1339 renderPolylineInterval( points2, context, averageOver, blankSegments );
1341 renderPolylineCentral( points2, context, averageOver, blankSegments );
1343 renderPolylineVertex( points2, context, Qgis::MarkerLinePlacement::Vertex, blankSegments );
1345 renderPolylineVertex( points2, context, Qgis::MarkerLinePlacement::InnerVertices, blankSegments );
1347 renderPolylineVertex( points2, context, Qgis::MarkerLinePlacement::LastVertex, blankSegments );
1348 if ( placements & Qgis::MarkerLinePlacement::FirstVertex && ( mPlaceOnEveryPart || !mHasRenderedFirstPart ) )
1349 {
1350 renderPolylineVertex( points2, context, Qgis::MarkerLinePlacement::FirstVertex, blankSegments );
1351 mHasRenderedFirstPart = mRenderingFeature;
1352 }
1354 renderPolylineVertex( points2, context, Qgis::MarkerLinePlacement::CurvePoint, blankSegments );
1356 renderPolylineVertex( points2, context, Qgis::MarkerLinePlacement::SegmentCenter, blankSegments );
1357 }
1358 }
1359
1360 QgsSymbolLayerUtils::ExtraItems extraItems;
1361 if ( !mBlockExtraItemsRendering && mDataDefinedProperties.isActive( QgsSymbolLayer::Property::ExtraItems ) )
1362 {
1363 const QString strExtraItems = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::ExtraItems, context.renderContext().expressionContext() );
1364 QString error;
1365 extraItems = QgsSymbolLayerUtils::parseExtraItems( strExtraItems, error );
1366
1367 if ( !error.isEmpty() )
1368 {
1369 QgsDebugError( u"Badly formatted extra items '%1', skip it: %2"_s.arg( strExtraItems ).arg( error ) );
1370 }
1371 else
1372 {
1373 const QgsMapToPixel &mtp = context.renderContext().mapToPixel();
1374 for ( std::pair<QPointF, double> &extraItem : extraItems )
1375 {
1376 mtp.transformInPlace( extraItem.first.rx(), extraItem.first.ry() );
1377
1378 setSymbolLineAngle( extraItem.second );
1379
1380 renderSymbol( extraItem.first, context.feature(), context.renderContext(), -1, shouldRenderUsingSelectionColor( context ) );
1381 }
1382 }
1383 }
1384}
1385
1386void QgsTemplatedLineSymbolLayerBase::renderPolygonStroke( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
1387{
1388 const QgsCurvePolygon *curvePolygon = dynamic_cast<const QgsCurvePolygon *>( context.renderContext().geometry() );
1389
1390 if ( curvePolygon )
1391 {
1392 context.renderContext().setGeometry( curvePolygon->exteriorRing() );
1393 }
1394
1395 QgsExpressionContextScope *scope = nullptr;
1396 std::unique_ptr< QgsExpressionContextScopePopper > scopePopper;
1398 {
1399 scope = new QgsExpressionContextScope();
1400 scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.renderContext().expressionContext(), scope );
1401 }
1402
1403 switch ( mRingFilter )
1404 {
1405 case AllRings:
1406 case ExteriorRingOnly:
1407 {
1408 if ( scope )
1410
1411 renderPolyline( points, context );
1412 mBlockExtraItemsRendering = true; // render extra items only once
1413 break;
1414 }
1415 case InteriorRingsOnly:
1416 break;
1417 }
1418
1419 if ( rings )
1420 {
1421 switch ( mRingFilter )
1422 {
1423 case AllRings:
1424 case InteriorRingsOnly:
1425 {
1426 mOffset = -mOffset; // invert the offset for rings!
1427 for ( int i = 0; i < rings->size(); ++i )
1428 {
1429 mRingIndex = i + 1;
1430 if ( curvePolygon )
1431 {
1432 context.renderContext().setGeometry( curvePolygon->interiorRing( i ) );
1433 }
1434 if ( scope )
1436
1437 renderPolyline( rings->at( i ), context );
1438 mBlockExtraItemsRendering = true; // render extra items only once
1439 }
1440 mOffset = -mOffset;
1441 mRingIndex = 0;
1442 }
1443 break;
1444 case ExteriorRingOnly:
1445 break;
1446 }
1447 }
1448
1449 mBlockExtraItemsRendering = false;
1450}
1451
1453{
1455 if ( intervalUnit() != unit || mOffsetUnit != unit || offsetAlongLineUnit() != unit )
1456 {
1458 }
1459 return unit;
1460}
1461
1463{
1465 mIntervalUnit = unit;
1466 mOffsetAlongLineUnit = unit;
1467 mAverageAngleLengthUnit = unit;
1468}
1469
1477
1486
1488{
1489 QVariantMap map;
1490 map[u"rotate"_s] = ( rotateSymbols() ? u"1"_s : u"0"_s );
1491 map[u"interval"_s] = QString::number( interval() );
1492 map[u"offset"_s] = QString::number( mOffset );
1493 map[u"offset_along_line"_s] = QString::number( offsetAlongLine() );
1494 map[u"offset_along_line_unit"_s] = QgsUnitTypes::encodeUnit( offsetAlongLineUnit() );
1495 map[u"offset_along_line_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( offsetAlongLineMapUnitScale() );
1496 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
1497 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
1498 map[u"interval_unit"_s] = QgsUnitTypes::encodeUnit( intervalUnit() );
1499 map[u"interval_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( intervalMapUnitScale() );
1500 map[u"average_angle_length"_s] = QString::number( mAverageAngleLength );
1501 map[u"average_angle_unit"_s] = QgsUnitTypes::encodeUnit( mAverageAngleLengthUnit );
1502 map[u"average_angle_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mAverageAngleLengthMapUnitScale );
1503 map[u"trim_distance_start"_s] = QString::number( mTrimDistanceStart );
1504 map[u"trim_distance_start_unit"_s] = QgsUnitTypes::encodeUnit( mTrimDistanceStartUnit );
1505 map[u"trim_distance_start_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mTrimDistanceStartMapUnitScale );
1506 map[u"trim_distance_end"_s] = QString::number( mTrimDistanceEnd );
1507 map[u"trim_distance_end_unit"_s] = QgsUnitTypes::encodeUnit( mTrimDistanceEndUnit );
1508 map[u"trim_distance_end_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mTrimDistanceEndMapUnitScale );
1509 map[u"blank_segments_unit"_s] = QgsUnitTypes::encodeUnit( mBlankSegmentsUnit );
1510
1511 map[u"placements"_s] = qgsFlagValueToKeys( mPlacements );
1512
1513 map[u"ring_filter"_s] = QString::number( static_cast< int >( mRingFilter ) );
1514 map[u"place_on_every_part"_s] = mPlaceOnEveryPart;
1515 return map;
1516}
1517
1519{
1520 return mPlaceOnEveryPart
1521 || ( mPlacements & Qgis::MarkerLinePlacement::Interval )
1522 || ( mPlacements & Qgis::MarkerLinePlacement::CentralPoint )
1523 || ( mPlacements & Qgis::MarkerLinePlacement::SegmentCenter );
1524}
1525
1527{
1528 installMasks( context, true );
1529
1530 mRenderingFeature = true;
1531 mHasRenderedFirstPart = false;
1532}
1533
1535{
1536 mRenderingFeature = false;
1537 if ( mPlaceOnEveryPart || !( mPlacements & Qgis::MarkerLinePlacement::LastVertex ) )
1538 {
1539 removeMasks( context, true );
1540 return;
1541 }
1542
1543 const double prevOpacity = subSymbol()->opacity();
1544 subSymbol()->setOpacity( prevOpacity * mFeatureSymbolOpacity );
1545
1546 // render final point
1547 renderSymbol( mFinalVertex, &feature, context, -1, mCurrentFeatureIsSelected );
1548 mFeatureSymbolOpacity = 1;
1549 subSymbol()->setOpacity( prevOpacity );
1550
1551 removeMasks( context, true );
1552}
1553
1555{
1556 destLayer->setSubSymbol( const_cast< QgsTemplatedLineSymbolLayerBase * >( this )->subSymbol()->clone() );
1557 destLayer->setOffset( mOffset );
1558 destLayer->setPlacements( placements() );
1559 destLayer->setOffsetUnit( mOffsetUnit );
1561 destLayer->setIntervalUnit( intervalUnit() );
1563 destLayer->setOffsetAlongLine( offsetAlongLine() );
1566 destLayer->setAverageAngleLength( mAverageAngleLength );
1567 destLayer->setAverageAngleUnit( mAverageAngleLengthUnit );
1568 destLayer->setAverageAngleMapUnitScale( mAverageAngleLengthMapUnitScale );
1569 destLayer->setBlankSegmentsUnit( mBlankSegmentsUnit );
1570 destLayer->setRingFilter( mRingFilter );
1571 destLayer->setPlaceOnEveryPart( mPlaceOnEveryPart );
1572 destLayer->setTrimDistanceStart( mTrimDistanceStart );
1573 destLayer->setTrimDistanceStartUnit( mTrimDistanceStartUnit );
1574 destLayer->setTrimDistanceStartMapUnitScale( mTrimDistanceStartMapUnitScale );
1575 destLayer->setTrimDistanceEnd( mTrimDistanceEnd );
1576 destLayer->setTrimDistanceEndUnit( mTrimDistanceEndUnit );
1577 destLayer->setTrimDistanceEndMapUnitScale( mTrimDistanceEndMapUnitScale );
1578
1579 copyCommonProperties( destLayer );
1580}
1581
1583{
1584 if ( properties.contains( u"offset"_s ) )
1585 {
1586 destLayer->setOffset( properties[u"offset"_s].toDouble() );
1587 }
1588 if ( properties.contains( u"offset_unit"_s ) )
1589 {
1590 destLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_unit"_s].toString() ) );
1591 }
1592 if ( properties.contains( u"interval_unit"_s ) )
1593 {
1594 destLayer->setIntervalUnit( QgsUnitTypes::decodeRenderUnit( properties[u"interval_unit"_s].toString() ) );
1595 }
1596 if ( properties.contains( u"offset_along_line"_s ) )
1597 {
1598 destLayer->setOffsetAlongLine( properties[u"offset_along_line"_s].toDouble() );
1599 }
1600 if ( properties.contains( u"offset_along_line_unit"_s ) )
1601 {
1602 destLayer->setOffsetAlongLineUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_along_line_unit"_s].toString() ) );
1603 }
1604 if ( properties.contains( ( u"offset_along_line_map_unit_scale"_s ) ) )
1605 {
1606 destLayer->setOffsetAlongLineMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_along_line_map_unit_scale"_s].toString() ) );
1607 }
1608
1609 if ( properties.contains( u"offset_map_unit_scale"_s ) )
1610 {
1611 destLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_map_unit_scale"_s].toString() ) );
1612 }
1613 if ( properties.contains( u"interval_map_unit_scale"_s ) )
1614 {
1615 destLayer->setIntervalMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"interval_map_unit_scale"_s].toString() ) );
1616 }
1617
1618 if ( properties.contains( u"average_angle_length"_s ) )
1619 {
1620 destLayer->setAverageAngleLength( properties[u"average_angle_length"_s].toDouble() );
1621 }
1622 if ( properties.contains( u"average_angle_unit"_s ) )
1623 {
1624 destLayer->setAverageAngleUnit( QgsUnitTypes::decodeRenderUnit( properties[u"average_angle_unit"_s].toString() ) );
1625 }
1626 if ( properties.contains( ( u"average_angle_map_unit_scale"_s ) ) )
1627 {
1628 destLayer->setAverageAngleMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"average_angle_map_unit_scale"_s].toString() ) );
1629 }
1630 if ( properties.contains( u"blank_segments_unit"_s ) )
1631 {
1632 destLayer->setBlankSegmentsUnit( QgsUnitTypes::decodeRenderUnit( properties[u"blank_segments_unit"_s].toString() ) );
1633 }
1634
1635 if ( properties.contains( u"trim_distance_start"_s ) )
1636 destLayer->setTrimDistanceStart( properties[u"trim_distance_start"_s].toDouble() );
1637 if ( properties.contains( u"trim_distance_start_unit"_s ) )
1638 destLayer->setTrimDistanceStartUnit( QgsUnitTypes::decodeRenderUnit( properties[u"trim_distance_start_unit"_s].toString() ) );
1639 if ( properties.contains( u"trim_distance_start_map_unit_scale"_s ) )
1640 destLayer->setTrimDistanceStartMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"trim_distance_start_map_unit_scale"_s].toString() ) );
1641 if ( properties.contains( u"trim_distance_end"_s ) )
1642 destLayer->setTrimDistanceEnd( properties[u"trim_distance_end"_s].toDouble() );
1643 if ( properties.contains( u"trim_distance_end_unit"_s ) )
1644 destLayer->setTrimDistanceEndUnit( QgsUnitTypes::decodeRenderUnit( properties[u"trim_distance_end_unit"_s].toString() ) );
1645 if ( properties.contains( u"trim_distance_end_map_unit_scale"_s ) )
1646 destLayer->setTrimDistanceEndMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"trim_distance_end_map_unit_scale"_s].toString() ) );
1647
1648 if ( properties.contains( u"placement"_s ) )
1649 {
1650 if ( properties[u"placement"_s] == "vertex"_L1 )
1652 else if ( properties[u"placement"_s] == "lastvertex"_L1 )
1654 else if ( properties[u"placement"_s] == "firstvertex"_L1 )
1656 else if ( properties[u"placement"_s] == "centralpoint"_L1 )
1658 else if ( properties[u"placement"_s] == "curvepoint"_L1 )
1660 else if ( properties[u"placement"_s] == "segmentcenter"_L1 )
1662 else
1664 }
1665 else if ( properties.contains( u"placements"_s ) )
1666 {
1668 destLayer->setPlacements( placements );
1669 }
1670
1671 if ( properties.contains( u"ring_filter"_s ) )
1672 {
1673 destLayer->setRingFilter( static_cast< RenderRingFilter>( properties[u"ring_filter"_s].toInt() ) );
1674 }
1675
1676 destLayer->setPlaceOnEveryPart( properties.value( u"place_on_every_part"_s, true ).toBool() );
1677
1679}
1680
1682
1687class BlankSegmentsWalker
1688{
1689 public:
1690 BlankSegmentsWalker( const QPolygonF &points, const QgsSymbolLayerUtils::BlankSegments &blankSegments )
1691 : mBlankSegments( blankSegments )
1692 , mPoints( points )
1693 , mItBlankSegment( blankSegments.cbegin() )
1694 {
1695 mDistances.reserve( mPoints.count() );
1696 mDistances << 0; // first point is start, so distance is 0
1697 }
1698
1699 bool insideBlankSegment( double distance )
1700 {
1701 while ( mItBlankSegment != mBlankSegments.cend() && distance > mItBlankSegment->second )
1702 {
1703 ++mItBlankSegment;
1704 }
1705
1706 return ( mItBlankSegment != mBlankSegments.cend() && distance >= mItBlankSegment->first );
1707 }
1708
1709
1710 // pointIndex : index of the point before point
1711 bool insideBlankSegment( const QPointF &point, int pointIndex )
1712 {
1713 if ( pointIndex < 0 || pointIndex >= mPoints.count() )
1714 return false;
1715
1716 // compute distances and fill distances array
1717 if ( pointIndex >= mDistances.count() )
1718 {
1719 for ( int i = static_cast<int>( mDistances.count() ); i < pointIndex + 1; i++ )
1720 {
1721 const QPointF diff = mPoints.at( i ) - mPoints.at( i - 1 );
1722 const double distance = std::sqrt( std::pow( diff.x(), 2 ) + std::pow( diff.y(), 2 ) );
1723 const double totalDistance = distance + mDistances.last();
1724 mDistances << totalDistance;
1725 }
1726 }
1727
1728 const QPointF diff = mPoints.at( pointIndex ) - point;
1729 const double distance = std::sqrt( std::pow( diff.x(), 2 ) + std::pow( diff.y(), 2 ) );
1730 const double currentDistance = mDistances.at( pointIndex ) + distance;
1731
1732 return insideBlankSegment( currentDistance );
1733 }
1734
1735 private:
1736 const QgsSymbolLayerUtils::BlankSegments &mBlankSegments;
1737 const QPolygonF &mPoints;
1738 QList<double> mDistances;
1739 QgsSymbolLayerUtils::BlankSegments::const_iterator mItBlankSegment;
1740};
1741
1742
1744
1745
1746void QgsTemplatedLineSymbolLayerBase::renderPolylineInterval( const QPolygonF &points, QgsSymbolRenderContext &context, double averageOver, const QgsSymbolLayerUtils::BlankSegments &blankSegments )
1747{
1748 if ( points.isEmpty() )
1749 return;
1750
1751 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
1752 double lengthLeft = 0; // how much is left until next marker
1753
1754 QgsRenderContext &rc = context.renderContext();
1755 double interval = mInterval;
1756
1757 QgsExpressionContextScope *scope = new QgsExpressionContextScope();
1758 QgsExpressionContextScopePopper scopePopper( context.renderContext().expressionContext(), scope );
1759
1761 {
1762 context.setOriginalValueVariable( mInterval );
1764 }
1765 if ( interval <= 0 )
1766 {
1767 interval = 0.1;
1768 }
1769 double offsetAlongLine = mOffsetAlongLine;
1771 {
1772 context.setOriginalValueVariable( mOffsetAlongLine );
1774 }
1775
1776 double painterUnitInterval = rc.convertToPainterUnits( interval, intervalUnit(), intervalMapUnitScale() );
1778 {
1779 // rendering for symbol previews -- an interval in meters in map units can't be calculated, so treat the size as millimeters
1780 // and clamp it to a reasonable range. It's the best we can do in this situation!
1781 painterUnitInterval = std::min( std::max( rc.convertToPainterUnits( interval, Qgis::RenderUnit::Millimeters ), 10.0 ), 100.0 );
1782 }
1783
1784 constexpr double EPSILON = 1e-5;
1785 if ( painterUnitInterval < EPSILON )
1786 return;
1787
1788 double painterUnitOffsetAlongLine = 0;
1789
1790 // only calculated if we need it!
1791 double totalLength = -1;
1792
1793 if ( !qgsDoubleNear( offsetAlongLine, 0 ) )
1794 {
1795 switch ( offsetAlongLineUnit() )
1796 {
1805 break;
1807 totalLength = QgsSymbolLayerUtils::polylineLength( points );
1808 painterUnitOffsetAlongLine = offsetAlongLine / 100 * totalLength;
1809 break;
1810 }
1811
1812 if ( points.isClosed() )
1813 {
1814 if ( painterUnitOffsetAlongLine > 0 )
1815 {
1816 if ( totalLength < 0 )
1817 totalLength = QgsSymbolLayerUtils::polylineLength( points );
1818 painterUnitOffsetAlongLine = std::fmod( painterUnitOffsetAlongLine, totalLength );
1819 }
1820 else if ( painterUnitOffsetAlongLine < 0 )
1821 {
1822 if ( totalLength < 0 )
1823 totalLength = QgsSymbolLayerUtils::polylineLength( points );
1824 painterUnitOffsetAlongLine = totalLength - std::fmod( -painterUnitOffsetAlongLine, totalLength );
1825 }
1826 }
1827 }
1828
1830 {
1831 // rendering for symbol previews -- an offset in meters in map units can't be calculated, so treat the size as millimeters
1832 // and clamp it to a reasonable range. It's the best we can do in this situation!
1833 painterUnitOffsetAlongLine = std::min( std::max( rc.convertToPainterUnits( offsetAlongLine, Qgis::RenderUnit::Millimeters ), 3.0 ), 100.0 );
1834 }
1835
1836 lengthLeft = painterUnitInterval - painterUnitOffsetAlongLine;
1837
1838 if ( averageOver > 0 && !qgsDoubleNear( averageOver, 0.0 ) )
1839 {
1840 QVector< QPointF > angleStartPoints;
1841 QVector< QPointF > symbolPoints;
1842 QVector< QPointF > angleEndPoints;
1843
1844 // we collect 3 arrays of points. These correspond to
1845 // 1. the actual point at which to render the symbol
1846 // 2. the start point of a line averaging the angle over the desired distance (i.e. -averageOver distance from the points in array 1)
1847 // 3. the end point of a line averaging the angle over the desired distance (i.e. +averageOver distance from the points in array 2)
1848 // it gets quite tricky, because for closed rings we need to trace backwards from the initial point to calculate this
1849 // (or trace past the final point)
1850
1851 QList<int> pointIndices; // keep a track on original pointIndices so we can decide later whether or not symbol points belong to a blank segment
1852 collectOffsetPoints( points, symbolPoints, painterUnitInterval, lengthLeft, blankSegments.isEmpty() ? nullptr : &pointIndices );
1853
1854 if ( symbolPoints.empty() )
1855 {
1856 // no symbols to draw, shortcut out early
1857 return;
1858 }
1859
1860 if ( symbolPoints.count() > 1 && symbolPoints.constFirst() == symbolPoints.constLast() )
1861 {
1862 // avoid duplicate points at start and end of closed rings
1863 symbolPoints.pop_back();
1864 }
1865
1866 angleEndPoints.reserve( symbolPoints.size() );
1867 angleStartPoints.reserve( symbolPoints.size() );
1868 if ( averageOver <= painterUnitOffsetAlongLine )
1869 {
1870 collectOffsetPoints( points, angleStartPoints, painterUnitInterval, lengthLeft + averageOver, nullptr, 0, symbolPoints.size() );
1871 }
1872 else
1873 {
1874 collectOffsetPoints( points, angleStartPoints, painterUnitInterval, 0, nullptr, averageOver - painterUnitOffsetAlongLine, symbolPoints.size() );
1875 }
1876 collectOffsetPoints( points, angleEndPoints, painterUnitInterval, lengthLeft - averageOver, nullptr, 0, symbolPoints.size() );
1877
1878 int pointNum = 0;
1879 BlankSegmentsWalker blankSegmentsWalker( points, blankSegments );
1880 for ( int i = 0; i < symbolPoints.size(); ++i )
1881 {
1882 if ( context.renderContext().renderingStopped() )
1883 break;
1884
1885 const QPointF pt = symbolPoints[i];
1886 if ( i < pointIndices.count() && blankSegmentsWalker.insideBlankSegment( pt, pointIndices.at( i ) ) )
1887 // skip the rendering
1888 continue;
1889
1890 const QPointF startPt = angleStartPoints[i];
1891 const QPointF endPt = angleEndPoints[i];
1892
1893 Line l( startPt, endPt );
1894 // rotate marker (if desired)
1895 if ( rotateSymbols() )
1896 {
1897 setSymbolLineAngle( l.angle() * 180 / M_PI );
1898 }
1899
1900 scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) );
1901 renderSymbol( pt, context.feature(), rc, -1, useSelectedColor );
1902 }
1903 }
1904 else
1905 {
1906 // not averaging line angle -- always use exact section angle
1907 int pointNum = 0;
1908 QPointF lastPt = points[0];
1909 BlankSegmentsWalker itBlankSegment( points, blankSegments );
1910 for ( int i = 1; i < points.count(); ++i )
1911 {
1912 if ( context.renderContext().renderingStopped() )
1913 break;
1914
1915 const QPointF &pt = points[i];
1916
1917 if ( lastPt == pt ) // must not be equal!
1918 continue;
1919
1920 // for each line, find out dx and dy, and length
1921 Line l( lastPt, pt );
1922 QPointF diff = l.diffForInterval( painterUnitInterval );
1923
1924 // if there's some length left from previous line
1925 // use only the rest for the first point in new line segment
1926 // "c" is 1 for regular point or in interval (0,1] for begin of line segment
1927 double c = 1 - lengthLeft / painterUnitInterval;
1928
1929 lengthLeft += l.length();
1930
1931 // rotate marker (if desired)
1932 if ( rotateSymbols() )
1933 {
1934 setSymbolLineAngle( l.angle() * 180 / M_PI );
1935 }
1936
1937 // while we're not at the end of line segment, draw!
1938 while ( lengthLeft > painterUnitInterval )
1939 {
1940 // "c" is 1 for regular point or in interval (0,1] for begin of line segment
1941 lastPt += c * diff;
1942 c = 1; // reset c (if wasn't 1 already)
1943
1944 // we draw
1945 if ( !itBlankSegment.insideBlankSegment( lastPt, i - 1 ) )
1946 {
1947 scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) );
1948 renderSymbol( lastPt, context.feature(), rc, -1, useSelectedColor );
1949 }
1950
1951 lengthLeft -= painterUnitInterval;
1952 }
1953
1954 lastPt = pt;
1955 }
1956 }
1957}
1958
1959static double _averageAngle( QPointF prevPt, QPointF pt, QPointF nextPt )
1960{
1961 // calc average angle between the previous and next point
1962 double a1 = Line( prevPt, pt ).angle();
1963 double a2 = Line( pt, nextPt ).angle();
1964 double unitX = std::cos( a1 ) + std::cos( a2 ), unitY = std::sin( a1 ) + std::sin( a2 );
1965
1966 return std::atan2( unitY, unitX );
1967}
1968
1969void QgsTemplatedLineSymbolLayerBase::renderPolylineVertex(
1970 const QPolygonF &points, QgsSymbolRenderContext &context, Qgis::MarkerLinePlacement placement, const QgsSymbolLayerUtils::BlankSegments &blankSegments
1971)
1972{
1973 if ( points.isEmpty() )
1974 return;
1975
1976 QgsRenderContext &rc = context.renderContext();
1977
1978 int i = -1, maxCount = 0;
1979 bool isRing = false;
1980
1981 QgsExpressionContextScope *scope = new QgsExpressionContextScope();
1982 QgsExpressionContextScopePopper scopePopper( context.renderContext().expressionContext(), scope );
1983 scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, points.size(), true ) );
1984
1985 double offsetAlongLine = mOffsetAlongLine;
1987 {
1988 context.setOriginalValueVariable( mOffsetAlongLine );
1990 }
1991
1992 // only calculated if we need it!!
1993 double totalLength = -1;
1994 if ( !qgsDoubleNear( offsetAlongLine, 0.0 ) )
1995 {
1996 //scale offset along line
1997 switch ( offsetAlongLineUnit() )
1998 {
2007 break;
2009 totalLength = QgsSymbolLayerUtils::polylineLength( points );
2010 offsetAlongLine = offsetAlongLine / 100 * totalLength;
2011 break;
2012 }
2013 if ( points.isClosed() )
2014 {
2015 if ( offsetAlongLine > 0 )
2016 {
2017 if ( totalLength < 0 )
2018 totalLength = QgsSymbolLayerUtils::polylineLength( points );
2019 offsetAlongLine = std::fmod( offsetAlongLine, totalLength );
2020 }
2021 else if ( offsetAlongLine < 0 )
2022 {
2023 if ( totalLength < 0 )
2024 totalLength = QgsSymbolLayerUtils::polylineLength( points );
2025 offsetAlongLine = totalLength - std::fmod( -offsetAlongLine, totalLength );
2026 }
2027 }
2028 }
2029
2030 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
2031 if ( qgsDoubleNear( offsetAlongLine, 0.0 )
2032 && context.renderContext().geometry()
2033 && context.renderContext().geometry()->hasCurvedSegments()
2035 {
2036 QgsCoordinateTransform ct = context.renderContext().coordinateTransform();
2037 const QgsMapToPixel &mtp = context.renderContext().mapToPixel();
2038
2039 QgsVertexId vId;
2040 QgsPoint vPoint;
2041 double x, y, z;
2042 QPointF mapPoint;
2043 int pointNum = 0;
2044 const int numPoints = context.renderContext().geometry()->nCoordinates();
2045 while ( context.renderContext().geometry()->nextVertex( vId, vPoint ) )
2046 {
2047 if ( context.renderContext().renderingStopped() )
2048 break;
2049
2050 scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) );
2051
2052 if ( pointNum == 1 && placement == Qgis::MarkerLinePlacement::InnerVertices )
2053 continue;
2054
2055 if ( pointNum == numPoints && placement == Qgis::MarkerLinePlacement::InnerVertices )
2056 continue;
2057
2060 {
2061 //transform
2062 x = vPoint.x();
2063 y = vPoint.y();
2064 z = 0.0;
2065 if ( ct.isValid() )
2066 {
2067 ct.transformInPlace( x, y, z );
2068 }
2069 mapPoint.setX( x );
2070 mapPoint.setY( y );
2071 mtp.transformInPlace( mapPoint.rx(), mapPoint.ry() );
2072 if ( rotateSymbols() )
2073 {
2074 double angle = context.renderContext().geometry()->vertexAngle( vId );
2075 setSymbolLineAngle( angle * 180 / M_PI );
2076 }
2077 renderSymbol( mapPoint, context.feature(), rc, -1, useSelectedColor );
2078 }
2079 }
2080
2081 return;
2082 }
2083
2084 int pointNum = 0;
2085
2086 switch ( placement )
2087 {
2089 {
2090 i = 0;
2091 maxCount = 1;
2092 break;
2093 }
2094
2096 {
2097 i = points.count() - 1;
2098 pointNum = i;
2099 maxCount = points.count();
2100 break;
2101 }
2102
2104 {
2105 i = 1;
2106 pointNum = 1;
2107 maxCount = points.count() - 1;
2108 break;
2109 }
2110
2113 {
2115 maxCount = points.count();
2116 if ( points.first() == points.last() )
2117 isRing = true;
2118 break;
2119 }
2120
2124 {
2125 return;
2126 }
2127 }
2128
2130 {
2131 double distance;
2133 renderOffsetVertexAlongLine( points, i, distance, context, placement, blankSegments );
2134
2135 return;
2136 }
2137
2138 QPointF prevPoint;
2139 if ( placement == Qgis::MarkerLinePlacement::SegmentCenter && !points.empty() )
2140 prevPoint = points.at( 0 );
2141
2142 QPointF symbolPoint;
2143 BlankSegmentsWalker blankSegmentsWalker( points, blankSegments );
2144 for ( ; i < maxCount; ++i )
2145 {
2146 scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) );
2147
2148 if ( isRing && placement == Qgis::MarkerLinePlacement::Vertex && i == points.count() - 1 )
2149 {
2150 continue; // don't draw the last marker - it has been drawn already
2151 }
2152
2154 {
2155 QPointF currentPoint = points.at( i );
2156 symbolPoint = QPointF( 0.5 * ( currentPoint.x() + prevPoint.x() ), 0.5 * ( currentPoint.y() + prevPoint.y() ) );
2157 if ( rotateSymbols() )
2158 {
2159 double angle = std::atan2( currentPoint.y() - prevPoint.y(), currentPoint.x() - prevPoint.x() );
2160 setSymbolLineAngle( angle * 180 / M_PI );
2161 }
2162 prevPoint = currentPoint;
2163 }
2164 else
2165 {
2166 symbolPoint = points.at( i );
2167 // rotate marker (if desired)
2168 if ( rotateSymbols() )
2169 {
2170 double angle = markerAngle( points, isRing, i );
2171 setSymbolLineAngle( angle * 180 / M_PI );
2172 }
2173 }
2174
2175 mFinalVertex = symbolPoint;
2176 if ( ( i != points.count() - 1 || placement != Qgis::MarkerLinePlacement::LastVertex || mPlaceOnEveryPart || !mRenderingFeature ) && !blankSegmentsWalker.insideBlankSegment( symbolPoint, i ) )
2177 renderSymbol( symbolPoint, context.feature(), rc, -1, useSelectedColor );
2178 }
2179}
2180
2181double QgsTemplatedLineSymbolLayerBase::markerAngle( const QPolygonF &points, bool isRing, int vertex )
2182{
2183 double angle = 0;
2184 const QPointF &pt = points[vertex];
2185
2186 if ( isRing || ( vertex > 0 && vertex < points.count() - 1 ) )
2187 {
2188 int prevIndex = vertex - 1;
2189 int nextIndex = vertex + 1;
2190
2191 if ( isRing && ( vertex == 0 || vertex == points.count() - 1 ) )
2192 {
2193 prevIndex = points.count() - 2;
2194 nextIndex = 1;
2195 }
2196
2197 QPointF prevPoint, nextPoint;
2198 while ( prevIndex >= 0 )
2199 {
2200 prevPoint = points[prevIndex];
2201 if ( prevPoint != pt )
2202 {
2203 break;
2204 }
2205 --prevIndex;
2206 }
2207
2208 while ( nextIndex < points.count() )
2209 {
2210 nextPoint = points[nextIndex];
2211 if ( nextPoint != pt )
2212 {
2213 break;
2214 }
2215 ++nextIndex;
2216 }
2217
2218 if ( prevIndex >= 0 && nextIndex < points.count() )
2219 {
2220 angle = _averageAngle( prevPoint, pt, nextPoint );
2221 }
2222 }
2223 else //no ring and vertex is at start / at end
2224 {
2225 if ( vertex == 0 )
2226 {
2227 while ( vertex < points.size() - 1 )
2228 {
2229 const QPointF &nextPt = points[vertex + 1];
2230 if ( pt != nextPt )
2231 {
2232 angle = Line( pt, nextPt ).angle();
2233 return angle;
2234 }
2235 ++vertex;
2236 }
2237 }
2238 else
2239 {
2240 // use last segment's angle
2241 while ( vertex >= 1 ) //in case of duplicated vertices, take the next suitable one
2242 {
2243 const QPointF &prevPt = points[vertex - 1];
2244 if ( pt != prevPt )
2245 {
2246 angle = Line( prevPt, pt ).angle();
2247 return angle;
2248 }
2249 --vertex;
2250 }
2251 }
2252 }
2253 return angle;
2254}
2255
2256void QgsTemplatedLineSymbolLayerBase::renderOffsetVertexAlongLine(
2257 const QPolygonF &points, int vertex, double distance, QgsSymbolRenderContext &context, Qgis::MarkerLinePlacement placement, const QgsSymbolLayerUtils::BlankSegments &blankSegments
2258)
2259{
2260 if ( points.isEmpty() )
2261 return;
2262
2263 QgsRenderContext &rc = context.renderContext();
2264 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
2265 if ( qgsDoubleNear( distance, 0.0 ) )
2266 {
2267 // rotate marker (if desired)
2268 if ( rotateSymbols() )
2269 {
2270 bool isRing = false;
2271 if ( points.first() == points.last() )
2272 isRing = true;
2273 double angle = markerAngle( points, isRing, vertex );
2274 setSymbolLineAngle( angle * 180 / M_PI );
2275 }
2276 mFinalVertex = points[vertex];
2277 if ( placement != Qgis::MarkerLinePlacement::LastVertex || mPlaceOnEveryPart || !mRenderingFeature )
2278 renderSymbol( points[vertex], context.feature(), rc, -1, useSelectedColor );
2279 return;
2280 }
2281
2282 int pointIncrement = distance > 0 ? 1 : -1;
2283 QPointF previousPoint = points[vertex];
2284 int startPoint = distance > 0 ? std::min( vertex + 1, static_cast<int>( points.count() ) - 1 ) : std::max( vertex - 1, 0 );
2285 int endPoint = distance > 0 ? points.count() - 1 : 0;
2286 double distanceLeft = std::fabs( distance );
2287 BlankSegmentsWalker blankSegmentsWalker( points, blankSegments );
2288
2289 for ( int i = startPoint; pointIncrement > 0 ? i <= endPoint : i >= endPoint; i += pointIncrement )
2290 {
2291 const QPointF &pt = points[i];
2292
2293 if ( previousPoint == pt ) // must not be equal!
2294 continue;
2295
2296 // create line segment
2297 Line l( previousPoint, pt );
2298
2299 if ( distanceLeft < l.length() )
2300 {
2301 //destination point is in current segment
2302 QPointF markerPoint = previousPoint + l.diffForInterval( distanceLeft );
2303 // rotate marker (if desired)
2304 if ( rotateSymbols() )
2305 {
2306 setSymbolLineAngle( l.angle() * 180 / M_PI );
2307 }
2308 mFinalVertex = markerPoint;
2309 if ( ( placement != Qgis::MarkerLinePlacement::LastVertex || mPlaceOnEveryPart || !mRenderingFeature ) && !blankSegmentsWalker.insideBlankSegment( markerPoint, i - 1 ) )
2310 renderSymbol( markerPoint, context.feature(), rc, -1, useSelectedColor );
2311 return;
2312 }
2313
2314 distanceLeft -= l.length();
2315 previousPoint = pt;
2316 }
2317
2318 //didn't find point
2319}
2320
2321void QgsTemplatedLineSymbolLayerBase::collectOffsetPoints(
2322 const QVector<QPointF> &p, QVector<QPointF> &dest, double intervalPainterUnits, double initialOffset, QList<int> *pointIndices, double initialLag, int numberPointsRequired
2323)
2324{
2325 if ( p.empty() )
2326 return;
2327
2328 QVector< QPointF > points = p;
2329 const bool closedRing = points.first() == points.last();
2330
2331 double lengthLeft = initialOffset;
2332
2333 double initialLagLeft = initialLag > 0 ? -initialLag : 1; // an initialLagLeft of > 0 signifies end of lagging start points
2334 if ( initialLagLeft < 0 && closedRing )
2335 {
2336 // tracking back around the ring from the first point, insert pseudo vertices before the first vertex
2337 QPointF lastPt = points.constLast();
2338 QVector< QPointF > pseudoPoints;
2339 for ( int i = points.count() - 2; i > 0; --i )
2340 {
2341 if ( initialLagLeft >= 0 )
2342 {
2343 break;
2344 }
2345
2346 const QPointF &pt = points[i];
2347
2348 if ( lastPt == pt ) // must not be equal!
2349 continue;
2350
2351 Line l( lastPt, pt );
2352 initialLagLeft += l.length();
2353 lastPt = pt;
2354
2355 pseudoPoints << pt;
2356 }
2357 std::reverse( pseudoPoints.begin(), pseudoPoints.end() );
2358
2359 points = pseudoPoints;
2360 points.append( p );
2361 }
2362 else
2363 {
2364 while ( initialLagLeft < 0 )
2365 {
2366 dest << points.constFirst();
2367 initialLagLeft += intervalPainterUnits;
2368 }
2369 }
2370 if ( initialLag > 0 )
2371 {
2372 lengthLeft += intervalPainterUnits - initialLagLeft;
2373 }
2374
2375 QPointF lastPt = points[0];
2376 for ( int i = 1; i < points.count(); ++i )
2377 {
2378 const QPointF &pt = points[i];
2379
2380 if ( lastPt == pt ) // must not be equal!
2381 {
2382 if ( closedRing && i == points.count() - 1 && numberPointsRequired > 0 && dest.size() < numberPointsRequired )
2383 {
2384 lastPt = points[0];
2385 i = 0;
2386 }
2387 continue;
2388 }
2389
2390 // for each line, find out dx and dy, and length
2391 Line l( lastPt, pt );
2392 QPointF diff = l.diffForInterval( intervalPainterUnits );
2393
2394 // if there's some length left from previous line
2395 // use only the rest for the first point in new line segment
2396 double c = 1 - lengthLeft / intervalPainterUnits;
2397
2398 lengthLeft += l.length();
2399
2400
2401 while ( lengthLeft > intervalPainterUnits || qgsDoubleNear( lengthLeft, intervalPainterUnits, 0.000000001 ) )
2402 {
2403 // "c" is 1 for regular point or in interval (0,1] for begin of line segment
2404 lastPt += c * diff;
2405 lengthLeft -= intervalPainterUnits;
2406 dest << lastPt;
2407 if ( pointIndices )
2408 *pointIndices << i - 1;
2409 c = 1; // reset c (if wasn't 1 already)
2410
2411 if ( numberPointsRequired > 0 && dest.size() >= numberPointsRequired )
2412 break;
2413 }
2414 lastPt = pt;
2415
2416 if ( numberPointsRequired > 0 && dest.size() >= numberPointsRequired )
2417 break;
2418
2419 // if a closed ring, we keep looping around the ring until we hit the required number of points
2420 if ( closedRing && i == points.count() - 1 && numberPointsRequired > 0 && dest.size() < numberPointsRequired )
2421 {
2422 lastPt = points[0];
2423 i = 0;
2424 }
2425 }
2426
2427 if ( !closedRing && numberPointsRequired > 0 && dest.size() < numberPointsRequired )
2428 {
2429 // pad with repeating last point to match desired size
2430 while ( dest.size() < numberPointsRequired )
2431 dest << points.constLast();
2432 }
2433}
2434
2435void QgsTemplatedLineSymbolLayerBase::renderPolylineCentral( const QPolygonF &points, QgsSymbolRenderContext &context, double averageAngleOver, const QgsSymbolLayerUtils::BlankSegments &blankSegments )
2436{
2437 if ( !points.isEmpty() )
2438 {
2439 // calc length
2440 qreal length = 0;
2441 QPolygonF::const_iterator it = points.constBegin();
2442 QPointF last = *it;
2443 for ( ++it; it != points.constEnd(); ++it )
2444 {
2445 length += std::sqrt( ( last.x() - it->x() ) * ( last.x() - it->x() ) + ( last.y() - it->y() ) * ( last.y() - it->y() ) );
2446 last = *it;
2447 }
2448 if ( qgsDoubleNear( length, 0.0 ) )
2449 return;
2450
2451 const double midPoint = length / 2;
2452
2453 BlankSegmentsWalker blankSegmentsWalker( points, blankSegments );
2454 if ( blankSegmentsWalker.insideBlankSegment( midPoint ) )
2455 return;
2456
2457 QPointF pt;
2458 double thisSymbolAngle = 0;
2459
2460 if ( averageAngleOver > 0 && !qgsDoubleNear( averageAngleOver, 0.0 ) )
2461 {
2462 QVector< QPointF > angleStartPoints;
2463 QVector< QPointF > symbolPoints;
2464 QVector< QPointF > angleEndPoints;
2465
2466 // collectOffsetPoints will have the first point in the line as the first result -- we don't want this, we need the second
2467 // already dealt with blank segment before, no need to make them check again
2468 collectOffsetPoints( points, symbolPoints, midPoint, midPoint, nullptr, 0.0, 2 );
2469 collectOffsetPoints( points, angleStartPoints, midPoint, 0, nullptr, averageAngleOver, 2 );
2470 collectOffsetPoints( points, angleEndPoints, midPoint, midPoint - averageAngleOver, nullptr, 0, 2 );
2471
2472 pt = symbolPoints.at( 1 );
2473 Line l( angleStartPoints.at( 1 ), angleEndPoints.at( 1 ) );
2474 thisSymbolAngle = l.angle();
2475 }
2476 else
2477 {
2478 // find the segment where the central point lies
2479 it = points.constBegin();
2480 last = *it;
2481 qreal last_at = 0, next_at = 0;
2482 QPointF next;
2483 for ( ++it; it != points.constEnd(); ++it )
2484 {
2485 next = *it;
2486 next_at += std::sqrt( ( last.x() - it->x() ) * ( last.x() - it->x() ) + ( last.y() - it->y() ) * ( last.y() - it->y() ) );
2487 if ( next_at >= midPoint )
2488 break; // we have reached the center
2489 last = *it;
2490 last_at = next_at;
2491 }
2492
2493 // find out the central point on segment
2494 Line l( last, next ); // for line angle
2495 qreal k = ( length * 0.5 - last_at ) / ( next_at - last_at );
2496 pt = last + ( next - last ) * k;
2497 thisSymbolAngle = l.angle();
2498 }
2499
2500 // draw the marker
2501 // rotate marker (if desired)
2502 if ( rotateSymbols() )
2503 {
2504 setSymbolLineAngle( thisSymbolAngle * 180 / M_PI );
2505 }
2506
2507 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
2508 renderSymbol( pt, context.feature(), context.renderContext(), -1, useSelectedColor );
2509 }
2510}
2511
2516
2518{
2519 if ( !symbol || symbol->type() != Qgis::SymbolType::Marker )
2520 {
2521 delete symbol;
2522 return false;
2523 }
2524
2525 mMarker.reset( static_cast<QgsMarkerSymbol *>( symbol ) );
2526 mColor = mMarker->color();
2527 return true;
2528}
2529
2530
2531//
2532// QgsMarkerLineSymbolLayer
2533//
2534
2540
2542
2543std::unique_ptr<QgsSymbolLayer> QgsMarkerLineSymbolLayer::create( const QVariantMap &props )
2544{
2545 bool rotate = DEFAULT_MARKERLINE_ROTATE;
2547
2548 if ( props.contains( u"interval"_s ) )
2549 interval = props[u"interval"_s].toDouble();
2550 if ( props.contains( u"rotate"_s ) )
2551 rotate = ( props[u"rotate"_s].toString() == "1"_L1 );
2552
2553 auto x = std::make_unique< QgsMarkerLineSymbolLayer >( rotate, interval );
2554 setCommonProperties( x.get(), props );
2555 return x;
2556}
2557
2559{
2560 return u"MarkerLine"_s;
2561}
2562
2564{
2565 mMarker->setColor( color );
2566 mColor = color;
2567}
2568
2570{
2571 return mMarker ? mMarker->color() : mColor;
2572}
2573
2575{
2576 // if being rotated, it gets initialized with every line segment
2578 if ( rotateSymbols() )
2580 mMarker->setRenderHints( hints );
2581
2582 mMarker->startRender( context.renderContext(), context.fields() );
2583}
2584
2586{
2587 mMarker->stopRender( context.renderContext() );
2588}
2589
2590
2592{
2593 auto x = std::make_unique< QgsMarkerLineSymbolLayer >( rotateSymbols(), interval() );
2595 return x.release();
2596}
2597
2598void QgsMarkerLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
2599{
2600 QgsSldExportContext context;
2601 context.setExtraProperties( props );
2602 toSld( doc, element, context );
2603}
2604
2605bool QgsMarkerLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
2606{
2607 const QVariantMap props = context.extraProperties();
2608 for ( int i = 0; i < mMarker->symbolLayerCount(); i++ )
2609 {
2610 QDomElement symbolizerElem = doc.createElement( u"se:LineSymbolizer"_s );
2611 if ( !props.value( u"uom"_s, QString() ).toString().isEmpty() )
2612 symbolizerElem.setAttribute( u"uom"_s, props.value( u"uom"_s, QString() ).toString() );
2613 element.appendChild( symbolizerElem );
2614
2615 // <Geometry>
2616 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( u"geom"_s, QString() ).toString(), context );
2617
2618 QString gap;
2620 symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, u"placement"_s, u"firstPoint"_s ) );
2622 symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, u"placement"_s, u"lastPoint"_s ) );
2624 symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, u"placement"_s, u"centralPoint"_s ) );
2626 // no way to get line/polygon's vertices, use a VendorOption
2627 symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, u"placement"_s, u"points"_s ) );
2628
2630 {
2632 gap = qgsDoubleToString( interval );
2633 }
2634
2635 if ( !rotateSymbols() )
2636 {
2637 // markers in LineSymbolizer must be drawn following the line orientation,
2638 // use a VendorOption when no marker rotation
2639 symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, u"rotateMarker"_s, u"0"_s ) );
2640 }
2641
2642 // <Stroke>
2643 QDomElement strokeElem = doc.createElement( u"se:Stroke"_s );
2644 symbolizerElem.appendChild( strokeElem );
2645
2646 // <GraphicStroke>
2647 QDomElement graphicStrokeElem = doc.createElement( u"se:GraphicStroke"_s );
2648 strokeElem.appendChild( graphicStrokeElem );
2649
2650 QgsSymbolLayer *layer = mMarker->symbolLayer( i );
2651 if ( QgsMarkerSymbolLayer *markerLayer = dynamic_cast<QgsMarkerSymbolLayer *>( layer ) )
2652 {
2653 markerLayer->writeSldMarker( doc, graphicStrokeElem, context );
2654 }
2655 else if ( layer )
2656 {
2657 QgsDebugError( u"QgsMarkerSymbolLayer expected, %1 found. Skip it."_s.arg( layer->layerType() ) );
2658 }
2659 else
2660 {
2661 QgsDebugError( u"Missing marker line symbol layer. Skip it."_s );
2662 }
2663
2664 if ( !gap.isEmpty() )
2665 {
2666 QDomElement gapElem = doc.createElement( u"se:Gap"_s );
2667 QgsSymbolLayerUtils::createExpressionElement( doc, gapElem, gap, context );
2668 graphicStrokeElem.appendChild( gapElem );
2669 }
2670
2671 if ( !qgsDoubleNear( mOffset, 0.0 ) )
2672 {
2673 QDomElement perpOffsetElem = doc.createElement( u"se:PerpendicularOffset"_s );
2675 perpOffsetElem.appendChild( doc.createTextNode( qgsDoubleToString( offset ) ) );
2676 symbolizerElem.appendChild( perpOffsetElem );
2677 }
2678 }
2679 return true;
2680}
2681
2682std::unique_ptr<QgsSymbolLayer> QgsMarkerLineSymbolLayer::createFromSld( QDomElement &element )
2683{
2684 QgsDebugMsgLevel( u"Entered."_s, 4 );
2685
2686 QDomElement strokeElem = element.firstChildElement( u"Stroke"_s );
2687 if ( strokeElem.isNull() )
2688 return nullptr;
2689
2690 QDomElement graphicStrokeElem = strokeElem.firstChildElement( u"GraphicStroke"_s );
2691 if ( graphicStrokeElem.isNull() )
2692 return nullptr;
2693
2694 // retrieve vendor options
2695 bool rotateMarker = true;
2697
2698 QgsStringMap vendorOptions = QgsSymbolLayerUtils::getVendorOptionList( element );
2699 for ( QgsStringMap::iterator it = vendorOptions.begin(); it != vendorOptions.end(); ++it )
2700 {
2701 if ( it.key() == "placement"_L1 )
2702 {
2703 if ( it.value() == "points"_L1 )
2705 else if ( it.value() == "firstPoint"_L1 )
2707 else if ( it.value() == "lastPoint"_L1 )
2709 else if ( it.value() == "centralPoint"_L1 )
2711 }
2712 else if ( it.value() == "rotateMarker"_L1 )
2713 {
2714 rotateMarker = it.value() == "0"_L1;
2715 }
2716 }
2717
2718 std::unique_ptr< QgsMarkerSymbol > marker;
2719
2720 std::unique_ptr< QgsSymbolLayer > l = QgsSymbolLayerUtils::createMarkerLayerFromSld( graphicStrokeElem );
2721 if ( l )
2722 {
2723 QgsSymbolLayerList layers;
2724 layers.append( l.release() );
2725 marker = std::make_unique<QgsMarkerSymbol>( layers );
2726 }
2727
2728 if ( !marker )
2729 return nullptr;
2730
2731 double interval = 0.0;
2732 QDomElement gapElem = graphicStrokeElem.firstChildElement( u"Gap"_s );
2733 if ( !gapElem.isNull() )
2734 {
2735 bool ok;
2736 double d = gapElem.firstChild().firstChild().nodeValue().toDouble( &ok );
2737 if ( ok )
2738 interval = d;
2739 }
2740
2741 double offset = 0.0;
2742 QDomElement perpOffsetElem = graphicStrokeElem.firstChildElement( u"PerpendicularOffset"_s );
2743 if ( !perpOffsetElem.isNull() )
2744 {
2745 bool ok;
2746 double d = perpOffsetElem.firstChild().nodeValue().toDouble( &ok );
2747 if ( ok )
2748 offset = d;
2749 }
2750
2751 double scaleFactor = 1.0;
2752 const QString uom = element.attribute( u"uom"_s );
2753 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
2754 interval = interval * scaleFactor;
2755 offset = offset * scaleFactor;
2756
2757 auto x = std::make_unique<QgsMarkerLineSymbolLayer>( rotateMarker );
2758 x->setOutputUnit( sldUnitSize );
2759 x->setPlacements( placement );
2760 x->setInterval( interval );
2761 x->setSubSymbol( marker.release() );
2762 x->setOffset( offset );
2763 return x;
2764}
2765
2767{
2768 mMarker->setSize( width );
2769}
2770
2772{
2773 if ( key == QgsSymbolLayer::Property::Width && mMarker && property )
2774 {
2775 mMarker->setDataDefinedSize( property );
2776 }
2778}
2779
2781{
2782 const double prevOpacity = mMarker->opacity();
2783 mMarker->setOpacity( mMarker->opacity() * context.opacity() );
2785 mMarker->setOpacity( prevOpacity );
2786}
2787
2789{
2790 mMarker->setLineAngle( angle );
2791}
2792
2794{
2795 return mMarker->angle();
2796}
2797
2799{
2800 mMarker->setAngle( angle );
2801}
2802
2803void QgsMarkerLineSymbolLayer::renderSymbol( const QPointF &point, const QgsFeature *feature, QgsRenderContext &context, int layer, bool selected )
2804{
2805 const bool prevIsSubsymbol = context.flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
2807
2808 mMarker->renderPoint( point, feature, context, layer, selected );
2809
2810 context.setFlag( Qgis::RenderContextFlag::RenderingSubSymbol, prevIsSubsymbol );
2811}
2812
2814{
2815 return mMarker->size();
2816}
2817
2819{
2820 return mMarker->size( context );
2821}
2822
2828
2844
2846{
2847 QSet<QString> attr = QgsLineSymbolLayer::usedAttributes( context );
2848 if ( mMarker )
2849 attr.unite( mMarker->usedAttributes( context ) );
2850 return attr;
2851}
2852
2854{
2856 return true;
2857 if ( mMarker && mMarker->hasDataDefinedProperties() )
2858 return true;
2859 return false;
2860}
2861
2863{
2864 return ( mMarker->size( context ) / 2.0 ) + context.convertToPainterUnits( std::fabs( mOffset ), mOffsetUnit, mOffsetMapUnitScale );
2865}
2866
2867
2868//
2869// QgsHashedLineSymbolLayer
2870//
2871
2873 : QgsTemplatedLineSymbolLayerBase( rotateSymbol, interval )
2874{
2875 setSubSymbol( new QgsLineSymbol() );
2876}
2877
2879
2880std::unique_ptr<QgsSymbolLayer> QgsHashedLineSymbolLayer::create( const QVariantMap &props )
2881{
2882 bool rotate = DEFAULT_MARKERLINE_ROTATE;
2884
2885 if ( props.contains( u"interval"_s ) )
2886 interval = props[u"interval"_s].toDouble();
2887 if ( props.contains( u"rotate"_s ) )
2888 rotate = ( props[u"rotate"_s] == "1"_L1 );
2889
2890 auto x = std::make_unique< QgsHashedLineSymbolLayer >( rotate, interval );
2891 setCommonProperties( x.get(), props );
2892 if ( props.contains( u"hash_angle"_s ) )
2893 {
2894 x->setHashAngle( props[u"hash_angle"_s].toDouble() );
2895 }
2896
2897 if ( props.contains( u"hash_length"_s ) )
2898 x->setHashLength( props[u"hash_length"_s].toDouble() );
2899
2900 if ( props.contains( u"hash_length_unit"_s ) )
2901 x->setHashLengthUnit( QgsUnitTypes::decodeRenderUnit( props[u"hash_length_unit"_s].toString() ) );
2902
2903 if ( props.contains( u"hash_length_map_unit_scale"_s ) )
2904 x->setHashLengthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"hash_length_map_unit_scale"_s].toString() ) );
2905
2906 return x;
2907}
2908
2910{
2911 return u"HashLine"_s;
2912}
2913
2915{
2916 // if being rotated, it gets initialized with every line segment
2918 if ( rotateSymbols() )
2920 mHashSymbol->setRenderHints( hints );
2921
2922 mHashSymbol->startRender( context.renderContext(), context.fields() );
2923}
2924
2926{
2927 mHashSymbol->stopRender( context.renderContext() );
2928}
2929
2931{
2933 map[u"hash_angle"_s] = QString::number( mHashAngle );
2934
2935 map[u"hash_length"_s] = QString::number( mHashLength );
2936 map[u"hash_length_unit"_s] = QgsUnitTypes::encodeUnit( mHashLengthUnit );
2937 map[u"hash_length_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mHashLengthMapUnitScale );
2938
2939 return map;
2940}
2941
2943{
2944 auto x = std::make_unique< QgsHashedLineSymbolLayer >( rotateSymbols(), interval() );
2946 x->setHashAngle( mHashAngle );
2947 x->setHashLength( mHashLength );
2948 x->setHashLengthUnit( mHashLengthUnit );
2949 x->setHashLengthMapUnitScale( mHashLengthMapUnitScale );
2950 return x.release();
2951}
2952
2954{
2955 mHashSymbol->setColor( color );
2956 mColor = color;
2957}
2958
2960{
2961 return mHashSymbol ? mHashSymbol->color() : mColor;
2962}
2963
2965{
2966 return mHashSymbol.get();
2967}
2968
2970{
2971 if ( !symbol || symbol->type() != Qgis::SymbolType::Line )
2972 {
2973 delete symbol;
2974 return false;
2975 }
2976
2977 mHashSymbol.reset( static_cast<QgsLineSymbol *>( symbol ) );
2978 mColor = mHashSymbol->color();
2979 return true;
2980}
2981
2983{
2984 mHashLength = width;
2985}
2986
2988{
2989 return mHashLength;
2990}
2991
2993{
2994 return context.convertToPainterUnits( mHashLength, mHashLengthUnit, mHashLengthMapUnitScale );
2995}
2996
2998{
2999 return ( mHashSymbol->width( context ) / 2.0 )
3000 + context.convertToPainterUnits( mHashLength, mHashLengthUnit, mHashLengthMapUnitScale )
3002}
3003
3005{
3007 mHashSymbol->setOutputUnit( unit );
3008}
3009
3011{
3012 QSet<QString> attr = QgsLineSymbolLayer::usedAttributes( context );
3013 if ( mHashSymbol )
3014 attr.unite( mHashSymbol->usedAttributes( context ) );
3015 return attr;
3016}
3017
3019{
3021 return true;
3022 if ( mHashSymbol && mHashSymbol->hasDataDefinedProperties() )
3023 return true;
3024 return false;
3025}
3026
3028{
3029 if ( key == QgsSymbolLayer::Property::Width && mHashSymbol && property )
3030 {
3031 mHashSymbol->setDataDefinedWidth( property );
3032 }
3034}
3035
3053
3055{
3056 mSymbolLineAngle = angle;
3057}
3058
3060{
3061 return mSymbolAngle;
3062}
3063
3065{
3066 mSymbolAngle = angle;
3067}
3068
3069void QgsHashedLineSymbolLayer::renderSymbol( const QPointF &point, const QgsFeature *feature, QgsRenderContext &context, int layer, bool selected )
3070{
3071 double lineLength = mHashLength;
3073 {
3074 context.expressionContext().setOriginalValueVariable( mHashLength );
3075 lineLength = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::LineDistance, context.expressionContext(), lineLength );
3076 }
3077 const double w = context.convertToPainterUnits( lineLength, mHashLengthUnit, mHashLengthMapUnitScale ) / 2.0;
3078
3079 double hashAngle = mHashAngle;
3081 {
3082 context.expressionContext().setOriginalValueVariable( mHashAngle );
3084 }
3085
3086 QgsPointXY center( point );
3087 QgsPointXY start = center.project( w, 180 - ( mSymbolAngle + mSymbolLineAngle + hashAngle ) );
3088 QgsPointXY end = center.project( -w, 180 - ( mSymbolAngle + mSymbolLineAngle + hashAngle ) );
3089
3090 QPolygonF points;
3091 points << QPointF( start.x(), start.y() ) << QPointF( end.x(), end.y() );
3092
3093 const bool prevIsSubsymbol = context.flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
3095
3096 mHashSymbol->renderPolyline( points, feature, context, layer, selected );
3097
3098 context.setFlag( Qgis::RenderContextFlag::RenderingSubSymbol, prevIsSubsymbol );
3099}
3100
3102{
3103 return mHashAngle;
3104}
3105
3107{
3108 mHashAngle = angle;
3109}
3110
3112{
3113 const double prevOpacity = mHashSymbol->opacity();
3114 mHashSymbol->setOpacity( mHashSymbol->opacity() * context.opacity() );
3116 mHashSymbol->setOpacity( prevOpacity );
3117}
3118
3119//
3120// QgsAbstractBrushedLineSymbolLayer
3121//
3122
3123void QgsAbstractBrushedLineSymbolLayer::renderPolylineUsingBrush( const QPolygonF &points, QgsSymbolRenderContext &context, const QBrush &brush, double patternThickness, double patternLength )
3124{
3125 if ( !context.renderContext().painter() )
3126 return;
3127
3128 double offset = mOffset;
3130 {
3133 }
3134
3135 QPolygonF offsetPoints;
3136 if ( qgsDoubleNear( offset, 0 ) )
3137 {
3138 renderLine( points, context, patternThickness, patternLength, brush );
3139 }
3140 else
3141 {
3142 const double scaledOffset = context.renderContext().convertToPainterUnits( offset, mOffsetUnit, mOffsetMapUnitScale );
3143
3144 const QList<QPolygonF> offsetLine = ::offsetLine( points, scaledOffset, context.originalGeometryType() != Qgis::GeometryType::Unknown ? context.originalGeometryType() : Qgis::GeometryType::Line );
3145 for ( const QPolygonF &part : offsetLine )
3146 {
3147 renderLine( part, context, patternThickness, patternLength, brush );
3148 }
3149 }
3150}
3151
3152void QgsAbstractBrushedLineSymbolLayer::renderLine( const QPolygonF &points, QgsSymbolRenderContext &context, const double lineThickness, const double patternLength, const QBrush &sourceBrush )
3153{
3154 QPainter *p = context.renderContext().painter();
3155 if ( !p )
3156 return;
3157
3158 QBrush brush = sourceBrush;
3159
3160 // duplicate points mess up the calculations, we need to remove them first
3161 // we'll calculate the min/max coordinate at the same time, since we're already looping
3162 // through the points
3163 QPolygonF inputPoints;
3164 inputPoints.reserve( points.size() );
3165 QPointF prev;
3166 double minX = std::numeric_limits< double >::max();
3167 double minY = std::numeric_limits< double >::max();
3168 double maxX = std::numeric_limits< double >::lowest();
3169 double maxY = std::numeric_limits< double >::lowest();
3170
3171 for ( const QPointF &pt : std::as_const( points ) )
3172 {
3173 if ( !inputPoints.empty() && qgsDoubleNear( prev.x(), pt.x(), 0.01 ) && qgsDoubleNear( prev.y(), pt.y(), 0.01 ) )
3174 continue;
3175
3176 inputPoints << pt;
3177 prev = pt;
3178 minX = std::min( minX, pt.x() );
3179 minY = std::min( minY, pt.y() );
3180 maxX = std::max( maxX, pt.x() );
3181 maxY = std::max( maxY, pt.y() );
3182 }
3183
3184 if ( inputPoints.size() < 2 ) // nothing to render
3185 return;
3186
3187 // buffer size to extend out the temporary image, just to ensure that we don't clip out any antialiasing effects
3188 constexpr int ANTIALIAS_ALLOWANCE_PIXELS = 10;
3189 // amount of overlap to use when rendering adjacent line segments to ensure that no artifacts are visible between segments
3190 constexpr double ANTIALIAS_OVERLAP_PIXELS = 0.5;
3191
3192 // our temporary image needs to extend out by the line thickness on each side, and we'll also add an allowance for antialiasing effects on each side
3193 const int imageWidth = static_cast< int >( std::ceil( maxX - minX ) + lineThickness * 2 ) + ANTIALIAS_ALLOWANCE_PIXELS * 2;
3194 const int imageHeight = static_cast< int >( std::ceil( maxY - minY ) + lineThickness * 2 ) + ANTIALIAS_ALLOWANCE_PIXELS * 2;
3195
3196 const bool isClosedLine = qgsDoubleNear( points.at( 0 ).x(), points.constLast().x(), 0.01 ) && qgsDoubleNear( points.at( 0 ).y(), points.constLast().y(), 0.01 );
3197
3198 QImage temporaryImage( imageWidth, imageHeight, QImage::Format_ARGB32_Premultiplied );
3199 if ( temporaryImage.isNull() )
3200 {
3201 QgsMessageLog::logMessage( QObject::tr( "Could not allocate sufficient memory for raster line symbol" ) );
3202 return;
3203 }
3204
3205 // clear temporary image contents
3206 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
3207 return;
3208 temporaryImage.fill( Qt::transparent );
3209 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
3210 return;
3211
3212 Qt::PenJoinStyle join = mPenJoinStyle;
3214 {
3217 if ( !QgsVariantUtils::isNull( exprVal ) )
3218 join = QgsSymbolLayerUtils::decodePenJoinStyle( exprVal.toString() );
3219 }
3220
3221 Qt::PenCapStyle cap = mPenCapStyle;
3223 {
3226 if ( !QgsVariantUtils::isNull( exprVal ) )
3227 cap = QgsSymbolLayerUtils::decodePenCapStyle( exprVal.toString() );
3228 }
3229
3230 // stroke out the path using the correct line cap/join style. We'll then use this as a clipping path
3231 QPainterPathStroker stroker;
3232 stroker.setWidth( lineThickness );
3233 stroker.setCapStyle( cap );
3234 stroker.setJoinStyle( join );
3235
3236 QPainterPath path;
3237 path.addPolygon( inputPoints );
3238 const QPainterPath stroke = stroker.createStroke( path ).simplified();
3239
3240 // prepare temporary image
3241 QPainter imagePainter;
3242 imagePainter.begin( &temporaryImage );
3243 context.renderContext().setPainterFlagsUsingContext( &imagePainter );
3244 imagePainter.translate( -minX + lineThickness + ANTIALIAS_ALLOWANCE_PIXELS, -minY + lineThickness + ANTIALIAS_ALLOWANCE_PIXELS );
3245
3246 imagePainter.setClipPath( stroke, Qt::IntersectClip );
3247 imagePainter.setPen( Qt::NoPen );
3248
3249 QPointF segmentStartPoint = inputPoints.at( 0 );
3250
3251 // current brush progress through the image (horizontally). Used to track which column of image data to start the next brush segment using.
3252 double progressThroughImage = 0;
3253
3254 QgsPoint prevSegmentPolygonEndLeft;
3255 QgsPoint prevSegmentPolygonEndRight;
3256
3257 // for closed rings this will store the left/right polygon points of the start/end of the line
3258 QgsPoint startLinePolygonLeft;
3259 QgsPoint startLinePolygonRight;
3260
3261 for ( int i = 1; i < inputPoints.size(); ++i )
3262 {
3263 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
3264 break;
3265
3266 const QPointF segmentEndPoint = inputPoints.at( i );
3267 const double segmentAngleDegrees = 180.0 / M_PI * QgsGeometryUtilsBase::lineAngle( segmentStartPoint.x(), segmentStartPoint.y(), segmentEndPoint.x(), segmentEndPoint.y() ) - 90;
3268
3269 // left/right end points of the current segment polygon
3270 QgsPoint thisSegmentPolygonEndLeft;
3271 QgsPoint thisSegmentPolygonEndRight;
3272 // left/right end points of the current segment polygon, tweaked to avoid antialiasing artifacts
3273 QgsPoint thisSegmentPolygonEndLeftForPainter;
3274 QgsPoint thisSegmentPolygonEndRightForPainter;
3275 if ( i == 1 )
3276 {
3277 // first line segment has special handling -- we extend back out by half the image thickness so that the line cap is correctly drawn.
3278 // (unless it's a closed line, that is. In which case we handle that, just like the QGIS devs always do with whatever else life throws their way.)
3279 if ( isClosedLine )
3280 {
3281 // project the current segment out by half the image thickness to either side of the line
3282 const QgsPoint startPointLeft = QgsPoint( segmentStartPoint ).project( lineThickness / 2, segmentAngleDegrees );
3283 const QgsPoint endPointLeft = QgsPoint( segmentEndPoint ).project( lineThickness / 2, segmentAngleDegrees );
3284 const QgsPoint startPointRight = QgsPoint( segmentStartPoint ).project( -lineThickness / 2, segmentAngleDegrees );
3285 const QgsPoint endPointRight = QgsPoint( segmentEndPoint ).project( -lineThickness / 2, segmentAngleDegrees );
3286
3287 // angle of LAST line segment in the whole line (i.e. the one which will eventually connect back to the first point in the line). Used to determine
3288 // what angle the current segment polygon should START on.
3289 const double lastSegmentAngleDegrees = 180.0
3290 / M_PI
3291 * QgsGeometryUtilsBase::lineAngle( points.at( points.size() - 2 ).x(), points.at( points.size() - 2 ).y(), segmentStartPoint.x(), segmentStartPoint.y() )
3292 - 90;
3293
3294 // project out the LAST segment in the line by half the image thickness to either side of the line
3295 const QgsPoint lastSegmentStartPointLeft = QgsPoint( points.at( points.size() - 2 ) ).project( lineThickness / 2, lastSegmentAngleDegrees );
3296 const QgsPoint lastSegmentEndPointLeft = QgsPoint( segmentStartPoint ).project( lineThickness / 2, lastSegmentAngleDegrees );
3297 const QgsPoint lastSegmentStartPointRight = QgsPoint( points.at( points.size() - 2 ) ).project( -lineThickness / 2, lastSegmentAngleDegrees );
3298 const QgsPoint lastSegmentEndPointRight = QgsPoint( segmentStartPoint ).project( -lineThickness / 2, lastSegmentAngleDegrees );
3299
3300 // the polygon representing the current segment STARTS at the points where the projected lines to the left/right
3301 // of THIS segment would intersect with the project lines to the left/right of the VERY LAST segment in the line (i.e. simulate a miter style
3302 // join)
3303 QgsPoint intersectionPoint;
3304 bool isIntersection = false;
3305 QgsGeometryUtils::segmentIntersection( lastSegmentStartPointLeft, lastSegmentEndPointLeft, startPointLeft, endPointLeft, prevSegmentPolygonEndLeft, isIntersection, 1e-8, true );
3306 if ( !isIntersection )
3307 prevSegmentPolygonEndLeft = startPointLeft;
3308 isIntersection = false;
3309 QgsGeometryUtils::segmentIntersection( lastSegmentStartPointRight, lastSegmentEndPointRight, startPointRight, endPointRight, prevSegmentPolygonEndRight, isIntersection, 1e-8, true );
3310 if ( !isIntersection )
3311 prevSegmentPolygonEndRight = startPointRight;
3312
3313 startLinePolygonLeft = prevSegmentPolygonEndLeft;
3314 startLinePolygonRight = prevSegmentPolygonEndRight;
3315 }
3316 else
3317 {
3318 prevSegmentPolygonEndLeft = QgsPoint( segmentStartPoint ).project( lineThickness / 2, segmentAngleDegrees );
3319 if ( cap != Qt::PenCapStyle::FlatCap )
3320 prevSegmentPolygonEndLeft = prevSegmentPolygonEndLeft.project( lineThickness / 2, segmentAngleDegrees - 90 );
3321 prevSegmentPolygonEndRight = QgsPoint( segmentStartPoint ).project( -lineThickness / 2, segmentAngleDegrees );
3322 if ( cap != Qt::PenCapStyle::FlatCap )
3323 prevSegmentPolygonEndRight = prevSegmentPolygonEndRight.project( lineThickness / 2, segmentAngleDegrees - 90 );
3324 }
3325 }
3326
3327 if ( i < inputPoints.size() - 1 )
3328 {
3329 // for all other segments except the last
3330
3331 // project the current segment out by half the image thickness to either side of the line
3332 const QgsPoint startPointLeft = QgsPoint( segmentStartPoint ).project( lineThickness / 2, segmentAngleDegrees );
3333 const QgsPoint endPointLeft = QgsPoint( segmentEndPoint ).project( lineThickness / 2, segmentAngleDegrees );
3334 const QgsPoint startPointRight = QgsPoint( segmentStartPoint ).project( -lineThickness / 2, segmentAngleDegrees );
3335 const QgsPoint endPointRight = QgsPoint( segmentEndPoint ).project( -lineThickness / 2, segmentAngleDegrees );
3336
3337 // angle of NEXT line segment (i.e. not the one we are drawing right now). Used to determine
3338 // what angle the current segment polygon should end on
3339 const double nextSegmentAngleDegrees = 180.0 / M_PI * QgsGeometryUtilsBase::lineAngle( segmentEndPoint.x(), segmentEndPoint.y(), inputPoints.at( i + 1 ).x(), inputPoints.at( i + 1 ).y() ) - 90;
3340
3341 // project out the next segment by half the image thickness to either side of the line
3342 const QgsPoint nextSegmentStartPointLeft = QgsPoint( segmentEndPoint ).project( lineThickness / 2, nextSegmentAngleDegrees );
3343 const QgsPoint nextSegmentEndPointLeft = QgsPoint( inputPoints.at( i + 1 ) ).project( lineThickness / 2, nextSegmentAngleDegrees );
3344 const QgsPoint nextSegmentStartPointRight = QgsPoint( segmentEndPoint ).project( -lineThickness / 2, nextSegmentAngleDegrees );
3345 const QgsPoint nextSegmentEndPointRight = QgsPoint( inputPoints.at( i + 1 ) ).project( -lineThickness / 2, nextSegmentAngleDegrees );
3346
3347 // the polygon representing the current segment ends at the points where the projected lines to the left/right
3348 // of THIS segment would intersect with the project lines to the left/right of the NEXT segment (i.e. simulate a miter style
3349 // join)
3350 QgsPoint intersectionPoint;
3351 bool isIntersection = false;
3352 QgsGeometryUtils::segmentIntersection( startPointLeft, endPointLeft, nextSegmentStartPointLeft, nextSegmentEndPointLeft, thisSegmentPolygonEndLeft, isIntersection, 1e-8, true );
3353 if ( !isIntersection )
3354 thisSegmentPolygonEndLeft = endPointLeft;
3355 isIntersection = false;
3356 QgsGeometryUtils::segmentIntersection( startPointRight, endPointRight, nextSegmentStartPointRight, nextSegmentEndPointRight, thisSegmentPolygonEndRight, isIntersection, 1e-8, true );
3357 if ( !isIntersection )
3358 thisSegmentPolygonEndRight = endPointRight;
3359
3360 thisSegmentPolygonEndLeftForPainter = thisSegmentPolygonEndLeft.project( ANTIALIAS_OVERLAP_PIXELS, segmentAngleDegrees + 90 );
3361 thisSegmentPolygonEndRightForPainter = thisSegmentPolygonEndRight.project( ANTIALIAS_OVERLAP_PIXELS, segmentAngleDegrees + 90 );
3362 }
3363 else
3364 {
3365 // last segment has special handling -- we extend forward by half the image thickness so that the line cap is correctly drawn
3366 // unless it's a closed line
3367 if ( isClosedLine )
3368 {
3369 thisSegmentPolygonEndLeft = startLinePolygonLeft;
3370 thisSegmentPolygonEndRight = startLinePolygonRight;
3371
3372 thisSegmentPolygonEndLeftForPainter = thisSegmentPolygonEndLeft.project( ANTIALIAS_OVERLAP_PIXELS, segmentAngleDegrees + 90 );
3373 thisSegmentPolygonEndRightForPainter = thisSegmentPolygonEndRight.project( ANTIALIAS_OVERLAP_PIXELS, segmentAngleDegrees + 90 );
3374 }
3375 else
3376 {
3377 thisSegmentPolygonEndLeft = QgsPoint( segmentEndPoint ).project( lineThickness / 2, segmentAngleDegrees );
3378 if ( cap != Qt::PenCapStyle::FlatCap )
3379 thisSegmentPolygonEndLeft = thisSegmentPolygonEndLeft.project( lineThickness / 2, segmentAngleDegrees + 90 );
3380 thisSegmentPolygonEndRight = QgsPoint( segmentEndPoint ).project( -lineThickness / 2, segmentAngleDegrees );
3381 if ( cap != Qt::PenCapStyle::FlatCap )
3382 thisSegmentPolygonEndRight = thisSegmentPolygonEndRight.project( lineThickness / 2, segmentAngleDegrees + 90 );
3383
3384 thisSegmentPolygonEndLeftForPainter = thisSegmentPolygonEndLeft;
3385 thisSegmentPolygonEndRightForPainter = thisSegmentPolygonEndRight;
3386 }
3387 }
3388
3389 // brush transform is designed to draw the image starting at the correct current progress through it (following on from
3390 // where we got with the previous segment), at the correct angle
3391 QTransform brushTransform;
3392 brushTransform.translate( segmentStartPoint.x(), segmentStartPoint.y() );
3393 brushTransform.rotate( -segmentAngleDegrees );
3394 if ( i == 1 && cap != Qt::PenCapStyle::FlatCap )
3395 {
3396 // special handling for first segment -- because we extend the line back by half its thickness (to show the cap),
3397 // we need to also do the same for the brush transform
3398 brushTransform.translate( -( lineThickness / 2 ), 0 );
3399 }
3400 brushTransform.translate( -progressThroughImage, -lineThickness / 2 );
3401
3402 brush.setTransform( brushTransform );
3403 imagePainter.setBrush( brush );
3404
3405 // now draw the segment polygon
3406 imagePainter.drawPolygon(
3407 QPolygonF()
3408 << prevSegmentPolygonEndLeft.toQPointF()
3409 << thisSegmentPolygonEndLeftForPainter.toQPointF()
3410 << thisSegmentPolygonEndRightForPainter.toQPointF()
3411 << prevSegmentPolygonEndRight.toQPointF()
3412 << prevSegmentPolygonEndLeft.toQPointF()
3413 );
3414
3415#if 0 // for debugging, will draw the segment polygons
3416 imagePainter.setPen( QPen( QColor( 0, 255, 255 ), 2 ) );
3417 imagePainter.setBrush( Qt::NoBrush );
3418 imagePainter.drawPolygon( QPolygonF() << prevSegmentPolygonEndLeft.toQPointF()
3419 << thisSegmentPolygonEndLeftForPainter.toQPointF()
3420 << thisSegmentPolygonEndRightForPainter.toQPointF()
3421 << prevSegmentPolygonEndRight.toQPointF()
3422 << prevSegmentPolygonEndLeft.toQPointF() );
3423 imagePainter.setPen( Qt::NoPen );
3424#endif
3425
3426 // calculate the new progress horizontal through the source image to account for the length
3427 // of the segment we've just drawn
3428 progressThroughImage += sqrt( std::pow( segmentStartPoint.x() - segmentEndPoint.x(), 2 ) + std::pow( segmentStartPoint.y() - segmentEndPoint.y(), 2 ) )
3429 + ( i == 1 && cap != Qt::PenCapStyle::FlatCap ? lineThickness / 2 : 0 ); // for first point we extended the pattern out by half its thickess at the start
3430 progressThroughImage = fmod( progressThroughImage, patternLength );
3431
3432 // shuffle buffered variables for next loop
3433 segmentStartPoint = segmentEndPoint;
3434 prevSegmentPolygonEndLeft = thisSegmentPolygonEndLeft;
3435 prevSegmentPolygonEndRight = thisSegmentPolygonEndRight;
3436 }
3437 imagePainter.end();
3438
3439 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
3440 return;
3441
3442 // lastly, draw the temporary image onto the destination painter at the correct place
3443 p->drawImage( QPointF( minX - lineThickness - ANTIALIAS_ALLOWANCE_PIXELS, minY - lineThickness - ANTIALIAS_ALLOWANCE_PIXELS ), temporaryImage );
3444}
3445
3446
3447//
3448// QgsRasterLineSymbolLayer
3449//
3450
3454
3456
3457std::unique_ptr<QgsSymbolLayer> QgsRasterLineSymbolLayer::create( const QVariantMap &properties )
3458{
3459 auto res = std::make_unique<QgsRasterLineSymbolLayer>();
3460
3461 if ( properties.contains( u"line_width"_s ) )
3462 {
3463 res->setWidth( properties[u"line_width"_s].toDouble() );
3464 }
3465 if ( properties.contains( u"line_width_unit"_s ) )
3466 {
3467 res->setWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"line_width_unit"_s].toString() ) );
3468 }
3469 if ( properties.contains( u"width_map_unit_scale"_s ) )
3470 {
3471 res->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"width_map_unit_scale"_s].toString() ) );
3472 }
3473
3474 if ( properties.contains( u"imageFile"_s ) )
3475 res->setPath( properties[u"imageFile"_s].toString() );
3476
3477 if ( properties.contains( u"offset"_s ) )
3478 {
3479 res->setOffset( properties[u"offset"_s].toDouble() );
3480 }
3481 if ( properties.contains( u"offset_unit"_s ) )
3482 {
3483 res->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_unit"_s].toString() ) );
3484 }
3485 if ( properties.contains( u"offset_map_unit_scale"_s ) )
3486 {
3487 res->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_map_unit_scale"_s].toString() ) );
3488 }
3489
3490 if ( properties.contains( u"joinstyle"_s ) )
3491 res->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( properties[u"joinstyle"_s].toString() ) );
3492 if ( properties.contains( u"capstyle"_s ) )
3493 res->setPenCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( properties[u"capstyle"_s].toString() ) );
3494
3495 if ( properties.contains( u"alpha"_s ) )
3496 {
3497 res->setOpacity( properties[u"alpha"_s].toDouble() );
3498 }
3499
3500 return res;
3501}
3502
3503
3505{
3506 QVariantMap map;
3507 map[u"imageFile"_s] = mPath;
3508
3509 map[u"line_width"_s] = QString::number( mWidth );
3510 map[u"line_width_unit"_s] = QgsUnitTypes::encodeUnit( mWidthUnit );
3511 map[u"width_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale );
3512
3515
3516 map[u"offset"_s] = QString::number( mOffset );
3517 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
3518 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
3519
3520 map[u"alpha"_s] = QString::number( mOpacity );
3521
3522 return map;
3523}
3524
3526{
3527 auto res = std::make_unique< QgsRasterLineSymbolLayer >( mPath );
3528 res->setWidth( mWidth );
3529 res->setWidthUnit( mWidthUnit );
3530 res->setWidthMapUnitScale( mWidthMapUnitScale );
3531 res->setPenJoinStyle( mPenJoinStyle );
3532 res->setPenCapStyle( mPenCapStyle );
3533 res->setOffsetUnit( mOffsetUnit );
3534 res->setOffsetMapUnitScale( mOffsetMapUnitScale );
3535 res->setOffset( mOffset );
3536 res->setOpacity( mOpacity );
3537 copyCommonProperties( res.get() );
3538 return res.release();
3539}
3540
3541void QgsRasterLineSymbolLayer::resolvePaths( QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving )
3542{
3543 const QVariantMap::iterator it = properties.find( u"imageFile"_s );
3544 if ( it != properties.end() && it.value().userType() == QMetaType::Type::QString )
3545 {
3546 if ( saving )
3547 it.value() = QgsSymbolLayerUtils::svgSymbolPathToName( it.value().toString(), pathResolver );
3548 else
3549 it.value() = QgsSymbolLayerUtils::svgSymbolNameToPath( it.value().toString(), pathResolver );
3550 }
3551}
3552
3554{
3555 mPath = path;
3556}
3557
3559{
3560 return u"RasterLine"_s;
3561}
3562
3567
3569{
3570 double scaledHeight = context.renderContext().convertToPainterUnits( mWidth, mWidthUnit, mWidthMapUnitScale );
3571
3573
3574 double opacity = mOpacity * context.opacity();
3575 bool cached = false;
3577 mPath,
3578 QSize( static_cast< int >( std::round( originalSize.width() / originalSize.height() * std::max( 1.0, scaledHeight ) ) ), static_cast< int >( std::ceil( scaledHeight ) ) ),
3579 true,
3580 opacity,
3581 cached,
3583 );
3584}
3585
3588
3590{
3591 if ( !context.renderContext().painter() )
3592 return;
3593
3594 QImage sourceImage = mLineImage;
3598 {
3599 QString path = mPath;
3601 {
3602 context.setOriginalValueVariable( path );
3604 }
3605
3606 double strokeWidth = mWidth;
3608 {
3609 context.setOriginalValueVariable( strokeWidth );
3610 strokeWidth = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::StrokeWidth, context.renderContext().expressionContext(), strokeWidth );
3611 }
3612 const double scaledHeight = context.renderContext().convertToPainterUnits( strokeWidth, mWidthUnit, mWidthMapUnitScale );
3613
3615 double opacity = mOpacity;
3617 {
3620 }
3621 opacity *= context.opacity();
3622
3623 bool cached = false;
3624 sourceImage = QgsApplication::imageCache()->pathAsImage(
3625 path,
3626 QSize( static_cast< int >( std::round( originalSize.width() / originalSize.height() * std::max( 1.0, scaledHeight ) ) ), static_cast< int >( std::ceil( scaledHeight ) ) ),
3627 true,
3628 opacity,
3629 cached,
3631 );
3632 }
3633
3634 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
3635 if ( useSelectedColor )
3636 {
3638 }
3639
3640 const QBrush brush( sourceImage );
3641
3642 renderPolylineUsingBrush( points, context, brush, sourceImage.height(), sourceImage.width() );
3643}
3644
3651
3653{
3655 if ( mWidthUnit != unit || mOffsetUnit != unit )
3656 {
3658 }
3659 return unit;
3660}
3661
3666
3672
3681
3683{
3684 return ( mWidth / 2.0 ) + mOffset;
3685}
3686
3688{
3689 return QColor();
3690}
3691
3692
3693//
3694// QgsLineburstSymbolLayer
3695//
3696
3703
3705
3706std::unique_ptr<QgsSymbolLayer> QgsLineburstSymbolLayer::create( const QVariantMap &properties )
3707{
3708 auto res = std::make_unique<QgsLineburstSymbolLayer>();
3709
3710 if ( properties.contains( u"line_width"_s ) )
3711 {
3712 res->setWidth( properties[u"line_width"_s].toDouble() );
3713 }
3714 if ( properties.contains( u"line_width_unit"_s ) )
3715 {
3716 res->setWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"line_width_unit"_s].toString() ) );
3717 }
3718 if ( properties.contains( u"width_map_unit_scale"_s ) )
3719 {
3720 res->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"width_map_unit_scale"_s].toString() ) );
3721 }
3722
3723 if ( properties.contains( u"offset"_s ) )
3724 {
3725 res->setOffset( properties[u"offset"_s].toDouble() );
3726 }
3727 if ( properties.contains( u"offset_unit"_s ) )
3728 {
3729 res->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_unit"_s].toString() ) );
3730 }
3731 if ( properties.contains( u"offset_map_unit_scale"_s ) )
3732 {
3733 res->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_map_unit_scale"_s].toString() ) );
3734 }
3735
3736 if ( properties.contains( u"joinstyle"_s ) )
3737 res->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( properties[u"joinstyle"_s].toString() ) );
3738 if ( properties.contains( u"capstyle"_s ) )
3739 res->setPenCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( properties[u"capstyle"_s].toString() ) );
3740
3741 if ( properties.contains( u"color_type"_s ) )
3742 res->setGradientColorType( static_cast< Qgis::GradientColorSource >( properties[u"color_type"_s].toInt() ) );
3743
3744 if ( properties.contains( u"color"_s ) )
3745 {
3746 res->setColor( QgsColorUtils::colorFromString( properties[u"color"_s].toString() ) );
3747 }
3748 if ( properties.contains( u"gradient_color2"_s ) )
3749 {
3750 res->setColor2( QgsColorUtils::colorFromString( properties[u"gradient_color2"_s].toString() ) );
3751 }
3752
3753 //attempt to create color ramp from props
3754 if ( properties.contains( u"rampType"_s ) && properties[u"rampType"_s] == QgsCptCityColorRamp::typeString() )
3755 {
3756 res->setColorRamp( QgsCptCityColorRamp::create( properties ).release() );
3757 }
3758 else
3759 {
3760 res->setColorRamp( QgsGradientColorRamp::create( properties ).release() );
3761 }
3762
3763 return res;
3764}
3765
3767{
3768 QVariantMap map;
3769
3770 map[u"line_width"_s] = QString::number( mWidth );
3771 map[u"line_width_unit"_s] = QgsUnitTypes::encodeUnit( mWidthUnit );
3772 map[u"width_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale );
3773
3776
3777 map[u"offset"_s] = QString::number( mOffset );
3778 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
3779 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
3780
3781 map[u"color"_s] = QgsColorUtils::colorToString( mColor );
3782 map[u"gradient_color2"_s] = QgsColorUtils::colorToString( mColor2 );
3783 map[u"color_type"_s] = QString::number( static_cast< int >( mGradientColorType ) );
3784 if ( mGradientRamp )
3785 {
3786 map.insert( mGradientRamp->properties() );
3787 }
3788
3789 return map;
3790}
3791
3793{
3794 auto res = std::make_unique< QgsLineburstSymbolLayer >();
3795 res->setWidth( mWidth );
3796 res->setWidthUnit( mWidthUnit );
3797 res->setWidthMapUnitScale( mWidthMapUnitScale );
3798 res->setPenJoinStyle( mPenJoinStyle );
3799 res->setPenCapStyle( mPenCapStyle );
3800 res->setOffsetUnit( mOffsetUnit );
3801 res->setOffsetMapUnitScale( mOffsetMapUnitScale );
3802 res->setOffset( mOffset );
3803 res->setColor( mColor );
3804 res->setColor2( mColor2 );
3805 res->setGradientColorType( mGradientColorType );
3806 if ( mGradientRamp )
3807 res->setColorRamp( mGradientRamp->clone() );
3808 copyCommonProperties( res.get() );
3809 return res.release();
3810}
3811
3813{
3814 return u"Lineburst"_s;
3815}
3816
3821
3824
3827
3829{
3830 if ( !context.renderContext().painter() )
3831 return;
3832
3833 double strokeWidth = mWidth;
3835 {
3836 context.setOriginalValueVariable( strokeWidth );
3837 strokeWidth = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::StrokeWidth, context.renderContext().expressionContext(), strokeWidth );
3838 }
3839 const double scaledWidth = context.renderContext().convertToPainterUnits( strokeWidth, mWidthUnit, mWidthMapUnitScale );
3840
3841 //update alpha of gradient colors
3842 QColor color1 = mColor;
3844 {
3847 }
3848 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
3849 if ( useSelectedColor )
3850 {
3851 color1 = context.renderContext().selectionColor();
3852 }
3853 color1.setAlphaF( context.opacity() * color1.alphaF() );
3854
3855 //second gradient color
3856 QColor color2 = mColor2;
3858 {
3861 }
3862
3863 //create a QGradient with the desired properties
3864 QGradient gradient = QLinearGradient( QPointF( 0, 0 ), QPointF( 0, scaledWidth ) );
3865 //add stops to gradient
3867 && mGradientRamp
3869 {
3870 //color ramp gradient
3871 QgsGradientColorRamp *gradRamp = static_cast<QgsGradientColorRamp *>( mGradientRamp.get() );
3872 gradRamp->addStopsToGradient( &gradient, context.opacity() );
3873 }
3874 else
3875 {
3876 //two color gradient
3877 gradient.setColorAt( 0.0, color1 );
3878 gradient.setColorAt( 1.0, color2 );
3879 }
3880 const QBrush brush( gradient );
3881
3882 renderPolylineUsingBrush( points, context, brush, scaledWidth, 100 );
3883}
3884
3891
3893{
3895 if ( mWidthUnit != unit || mOffsetUnit != unit )
3896 {
3898 }
3899 return unit;
3900}
3901
3906
3912
3921
3923{
3924 return ( mWidth / 2.0 ) + mOffset;
3925}
3926
3931
3933{
3934 mGradientRamp.reset( ramp );
3935}
3936
3937//
3938// QgsFilledLineSymbolLayer
3939//
3940
3943{
3944 mWidth = width;
3945 mFill = fillSymbol ? std::unique_ptr< QgsFillSymbol >( fillSymbol ) : QgsFillSymbol::createSimple( QVariantMap() );
3946}
3947
3949
3950std::unique_ptr<QgsSymbolLayer> QgsFilledLineSymbolLayer::create( const QVariantMap &props )
3951{
3953
3954 // throughout the history of QGIS and different layer types, we've used
3955 // a huge range of different strings for the same property. The logic here
3956 // is designed to be forgiving to this and accept a range of string keys:
3957 if ( props.contains( u"line_width"_s ) )
3958 {
3959 width = props[u"line_width"_s].toDouble();
3960 }
3961 else if ( props.contains( u"outline_width"_s ) )
3962 {
3963 width = props[u"outline_width"_s].toDouble();
3964 }
3965 else if ( props.contains( u"width"_s ) )
3966 {
3967 width = props[u"width"_s].toDouble();
3968 }
3969
3970 auto l = std::make_unique< QgsFilledLineSymbolLayer >( width, QgsFillSymbol::createSimple( props ).release() );
3971
3972 if ( props.contains( u"line_width_unit"_s ) )
3973 {
3974 l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"line_width_unit"_s].toString() ) );
3975 }
3976 else if ( props.contains( u"outline_width_unit"_s ) )
3977 {
3978 l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"outline_width_unit"_s].toString() ) );
3979 }
3980 else if ( props.contains( u"width_unit"_s ) )
3981 {
3982 l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"width_unit"_s].toString() ) );
3983 }
3984
3985 if ( props.contains( u"width_map_unit_scale"_s ) )
3986 l->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"width_map_unit_scale"_s].toString() ) );
3987 if ( props.contains( u"offset"_s ) )
3988 l->setOffset( props[u"offset"_s].toDouble() );
3989 if ( props.contains( u"offset_unit"_s ) )
3990 l->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[u"offset_unit"_s].toString() ) );
3991 if ( props.contains( u"offset_map_unit_scale"_s ) )
3992 l->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"offset_map_unit_scale"_s].toString() ) );
3993 if ( props.contains( u"joinstyle"_s ) )
3994 l->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( props[u"joinstyle"_s].toString() ) );
3995 if ( props.contains( u"capstyle"_s ) )
3996 l->setPenCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( props[u"capstyle"_s].toString() ) );
3997
3998 l->restoreOldDataDefinedProperties( props );
3999
4000 return l;
4001}
4002
4004{
4005 return u"FilledLine"_s;
4006}
4007
4009{
4010 if ( mFill )
4011 {
4012 mFill->setRenderHints( mFill->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
4013 mFill->startRender( context.renderContext(), context.fields() );
4014 }
4015}
4016
4018{
4019 if ( mFill )
4020 {
4021 mFill->stopRender( context.renderContext() );
4022 }
4023}
4024
4026{
4027 installMasks( context, true );
4028
4029 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
4030}
4031
4033{
4034 removeMasks( context, true );
4035
4036 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
4037}
4038
4040{
4041 QPainter *p = context.renderContext().painter();
4042 if ( !p || !mFill )
4043 return;
4044
4045 double width = mWidth;
4047 {
4050 }
4051
4052 const double scaledWidth = context.renderContext().convertToPainterUnits( width, mWidthUnit, mWidthMapUnitScale );
4053
4054 Qt::PenJoinStyle join = mPenJoinStyle;
4056 {
4059 if ( !QgsVariantUtils::isNull( exprVal ) )
4060 join = QgsSymbolLayerUtils::decodePenJoinStyle( exprVal.toString() );
4061 }
4062
4063 Qt::PenCapStyle cap = mPenCapStyle;
4065 {
4068 if ( !QgsVariantUtils::isNull( exprVal ) )
4069 cap = QgsSymbolLayerUtils::decodePenCapStyle( exprVal.toString() );
4070 }
4071
4072 double offset = mOffset;
4074 {
4077 }
4078
4079 const double prevOpacity = mFill->opacity();
4080 mFill->setOpacity( mFill->opacity() * context.opacity() );
4081
4082 const bool prevIsSubsymbol = context.renderContext().flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
4084
4085 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
4086
4087 if ( points.count() >= 2 )
4088 {
4089 std::unique_ptr< QgsAbstractGeometry > ls = QgsLineString::fromQPolygonF( points );
4090 geos::unique_ptr lineGeom;
4091
4092 if ( !qgsDoubleNear( offset, 0 ) )
4093 {
4094 double scaledOffset = context.renderContext().convertToPainterUnits( offset, mOffsetUnit, mOffsetMapUnitScale );
4097 {
4098 // rendering for symbol previews -- a size in meters in map units can't be calculated, so treat the size as millimeters
4099 // and clamp it to a reasonable range. It's the best we can do in this situation!
4100 scaledOffset = std::min( std::max( context.renderContext().convertToPainterUnits( offset, Qgis::RenderUnit::Millimeters ), 3.0 ), 100.0 );
4101 }
4102
4104 if ( geometryType == Qgis::GeometryType::Polygon )
4105 {
4106 auto inputPoly = std::make_unique< QgsPolygon >( static_cast< QgsLineString * >( ls.release() ) );
4107 geos::unique_ptr g( QgsGeos::asGeos( inputPoly.get() ) );
4108 lineGeom = QgsGeos::buffer( g.get(), -scaledOffset, 0, Qgis::EndCapStyle::Flat, Qgis::JoinStyle::Miter, 2, nullptr, context.renderContext().feedback() );
4109 // the result is a polygon => extract line work
4110 QgsGeometry polygon( QgsGeos::fromGeos( lineGeom.get() ) );
4111 QVector<QgsGeometry> parts = polygon.coerceToType( Qgis::WkbType::MultiLineString );
4112 if ( !parts.empty() )
4113 {
4114 lineGeom = QgsGeos::asGeos( parts.at( 0 ).constGet() );
4115 }
4116 else
4117 {
4118 lineGeom.reset();
4119 }
4120 }
4121 else
4122 {
4123 geos::unique_ptr g( QgsGeos::asGeos( ls.get() ) );
4124 lineGeom = QgsGeos::offsetCurve( g.get(), scaledOffset, 0, Qgis::JoinStyle::Miter, 8.0 );
4125 }
4126 }
4127 else
4128 {
4129 lineGeom = QgsGeos::asGeos( ls.get() );
4130 }
4131
4132 if ( lineGeom )
4133 {
4134 geos::unique_ptr buffered = QgsGeos::
4135 buffer( lineGeom.get(), scaledWidth / 2, 8, QgsSymbolLayerUtils::penCapStyleToEndCapStyle( cap ), QgsSymbolLayerUtils::penJoinStyleToJoinStyle( join ), 8, nullptr, context.renderContext().feedback() );
4136 if ( buffered )
4137 {
4138 // convert to rings
4139 std::unique_ptr< QgsAbstractGeometry > bufferedGeom = QgsGeos::fromGeos( buffered.get() );
4140 const QList< QList< QPolygonF > > parts = QgsSymbolLayerUtils::toQPolygonF( bufferedGeom.get(), Qgis::SymbolType::Fill );
4141 for ( const QList< QPolygonF > &polygon : parts )
4142 {
4143 QVector< QPolygonF > rings;
4144 for ( int i = 1; i < polygon.size(); ++i )
4145 rings << polygon.at( i );
4146 mFill->renderPolygon( polygon.value( 0 ), &rings, context.feature(), context.renderContext(), -1, useSelectedColor );
4147 }
4148 }
4149 }
4150 }
4151
4153
4154 mFill->setOpacity( prevOpacity );
4155}
4156
4158{
4159 QVariantMap map;
4160
4161 map[u"line_width"_s] = QString::number( mWidth );
4162 map[u"line_width_unit"_s] = QgsUnitTypes::encodeUnit( mWidthUnit );
4163 map[u"width_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale );
4164 map[u"joinstyle"_s] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle );
4165 map[u"capstyle"_s] = QgsSymbolLayerUtils::encodePenCapStyle( mPenCapStyle );
4166 map[u"offset"_s] = QString::number( mOffset );
4167 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
4168 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
4169 if ( mFill )
4170 {
4171 map[u"color"_s] = QgsColorUtils::colorToString( mFill->color() );
4172 }
4173 return map;
4174}
4175
4177{
4178 auto res = qgis::unique_ptr_static_cast<QgsFilledLineSymbolLayer>( QgsFilledLineSymbolLayer::create( properties() ) );
4179 copyCommonProperties( res.get() );
4180 res->setSubSymbol( mFill->clone() );
4181 return res.release();
4182}
4183
4185{
4186 return mFill.get();
4187}
4188
4190{
4191 if ( symbol && symbol->type() == Qgis::SymbolType::Fill )
4192 {
4193 mFill.reset( static_cast<QgsFillSymbol *>( symbol ) );
4194 return true;
4195 }
4196 else
4197 {
4198 delete symbol;
4199 return false;
4200 }
4201}
4202
4204{
4205 if ( mFill )
4206 {
4207 return QgsSymbolLayerUtils::estimateMaxSymbolBleed( mFill.get(), context );
4208 }
4209 return 0;
4210}
4211
4213{
4214 QSet<QString> attr = QgsLineSymbolLayer::usedAttributes( context );
4215 if ( mFill )
4216 attr.unite( mFill->usedAttributes( context ) );
4217 return attr;
4218}
4219
4221{
4223 return true;
4224 if ( mFill && mFill->hasDataDefinedProperties() )
4225 return true;
4226 return false;
4227}
4228
4230{
4231 mColor = c;
4232 if ( mFill )
4233 mFill->setColor( c );
4234}
4235
4237{
4238 return mFill ? mFill->color() : mColor;
4239}
4240
4249
4251{
4253 if ( mFill )
4254 mFill->setMapUnitScale( scale );
4255}
4256
4258{
4259 if ( mFill )
4260 {
4261 return mFill->mapUnitScale();
4262 }
4263 return QgsMapUnitScale();
4264}
4265
4267{
4269 if ( mFill )
4270 mFill->setOutputUnit( unit );
4271}
4272
4274{
4275 if ( mFill )
4276 {
4277 return mFill->outputUnit();
4278 }
4280}
MarkerLinePlacement
Defines how/where the symbols should be placed on a line.
Definition qgis.h:3379
@ CurvePoint
Place symbols at every virtual curve point in the line (used when rendering curved geometry types onl...
Definition qgis.h:3385
@ InnerVertices
Inner vertices (i.e. all vertices except the first and last vertex).
Definition qgis.h:3387
@ LastVertex
Place symbols on the last vertex in the line.
Definition qgis.h:3382
@ CentralPoint
Place symbols at the mid point of the line.
Definition qgis.h:3384
@ SegmentCenter
Place symbols at the center of every line segment.
Definition qgis.h:3386
@ Vertex
Place symbols on every vertex in the line.
Definition qgis.h:3381
@ Interval
Place symbols at regular intervals.
Definition qgis.h:3380
@ FirstVertex
Place symbols on the first vertex in the line.
Definition qgis.h:3383
@ DynamicRotation
Rotation of symbol may be changed during rendering and symbol should not be cached.
Definition qgis.h:831
@ IsSymbolLayerSubSymbol
Symbol is being rendered as a sub-symbol of a QgsSymbolLayer.
Definition qgis.h:832
@ AntialiasingSimplification
The geometries can be rendered with 'AntiAliasing' disabled because of it is '1-pixel size'.
Definition qgis.h:3269
GradientColorSource
Gradient color sources.
Definition qgis.h:3428
@ ColorRamp
Gradient color ramp.
Definition qgis.h:3430
@ CanCalculateMaskGeometryPerFeature
If present, indicates that mask geometry can safely be calculated per feature for the symbol layer....
Definition qgis.h:964
@ Curve
An intermediate point on a segment defining the curvature of the segment.
Definition qgis.h:3317
@ Segment
The actual start or end point of a segment.
Definition qgis.h:3316
QFlags< SymbolLayerFlag > SymbolLayerFlags
Symbol layer flags.
Definition qgis.h:969
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:399
@ Line
Lines.
Definition qgis.h:401
@ Polygon
Polygons.
Definition qgis.h:402
@ Unknown
Unknown types.
Definition qgis.h:403
@ Miter
Use mitered joins.
Definition qgis.h:2295
RenderUnit
Rendering size units.
Definition qgis.h:5770
@ Percentage
Percentage of another measurement (e.g., canvas size, feature size).
Definition qgis.h:5774
@ Millimeters
Millimeters.
Definition qgis.h:5771
@ Points
Points (e.g., for font sizes).
Definition qgis.h:5775
@ Unknown
Mixed or unknown units.
Definition qgis.h:5777
@ MapUnits
Map units.
Definition qgis.h:5772
@ Pixels
Pixels.
Definition qgis.h:5773
@ Inches
Inches.
Definition qgis.h:5776
@ MetersInMapUnits
Meters value as Map units.
Definition qgis.h:5778
@ Flat
Flat cap (in line with start/end of line).
Definition qgis.h:2282
@ RenderingSubSymbol
Set whenever a sub-symbol of a parent symbol is currently being rendered. Can be used during symbol a...
Definition qgis.h:2993
@ RenderSymbolPreview
The render is for a symbol preview only and map based properties may not be available,...
Definition qgis.h:2988
@ RenderLayerTree
The render is for a layer tree display where map based properties are not available and where avoidan...
Definition qgis.h:2999
@ RenderBlocking
Render and load remote sources in the same thread to ensure rendering remote sources (svg and images)...
Definition qgis.h:2987
QFlags< SymbolRenderHint > SymbolRenderHints
Symbol render hints.
Definition qgis.h:838
@ Marker
Marker symbol.
Definition qgis.h:672
@ Line
Line symbol.
Definition qgis.h:673
@ Fill
Fill symbol.
Definition qgis.h:674
@ MultiLineString
MultiLineString.
Definition qgis.h:321
QFlags< MarkerLinePlacement > MarkerLinePlacements
Definition qgis.h:3390
Base class for line symbol layer types which draws line sections using a QBrush.
void renderPolylineUsingBrush(const QPolygonF &points, QgsSymbolRenderContext &context, const QBrush &brush, double patternThickness, double patternLength)
Renders a polyline of points using the specified brush.
static bool isGeneralizableByDeviceBoundingBox(const QgsRectangle &envelope, float mapToPixelTol=1.0f)
Returns whether the device-envelope can be replaced by its BBOX when is applied the specified toleran...
virtual double vertexAngle(QgsVertexId vertex) const =0
Returns approximate angle at a vertex.
virtual int nCoordinates() const
Returns the number of nodes contained in the geometry.
virtual bool hasCurvedSegments() const
Returns true if the geometry contains curved segments.
virtual bool nextVertex(QgsVertexId &id, QgsPoint &vertex) const =0
Returns next vertex id and coordinates.
double valueAsDouble(int key, const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a double.
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images.
Abstract base class for color ramps.
static QColor colorFromString(const QString &string)
Decodes a string into a color value.
static QString colorToString(const QColor &color)
Encodes a color into a string value.
void transformInPlace(double &x, double &y, double &z, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transforms an array of x, y and z double coordinates in place, from the source CRS to the destination...
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
static QString typeString()
Returns the string identifier for QgsCptCityColorRamp.
static std::unique_ptr< QgsColorRamp > create(const QVariantMap &properties=QVariantMap())
Creates the symbol layer.
Curve polygon geometry type.
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.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
static const QString EXPR_GEOMETRY_POINT_COUNT
Inbuilt variable name for point count variable.
static const QString EXPR_GEOMETRY_POINT_NUM
Inbuilt variable name for point number variable.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
static const QString EXPR_GEOMETRY_RING_NUM
Inbuilt variable name for geometry ring number variable.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
A fill symbol type, for rendering Polygon and MultiPolygon geometries.
static std::unique_ptr< QgsFillSymbol > createSimple(const QVariantMap &properties)
Create a fill symbol with one symbol layer: SimpleFill with specified properties.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
void renderPolyline(const QPolygonF &points, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the line joining points, using the given render context.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QString layerType() const override
Returns a string that represents this layer type.
bool setSubSymbol(QgsSymbol *symbol) override
Sets layer's subsymbol. takes ownership of the passed symbol.
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsFilledLineSymbolLayer, using the settings serialized in the properties map (correspo...
~QgsFilledLineSymbolLayer() override
QgsFilledLineSymbolLayer(double width=DEFAULT_SIMPLELINE_WIDTH, QgsFillSymbol *fillSymbol=nullptr)
Constructor for QgsFilledLineSymbolLayer.
void setMapUnitScale(const QgsMapUnitScale &scale) override
void setColor(const QColor &c) override
Sets the "representative" color for the symbol layer.
QColor color() const override
Returns the "representative" color of the symbol layer.
void stopFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called after the layer has been rendered for a particular feature.
void startFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called before the layer will be rendered for a particular feature.
QgsFilledLineSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
QgsMapUnitScale mapUnitScale() const override
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
static double lineAngle(double x1, double y1, double x2, double y2)
Calculates the direction of line joining two points in radians, clockwise from the north direction.
static bool segmentIntersection(const QgsPoint &p1, const QgsPoint &p2, const QgsPoint &q1, const QgsPoint &q2, QgsPoint &intersectionPoint, bool &isIntersection, double tolerance=1e-8, bool acceptImproperIntersection=false)
Compute the intersection between two segments.
A geometry is the spatial representation of a feature.
QVector< QgsGeometry > coerceToType(Qgis::WkbType type, double defaultZ=0, double defaultM=0, bool avoidDuplicates=true) const
Attempts to coerce this geometry into the specified destination type.
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...
Definition qgsgeos.cpp:284
static geos::unique_ptr offsetCurve(const GEOSGeometry *geometry, double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr)
Directly calculates the offset curve for a GEOS geometry object and returns a GEOS geometry result.
Definition qgsgeos.cpp:3381
QgsAbstractGeometry * buffer(double distance, int segments, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Buffers the geometry.
Definition qgsgeos.cpp:2428
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
Definition qgsgeos.cpp:1722
Gradient color ramp, which smoothly interpolates between two colors and also supports optional extra ...
static std::unique_ptr< QgsColorRamp > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsColorRamp from a map of properties.
static QString typeString()
Returns the string identifier for QgsGradientColorRamp.
void addStopsToGradient(QGradient *gradient, double opacity=1) const
Copy color ramp stops to a QGradient.
double hashAngle() const
Returns the angle to use when drawing the hashed lines sections, in degrees clockwise.
QgsHashedLineSymbolLayer(bool rotateSymbol=true, double interval=3)
Constructor for QgsHashedLineSymbolLayer.
bool setSubSymbol(QgsSymbol *symbol) override
Sets layer's subsymbol. takes ownership of the passed symbol.
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
void setWidth(double width) override
Sets the width of the line symbol layer.
double symbolAngle() const override
Returns the symbol's current angle, in degrees clockwise.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
double width() const override
Returns the estimated width for the line symbol layer.
void setDataDefinedProperty(QgsSymbolLayer::Property key, const QgsProperty &property) override
Sets a data defined property for the layer.
void setSymbolLineAngle(double angle) override
Sets the line angle modification for the symbol's angle.
void setSymbolAngle(double angle) override
Sets the symbol's angle, in degrees clockwise.
void renderPolyline(const QPolygonF &points, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the line joining points, using the given render context.
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
QgsHashedLineSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
~QgsHashedLineSymbolLayer() override
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
QColor color() const override
Returns the "representative" color of the symbol layer.
void renderSymbol(const QPointF &point, const QgsFeature *feature, QgsRenderContext &context, int layer=-1, bool selected=false) override
Renders the templated symbol at the specified point, using the given render context.
void setColor(const QColor &color) override
Sets the "representative" color for the symbol layer.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsHashedLineSymbolLayer, using the settings serialized in the properties map (correspo...
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QString layerType() const override
Returns a string that represents this layer type.
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
void setHashAngle(double angle)
Sets the angle to use when drawing the hashed lines sections, in degrees clockwise.
QSize originalSize(const QString &path, bool blocking=false) const
Returns the original size (in pixels) of the image at the specified path.
QImage pathAsImage(const QString &path, const QSize size, const bool keepAspectRatio, const double opacity, bool &fitsInCache, bool blocking=false, double targetDpi=96, int frameNumber=-1, bool *isMissing=nullptr)
Returns the specified path rendered as an image.
static void overlayColor(QImage &image, const QColor &color)
Overlays a color onto an image.
Line string geometry type, with support for z-dimension and m-values.
static std::unique_ptr< QgsLineString > fromQPolygonF(const QPolygonF &polygon)
Returns a new linestring from a QPolygonF polygon input.
Qgis::RenderUnit mOffsetUnit
RenderRingFilter
Options for filtering rings when the line symbol layer is being used to render a polygon's rings.
@ ExteriorRingOnly
Render the exterior ring only.
@ InteriorRingsOnly
Render the interior rings only.
@ AllRings
Render both exterior and interior rings.
QgsMapUnitScale mWidthMapUnitScale
QgsLineSymbolLayer(const QgsLineSymbolLayer &other)=delete
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
void setWidthMapUnitScale(const QgsMapUnitScale &scale)
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
Qgis::RenderUnit mWidthUnit
void setOffset(double offset)
Sets the line's offset.
RenderRingFilter mRingFilter
void setOffsetUnit(Qgis::RenderUnit unit)
Sets the unit for the line's offset.
void setWidthUnit(Qgis::RenderUnit unit)
Sets the units for the line's width.
virtual double width() const
Returns the estimated width for the line symbol layer.
QgsMapUnitScale mOffsetMapUnitScale
void setOffsetMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the line's offset.
QgsMapUnitScale mapUnitScale() const override
void setRingFilter(QgsLineSymbolLayer::RenderRingFilter filter)
Sets the line symbol layer's ring filter, which controls which rings are rendered when the line symbo...
void setMapUnitScale(const QgsMapUnitScale &scale) override
double offset() const
Returns the line's offset.
Qgis::RenderUnit offsetUnit() const
Returns the units for the line's offset.
Qgis::RenderUnit widthUnit() const
Returns the units for the line's width.
A line symbol type, for rendering LineString and MultiLineString geometries.
std::unique_ptr< QgsColorRamp > mGradientRamp
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
void setColorRamp(QgsColorRamp *ramp)
Sets the color ramp used for the gradient line.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsLineburstSymbolLayer, using the settings serialized in the properties map (correspon...
QColor color2() const
Returns the color for endpoint of gradient, only used if the gradient color type is set to SimpleTwoC...
Qgis::GradientColorSource mGradientColorType
QString layerType() const override
Returns a string that represents this layer type.
~QgsLineburstSymbolLayer() override
QgsLineburstSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
void setMapUnitScale(const QgsMapUnitScale &scale) override
QgsMapUnitScale mapUnitScale() const override
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
Qgis::SymbolLayerFlags flags() const override
Returns flags which control the symbol layer's behavior.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
QgsLineburstSymbolLayer(const QColor &color=DEFAULT_SIMPLELINE_COLOR, const QColor &color2=Qt::white)
Constructor for QgsLineburstSymbolLayer, with the specified start and end gradient colors.
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
QgsColorRamp * colorRamp()
Returns the color ramp used for the gradient line.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
void renderPolyline(const QPolygonF &points, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the line joining points, using the given render context.
Perform transforms between map coordinates and device coordinates.
void transformInPlace(double &x, double &y) const
Transforms map coordinates to device coordinates.
Struct for storing maximum and minimum scales for measurements in map units.
Q_DECL_DEPRECATED bool rotateMarker() const
Shall the marker be rotated.
std::unique_ptr< QgsMarkerSymbol > mMarker
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
Creates a new QgsMarkerLineSymbolLayer from an SLD XML DOM element.
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
QgsMarkerLineSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsMarkerLineSymbolLayer, using the settings serialized in the properties map (correspo...
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
void setDataDefinedProperty(QgsSymbolLayer::Property key, const QgsProperty &property) override
Sets a data defined property for the layer.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
void setColor(const QColor &color) override
Sets the "representative" color for the symbol layer.
double symbolAngle() const override
Returns the symbol's current angle, in degrees clockwise.
double width() const override
Returns the estimated width for the line symbol layer.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QgsMarkerLineSymbolLayer(bool rotateMarker=DEFAULT_MARKERLINE_ROTATE, double interval=DEFAULT_MARKERLINE_INTERVAL)
Constructor for QgsMarkerLineSymbolLayer.
void setWidth(double width) override
Sets the width of the line symbol layer.
QColor color() const override
Returns the "representative" color of the symbol layer.
void setSymbolLineAngle(double angle) override
Sets the line angle modification for the symbol's angle.
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
~QgsMarkerLineSymbolLayer() override
bool setSubSymbol(QgsSymbol *symbol) override
Sets layer's subsymbol. takes ownership of the passed symbol.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
QString layerType() const override
Returns a string that represents this layer type.
void renderPolyline(const QPolygonF &points, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the line joining points, using the given render context.
void setSymbolAngle(double angle) override
Sets the symbol's angle, in degrees clockwise.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
void renderSymbol(const QPointF &point, const QgsFeature *feature, QgsRenderContext &context, int layer=-1, bool selected=false) override
Renders the templated symbol at the specified point, using the given render context.
Abstract base class for marker symbol layers.
A marker symbol type, for rendering Point and MultiPoint geometries.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
Resolves relative paths into absolute paths and vice versa.
Represents a 2D point.
Definition qgspointxy.h:62
QgsPointXY project(double distance, double bearing) const
Returns a new point which corresponds to this point projected by a specified distance in a specified ...
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
QPointF toQPointF() const
Returns the point as a QPointF.
Definition qgspoint.h:426
double x
Definition qgspoint.h:56
QgsPoint project(double distance, double azimuth, double inclination=90.0) const
Returns a new point which corresponds to this point projected by a specified distance with specified ...
Definition qgspoint.cpp:743
double y
Definition qgspoint.h:57
A grouped map of multiple QgsProperty objects, each referenced by an integer key value.
bool isActive(int key) const final
Returns true if the collection contains an active property with the specified key.
A store for object properties.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
QgsRasterLineSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
double opacity() const
Returns the line opacity.
QString path() const
Returns the raster image path.
void setPath(const QString &path)
Set the raster image path.
QString layerType() const override
Returns a string that represents this layer type.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsRasterLineSymbolLayer, using the settings serialized in the properties map (correspo...
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
void renderPolyline(const QPolygonF &points, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the line joining points, using the given render context.
static void resolvePaths(QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving)
Turns relative paths in properties map to absolute when reading and vice versa when writing.
QgsRasterLineSymbolLayer(const QString &path=QString())
Constructor for QgsRasterLineSymbolLayer, with the specified raster image path.
Qgis::SymbolLayerFlags flags() const override
Returns flags which control the symbol layer's behavior.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
QColor color() const override
Returns the "representative" color of the symbol layer.
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
~QgsRasterLineSymbolLayer() override
void setMapUnitScale(const QgsMapUnitScale &scale) override
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
QgsMapUnitScale mapUnitScale() const override
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
Contains information about the context of a rendering operation.
double convertToMapUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
QgsVectorSimplifyMethod & vectorSimplifyMethod()
Returns the simplification settings to use when rendering vector layers.
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
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 ...
QgsExpressionContext & expressionContext()
Gets the expression context.
void setGeometry(const QgsAbstractGeometry *geometry)
Sets pointer to original (unsegmentized) geometry.
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QColor selectionColor() const
Returns the color to use when rendering selected features.
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly during rendering to check if rendering shou...
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
Qgis::RenderContextFlags flags() const
Returns combination of flags used for rendering.
const QgsAbstractGeometry * geometry() const
Returns pointer to the unsegmentized geometry.
Scoped object for saving and restoring a QPainter object's state.
@ NoSave
Do not save the current painter state.
void save()
Performs a manual save on the painter state, pushing another saved state to the painter.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
void setDrawInsidePolygon(bool drawInsidePolygon)
Sets whether the line should only be drawn inside polygons, and any portion of the line which falls o...
bool tweakDashPatternOnCorners() const
Returns true if dash patterns tweaks should be applied on sharp corners, to ensure that a double-leng...
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
Qgis::SymbolLayerFlags flags() const override
Returns flags which control the symbol layer's behavior.
void setPenCapStyle(Qt::PenCapStyle style)
Sets the pen cap style used to render the line (e.g.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
QgsMapUnitScale mapUnitScale() const override
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
QVector< qreal > customDashVector() const
Returns the custom dash vector, which is the pattern of alternating drawn/skipped lengths used while ...
Qt::PenJoinStyle penJoinStyle() const
Returns the pen join style used to render the line (e.g.
void renderPolygonStroke(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the outline of polygon, using the given render context.
double dxfWidth(QgsSymbolRenderContext &context) const override
Gets line width.
double dxfOffset(QgsSymbolRenderContext &context) const override
Gets offset.
Qt::PenStyle dxfPenStyle() const override
Gets pen style.
void setCustomDashPatternMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for lengths used in the custom dash pattern.
void setTrimDistanceEndMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the trim distance for the end of the line.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
void setTrimDistanceEnd(double distance)
Sets the trim distance for the end of the line, which dictates a length from the end of the line at w...
QgsSimpleLineSymbolLayer(const QColor &color=DEFAULT_SIMPLELINE_COLOR, double width=DEFAULT_SIMPLELINE_WIDTH, Qt::PenStyle penStyle=DEFAULT_SIMPLELINE_PENSTYLE)
Constructor for QgsSimpleLineSymbolLayer.
~QgsSimpleLineSymbolLayer() override
void setUseCustomDashPattern(bool b)
Sets whether the line uses a custom dash pattern.
void setTweakDashPatternOnCorners(bool enabled)
Sets whether dash patterns tweaks should be applied on sharp corners, to ensure that a double-length ...
bool canCauseArtifactsBetweenAdjacentTiles() const override
Returns true if the symbol layer rendering can cause visible artifacts across a single feature when t...
void setCustomDashVector(const QVector< qreal > &vector)
Sets the custom dash vector, which is the pattern of alternating drawn/skipped lengths used while ren...
void setDashPatternOffset(double offset)
Sets the dash pattern offset, which dictates how far along the dash pattern the pattern should start ...
QColor dxfColor(QgsSymbolRenderContext &context) const override
Gets color.
QString layerType() const override
Returns a string that represents this layer type.
void setDashPatternOffsetMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the dash pattern offset.
QgsSimpleLineSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
Qt::PenStyle penStyle() const
Returns the pen style used to render the line (e.g.
void setPenJoinStyle(Qt::PenJoinStyle style)
Sets the pen join style used to render the line (e.g.
void setAlignDashPattern(bool enabled)
Sets whether dash patterns should be aligned to the start and end of lines, by applying subtle tweaks...
void setTrimDistanceStartMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the trim distance for the start of the line.
QVector< qreal > dxfCustomDashPattern(Qgis::RenderUnit &unit) const override
Gets dash pattern.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsSimpleLineSymbolLayer, using the settings serialized in the properties map (correspo...
Qt::PenCapStyle penCapStyle() const
Returns the pen cap style used to render the line (e.g.
void setTrimDistanceEndUnit(Qgis::RenderUnit unit)
Sets the unit for the trim distance for the end of the line.
void setDashPatternOffsetUnit(Qgis::RenderUnit unit)
Sets the unit for the dash pattern offset.
void renderPolyline(const QPolygonF &points, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the line joining points, using the given render context.
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
Creates a new QgsSimpleLineSymbolLayer from an SLD XML DOM element.
void setMapUnitScale(const QgsMapUnitScale &scale) override
void setTrimDistanceStart(double distance)
Sets the trim distance for the start of the line, which dictates a length from the start of the line ...
QString ogrFeatureStyle(double mmScaleFactor, double mapUnitScaleFactor) const override
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
void setTrimDistanceStartUnit(Qgis::RenderUnit unit)
Sets the unit for the trim distance for the start of the line.
bool alignDashPattern() const
Returns true if dash patterns should be aligned to the start and end of lines, by applying subtle twe...
void setCustomDashPatternUnit(Qgis::RenderUnit unit)
Sets the unit for lengths used in the custom dash pattern.
Holds SLD export options and other information related to SLD export of a QGIS layer style.
void setExtraProperties(const QVariantMap &properties)
Sets the open ended set of properties that can drive/inform the SLD encoding.
QVariantMap extraProperties() const
Returns the open ended set of properties that can drive/inform the SLD encoding.
static QString encodePenStyle(Qt::PenStyle style)
static Qt::PenJoinStyle decodePenJoinStyle(const QString &str)
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
static Q_DECL_DEPRECATED bool createExpressionElement(QDomDocument &doc, QDomElement &element, const QString &function)
Creates a OGC Expression element based on the provided function expression.
static QString svgSymbolPathToName(const QString &path, const QgsPathResolver &pathResolver)
Determines an SVG symbol's name from its path.
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
static double rescaleUom(double size, Qgis::RenderUnit unit, const QVariantMap &props)
Rescales the given size based on the uomScale found in the props, if any is found,...
static std::unique_ptr< QgsSymbolLayer > createMarkerLayerFromSld(QDomElement &element)
Creates a new marker layer from a SLD DOM element.
static bool isSharpCorner(QPointF p1, QPointF p2, QPointF p3)
Returns true if the angle formed by the line p1 - p2 - p3 forms a "sharp" corner.
static QString ogrFeatureStylePen(double width, double mmScaleFactor, double mapUnitsScaleFactor, const QColor &c, Qt::PenJoinStyle joinStyle=Qt::MiterJoin, Qt::PenCapStyle capStyle=Qt::FlatCap, double offset=0.0, const QVector< qreal > *dashPattern=nullptr)
Create ogr feature style string for pen.
static Qt::PenCapStyle decodePenCapStyle(const QString &str)
static QList< QList< QPolygonF > > toQPolygonF(const QgsGeometry &geometry, Qgis::SymbolType type)
Converts a geometry to a set of QPolygonF objects representing how the geometry should be drawn for a...
static QVector< qreal > decodeRealVector(const QString &s)
static bool lineFromSld(QDomElement &element, Qt::PenStyle &penStyle, QColor &color, double &width, Qt::PenJoinStyle *penJoinStyle=nullptr, Qt::PenCapStyle *penCapStyle=nullptr, QVector< qreal > *customDashPattern=nullptr, double *dashOffset=nullptr)
static QString encodePenCapStyle(Qt::PenCapStyle style)
static QDomElement createVendorOptionElement(QDomDocument &doc, const QString &name, const QString &value)
static void appendPolyline(QPolygonF &target, const QPolygonF &line)
Appends a polyline line to an existing target polyline.
static QString svgSymbolNameToPath(const QString &name, const QgsPathResolver &pathResolver)
Determines an SVG symbol's path from its name.
static QString encodeColor(const QColor &color)
Lossy-encodes a color to a string.
static Qgis::EndCapStyle penCapStyleToEndCapStyle(Qt::PenCapStyle style)
Converts a Qt pen cap style to a QGIS end cap style.
static double polylineLength(const QPolygonF &polyline)
Returns the total length of a polyline.
static Qgis::RenderUnit decodeSldUom(const QString &str, double *scaleFactor=nullptr)
Decodes a SLD unit of measure string to a render unit.
static Q_DECL_DEPRECATED void createGeometryElement(QDomDocument &doc, QDomElement &element, const QString &geomFunc)
Creates an SLD geometry element.
static double estimateMaxSymbolBleed(QgsSymbol *symbol, const QgsRenderContext &context)
Returns the maximum estimated bleed for the symbol.
static Qt::PenStyle decodePenStyle(const QString &str)
static QString encodePenJoinStyle(Qt::PenJoinStyle style)
static QgsStringMap getVendorOptionList(QDomElement &element)
static Qgis::JoinStyle penJoinStyleToJoinStyle(Qt::PenJoinStyle style)
Converts a Qt pen joinstyle to a QGIS join style.
static QPolygonF polylineSubstring(const QPolygonF &polyline, double startOffset, double endOffset)
Returns the substring of a polyline which starts at startOffset from the beginning of the line and en...
static void lineToSld(QDomDocument &doc, QDomElement &element, Qt::PenStyle penStyle, const QColor &color, QgsSldExportContext &context, double width=-1, const Qt::PenJoinStyle *penJoinStyle=nullptr, const Qt::PenCapStyle *penCapStyle=nullptr, const QVector< qreal > *customDashPattern=nullptr, double dashOffset=0.0)
static QString encodeRealVector(const QVector< qreal > &v)
void copyCommonProperties(QgsSymbolLayer *destLayer) const
Copies all common base class properties from this layer to another symbol layer.
virtual QgsSymbolLayer * clone() const =0
Shall be reimplemented by subclasses to create a deep copy of the instance.
virtual bool setSubSymbol(QgsSymbol *symbol)
Sets layer's subsymbol. takes ownership of the passed symbol.
bool shouldRenderUsingSelectionColor(const QgsSymbolRenderContext &context) const
Returns true if the symbol layer should be rendered using the selection color from the render context...
friend class QgsSymbol
static const bool SELECTION_IS_OPAQUE
Whether styles for selected features ignore symbol alpha.
bool installMasks(QgsRenderContext &context, bool recursive, const QRectF &rect=QRectF())
When rendering, install masks on context painter.
void removeMasks(QgsRenderContext &context, bool recursive)
When rendering, remove previously installed masks from context painter if recursive is true masks are...
virtual QSet< QString > usedAttributes(const QgsRenderContext &context) const
Returns the set of attributes referenced by the layer.
Property
Data definable properties.
@ SecondaryColor
Secondary color (eg for gradient fills).
@ File
Filename, eg for svg files.
@ BlankSegments
String list of distance to define blank segments along line for templated line symbol layers.
@ DashPatternOffset
Dash pattern offset,.
@ OffsetAlongLine
Offset along line.
@ CustomDash
Custom dash pattern.
@ StrokeStyle
Stroke style (eg solid, dashed).
@ TrimStart
Trim distance from start of line.
@ CapStyle
Line cap style.
@ Placement
Line marker placement.
@ LineAngle
Line angle, or angle of hash lines for hash line symbols.
@ JoinStyle
Line join style.
@ AverageAngleLength
Length to average symbol angles over.
@ Interval
Line marker interval.
@ LineDistance
Distance between lines, or length of lines for hash line symbols.
@ ExtraItems
String list of tuple (x, y and rotation angle) to define extra items to be rendered for templated lin...
@ TrimEnd
Trim distance from end of line.
void restoreOldDataDefinedProperties(const QVariantMap &stringMap)
Restores older data defined properties from string map.
bool enabled() const
Returns true if symbol layer is enabled and will be drawn.
virtual QString layerType() const =0
Returns a string that represents this layer type.
virtual void setDataDefinedProperty(Property key, const QgsProperty &property)
Sets a data defined property for the layer.
virtual void setColor(const QColor &color)
Sets the "representative" color for the symbol layer.
virtual QgsSymbol * subSymbol()
Returns the symbol's sub symbol, if present.
virtual QColor color() const
Returns the "representative" color of the symbol layer.
virtual Qgis::SymbolLayerFlags flags() const
Returns flags which control the symbol layer's behavior.
QgsPropertyCollection mDataDefinedProperties
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the symbol layer's property collection, used for data defined overrides.
virtual bool hasDataDefinedProperties() const
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
QgsSymbolLayer(const QgsSymbolLayer &other)
Encapsulates the context in which a symbol is being rendered.
const QgsFeature * feature() const
Returns the current feature being rendered.
Qgis::GeometryType originalGeometryType() const
Returns the geometry type for the original feature geometry being rendered.
QgsFields fields() const
Fields of the layer.
int geometryPartNum() const
Part number of current geometry.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for data defined symbology.
qreal opacity() const
Returns the opacity for the symbol.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
qreal opacity() const
Returns the opacity for the symbol.
Definition qgssymbol.h:677
void setOpacity(qreal opacity)
Sets the opacity for the symbol.
Definition qgssymbol.h:684
Qgis::SymbolType type() const
Returns the symbol's type.
Definition qgssymbol.h:296
bool rotateSymbols() const
Returns true if the repeating symbols be rotated to match their line segment orientation.
void setTrimDistanceStartMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the trim distance for the start of the line.
void startFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called before the layer will be rendered for a particular feature.
static void setCommonProperties(QgsTemplatedLineSymbolLayerBase *destLayer, const QVariantMap &properties)
Sets all common symbol properties in the destLayer, using the settings serialized in the properties m...
void setMapUnitScale(const QgsMapUnitScale &scale) final
void renderPolygonStroke(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) final
Renders the line symbol layer along the outline of polygon, using the given render context.
bool canCauseArtifactsBetweenAdjacentTiles() const override
Returns true if the symbol layer rendering can cause visible artifacts across a single feature when t...
void renderPolyline(const QPolygonF &pts, QgsSymbolRenderContext &context) override
Renders the line symbol layer along the line joining points, using the given render context.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
void setIntervalUnit(Qgis::RenderUnit unit)
Sets the units for the interval between symbols.
void setAverageAngleUnit(Qgis::RenderUnit unit)
Sets the unit for the length over which the line's direction is averaged when calculating individual ...
double interval() const
Returns the interval between individual symbols.
void setOffsetAlongLineUnit(Qgis::RenderUnit unit)
Sets the unit used for calculating the offset along line for symbols.
void setAverageAngleMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the length over which the line's direction is averaged when calculating i...
const QgsMapUnitScale & intervalMapUnitScale() const
Returns the map unit scale for the interval between symbols.
double offsetAlongLine() const
Returns the offset along the line for the symbol placement.
void copyTemplateSymbolProperties(QgsTemplatedLineSymbolLayerBase *destLayer) const
Copies all common properties of this layer to another templated symbol layer destLayer.
Qgis::MarkerLinePlacements placements() const
Returns the placement of the symbols.
void setOffsetAlongLine(double offsetAlongLine)
Sets the the offset along the line for the symbol placement.
void setTrimDistanceEndMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the trim distance for the end of the line.
Qgis::RenderUnit offsetAlongLineUnit() const
Returns the unit used for calculating the offset along line for symbols.
Qgis::RenderUnit outputUnit() const final
Returns the units to use for sizes and widths within the symbol layer.
QgsTemplatedLineSymbolLayerBase(bool rotateSymbol=true, double interval=3)
Constructor for QgsTemplatedLineSymbolLayerBase.
virtual void setSymbolLineAngle(double angle)=0
Sets the line angle modification for the symbol's angle.
QgsMapUnitScale mapUnitScale() const final
Qgis::RenderUnit intervalUnit() const
Returns the units for the interval between symbols.
Q_DECL_DEPRECATED Qgis::MarkerLinePlacement placement() const
Returns the placement of the symbols.
void setTrimDistanceStartUnit(Qgis::RenderUnit unit)
Sets the unit for the trim distance for the start of the line.
void setPlaceOnEveryPart(bool respect)
Sets whether the placement applies for every part of multi-part feature geometries.
void setPlacements(Qgis::MarkerLinePlacements placements)
Sets the placement of the symbols.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
void setTrimDistanceStart(double distance)
Sets the trim distance for the start of the line, which dictates a length from the start of the line ...
Qgis::RenderUnit averageAngleUnit() const
Returns the unit for the length over which the line's direction is averaged when calculating individu...
Q_DECL_DEPRECATED void setPlacement(Qgis::MarkerLinePlacement placement)
Sets the placement of the symbols.
void stopFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called after the layer has been rendered for a particular feature.
Qgis::RenderUnit blankSegmentsUnit() const
Returns the unit for for blank segments start and end distances.
void setBlankSegmentsUnit(Qgis::RenderUnit unit)
Sets the unit for blank segments start and end distances.
void setTrimDistanceEnd(double distance)
Sets the trim distance for the end of the line, which dictates a length from the end of the line at w...
const QgsMapUnitScale & offsetAlongLineMapUnitScale() const
Returns the map unit scale used for calculating the offset in map units along line for symbols.
void setTrimDistanceEndUnit(Qgis::RenderUnit unit)
Sets the unit for the trim distance for the end of the line.
virtual void renderSymbol(const QPointF &point, const QgsFeature *feature, QgsRenderContext &context, int layer=-1, bool selected=false)=0
Renders the templated symbol at the specified point, using the given render context.
void setIntervalMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale for the interval between symbols.
void setOffsetAlongLineMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale used for calculating the offset in map units along line for symbols.
void setAverageAngleLength(double length)
Sets the length of line over which the line's direction is averaged when calculating individual symbo...
static Q_INVOKABLE Qgis::RenderUnit decodeRenderUnit(const QString &string, bool *ok=nullptr)
Decodes a render unit from a string.
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Qgis::VectorRenderingSimplificationFlags simplifyHints() const
Gets the simplification hints of the vector layer managed.
float threshold() const
Gets the simplification threshold of the vector layer managed.
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored).
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition qgsgeos.h:165
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 c
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:7718
QString qgsFlagValueToKeys(const T &value, bool *returnOk=nullptr)
Returns the value for the given keys of a flag.
Definition qgis.h:8143
T qgsFlagKeysToValue(const QString &keys, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given keys of a flag.
Definition qgis.h:8172
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
QMap< QString, QString > QgsStringMap
Definition qgis.h:8418
constexpr QgsDataDefinedStringDecoder< V, N > makeDataDefinedStringDecoder(const DataDefinedDecoderEntry< V >(&values)[N])
Creates a QgsDataDefinedStringDecoder from a hardcoded lookup table.
void trimPoints(QPolygonF &points, double startTrim, double endTrim, Qgis::RenderUnit trimDistanceStartUnit, Qgis::RenderUnit trimDistanceEndUnit, const QgsMapUnitScale &trimDistanceStartMapUnitScale, const QgsMapUnitScale &trimDistanceEndMapUnitScale, const QgsPropertyCollection &mDataDefinedProperties, QgsSymbolRenderContext &context)
trim points according to start and end trim distance based on data defined properties and render cont...
#define DEFAULT_MARKERLINE_INTERVAL
#define DEFAULT_SIMPLELINE_WIDTH
#define DEFAULT_MARKERLINE_ROTATE
#define DEFAULT_SIMPLELINE_PENSTYLE
#define DEFAULT_SIMPLELINE_COLOR
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71
QList< QgsSymbolLayer * > QgsSymbolLayerList
Definition qgssymbol.h:30
QList< QPolygonF > offsetLine(QPolygonF polyline, double dist, Qgis::GeometryType geometryType)
calculate geometry shifted by a specified distance
Single variable definition for use within a QgsExpressionContextScope.
Qgis::VertexType type
Vertex type.
#define EPSILON
Definition util.h:80