KiCad PCB EDA Suite
Loading...
Searching...
No Matches
SVG_plotter.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2020 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21/* Some info on basic items SVG format, used here:
22 * The root element of all SVG files is the <svg> element.
23 *
24 * The <g> element is used to group SVG shapes together.
25 * Once grouped you can transform the whole group of shapes as if it was a single shape.
26 * This is an advantage compared to a nested <svg> element
27 * which cannot be the target of transformation by itself.
28 *
29 * The <rect> element represents a rectangle.
30 * Using this element you can draw rectangles of various width, height,
31 * with different stroke (outline) and fill colors, with sharp or rounded corners etc.
32 *
33 * <svg xmlns="http://www.w3.org/2000/svg"
34 * xmlns:xlink="http://www.w3.org/1999/xlink">
35 *
36 * <rect x="10" y="10" height="100" width="100"
37 * style="stroke:#006600; fill: #00cc00"/>
38 *
39 * </svg>
40 *
41 * The <circle> element is used to draw circles.
42 * <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
43 *
44 * The <ellipse> element is used to draw ellipses.
45 * An ellipse is a circle that does not have equal height and width.
46 * Its radius in the x and y directions are different, in other words.
47 * <ellipse cx="40" cy="40" rx="30" ry="15"
48 * style="stroke:#006600; fill:#00cc00"/>
49 *
50 * The <line> element is used to draw lines.
51 *
52 * <line x1="0" y1="10" x2="0" y2="100" style="stroke:#006600;"/>
53 * <line x1="10" y1="10" x2="100" y2="100" style="stroke:#006600;"/>
54 *
55 * The <polyline> element is used to draw multiple connected lines
56 * Here is a simple example:
57 *
58 * <polyline points="0,0 30,0 15,30" style="stroke:#006600;"/>
59 *
60 * The <polygon> element is used to draw with multiple (3 or more) sides / edges.
61 * Here is a simple example:
62 *
63 * <polygon points="0,0 50,0 25,50" style="stroke:#660000; fill:#cc3333;"/>
64 *
65 * The <path> element is used to draw advanced shapes combined from lines and arcs,
66 * with or without fill.
67 * It is probably the most advanced and versatile SVG shape of them all.
68 * It is probably also the hardest element to master.
69 * <path d="M50,50
70 * A30,30 0 0,1 35,20
71 * L100,100
72 * M110,110
73 * L100,0"
74 * style="stroke:#660000; fill:none;"/>
75 *
76 * Draw an elliptic arc: it is one of basic path command:
77 * <path d="M(startx,starty) A(radiusx,radiusy)
78 * rotation-axe-x
79 * flag_arc_large,flag_sweep endx,endy">
80 * flag_arc_large: 0 = small arc > 180 deg, 1 = large arc > 180 deg
81 * flag_sweep : 0 = CCW, 1 = CW
82 * The center of ellipse is automatically calculated.
83 */
84
85#include <core/base64.h>
86#include <eda_shape.h>
87#include <string_utils.h>
89#include <font/font.h>
90#include <macros.h>
91#include <trigo.h>
92#include <fmt/format.h>
93
94#include <cstdint>
95#include <wx/mstream.h>
96
98
99// Note:
100// During tests, we (JPC) found issues when the coordinates used 6 digits in mantissa
101// especially for stroke-width using very small (but not null) values < 0.00001 mm
102// So to avoid this king of issue, we are using 4 digits in mantissa
103// The resolution (m_precision ) is 0.1 micron, that looks enough for a SVG file
104
110static wxString XmlEsc( const wxString& aStr, bool isAttribute = false )
111{
112 wxString escaped;
113
114 escaped.reserve( aStr.length() );
115
116 for( wxString::const_iterator it = aStr.begin(); it != aStr.end(); ++it )
117 {
118 const wxChar c = *it;
119
120 switch( c )
121 {
122 case wxS( '<' ):
123 escaped.append( wxS( "&lt;" ) );
124 break;
125 case wxS( '>' ):
126 escaped.append( wxS( "&gt;" ) );
127 break;
128 case wxS( '&' ):
129 escaped.append( wxS( "&amp;" ) );
130 break;
131 case wxS( '\r' ):
132 escaped.append( wxS( "&#xD;" ) );
133 break;
134 default:
135 if( isAttribute )
136 {
137 switch( c )
138 {
139 case wxS( '"' ):
140 escaped.append( wxS( "&quot;" ) );
141 break;
142 case wxS( '\t' ):
143 escaped.append( wxS( "&#x9;" ) );
144 break;
145 case wxS( '\n' ):
146 escaped.append( wxS( "&#xA;" ));
147 break;
148 default:
149 escaped.append(c);
150 }
151 }
152 else
153 {
154 escaped.append(c);
155 }
156 }
157 }
158
159 return escaped;
160}
161
162
164 PSLIKE_PLOTTER( aProject )
165{
166 m_graphics_changed = true;
168 m_fillMode = FILL_T::NO_FILL; // or FILLED_SHAPE or FILLED_WITH_BG_BODYCOLOR
169 m_pen_rgb_color = 0; // current color value (black)
170 m_brush_rgb_color = 0; // current color value with alpha(black)
171 m_brush_alpha = 1.0;
173 m_precision = 4; // default: 4 digits in mantissa.
174}
175
176
177void SVG_PLOTTER::SetViewport( const VECTOR2I& aOffset, double aIusPerDecimil,
178 double aScale, bool aMirror )
179{
180 m_plotMirror = aMirror;
181 m_yaxisReversed = true; // unlike other plotters, SVG has Y axis reversed
182 m_plotOffset = aOffset;
183 m_plotScale = aScale;
184 m_IUsPerDecimil = aIusPerDecimil;
185
186 // Compute the paper size in IUs. for historical reasons the page size is in mils
187 m_paperSize = m_pageInfo.GetSizeMils();
188 m_paperSize.x *= 10.0 * aIusPerDecimil;
189 m_paperSize.y *= 10.0 * aIusPerDecimil;
190
191 // gives now a default value to iuPerDeviceUnit (because the units of the caller is now known)
192 double iusPerMM = m_IUsPerDecimil / 2.54 * 1000;
193 m_iuPerDeviceUnit = 1 / iusPerMM;
194
196}
197
198
199void SVG_PLOTTER::SetSvgCoordinatesFormat( unsigned aPrecision )
200{
201 // Only number of digits in mantissa are adjustable.
202 // SVG units are always mm
203 m_precision = aPrecision;
204}
205
206
207void SVG_PLOTTER::SetPlotBBox( const BOX2I& aBBoxIU )
208{
209 m_plotBBoxIU = aBBoxIU;
210}
211
212
214{
215 VECTOR2D pos = PLOTTER::userToDeviceCoordinates( aCoordinate );
216
217 if( m_plotMirror )
218 {
221 else
223 }
224
225 return pos;
226}
227
228
230{
231 if( m_fillMode != fill )
232 {
233 m_graphics_changed = true;
234 m_fillMode = fill;
235 }
236}
237
238
239void SVG_PLOTTER::setSVGPlotStyle( int aLineWidth, bool aIsGroup, const std::string& aExtraStyle )
240{
241 if( aIsGroup )
242 fmt::print( m_outputFile, "</g>\n<g " );
243
244 fmt::print( m_outputFile, "style=\"" );
245
247 {
248 fmt::print( m_outputFile, "fill:none; " );
249 }
250 else
251 {
252 // output the background fill color
253 fmt::print( m_outputFile, "fill:#{:06X}; ", m_brush_rgb_color );
254
255 switch( m_fillMode )
256 {
260 fmt::print( m_outputFile, "fill-opacity:{:.{}f}; ", m_brush_alpha, m_precision );
261 break;
262 default: break;
263 }
264 }
265
266 double pen_w = userToDeviceSize( aLineWidth );
267
268 if( pen_w <= 0 )
269 {
270 fmt::print( m_outputFile, "stroke:none;" );
271 }
272 else
273 {
274 // Fix a strange issue found in Inkscape: aWidth < 100 nm create issues on degrouping
275 // objects.
276 // So we use only 4 digits in mantissa for stroke-width.
277 // TODO: perhaps used only 3 or 4 digits in mantissa for all values in mm, because some
278 // issues were previously reported reported when using nm as integer units
279 fmt::print( m_outputFile,
280 "\nstroke:#{:06X}; stroke-width:{:.{}f}; stroke-opacity:{:.{}f}; \n",
282 fmt::print( m_outputFile, "stroke-linecap:round; stroke-linejoin:round;" );
283
284 //set any extra attributes for non-solid lines
285 switch( m_dashed )
286 {
287 case LINE_STYLE::DASH:
288 fmt::print( m_outputFile, "stroke-dasharray:{:.{}f},{:.{}f};",
289 GetDashMarkLenIU( aLineWidth ), m_precision,
290 GetDashGapLenIU( aLineWidth ), m_precision );
291 break;
292
293 case LINE_STYLE::DOT:
294 fmt::print( m_outputFile, "stroke-dasharray:{:f},{:f};", GetDotMarkLenIU( aLineWidth ),
295 GetDashGapLenIU( aLineWidth ) );
296 break;
297
299 fmt::print( m_outputFile, "stroke-dasharray:{:f},{:f},{:f},{:f};",
300 GetDashMarkLenIU( aLineWidth ),
301 GetDashGapLenIU( aLineWidth ), GetDotMarkLenIU( aLineWidth ),
302 GetDashGapLenIU( aLineWidth ) );
303 break;
304
306 fmt::print( m_outputFile, "stroke-dasharray:{:f},{:f},{:f},{:f},{:f},{:f};",
307 GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
308 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
309 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
310 break;
311
314 default:
315 // Explicitly reset the dash pattern: stroke-dasharray is inherited in SVG, so
316 // inline path styles inside a dashed group would otherwise pick it up.
317 fmt::print( m_outputFile, "stroke-dasharray:none;" );
318 break;
319 }
320 }
321
322 if( aExtraStyle.length() )
323 fmt::print( m_outputFile, "{}", aExtraStyle );
324
325 fmt::print( m_outputFile, "\"" );
326
327 if( aIsGroup )
328 {
329 fmt::print( m_outputFile, ">" );
330 m_graphics_changed = false;
331 }
332
333 fmt::print( m_outputFile, "\n" );
334}
335
336
337void SVG_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
338{
339 if( aWidth == DO_NOT_SET_LINE_WIDTH )
340 return;
341 else if( aWidth == USE_DEFAULT_LINE_WIDTH )
342 aWidth = m_renderSettings->GetDefaultPenWidth();
343
344 // Note: aWidth == 0 is fine: used for filled shapes with no outline thickness
345 wxASSERT_MSG( aWidth >= 0, "Plotter called to set negative pen width" );
346
347 if( aWidth != m_currentPenWidth )
348 {
349 m_graphics_changed = true;
350 m_currentPenWidth = aWidth;
351 }
352}
353
354
355void SVG_PLOTTER::StartBlock( void* aData )
356{
357 // We can't use <g></g> for blocks because we're already using it for graphics context, and
358 // our graphics context handling is lazy (ie: it leaves the last group open until the context
359 // changes).
360}
361
362
363void SVG_PLOTTER::EndBlock( void* aData )
364{
365}
366
367
368void SVG_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
369{
370 uint32_t red = (uint32_t) ( 255.0 * r );
371 uint32_t green = (uint32_t) ( 255.0 * g );
372 uint32_t blue = (uint32_t) ( 255.0 * b );
373 uint32_t rgb_color = ( red << 16 ) | ( green << 8 ) | blue;
374
375 if( m_pen_rgb_color != rgb_color || m_brush_alpha != a )
376 {
377 m_graphics_changed = true;
378 m_pen_rgb_color = rgb_color;
379
380 // Currently, use the same color for brush and pen (i.e. to draw and fill a contour).
381 m_brush_rgb_color = rgb_color;
382 m_brush_alpha = a;
383 }
384}
385
386
387void SVG_PLOTTER::SetDash( int aLineWidth, LINE_STYLE aLineStyle )
388{
389 if( m_dashed != aLineStyle )
390 {
391 m_graphics_changed = true;
392 m_dashed = aLineStyle;
393 }
394}
395
396
397void SVG_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width,
398 int aCornerRadius )
399{
400 BOX2I rect( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
401 rect.Normalize();
402
403 VECTOR2D org_dev = userToDeviceCoordinates( rect.GetOrigin() );
404 VECTOR2D end_dev = userToDeviceCoordinates( rect.GetEnd() );
405 VECTOR2D size_dev = end_dev - org_dev;
406
407 // Ensure size of rect in device coordinates is > 0
408 // I don't know if this is a SVG issue or a Inkscape issue, but
409 // Inkscape has problems with negative or null values for width and/or height, so avoid them
410 BOX2D rect_dev( org_dev, size_dev );
411 rect_dev.Normalize();
412
413 setFillMode( fill );
414 SetCurrentLineWidth( width );
415
418
419 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
420 // so use a line when happens.
421 if( rect_dev.GetSize().x == 0.0 || rect_dev.GetSize().y == 0.0 ) // Draw a line
422 {
423 fmt::print( m_outputFile,
424 "<line x1=\"{:.{}f}\" y1=\"{:.{}f}\" x2=\"{:.{}f}\" y2=\"{:.{}f}\" />\n",
425 rect_dev.GetPosition().x, m_precision,
426 rect_dev.GetPosition().y, m_precision,
427 rect_dev.GetEnd().x, m_precision,
428 rect_dev.GetEnd().y, m_precision );
429 }
430 else
431 {
432 fmt::print( m_outputFile,
433 "<rect x=\"{:f}\" y=\"{:f}\" width=\"{:f}\" height=\"{:f}\" rx=\"{:f}\" />\n",
434 rect_dev.GetPosition().x,
435 rect_dev.GetPosition().y,
436 rect_dev.GetSize().x,
437 rect_dev.GetSize().y,
438 userToDeviceSize( aCornerRadius ) );
439 }
440}
441
442
443void SVG_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T fill, int width )
444{
445 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
446 double radius = userToDeviceSize( diametre / 2.0 );
447
448 setFillMode( fill );
449 SetCurrentLineWidth( width );
450
453
454 // If diameter is less than width, switch to filled mode
455 if( fill == FILL_T::NO_FILL && diametre < GetCurrentLineWidth() )
456 {
458 width = GetCurrentLineWidth();
460
461 radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
462 }
463
464 fmt::print( m_outputFile,
465 "<circle cx=\"{:.{}f}\" cy=\"{:.{}f}\" r=\"{:.{}f}\" /> \n",
466 pos_dev.x, m_precision,
467 pos_dev.y, m_precision,
469}
470
471
472void SVG_PLOTTER::Arc( const VECTOR2D& aCenter, const EDA_ANGLE& aStartAngle,
473 const EDA_ANGLE& aAngle, double aRadius, FILL_T aFill, int aWidth )
474{
475 /* Draws an arc of a circle, centered on (xc,yc), with starting point (x1, y1) and ending
476 * at (x2, y2). The current pen is used for the outline and the current brush for filling
477 * the shape.
478 *
479 * The arc is drawn in an anticlockwise direction from the start point to the end point.
480 */
481 if( aRadius <= 0 )
482 {
483 Circle( aCenter, aWidth, FILL_T::FILLED_SHAPE, 0 );
484 return;
485 }
486
487 EDA_ANGLE startAngle = -aStartAngle;
488 EDA_ANGLE endAngle = startAngle - aAngle;
489
490 if( endAngle < startAngle )
491 std::swap( startAngle, endAngle );
492
493 // Calculate start point.
494 VECTOR2D centre_device = userToDeviceCoordinates( aCenter );
495 double radius_device = userToDeviceSize( aRadius );
496
497 if( m_plotMirror )
498 {
500 {
501 std::swap( startAngle, endAngle );
502 startAngle = ANGLE_180 - startAngle;
503 endAngle = ANGLE_180 - endAngle;
504 }
505 else
506 {
507 startAngle = -startAngle;
508 endAngle = -endAngle;
509 }
510 }
511
512 VECTOR2D start;
513 start.x = radius_device;
514 RotatePoint( start, startAngle );
516 end.x = radius_device;
517 RotatePoint( end, endAngle );
518 start += centre_device;
519 end += centre_device;
520
521 double theta1 = startAngle.AsRadians();
522
523 if( theta1 < 0 )
524 theta1 = theta1 + M_PI * 2;
525
526 double theta2 = endAngle.AsRadians();
527
528 if( theta2 < 0 )
529 theta2 = theta2 + M_PI * 2;
530
531 if( theta2 < theta1 )
532 theta2 = theta2 + M_PI * 2;
533
534 int flg_arc = 0; // flag for large or small arc. 0 means less than 180 degrees
535
536 if( fabs( theta2 - theta1 ) > M_PI )
537 flg_arc = 1;
538
539 int flg_sweep = 0; // flag for sweep always 0
540
541 // Draw a single arc: an arc is one of 3 curve commands (2 other are 2 bezier curves)
542 // params are start point, radius1, radius2, X axe rotation,
543 // flag arc size (0 = small arc > 180 deg, 1 = large arc > 180 deg),
544 // sweep arc ( 0 = CCW, 1 = CW),
545 // end point
546 if( aFill != FILL_T::NO_FILL )
547 {
548 // Filled arcs (in Eeschema) consist of the pie wedge and a stroke only on the arc
549 // This needs to be drawn in two steps.
550 setFillMode( aFill );
552
555
556 fmt::print( m_outputFile,
557 "<path d=\"M{:.{}f} {:.{}f} A{:.{}f} {:.{}f} 0.0 {:d} {:d} {:.{}f} {:.{}f} L {:.{}f} {:.{}f} Z\" />\n",
558 start.x, m_precision,
559 start.y, m_precision,
560 radius_device, m_precision,
561 radius_device, m_precision,
562 flg_arc,
563 flg_sweep,
564 end.x, m_precision,
565 end.y, m_precision,
566 centre_device.x, m_precision,
567 centre_device.y, m_precision );
568 }
569
571 SetCurrentLineWidth( aWidth );
572
575
576 fmt::print( m_outputFile,
577 "<path d=\"M{:.{}f} {:.{}f} A{:.{}f} {:.{}f} 0.0 {:d} {:d} {:.{}f} {:.{}f}\" />\n",
578 start.x, m_precision,
579 start.y, m_precision,
580 radius_device, m_precision,
581 radius_device, m_precision,
582 flg_arc,
583 flg_sweep,
584 end.x, m_precision,
585 end.y, m_precision );
586}
587
588
589void SVG_PLOTTER::BezierCurve( const VECTOR2I& aStart, const VECTOR2I& aControl1,
590 const VECTOR2I& aControl2, const VECTOR2I& aEnd,
591 int aTolerance, int aLineThickness )
592{
593#if 1
595 SetCurrentLineWidth( aLineThickness );
596
599
600 VECTOR2D start = userToDeviceCoordinates( aStart );
601 VECTOR2D ctrl1 = userToDeviceCoordinates( aControl1 );
602 VECTOR2D ctrl2 = userToDeviceCoordinates( aControl2 );
604
605 // Generate a cubic curve: start point and 3 other control points.
606 fmt::print( m_outputFile,
607 "<path d=\"M{:.{}f},{:.{}f} C{:.{}f},{:.{}f} {:.{}f},{:.{}f} {:.{}f},{:.{}f}\" />\n",
608 start.x, m_precision,
609 start.y, m_precision,
610 ctrl1.x,m_precision,
611 ctrl1.y, m_precision,
612 ctrl2.x, m_precision,
613 ctrl2.y, m_precision,
614 end.x, m_precision,
615 end.y, m_precision );
616#else
617 PLOTTER::BezierCurve( aStart, aControl1, aControl2, aEnd, aTolerance, aLineThickness );
618#endif
619}
620
621
622void SVG_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill,
623 int aWidth, void* aData )
624{
625 if( aCornerList.size() <= 1 )
626 return;
627
628 setFillMode( aFill );
629 SetCurrentLineWidth( aWidth );
630 fmt::print( m_outputFile, "<path " );
631
632 switch( aFill )
633 {
634 case FILL_T::NO_FILL:
635 case FILL_T::HATCH:
638 setSVGPlotStyle( aWidth, false, "fill:none" );
639 break;
640
644 setSVGPlotStyle( aWidth, false, "fill-rule:evenodd;" );
645 break;
646 }
647
648 VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
649 fmt::print( m_outputFile, "d=\"M {:.{}f},{:.{}f}\n", pos.x, m_precision, pos.y, m_precision );
650
651 for( unsigned ii = 1; ii < aCornerList.size() - 1; ii++ )
652 {
653 pos = userToDeviceCoordinates( aCornerList[ii] );
654 fmt::print( m_outputFile, "{:.{}f},{:.{}f}\n", pos.x, m_precision, pos.y, m_precision );
655 }
656
657 // If the corner list ends where it begins, then close the poly
658 if( aCornerList.front() == aCornerList.back() )
659 {
660 fmt::print( m_outputFile, "Z\" /> \n" );
661 }
662 else
663 {
664 pos = userToDeviceCoordinates( aCornerList.back() );
665 fmt::print( m_outputFile,
666 "{:.{}f},{:.{}f}\n\" /> \n",
667 pos.x, m_precision,
668 pos.y, m_precision );
669 }
670}
671
672
673void SVG_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor )
674{
675 VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );
676
677 // Requested size (in IUs)
678 VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );
679
680 // calculate the bitmap start position
681 VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y - drawsize.y / 2 );
682
683 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
684 // so use a line when happens.
685 if( drawsize.x == 0.0 || drawsize.y == 0.0 ) // Draw a line
686 {
687 PLOTTER::PlotImage( aImage, aPos, aScaleFactor );
688 }
689 else
690 {
691 wxMemoryOutputStream img_stream;
692
693 if( m_colorMode )
694 {
695 aImage.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
696 }
697 else // Plot in B&W
698 {
699 wxImage image = aImage.ConvertToGreyscale();
700 image.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
701 }
702
703 size_t input_len = img_stream.GetOutputStreamBuffer()->GetBufferSize();
704 std::vector<uint8_t> buffer( input_len );
705 std::vector<uint8_t> encoded;
706
707 img_stream.CopyTo( buffer.data(), buffer.size() );
708 base64::encode( buffer, encoded );
709
710 VECTOR2D pos = userToDeviceCoordinates( start );
711 fmt::print( m_outputFile,
712 "<image x=\"{:f}\" y=\"{:f}\" xlink:href=\"data:image/png;base64,", pos.x, pos.y );
713
714 for( size_t i = 0; i < encoded.size(); i++ )
715 {
716 fmt::print( m_outputFile, "{}", static_cast<char>( encoded[i] ) );
717
718 if( ( i % 64 ) == 63 )
719 fmt::print( m_outputFile, "\n" );
720 }
721
722 fmt::print( m_outputFile,
723 "\"\npreserveAspectRatio=\"none\" width=\"{:.{}f}\" height=\"{:.{}f}\" />",
724 userToDeviceSize( drawsize.x ), m_precision,
725 userToDeviceSize( drawsize.y ), m_precision );
726 }
727}
728
729
730void SVG_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
731{
732 if( plume == 'Z' )
733 {
734 if( m_penState != 'Z' )
735 {
736 fmt::print( m_outputFile, "\" />\n" );
737 m_penState = 'Z';
738 m_penLastpos.x = -1;
739 m_penLastpos.y = -1;
740 }
741
742 return;
743 }
744
745 if( m_penState == 'Z' ) // here plume = 'D' or 'U'
746 {
747 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
748
749 // Ensure we do not use a fill mode when moving the pen,
750 // in SVG mode (i;e. we are plotting only basic lines, not a filled area
753
756
757 fmt::print( m_outputFile, "<path d=\"M{:.{}f} {:.{}f}\n",
758 pos_dev.x, m_precision,
759 pos_dev.y, m_precision );
760 }
761 else if( m_penState != plume || pos != m_penLastpos )
762 {
765
766 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
767
768 fmt::print( m_outputFile, "L{:.{}f} {:.{}f}\n",
769 pos_dev.x, m_precision,
770 pos_dev.y, m_precision );
771 }
772
773 m_penState = plume;
774 m_penLastpos = pos;
775}
776
777
778bool SVG_PLOTTER::StartPlot( const wxString& aPageNumber )
779{
780 wxASSERT( m_outputFile );
781
782 std::string header = "<?xml version=\"1.0\" standalone=\"no\"?>\n"
783 " <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n"
784 " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"> \n"
785 "<svg\n"
786 " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"
787 " xmlns=\"http://www.w3.org/2000/svg\"\n"
788 " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
789 " xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\n"
790 " version=\"1.1\"\n";
791
792 // Write header.
793 fmt::print( m_outputFile, "{}", header );
794
795 // Write viewport pos and size. The SVG width/height and viewBox are in mm (device
796 // units). When a plot bounding box was supplied, the viewBox is that box
797 // transformed by the viewport, so the content keeps its origin at the SVG
798 // origin even when it extends to negative coordinates. Otherwise the page
799 // size is used and the origin is the viewbox (which is also the page) corner.
800 VECTOR2D viewBoxOrigin( 0, 0 );
802
803 if( m_plotBBoxIU )
804 {
805 double deviceScale = m_plotScale * m_iuPerDeviceUnit;
806
807 viewBoxOrigin.x = ( m_plotBBoxIU->GetLeft() - m_plotOffset.x ) * deviceScale;
808 viewBoxOrigin.y = ( m_plotBBoxIU->GetTop() - m_plotOffset.y ) * deviceScale;
809 viewboxSize.x = static_cast<double>( m_plotBBoxIU->GetWidth() ) * deviceScale;
810 viewboxSize.y = static_cast<double>( m_plotBBoxIU->GetHeight() ) * deviceScale;
811 }
812
813 // When mirroring, the viewbox also needs to be mirrored, so that the same content is
814 // still visible in it.
815 if( m_plotMirror )
816 {
818 viewBoxOrigin.x = -viewBoxOrigin.x - viewboxSize.x;
819 else
820 viewBoxOrigin.y = -viewBoxOrigin.y - viewboxSize.y;
821 }
822
823 fmt::print( m_outputFile,
824 " width=\"{:.{}f}mm\" height=\"{:.{}f}mm\" viewBox=\"{:.{}f} {:.{}f} {:.{}f} {:.{}f}\">\n",
825 viewboxSize.x, m_precision, viewboxSize.y, m_precision,
826 viewBoxOrigin.x, m_precision, viewBoxOrigin.y, m_precision,
827 viewboxSize.x, m_precision, viewboxSize.y, m_precision );
828
829 // Write title
830 wxString date = GetISO8601CurrentDateTime();
831
832 fmt::print( m_outputFile,
833 "<title>SVG Image created as {} date {} </title>\n",
834 TO_UTF8( XmlEsc( wxFileName( m_filename ).GetFullName() ) ),
835 TO_UTF8( date ) );
836
837 // End of header
838 fmt::print( m_outputFile, " <desc>Image generated by {} </desc>\n",
839 TO_UTF8( XmlEsc( m_creator ) ) );
840
841 // output the pen and brush color (RVB values in hex) and opacity
842 double opacity = 1.0; // 0.0 (transparent to 1.0 (solid)
843 fmt::print( m_outputFile,
844 "<g style=\"fill:#{:06X}; fill-opacity:{:.{}f};stroke:#{:06X}; stroke-opacity:{:.{}f};\n",
849 opacity,
850 m_precision );
851
852 // output the pen cap and line joint
853 fmt::print( m_outputFile, "stroke-linecap:round; stroke-linejoin:round;\"\n" );
854 fmt::print( m_outputFile, " transform=\"translate(0 0) scale(1 1)\">\n" );
855 return true;
856}
857
858
860{
861 fmt::print( m_outputFile, "</g> \n</svg>\n" );
862 fclose( m_outputFile );
863 m_outputFile = nullptr;
864
865 return true;
866}
867
868
869void SVG_PLOTTER::Text( const VECTOR2I& aPos,
870 const COLOR4D& aColor,
871 const wxString& aText,
872 const EDA_ANGLE& aOrient,
873 const VECTOR2I& aSize,
874 enum GR_TEXT_H_ALIGN_T aH_justify,
875 enum GR_TEXT_V_ALIGN_T aV_justify,
876 int aWidth,
877 bool aItalic,
878 bool aBold,
879 bool aMultilineAllowed,
880 KIFONT::FONT* aFont,
881 const KIFONT::METRICS& aFontMetrics,
882 void* aData )
883{
885 SetColor( aColor );
886 SetCurrentLineWidth( aWidth );
887
888 wxString text( aText );
889
890 if( text.Contains( wxS( "@{" ) ) )
891 {
892 EXPRESSION_EVALUATOR evaluator;
893 text = evaluator.Evaluate( text );
894 }
895
898
899 VECTOR2I text_pos = aPos;
900 const char* hjust = "start";
901
902 switch( aH_justify )
903 {
904 case GR_TEXT_H_ALIGN_CENTER: hjust = "middle"; break;
905 case GR_TEXT_H_ALIGN_RIGHT: hjust = "end"; break;
906 case GR_TEXT_H_ALIGN_LEFT: hjust = "start"; break;
908 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
909 break;
910 }
911
912 switch( aV_justify )
913 {
914 case GR_TEXT_V_ALIGN_CENTER: text_pos.y += aSize.y / 2; break;
915 case GR_TEXT_V_ALIGN_TOP: text_pos.y += aSize.y; break;
916 case GR_TEXT_V_ALIGN_BOTTOM: break;
918 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
919 break;
920 }
921
922 VECTOR2I text_size;
923
924 // aSize.x or aSize.y is < 0 for mirrored texts.
925 // The actual text size value is the absolute value
926 text_size.x = std::abs( GRTextWidth( text, aFont, aSize, GetCurrentLineWidth(), aBold, aItalic,
927 aFontMetrics ) );
928 text_size.y = std::abs( aSize.x * 4/3 ); // Hershey font height to em size conversion
929 VECTOR2D anchor_pos_dev = userToDeviceCoordinates( aPos );
930 VECTOR2D text_pos_dev = userToDeviceCoordinates( text_pos );
931 VECTOR2D sz_dev = userToDeviceSize( text_size );
932
933 // Output the text as a hidden string (opacity = 0). This allows WYSIWYG search to highlight
934 // a selection in approximately the right area. It also makes it easier for those that need
935 // to edit the text (as text) in subsequent processes.
936 {
937 if( !aOrient.IsZero() )
938 {
939 fmt::print( m_outputFile,
940 "<g transform=\"rotate({:f} {:.{}f} {:.{}f})\">\n",
941 m_plotMirror ? aOrient.AsDegrees() : -aOrient.AsDegrees(),
942 anchor_pos_dev.x,
944 anchor_pos_dev.y,
945 m_precision );
946 }
947
948 fmt::print( m_outputFile,
949 "<text x=\"{:.{}f}\" y=\"{:.{}f}\"\n",
950 text_pos_dev.x, m_precision,
951 text_pos_dev.y, m_precision );
952
954 if( m_plotMirror != ( aSize.x < 0 ) )
955 {
956 fmt::print( m_outputFile, "transform=\"scale(-1 1) translate({:f} 0)\"\n",
957 -2 * text_pos_dev.x );
958 }
959
960 fmt::print( m_outputFile,
961 "textLength=\"{:.{}f}\" font-size=\"{:.{}f}\" lengthAdjust=\"spacingAndGlyphs\"\n"
962 "text-anchor=\"{}\" opacity=\"0\" stroke-opacity=\"0\">{}</text>\n",
963 sz_dev.x,
965 sz_dev.y,
967 hjust,
968 TO_UTF8( XmlEsc( text ) ) );
969
970 if( !aOrient.IsZero() )
971 fmt::print( m_outputFile, "</g>\n" );
972 }
973
974 // Output the text again as graphics with a <desc> tag (for non-WYSIWYG search and for
975 // screen readers)
976 {
977 fmt::print( m_outputFile,
978 "<g class=\"stroked-text\"><desc>{}</desc>\n",
979 TO_UTF8( XmlEsc( text ) ) );
980
981 PLOTTER::Text( aPos, aColor, text, aOrient, aSize, aH_justify, aV_justify, GetCurrentLineWidth(),
982 aItalic, aBold, aMultilineAllowed, aFont, aFontMetrics );
983
984 fmt::print( m_outputFile, "</g>" );
985 }
986}
987
988
990 const COLOR4D& aColor,
991 const wxString& aText,
992 const TEXT_ATTRIBUTES& aAttributes,
993 KIFONT::FONT* aFont,
994 const KIFONT::METRICS& aFontMetrics,
995 void* aData )
996{
997 VECTOR2I size = aAttributes.m_Size;
998
999 if( aAttributes.m_Mirrored )
1000 size.x = -size.x;
1001
1002 SVG_PLOTTER::Text( aPos, aColor, aText, aAttributes.m_Angle, size, aAttributes.m_Halign,
1003 aAttributes.m_Valign, aAttributes.m_StrokeWidth, aAttributes.m_Italic,
1004 aAttributes.m_Bold, aAttributes.m_Multiline, aFont, aFontMetrics, aData );
1005}
int blue
int red
int green
static wxString XmlEsc(const wxString &aStr, bool isAttribute=false)
Translates '<' to "<", '>' to ">" and so on, according to the spec: http://www.w3....
BOX2< VECTOR2I > BOX2I
Definition box2.h:927
BOX2< VECTOR2D > BOX2D
Definition box2.h:928
constexpr const Vec & GetPosition() const
Definition box2.h:208
constexpr const Vec GetEnd() const
Definition box2.h:209
constexpr BOX2< Vec > & Normalize()
Ensure that the height and width are positive.
Definition box2.h:143
constexpr const Vec & GetOrigin() const
Definition box2.h:207
constexpr const SizeVec & GetSize() const
Definition box2.h:203
double AsDegrees() const
Definition eda_angle.h:116
bool IsZero() const
Definition eda_angle.h:136
double AsRadians() const
Definition eda_angle.h:120
High-level wrapper for evaluating mathematical and string expressions in wxString format.
wxString Evaluate(const wxString &aInput)
Main evaluation function - processes input string and evaluates all} expressions.
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
double GetDotMarkLenIU(int aLineWidth) const
Definition plotter.cpp:132
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor)
Only PostScript plotters can plot bitmaps.
Definition plotter.cpp:258
double GetDashGapLenIU(int aLineWidth) const
Definition plotter.cpp:144
bool m_mirrorIsHorizontal
Definition plotter.h:713
PAGE_INFO m_pageInfo
Definition plotter.h:731
bool m_plotMirror
Definition plotter.h:711
static const int USE_DEFAULT_LINE_WIDTH
Definition plotter.h:140
bool m_yaxisReversed
Definition plotter.h:714
double m_iuPerDeviceUnit
Definition plotter.h:708
VECTOR2I m_plotOffset
Definition plotter.h:710
VECTOR2I m_penLastpos
Definition plotter.h:724
virtual VECTOR2D userToDeviceCoordinates(const VECTOR2I &aCoordinate)
Modify coordinates according to the orientation, scale factor, and offsets trace.
Definition plotter.cpp:91
VECTOR2I m_paperSize
Definition plotter.h:732
virtual VECTOR2D userToDeviceSize(const VECTOR2I &size)
Modify size according to the plotter scale factors (VECTOR2I version, returns a VECTOR2D).
Definition plotter.cpp:116
char m_penState
Definition plotter.h:723
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness)
Generic fallback: Cubic Bezier curve rendered as a polyline.
Definition plotter.cpp:230
wxString m_creator
Definition plotter.h:726
int m_currentPenWidth
Definition plotter.h:722
double m_plotScale
Plot scale - chosen by the user (even implicitly with 'fit in a4')
Definition plotter.h:700
FILE * m_outputFile
Output file.
Definition plotter.h:717
static const int DO_NOT_SET_LINE_WIDTH
Definition plotter.h:139
RENDER_SETTINGS * m_renderSettings
Definition plotter.h:736
virtual void Text(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const EDA_ANGLE &aOrient, const VECTOR2I &aSize, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_T aV_justify, int aPenWidth, bool aItalic, bool aBold, bool aMultilineAllowed, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr)
Draw text with the plotter.
Definition plotter.cpp:547
double m_IUsPerDecimil
Definition plotter.h:706
virtual int GetCurrentLineWidth() const
Definition plotter.h:182
bool m_colorMode
Definition plotter.h:720
double GetDashMarkLenIU(int aLineWidth) const
Definition plotter.cpp:138
wxString m_filename
Definition plotter.h:727
Container for project specific data.
Definition project.h:63
virtual void SetColor(const COLOR4D &color) override
The SetColor implementation is split with the subclasses: the PSLIKE computes the rgb values,...
PSLIKE_PLOTTER(const PROJECT *aProject=nullptr)
virtual void SetTextMode(PLOT_TEXT_MODE mode) override
PS and PDF fully implement native text (for the Latin-1 subset)
virtual void emitSetRGBColor(double r, double g, double b, double a) override
Initialize m_pen_rgb_color from reduced values r, g ,b ( reduced values are 0.0 to 1....
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor) override
PostScript-likes at the moment are the only plot engines supporting bitmaps.
unsigned m_precision
virtual bool StartPlot(const wxString &aPageNumber) override
Create SVG file header.
virtual void SetPlotBBox(const BOX2I &aBBoxIU) override
Set an explicit bounding box for the plotted content (in IUs).
virtual void EndBlock(void *aData) override
Calling this function allows one to define the end of a group of drawing items the group is started b...
virtual void SetViewport(const VECTOR2I &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
LINE_STYLE m_dashed
SVG_PLOTTER(const PROJECT *aProject=nullptr)
virtual void Text(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const EDA_ANGLE &aOrient, const VECTOR2I &aSize, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_T aV_justify, int aWidth, bool aItalic, bool aBold, bool aMultilineAllowed, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr) override
Draw text with the plotter.
uint32_t m_brush_rgb_color
virtual void Rect(const VECTOR2I &p1, const VECTOR2I &p2, FILL_T fill, int width, int aCornerRadius=0) override
virtual void SetSvgCoordinatesFormat(unsigned aPrecision) override
Select SVG coordinate precision (number of digits needed for 1 mm ) (SVG plotter uses always metric u...
virtual bool EndPlot() override
void setSVGPlotStyle(int aLineWidth, bool aIsGroup=true, const std::string &aExtraStyle={})
Output the string which define pen and brush color, shape, transparency.
std::optional< BOX2I > m_plotBBoxIU
virtual void Circle(const VECTOR2I &pos, int diametre, FILL_T fill, int width) override
virtual void PlotPoly(const std::vector< VECTOR2I > &aCornerList, FILL_T aFill, int aWidth, void *aData) override
Draw a polygon ( filled or not ).
virtual void PlotText(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const TEXT_ATTRIBUTES &aAttributes, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr) override
virtual VECTOR2D userToDeviceCoordinates(const VECTOR2I &aCoordinate) override
Modify coordinates according to the orientation, scale factor, and offsets trace.
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness) override
Generic fallback: Cubic Bezier curve rendered as a polyline.
virtual void Arc(const VECTOR2D &aCenter, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aAngle, double aRadius, FILL_T aFill, int aWidth) override
virtual void PenTo(const VECTOR2I &pos, char plume) override
Moveto/lineto primitive, moves the 'pen' to the specified direction.
uint32_t m_pen_rgb_color
virtual void SetDash(int aLineWidth, LINE_STYLE aLineStyle) override
SVG supports dashed lines.
virtual void StartBlock(void *aData) override
Calling this function allows one to define the beginning of a group of drawing items (used in SVG for...
void setFillMode(FILL_T fill)
Prepare parameters for setSVGPlotStyle()
virtual void SetCurrentLineWidth(int width, void *aData=nullptr) override
Set the current line width (in IUs) for the next plot.
GR_TEXT_H_ALIGN_T m_Halign
GR_TEXT_V_ALIGN_T m_Valign
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:426
FILL_T
Definition eda_fill.h:29
@ FILLED_WITH_COLOR
Definition eda_fill.h:33
@ NO_FILL
Definition eda_fill.h:30
@ REVERSE_HATCH
Definition eda_fill.h:35
@ HATCH
Definition eda_fill.h:34
@ FILLED_WITH_BG_BODYCOLOR
Definition eda_fill.h:32
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
@ CROSS_HATCH
Definition eda_fill.h:36
int GRTextWidth(const wxString &aText, KIFONT::FONT *aFont, const VECTOR2I &aSize, int aThickness, bool aBold, bool aItalic, const KIFONT::METRICS &aFontMetrics)
Definition gr_text.cpp:95
This file contains miscellaneous commonly used macros and functions.
void encode(const std::vector< uint8_t > &aInput, std::vector< uint8_t > &aOutput)
Definition base64.cpp:76
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:411
Plotting engines similar to ps (PostScript, Gerber, svg)
wxString GetISO8601CurrentDateTime()
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
LINE_STYLE
Dashed line types.
int radius
VECTOR2I end
GR_TEXT_H_ALIGN_T
This is API surface mapped to common.types.HorizontalAlignment.
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
@ GR_TEXT_H_ALIGN_INDETERMINATE
GR_TEXT_V_ALIGN_T
This is API surface mapped to common.types.VertialAlignment.
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_INDETERMINATE
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
#define M_PI
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition trigo.cpp:225
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683
VECTOR2< double > VECTOR2D
Definition vector2d.h:682