KiCad PCB EDA Suite
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 (C) 1992-2022 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, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25/* Some info on basic items SVG format, used here:
26 * The root element of all SVG files is the <svg> element.
27 *
28 * The <g> element is used to group SVG shapes together.
29 * Once grouped you can transform the whole group of shapes as if it was a single shape.
30 * This is an advantage compared to a nested <svg> element
31 * which cannot be the target of transformation by itself.
32 *
33 * The <rect> element represents a rectangle.
34 * Using this element you can draw rectangles of various width, height,
35 * with different stroke (outline) and fill colors, with sharp or rounded corners etc.
36 *
37 * <svg xmlns="http://www.w3.org/2000/svg"
38 * xmlns:xlink="http://www.w3.org/1999/xlink">
39 *
40 * <rect x="10" y="10" height="100" width="100"
41 * style="stroke:#006600; fill: #00cc00"/>
42 *
43 * </svg>
44 *
45 * The <circle> element is used to draw circles.
46 * <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
47 *
48 * The <ellipse> element is used to draw ellipses.
49 * An ellipse is a circle that does not have equal height and width.
50 * Its radius in the x and y directions are different, in other words.
51 * <ellipse cx="40" cy="40" rx="30" ry="15"
52 * style="stroke:#006600; fill:#00cc00"/>
53 *
54 * The <line> element is used to draw lines.
55 *
56 * <line x1="0" y1="10" x2="0" y2="100" style="stroke:#006600;"/>
57 * <line x1="10" y1="10" x2="100" y2="100" style="stroke:#006600;"/>
58 *
59 * The <polyline> element is used to draw multiple connected lines
60 * Here is a simple example:
61 *
62 * <polyline points="0,0 30,0 15,30" style="stroke:#006600;"/>
63 *
64 * The <polygon> element is used to draw with multiple (3 or more) sides / edges.
65 * Here is a simple example:
66 *
67 * <polygon points="0,0 50,0 25,50" style="stroke:#660000; fill:#cc3333;"/>
68 *
69 * The <path> element is used to draw advanced shapes combined from lines and arcs,
70 * with or without fill.
71 * It is probably the most advanced and versatile SVG shape of them all.
72 * It is probably also the hardest element to master.
73 * <path d="M50,50
74 * A30,30 0 0,1 35,20
75 * L100,100
76 * M110,110
77 * L100,0"
78 * style="stroke:#660000; fill:none;"/>
79 *
80 * Draw an elliptic arc: it is one of basic path command:
81 * <path d="M(startx,starty) A(radiusx,radiusy)
82 * rotation-axe-x
83 * flag_arc_large,flag_sweep endx,endy">
84 * flag_arc_large: 0 = small arc > 180 deg, 1 = large arc > 180 deg
85 * flag_sweep : 0 = CCW, 1 = CW
86 * The center of ellipse is automatically calculated.
87 */
88
89#include <base64.h>
90#include <eda_shape.h>
91#include <string_utils.h>
92#include <font/font.h>
93#include <macros.h>
94#include <trigo.h>
95
96#include <cstdint>
97#include <wx/mstream.h>
98
100
101// Note:
102// During tests, we (JPC) found issues when the coordinates used 6 digits in mantissa
103// especially for stroke-width using very small (but not null) values < 0.00001 mm
104// So to avoid this king of issue, we are using 4 digits in mantissa
105// The resolution (m_precision ) is 0.1 micron, that looks enougt for a SVG file
106
112static wxString XmlEsc( const wxString& aStr, bool isAttribute = false )
113{
114 wxString escaped;
115
116 escaped.reserve( aStr.length() );
117
118 for( wxString::const_iterator it = aStr.begin(); it != aStr.end(); ++it )
119 {
120 const wxChar c = *it;
121
122 switch( c )
123 {
124 case wxS( '<' ):
125 escaped.append( wxS( "&lt;" ) );
126 break;
127 case wxS( '>' ):
128 escaped.append( wxS( "&gt;" ) );
129 break;
130 case wxS( '&' ):
131 escaped.append( wxS( "&amp;" ) );
132 break;
133 case wxS( '\r' ):
134 escaped.append( wxS( "&#xD;" ) );
135 break;
136 default:
137 if( isAttribute )
138 {
139 switch( c )
140 {
141 case wxS( '"' ):
142 escaped.append( wxS( "&quot;" ) );
143 break;
144 case wxS( '\t' ):
145 escaped.append( wxS( "&#x9;" ) );
146 break;
147 case wxS( '\n' ):
148 escaped.append( wxS( "&#xA;" ));
149 break;
150 default:
151 escaped.append(c);
152 }
153 }
154 else
155 escaped.append(c);
156 }
157 }
158
159 return escaped;
160}
161
162
164{
165 m_graphics_changed = true;
167 m_fillMode = FILL_T::NO_FILL; // or FILLED_SHAPE or FILLED_WITH_BG_BODYCOLOR
168 m_pen_rgb_color = 0; // current color value (black)
169 m_brush_rgb_color = 0; // current color value (black)
170 m_brush_alpha = 1.0;
172 m_useInch = false; // millimeters are always the svg unit
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
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
208{
210
213}
214
215
217{
218 if( m_fillMode != fill )
219 {
220 m_graphics_changed = true;
221 m_fillMode = fill;
222 }
223}
224
225
226void SVG_PLOTTER::setSVGPlotStyle( int aLineWidth, bool aIsGroup, const std::string& aExtraStyle )
227{
228 if( aIsGroup )
229 fputs( "</g>\n<g ", m_outputFile );
230
231 // output the background fill color
232 fprintf( m_outputFile, "style=\"fill:#%6.6lX; ", m_brush_rgb_color );
233
234 switch( m_fillMode )
235 {
236 case FILL_T::NO_FILL:
237 fputs( "fill-opacity:0.0; ", m_outputFile );
238 break;
239
243 fprintf( m_outputFile, "fill-opacity:%.*f; ", m_precision, m_brush_alpha );
244 break;
245 }
246
247 double pen_w = userToDeviceSize( aLineWidth );
248
249 if( pen_w < 0.0 ) // Ensure pen width validity
250 pen_w = 0.0;
251
252 // Fix a strange issue found in Inkscape: aWidth < 100 nm create issues on degrouping objects
253 // So we use only 4 digits in mantissa for stroke-width.
254 // TODO: perhaps used only 3 or 4 digits in mantissa for all values in mm, because some
255 // issues were previously reported reported when using nm as integer units
256
257 fprintf( m_outputFile, "\nstroke:#%6.6lX; stroke-width:%.*f; stroke-opacity:1; \n",
259 fputs( "stroke-linecap:round; stroke-linejoin:round;", m_outputFile );
260
261 //set any extra attributes for non-solid lines
262 switch( m_dashed )
263 {
265 fprintf( m_outputFile, "stroke-dasharray:%.*f,%.*f;",
266 m_precision, GetDashMarkLenIU( aLineWidth ),
267 m_precision, GetDashGapLenIU( aLineWidth ) );
268 break;
269
271 fprintf( m_outputFile, "stroke-dasharray:%f,%f;",
272 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
273 break;
274
276 fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f;",
277 GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
278 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
279 break;
280
282 fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f,%f,%f;",
283 GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
284 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
285 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
286 break;
287
290 default:
291 //do nothing
292 break;
293 }
294
295 if( aExtraStyle.length() )
296 fputs( aExtraStyle.c_str(), m_outputFile );
297
298 fputs( "\"", m_outputFile );
299
300 if( aIsGroup )
301 {
302 fputs( ">", m_outputFile );
303 m_graphics_changed = false;
304 }
305
306 fputs( "\n", m_outputFile );
307}
308
309
310void SVG_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
311{
312 if( aWidth == DO_NOT_SET_LINE_WIDTH )
313 return;
314 else if( aWidth == USE_DEFAULT_LINE_WIDTH )
316
317 // Note: aWidth == 0 is fine: used for filled shapes with no outline thickness
318
319 wxASSERT_MSG( aWidth >= 0, "Plotter called to set negative pen width" );
320
321 if( aWidth != m_currentPenWidth )
322 {
323 m_graphics_changed = true;
324 m_currentPenWidth = aWidth;
325 }
326
328 setSVGPlotStyle( aWidth );
329}
330
331
332void SVG_PLOTTER::StartBlock( void* aData )
333{
334 std::string* idstr = reinterpret_cast<std::string*>( aData );
335
336 fputs( "<g ", m_outputFile );
337
338 if( idstr )
339 fprintf( m_outputFile, "id=\"%s\"", idstr->c_str() );
340
341 fprintf( m_outputFile, ">\n" );
342}
343
344
345void SVG_PLOTTER::EndBlock( void* aData )
346{
347 fprintf( m_outputFile, "</g>\n" );
348
349 m_graphics_changed = true;
350}
351
352
353void SVG_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
354{
355 int red = (int) ( 255.0 * r );
356 int green = (int) ( 255.0 * g );
357 int blue = (int) ( 255.0 * b );
358 long rgb_color = (red << 16) | (green << 8) | blue;
359
360 if( m_pen_rgb_color != rgb_color )
361 {
362 m_graphics_changed = true;
363 m_pen_rgb_color = rgb_color;
364
365 // Currently, use the same color for brush and pen (i.e. to draw and fill a contour).
366 m_brush_rgb_color = rgb_color;
367 m_brush_alpha = a;
368 }
369}
370
371
372void SVG_PLOTTER::SetDash( int aLineWidth, PLOT_DASH_TYPE aLineStyle )
373{
374 if( m_dashed != aLineStyle )
375 {
376 m_graphics_changed = true;
377 m_dashed = aLineStyle;
378 }
379
381 setSVGPlotStyle( aLineWidth );
382}
383
384
385void SVG_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width )
386{
387 BOX2I rect( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
388 rect.Normalize();
389
390 VECTOR2D org_dev = userToDeviceCoordinates( rect.GetOrigin() );
391 VECTOR2D end_dev = userToDeviceCoordinates( rect.GetEnd() );
392 VECTOR2D size_dev = end_dev - org_dev;
393
394 // Ensure size of rect in device coordinates is > 0
395 // I don't know if this is a SVG issue or a Inkscape issue, but
396 // Inkscape has problems with negative or null values for width and/or height, so avoid them
397 BOX2D rect_dev( org_dev, size_dev );
398 rect_dev.Normalize();
399
400 setFillMode( fill );
401 SetCurrentLineWidth( width );
402
403 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
404 // so use a line when happens.
405 if( rect_dev.GetSize().x == 0.0 || rect_dev.GetSize().y == 0.0 ) // Draw a line
406 {
407 fprintf( m_outputFile,
408 "<line x1=\"%.*f\" y1=\"%.*f\" x2=\"%.*f\" y2=\"%.*f\" />\n",
409 m_precision, rect_dev.GetPosition().x, m_precision, rect_dev.GetPosition().y,
410 m_precision, rect_dev.GetEnd().x, m_precision, rect_dev.GetEnd().y );
411 }
412 else
413 {
414 fprintf( m_outputFile,
415 "<rect x=\"%f\" y=\"%f\" width=\"%f\" height=\"%f\" rx=\"%f\" />\n",
416 rect_dev.GetPosition().x, rect_dev.GetPosition().y,
417 rect_dev.GetSize().x, rect_dev.GetSize().y,
418 0.0 /* radius of rounded corners */ );
419 }
420}
421
422
423void SVG_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T fill, int width )
424{
425 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
426 double radius = userToDeviceSize( diametre / 2.0 );
427
428 setFillMode( fill );
429 SetCurrentLineWidth( width );
430
431 // If diameter is less than width, switch to filled mode
432 if( fill == FILL_T::NO_FILL && diametre < width )
433 {
436
437 radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
438 }
439
440 fprintf( m_outputFile,
441 "<circle cx=\"%.*f\" cy=\"%.*f\" r=\"%.*f\" /> \n",
442 m_precision, pos_dev.x, m_precision, pos_dev.y, m_precision, radius );
443}
444
445
446void SVG_PLOTTER::Arc( const VECTOR2I& aCenter, const EDA_ANGLE& aStartAngle,
447 const EDA_ANGLE& aEndAngle, int aRadius, FILL_T aFill, int aWidth )
448{
449 /* Draws an arc of a circle, centered on (xc,yc), with starting point (x1, y1) and ending
450 * at (x2, y2). The current pen is used for the outline and the current brush for filling
451 * the shape.
452 *
453 * The arc is drawn in an anticlockwise direction from the start point to the end point.
454 */
455
456 if( aRadius <= 0 )
457 {
458 Circle( aCenter, aWidth, FILL_T::FILLED_SHAPE, 0 );
459 return;
460 }
461
462 EDA_ANGLE startAngle( aStartAngle );
463 EDA_ANGLE endAngle( aEndAngle );
464
465 if( startAngle > endAngle )
466 std::swap( startAngle, endAngle );
467
468 // Calculate start point.
469 VECTOR2D centre_device = userToDeviceCoordinates( aCenter );
470 double radius_device = userToDeviceSize( aRadius );
471
472 if( m_plotMirror )
473 {
475 {
476 std::swap( startAngle, endAngle );
477 startAngle = ANGLE_180 - startAngle;
478 endAngle = ANGLE_180 - endAngle;
479 }
480 else
481 {
482 startAngle = -startAngle;
483 endAngle = -endAngle;
484 }
485 }
486
487 VECTOR2D start;
488 start.x = radius_device;
489 RotatePoint( start, startAngle );
490 VECTOR2D end;
491 end.x = radius_device;
492 RotatePoint( end, endAngle );
493 start += centre_device;
494 end += centre_device;
495
496 double theta1 = startAngle.AsRadians();
497
498 if( theta1 < 0 )
499 theta1 = theta1 + M_PI * 2;
500
501 double theta2 = endAngle.AsRadians();
502
503 if( theta2 < 0 )
504 theta2 = theta2 + M_PI * 2;
505
506 if( theta2 < theta1 )
507 theta2 = theta2 + M_PI * 2;
508
509 int flg_arc = 0; // flag for large or small arc. 0 means less than 180 degrees
510
511 if( fabs( theta2 - theta1 ) > M_PI )
512 flg_arc = 1;
513
514 int flg_sweep = 0; // flag for sweep always 0
515
516 // Draw a single arc: an arc is one of 3 curve commands (2 other are 2 bezier curves)
517 // params are start point, radius1, radius2, X axe rotation,
518 // flag arc size (0 = small arc > 180 deg, 1 = large arc > 180 deg),
519 // sweep arc ( 0 = CCW, 1 = CW),
520 // end point
521 if( aFill != FILL_T::NO_FILL )
522 {
523 // Filled arcs (in Eeschema) consist of the pie wedge and a stroke only on the arc
524 // This needs to be drawn in two steps.
525 setFillMode( aFill );
527
528 fprintf( m_outputFile, "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f L %.*f %.*f Z\" />\n",
529 m_precision, start.x, m_precision, start.y,
530 m_precision, radius_device, m_precision, radius_device,
531 flg_arc, flg_sweep,
532 m_precision, end.x, m_precision, end.y,
533 m_precision, centre_device.x, m_precision, centre_device.y );
534 }
535
537 SetCurrentLineWidth( aWidth );
538 fprintf( m_outputFile, "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f\" />\n",
539 m_precision, start.x, m_precision, start.y,
540 m_precision, radius_device, m_precision, radius_device,
541 flg_arc, flg_sweep,
542 m_precision, end.x, m_precision, end.y );
543}
544
545
546void SVG_PLOTTER::BezierCurve( const VECTOR2I& aStart, const VECTOR2I& aControl1,
547 const VECTOR2I& aControl2, const VECTOR2I& aEnd,
548 int aTolerance, int aLineThickness )
549{
550#if 1
552 SetCurrentLineWidth( aLineThickness );
553
554 VECTOR2D start = userToDeviceCoordinates( aStart );
555 VECTOR2D ctrl1 = userToDeviceCoordinates( aControl1 );
556 VECTOR2D ctrl2 = userToDeviceCoordinates( aControl2 );
557 VECTOR2D end = userToDeviceCoordinates( aEnd );
558
559 // Generate a cubic curve: start point and 3 other control points.
560 fprintf( m_outputFile, "<path d=\"M%.*f,%.*f C%.*f,%.*f %.*f,%.*f %.*f,%.*f\" />\n",
561 m_precision, start.x, m_precision, start.y,
562 m_precision, ctrl1.x, m_precision, ctrl1.y,
563 m_precision, ctrl2.x, m_precision, ctrl2.y,
564 m_precision, end.x, m_precision, end.y );
565#else
566 PLOTTER::BezierCurve( aStart, aControl1, aControl2, aEnd, aTolerance, aLineThickness );
567#endif
568}
569
570
571void SVG_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill,
572 int aWidth, void* aData )
573{
574 if( aCornerList.size() <= 1 )
575 return;
576
577 setFillMode( aFill );
578 SetCurrentLineWidth( aWidth );
579 fprintf( m_outputFile, "<path ");
580
581 switch( aFill )
582 {
583 case FILL_T::NO_FILL:
584 setSVGPlotStyle( aWidth, false, "fill:none" );
585 break;
586
590 setSVGPlotStyle( aWidth, false, "fill-rule:evenodd;" );
591 break;
592 }
593
594 VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
595 fprintf( m_outputFile, "d=\"M %.*f,%.*f\n", m_precision, pos.x, m_precision, pos.y );
596
597 for( unsigned ii = 1; ii < aCornerList.size() - 1; ii++ )
598 {
599 pos = userToDeviceCoordinates( aCornerList[ii] );
600 fprintf( m_outputFile, "%.*f,%.*f\n", m_precision, pos.x, m_precision, pos.y );
601 }
602
603 // If the corner list ends where it begins, then close the poly
604 if( aCornerList.front() == aCornerList.back() )
605 {
606 fprintf( m_outputFile, "Z\" /> \n" );
607 }
608 else
609 {
610 pos = userToDeviceCoordinates( aCornerList.back() );
611 fprintf( m_outputFile, "%.*f,%.*f\n\" /> \n", m_precision, pos.x, m_precision, pos.y );
612 }
613}
614
615
616void SVG_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor )
617{
618 VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );
619
620 // Requested size (in IUs)
621 VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );
622
623 // calculate the bitmap start position
624 VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y - drawsize.y / 2 );
625
626 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
627 // so use a line when happens.
628 if( drawsize.x == 0.0 || drawsize.y == 0.0 ) // Draw a line
629 {
630 PLOTTER::PlotImage( aImage, aPos, aScaleFactor );
631 }
632 else
633 {
634 wxMemoryOutputStream img_stream;
635
636 aImage.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
637 size_t input_len = img_stream.GetOutputStreamBuffer()->GetBufferSize();
638 std::vector<uint8_t> buffer( input_len );
639 std::vector<uint8_t> encoded;
640
641 img_stream.CopyTo( buffer.data(), buffer.size() );
642 base64::encode( buffer, encoded );
643
644 fprintf( m_outputFile,
645 "<image x=\"%f\" y=\"%f\" xlink:href=\"data:image/png;base64,",
646 userToDeviceSize( start.x ), userToDeviceSize( start.y ) );
647
648 for( size_t i = 0; i < encoded.size(); i++ )
649 {
650 fprintf( m_outputFile, "%c", static_cast<char>( encoded[i] ) );
651
652 if( ( i % 64 ) == 63 )
653 fprintf( m_outputFile, "\n" );
654 }
655
656 fprintf( m_outputFile, "\"\npreserveAspectRatio=\"none\" width=\"%.*f\" height=\"%.*f\" />",
657 m_precision, userToDeviceSize( drawsize.x ), m_precision, userToDeviceSize( drawsize.y ) );
658 }
659}
660
661
662void SVG_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
663{
664 if( plume == 'Z' )
665 {
666 if( m_penState != 'Z' )
667 {
668 fputs( "\" />\n", m_outputFile );
669 m_penState = 'Z';
670 m_penLastpos.x = -1;
671 m_penLastpos.y = -1;
672 }
673
674 return;
675 }
676
677 if( m_penState == 'Z' ) // here plume = 'D' or 'U'
678 {
679 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
680
681 // Ensure we do not use a fill mode when moving the pen,
682 // in SVG mode (i;e. we are plotting only basic lines, not a filled area
684 {
687 }
688
689 fprintf( m_outputFile, "<path d=\"M%.*f %.*f\n",
690 m_precision, pos_dev.x,
691 m_precision, pos_dev.y );
692 }
693 else if( m_penState != plume || pos != m_penLastpos )
694 {
695 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
696
697 fprintf( m_outputFile, "L%.*f %.*f\n",
698 m_precision, pos_dev.x,
699 m_precision, pos_dev.y );
700 }
701
702 m_penState = plume;
703 m_penLastpos = pos;
704}
705
706
707bool SVG_PLOTTER::StartPlot( const wxString& aPageNumber )
708{
709 wxASSERT( m_outputFile );
710
711 static const char* header[] =
712 {
713 "<?xml version=\"1.0\" standalone=\"no\"?>\n",
714 " <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n",
715 " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"> \n",
716 "<svg\n"
717 " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"
718 " xmlns=\"http://www.w3.org/2000/svg\"\n",
719 " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n",
720 " version=\"1.1\"\n",
721 nullptr
722 };
723
724 // Write header.
725 for( int ii = 0; header[ii] != nullptr; ii++ )
726 {
727 fputs( header[ii], m_outputFile );
728 }
729
730 // Write viewport pos and size
731 VECTOR2D origin; // TODO set to actual value
732 fprintf( m_outputFile, " width=\"%.*fmm\" height=\"%.*fmm\" viewBox=\"%.*f %.*f %.*f %.*f\">\n",
733 m_precision, (double) m_paperSize.x / m_IUsPerDecimil * 2.54 / 1000,
734 m_precision, (double) m_paperSize.y / m_IUsPerDecimil * 2.54 / 1000,
735 m_precision, origin.x, m_precision, origin.y,
738
739 // Write title
740 char date_buf[250];
741 time_t ltime = time( nullptr );
742 strftime( date_buf, 250, "%Y/%m/%d %H:%M:%S", localtime( &ltime ) );
743
744 fprintf( m_outputFile,
745 "<title>SVG Picture created as %s date %s </title>\n",
746 TO_UTF8( XmlEsc( wxFileName( m_filename ).GetFullName() ) ), date_buf );
747
748 // End of header
749 fprintf( m_outputFile, " <desc>Picture generated by %s </desc>\n",
750 TO_UTF8( XmlEsc( m_creator ) ) );
751
752 // output the pen and brush color (RVB values in hex) and opacity
753 double opacity = 1.0; // 0.0 (transparent to 1.0 (solid)
754 fprintf( m_outputFile,
755 "<g style=\"fill:#%6.6lX; fill-opacity:%.*f;stroke:#%6.6lX; stroke-opacity:%.*f;\n",
757
758 // output the pen cap and line joint
759 fputs( "stroke-linecap:round; stroke-linejoin:round;\"\n", m_outputFile );
760 fputs( " transform=\"translate(0 0) scale(1 1)\">\n", m_outputFile );
761 return true;
762}
763
764
766{
767 fputs( "</g> \n</svg>\n", m_outputFile );
768 fclose( m_outputFile );
769 m_outputFile = nullptr;
770
771 return true;
772}
773
774
775void SVG_PLOTTER::Text( const VECTOR2I& aPos,
776 const COLOR4D& aColor,
777 const wxString& aText,
778 const EDA_ANGLE& aOrient,
779 const VECTOR2I& aSize,
780 enum GR_TEXT_H_ALIGN_T aH_justify,
781 enum GR_TEXT_V_ALIGN_T aV_justify,
782 int aWidth,
783 bool aItalic,
784 bool aBold,
785 bool aMultilineAllowed,
786 KIFONT::FONT* aFont,
787 void* aData )
788{
790 SetColor( aColor );
791 SetCurrentLineWidth( aWidth );
792
793 VECTOR2I text_pos = aPos;
794 const char* hjust = "start";
795
796 switch( aH_justify )
797 {
798 case GR_TEXT_H_ALIGN_CENTER: hjust = "middle"; break;
799 case GR_TEXT_H_ALIGN_RIGHT: hjust = "end"; break;
800 case GR_TEXT_H_ALIGN_LEFT: hjust = "start"; break;
801 }
802
803 switch( aV_justify )
804 {
805 case GR_TEXT_V_ALIGN_CENTER: text_pos.y += aSize.y / 2; break;
806 case GR_TEXT_V_ALIGN_TOP: text_pos.y += aSize.y; break;
807 case GR_TEXT_V_ALIGN_BOTTOM: break;
808 }
809
810 VECTOR2I text_size;
811
812 // aSize.x or aSize.y is < 0 for mirrored texts.
813 // The actual text size value is the absolute value
814 text_size.x = std::abs( GraphicTextWidth( aText, aFont, aSize, aWidth, aBold, aItalic ) );
815 text_size.y = std::abs( aSize.x * 4/3 ); // Hershey font height to em size conversion
816 VECTOR2D anchor_pos_dev = userToDeviceCoordinates( aPos );
817 VECTOR2D text_pos_dev = userToDeviceCoordinates( text_pos );
818 VECTOR2D sz_dev = userToDeviceSize( text_size );
819
820 if( !aOrient.IsZero() )
821 {
822 fprintf( m_outputFile,
823 "<g transform=\"rotate(%f %.*f %.*f)\">\n",
824 - aOrient.AsDegrees(), m_precision, anchor_pos_dev.x, m_precision, anchor_pos_dev.y );
825 }
826
827 fprintf( m_outputFile, "<text x=\"%.*f\" y=\"%.*f\"\n",
828 m_precision, text_pos_dev.x, m_precision, text_pos_dev.y );
829
831 if( aSize.x < 0 )
832 fprintf( m_outputFile, "transform=\"scale(-1 1) translate(%f 0)\"\n", -2 * text_pos_dev.x );
833
834 fprintf( m_outputFile,
835 "textLength=\"%.*f\" font-size=\"%.*f\" lengthAdjust=\"spacingAndGlyphs\"\n"
836 "text-anchor=\"%s\" opacity=\"0\">%s</text>\n",
837 m_precision, sz_dev.x, m_precision, sz_dev.y, hjust, TO_UTF8( XmlEsc( aText ) ) );
838
839 if( !aOrient.IsZero() )
840 fputs( "</g>\n", m_outputFile );
841
842 fprintf( m_outputFile, "<g class=\"stroked-text\"><desc>%s</desc>\n",
843 TO_UTF8( XmlEsc( aText ) ) );
844
845 PLOTTER::Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify, aWidth, aItalic,
846 aBold, aMultilineAllowed, aFont );
847
848 fputs( "</g>", m_outputFile );
849}
int color
Definition: DXF_plotter.cpp:57
static wxString XmlEsc(const wxString &aStr, bool isAttribute=false)
Translates '<' to "<", '>' to ">" and so on, according to the spec: http://www.w3....
BOX2< Vec > & Normalize()
Ensure that the height and width are positive.
Definition: box2.h:119
const Vec & GetPosition() const
Definition: box2.h:184
const Vec & GetOrigin() const
Definition: box2.h:183
const Vec GetEnd() const
Definition: box2.h:185
const Vec & GetSize() const
Definition: box2.h:179
double AsDegrees() const
Definition: eda_angle.h:149
bool IsZero() const
Definition: eda_angle.h:169
double AsRadians() const
Definition: eda_angle.h:153
FONT is an abstract base class for both outline and stroke fonts.
Definition: font.h:105
A color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:104
int GetDefaultPenWidth() const
const VECTOR2I & GetSizeMils() const
Definition: page_info.h:135
double GetDotMarkLenIU(int aLineWidth) const
Definition: plotter.cpp:131
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor)
Only PostScript plotters can plot bitmaps.
Definition: plotter.cpp:254
double GetDashGapLenIU(int aLineWidth) const
Definition: plotter.cpp:143
bool m_mirrorIsHorizontal
Definition: plotter.h:629
PAGE_INFO m_pageInfo
Definition: plotter.h:645
bool m_plotMirror
Definition: plotter.h:627
static const int USE_DEFAULT_LINE_WIDTH
Definition: plotter.h:114
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness=USE_DEFAULT_LINE_WIDTH)
Generic fallback: Cubic Bezier curve rendered as a polyline In KiCad the bezier curves have 4 control...
Definition: plotter.cpp:224
bool m_yaxisReversed
Definition: plotter.h:630
double m_iuPerDeviceUnit
Definition: plotter.h:624
VECTOR2I m_plotOffset
Definition: plotter.h:626
VECTOR2I m_penLastpos
Definition: plotter.h:640
virtual VECTOR2D userToDeviceCoordinates(const VECTOR2I &aCoordinate)
Modify coordinates according to the orientation, scale factor, and offsets trace.
Definition: plotter.cpp:90
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, void *aData=nullptr)
Draw text with the plotter.
Definition: plotter.cpp:714
VECTOR2I m_paperSize
Definition: plotter.h:646
virtual VECTOR2D userToDeviceSize(const VECTOR2I &size)
Modify size according to the plotter scale factors (VECTOR2I version, returns a VECTOR2D).
Definition: plotter.cpp:115
char m_penState
Definition: plotter.h:639
wxString m_creator
Definition: plotter.h:642
int m_currentPenWidth
Definition: plotter.h:638
double m_plotScale
Plot scale - chosen by the user (even implicitly with 'fit in a4')
Definition: plotter.h:616
FILE * m_outputFile
Output file.
Definition: plotter.h:633
static const int DO_NOT_SET_LINE_WIDTH
Definition: plotter.h:113
RENDER_SETTINGS * m_renderSettings
Definition: plotter.h:650
double m_IUsPerDecimil
Definition: plotter.h:622
virtual int GetCurrentLineWidth() const
Definition: plotter.h:153
double GetDashMarkLenIU(int aLineWidth) const
Definition: plotter.cpp:137
wxString m_filename
Definition: plotter.h:643
virtual void SetColor(const COLOR4D &color) override
The SetColor implementation is split with the subclasses: The PSLIKE computes the rgb values,...
Definition: PS_plotter.cpp:62
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 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 PlotPoly(const std::vector< VECTOR2I > &aCornerList, FILL_T aFill, int aWidth=USE_DEFAULT_LINE_WIDTH, void *aData=nullptr) override
Draw a polygon ( filled or not ).
virtual void SetViewport(const VECTOR2I &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness=USE_DEFAULT_LINE_WIDTH) override
Generic fallback: Cubic Bezier curve rendered as a polyline In KiCad the bezier curves have 4 control...
virtual void SetDash(int aLineWidth, PLOT_DASH_TYPE aLineStyle) override
SVG supports dashed lines.
double m_brush_alpha
virtual void Arc(const VECTOR2I &aCenter, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aEndAngle, int aRadius, FILL_T aFill, int aWidth=USE_DEFAULT_LINE_WIDTH) override
Generic fallback: arc rendered as a polyline.
virtual void Rect(const VECTOR2I &p1, const VECTOR2I &p2, FILL_T fill, int width=USE_DEFAULT_LINE_WIDTH) override
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=false, KIFONT::FONT *aFont=nullptr, void *aData=nullptr) override
Draw text with the plotter.
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
virtual void SetColor(const COLOR4D &color) override
The SetColor implementation is split with the subclasses: The PSLIKE computes the rgb values,...
void setSVGPlotStyle(int aLineWidth, bool aIsGroup=true, const std::string &aExtraStyle={})
Output the string which define pen and brush color, shape, transparency.
virtual void PenTo(const VECTOR2I &pos, char plume) override
Moveto/lineto primitive, moves the 'pen' to the specified direction.
long m_brush_rgb_color
virtual void Circle(const VECTOR2I &pos, int diametre, FILL_T fill, int width=USE_DEFAULT_LINE_WIDTH) override
bool m_graphics_changed
PLOT_DASH_TYPE m_dashed
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.
static constexpr EDA_ANGLE & ANGLE_180
Definition: eda_angle.h:416
FILL_T
Definition: eda_shape.h:54
@ FILLED_WITH_COLOR
@ FILLED_WITH_BG_BODYCOLOR
@ FILLED_SHAPE
E_SERIE r
Definition: eserie.cpp:41
int GraphicTextWidth(const wxString &aText, KIFONT::FONT *aFont, const VECTOR2I &aSize, int aThickness, bool aBold, bool aItalic)
The full X size is GraphicTextWidth + the thickness of graphic lines.
Definition: gr_text.cpp:101
This file contains miscellaneous commonly used macros and functions.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:96
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:401
Plotting engines similar to ps (PostScript, Gerber, svg)
PLOT_DASH_TYPE
Dashed line types.
Definition: stroke_params.h:48
GR_TEXT_H_ALIGN_T
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
GR_TEXT_V_ALIGN_T
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Definition: trigo.cpp:183
VECTOR2< int > VECTOR2I
Definition: vector2d.h:618