KiCad PCB EDA Suite
Loading...
Searching...
No Matches
bitmap2component.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) 1992-2019 jean-pierre.charras
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#include <algorithm> // std::max
22#include <cerrno>
23#include <cmath>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <string>
28#include <vector>
29#include <kiid.h>
30
31#include <build_version.h>
32#include <locale_io.h>
33#include <macros.h>
34#include <potracelib.h>
35#include <reporter.h>
36#include <fmt/format.h>
37#include <wx/translation.h>
38
39#include "bitmap2component.h"
40
41
42/* free a potrace bitmap */
43static void bm_free( potrace_bitmap_t* bm )
44{
45 if( bm )
46 free( bm->map );
47
48 free( bm );
49}
50
51
52static void BezierToPolyline( std::vector <potrace_dpoint_t>& aCornersBuffer,
53 potrace_dpoint_t p1, potrace_dpoint_t p2,
54 potrace_dpoint_t p3, potrace_dpoint_t p4 );
55
56
57BITMAPCONV_INFO::BITMAPCONV_INFO( std::string& aData, REPORTER& aReporter ):
58 m_Data( aData ),
59 m_reporter( aReporter )
60{
62 m_PixmapWidth = 0;
64 m_ScaleX = 1.0;
65 m_ScaleY = 1.0;
66 m_Paths = nullptr;
67 m_CmpName = "LOGO";
68}
69
70
71int BITMAPCONV_INFO::ConvertBitmap( potrace_bitmap_t* aPotrace_bitmap, OUTPUT_FMT_ID aFormat,
72 int aDpi_X, int aDpi_Y, const wxString& aLayer )
73{
74 potrace_param_t* param;
75 potrace_state_t* st;
76
77 // set tracing parameters, starting from defaults
78 param = potrace_param_default();
79
80 if( !param )
81 {
82 m_reporter.Report( fmt::format( "Error allocating parameters: {}\n", strerror( errno ) ),
84 return 1;
85 }
86
87 // For parameters: see http://potrace.sourceforge.net/potracelib.pdf
88 param->turdsize = 0; // area (in pixels) of largest path to be ignored.
89 // Potrace default is 2
90 param->opttolerance = 0.2; // curve optimization tolerance. Potrace default is 0.2
91
92 /* convert the bitmap to curves */
93 st = potrace_trace( param, aPotrace_bitmap );
94
95 if( !st || st->status != POTRACE_STATUS_OK )
96 {
97 if( st )
98 potrace_state_free( st );
99
100 potrace_param_free( param );
101
102 m_reporter.Report( fmt::format( "Error tracing bitmap: {}\n", strerror( errno ) ),
104 return 1;
105 }
106
107 m_PixmapWidth = aPotrace_bitmap->w;
108 m_PixmapHeight = aPotrace_bitmap->h; // the bitmap size in pixels
109 m_Paths = st->plist;
110 m_Format = aFormat;
111
112 switch( aFormat )
113 {
115 m_ScaleX = PL_IU_PER_MM * 25.4 / aDpi_X; // the conversion scale from PPI to micron
116 m_ScaleY = PL_IU_PER_MM * 25.4 / aDpi_Y; // Y axis is top to bottom
118 break;
119
120 case POSTSCRIPT_FMT:
121 m_ScaleX = 1.0; // the conversion scale
124 break;
125
126 case SYMBOL_FMT:
127 case SYMBOL_PASTE_FMT:
128 m_ScaleX = SCH_IU_PER_MM * 25.4 / aDpi_X; // the conversion scale from PPI to eeschema iu
129 m_ScaleY = -SCH_IU_PER_MM * 25.4 / aDpi_Y; // Y axis is bottom to Top for components in libs
131 break;
132
133 case FOOTPRINT_FMT:
134 m_ScaleX = PCB_IU_PER_MM * 25.4 / aDpi_X; // the conversion scale from PPI to IU
135 m_ScaleY = PCB_IU_PER_MM * 25.4 / aDpi_Y; // Y axis is top to bottom in Footprint Editor
136 createOutputData( aLayer );
137 break;
138 }
139
140 bm_free( aPotrace_bitmap );
141 potrace_state_free( st );
142 potrace_param_free( param );
143
144 return 0;
145}
146
147
148void BITMAPCONV_INFO::outputDataHeader( const wxString& aBrdLayerName )
149{
150 double Ypos = ( m_PixmapHeight / 2.0 * m_ScaleY ); // fields Y position in mm
151 double fieldSize; // fields text size in mm
152
153 switch( m_Format )
154 {
155 case POSTSCRIPT_FMT:
156 m_Data += "%!PS-Adobe-3.0 EPSF-3.0\n";
157 m_Data += fmt::format( "%%BoundingBox: 0 0 {} {}\n", m_PixmapWidth, m_PixmapHeight );
158 m_Data += "gsave\n";
159 break;
160
161 case FOOTPRINT_FMT:
162 // fields text size = 1.5 mm
163 // fields text thickness = 1.5 / 5 = 0.3mm
164 m_Data += fmt::format( "(footprint \"{}\" (version 20221018) (generator \"bitmap2component\") (generator_version \"{}\")\n"
165 " (layer \"F.Cu\")\n",
166 m_CmpName.c_str(),
167 GetMajorMinorVersion().ToStdString() );
168
169 m_Data += fmt::format( " (attr board_only exclude_from_pos_files exclude_from_bom)\n" );
170 m_Data += fmt::format( " (fp_text reference \"G***\" (at 0 0) (layer \"{}\")\n"
171 " (effects (font (size 1.5 1.5) (thickness 0.3)))\n"
172 " (uuid {})\n )\n",
173 aBrdLayerName.ToStdString().c_str(),
174 KIID().AsString().ToStdString().c_str() );
175
176 m_Data += fmt::format( " (fp_text value \"{}\" (at 0.75 0) (layer \"{}\") hide\n"
177 " (effects (font (size 1.5 1.5) (thickness 0.3)))\n"
178 " (uuid {})\n )\n",
179 m_CmpName.c_str(),
180 aBrdLayerName.ToStdString().c_str(),
181 KIID().AsString().ToStdString().c_str() );
182 break;
183
185 m_Data += fmt::format( "(kicad_wks (version 20220228) (generator \"bitmap2component\") (generator_version \"{}\")\n",
186 GetMajorMinorVersion().ToStdString() );
187 m_Data += " (setup (textsize 1.5 1.5)(linewidth 0.15)(textlinewidth 0.15)\n";
188 m_Data += " (left_margin 10)(right_margin 10)(top_margin 10)(bottom_margin 10))\n";
189 m_Data += " (polygon (name \"\") (pos 0 0) (linewidth 0.01)\n";
190 break;
191
192 case SYMBOL_FMT:
193 m_Data += fmt::format( "(kicad_symbol_lib (version 20220914) (generator \"bitmap2component\") (generator_version \"{}\")\n",
194 GetMajorMinorVersion().ToStdString() );
196
197 case SYMBOL_PASTE_FMT:
198 fieldSize = 1.27; // fields text size in mm (= 50 mils)
199 Ypos /= SCH_IU_PER_MM;
200 Ypos += fieldSize / 2;
201 m_Data += fmt::format( " (symbol \"{}\" (pin_names (offset 1.016)) (in_bom yes) (on_board yes)\n",
202 m_CmpName.c_str() );
203
204 m_Data += fmt::format( " (property \"Reference\" \"#G\" (at 0 {:g} 0)\n"
205 " (effects (font (size {:g} {:g})) hide)\n )\n",
206 -Ypos,
207 fieldSize,
208 fieldSize );
209
210 m_Data += fmt::format( " (property \"Value\" \"{}\" (at 0 {:g} 0)\n"
211 " (effects (font (size {:g} {:g})) hide)\n )\n",
212 m_CmpName.c_str(),
213 Ypos,
214 fieldSize,
215 fieldSize );
216
217 m_Data += fmt::format( " (property \"Footprint\" \"\" (at 0 0 0)\n"
218 " (effects (font (size {:g} {:g})) hide)\n )\n",
219 fieldSize,
220 fieldSize );
221
222 m_Data += fmt::format( " (property \"Datasheet\" \"\" (at 0 0 0)\n"
223 " (effects (font (size {:g} {:g})) hide)\n )\n",
224 fieldSize,
225 fieldSize );
226
227 m_Data += fmt::format( " (symbol \"{}_0_0\"\n", m_CmpName.c_str() );
228 break;
229 }
230}
231
232
234{
235 switch( m_Format )
236 {
237 case POSTSCRIPT_FMT:
238 m_Data += "grestore\n";
239 m_Data += "%%EOF\n";
240 break;
241
242 case FOOTPRINT_FMT:
243 m_Data += ")\n";
244 break;
245
247 m_Data += " )\n)\n";
248 break;
249
250 case SYMBOL_PASTE_FMT:
251 m_Data += " )\n"; // end symbol_0_0
252 m_Data += " )\n"; // end symbol
253 break;
254
255 case SYMBOL_FMT:
256 m_Data += " )\n"; // end symbol_0_0
257 m_Data += " )\n"; // end symbol
258 m_Data += ")\n"; // end lib
259 break;
260 }
261}
262
263
264void BITMAPCONV_INFO::outputOnePolygon( SHAPE_LINE_CHAIN& aPolygon, const wxString& aBrdLayerName )
265{
266 // write one polygon to output file.
267 // coordinates are expected in target unit.
268 int ii, jj;
269 VECTOR2I currpoint;
270 int offsetX = KiROUND( m_PixmapWidth / 2.0 * m_ScaleX );
271 int offsetY = KiROUND( m_PixmapHeight / 2.0 * m_ScaleY );
272
273 const VECTOR2I startpoint = aPolygon.CPoint( 0 );
274
275 switch( m_Format )
276 {
277 case POSTSCRIPT_FMT:
278 offsetY = (int)( m_PixmapHeight * m_ScaleY );
279 m_Data += fmt::format( "newpath\n{} {} moveto\n", startpoint.x, offsetY - startpoint.y );
280 jj = 0;
281
282 for( ii = 1; ii < aPolygon.PointCount(); ii++ )
283 {
284 currpoint = aPolygon.CPoint( ii );
285 m_Data += fmt::format( " {} {} lineto", currpoint.x, offsetY - currpoint.y );
286
287 if( jj++ > 6 )
288 {
289 jj = 0;
290 m_Data += "\n";
291 }
292 }
293
294 m_Data += "\nclosepath fill\n";
295 break;
296
297 case FOOTPRINT_FMT:
298 m_Data += " (fp_poly\n (pts\n";
299
300 jj = 0;
301
302 for( ii = 0; ii < aPolygon.PointCount(); ii++ )
303 {
304 currpoint = aPolygon.CPoint( ii );
305 m_Data += fmt::format( " (xy {} {})\n",
306 ( currpoint.x - offsetX ) / PCB_IU_PER_MM,
307 ( currpoint.y - offsetY ) / PCB_IU_PER_MM );
308 }
309 // No need to close polygon
310
311 m_Data += " )\n\n";
312 m_Data += fmt::format( " (stroke (width {:f}) (type solid)) (fill solid) (layer \"{}\") (uuid {}))\n",
313 0.0,
314 aBrdLayerName.ToStdString().c_str(),
315 KIID().AsString().ToStdString().c_str() );
316 break;
317
319 m_Data += " (pts";
320
321 // Internal units = micron, file unit = mm
322 jj = 1;
323
324 for( ii = 0; ii < aPolygon.PointCount(); ii++ )
325 {
326 currpoint = aPolygon.CPoint( ii );
327 m_Data += fmt::format( " (xy {:.3f} {:.3f})",
328 ( currpoint.x - offsetX ) / PL_IU_PER_MM,
329 ( currpoint.y - offsetY ) / PL_IU_PER_MM );
330
331 if( jj++ > 4 )
332 {
333 jj = 0;
334 m_Data += "\n ";
335 }
336 }
337
338 // Close polygon
339 m_Data += fmt::format( " (xy {:.3f} {:.3f}) )\n",
340 ( startpoint.x - offsetX ) / PL_IU_PER_MM,
341 ( startpoint.y - offsetY ) / PL_IU_PER_MM );
342 break;
343
344 case SYMBOL_FMT:
345 case SYMBOL_PASTE_FMT:
346 // The polygon outline thickness is fixed here to 0.01 ( 0.0 is the default thickness)
347#define SCH_LINE_THICKNESS_MM 0.01
348 //snprintf( strbuf, sizeof(strbuf), "P %d 0 0 %d", (int) aPolygon.PointCount() + 1, EE_LINE_THICKNESS );
349 m_Data += " (polyline\n (pts\n";
350
351 for( ii = 0; ii < aPolygon.PointCount(); ii++ )
352 {
353 currpoint = aPolygon.CPoint( ii );
354 m_Data += fmt::format( " (xy {:f} {:f})\n",
355 ( currpoint.x - offsetX ) / SCH_IU_PER_MM,
356 ( currpoint.y - offsetY ) / SCH_IU_PER_MM );
357 }
358
359 // Close polygon
360 m_Data += fmt::format( " (xy {:f} {:f})\n",
361 ( startpoint.x - offsetX ) / SCH_IU_PER_MM,
362 ( startpoint.y - offsetY ) / SCH_IU_PER_MM );
363 m_Data += " )\n"; // end pts
364
365 m_Data += fmt::format( " (stroke (width {:g}) (type default))\n"
366 " (fill (type outline))\n",
368 m_Data += " )\n"; // end polyline
369 break;
370 }
371}
372
373
374void BITMAPCONV_INFO::createOutputData( const wxString& aLayer )
375{
376 std::vector <potrace_dpoint_t> cornersBuffer;
377
378 // polyset_areas is a set of polygon to draw
379 SHAPE_POLY_SET polyset_areas;
380
381 // polyset_holes is the set of holes inside polyset_areas outlines
382 SHAPE_POLY_SET polyset_holes;
383
384 potrace_dpoint_t( *c )[3];
385
386 // The layer name has meaning only for .kicad_mod files.
387 // For these files the header creates 2 invisible texts: value and ref
388 // (needed but not useful) on silk screen layer
389 outputDataHeader( "F.SilkS" );
390
391 bool main_outline = true;
392
393 /* draw each as a polygon with no hole.
394 * Bezier curves are approximated by a polyline
395 */
396 potrace_path_t* paths = m_Paths; // the list of paths
397
398 if( !m_Paths )
399 {
400 m_reporter.Report( _( "No shape in black and white image to convert: no outline created." ),
402 }
403
404 while( paths != nullptr )
405 {
406 int cnt = paths->curve.n;
407 int* tag = paths->curve.tag;
408 c = paths->curve.c;
409 potrace_dpoint_t startpoint = c[cnt - 1][2];
410
411 for( int i = 0; i < cnt; i++ )
412 {
413 switch( tag[i] )
414 {
415 case POTRACE_CORNER:
416 cornersBuffer.push_back( c[i][1] );
417 cornersBuffer.push_back( c[i][2] );
418 startpoint = c[i][2];
419 break;
420
421 case POTRACE_CURVETO:
422 BezierToPolyline( cornersBuffer, startpoint, c[i][0], c[i][1], c[i][2] );
423 startpoint = c[i][2];
424 break;
425 }
426 }
427
428 // Store current path
429 if( main_outline )
430 {
431 main_outline = false;
432
433 // build the current main polygon
434 polyset_areas.NewOutline();
435
436 for( const potrace_dpoint_s& pt : cornersBuffer )
437 {
438 polyset_areas.Append( int( pt.x * m_ScaleX ),
439 int( pt.y * m_ScaleY ) );
440 }
441 }
442 else
443 {
444 // Add current hole in polyset_holes
445 polyset_holes.NewOutline();
446
447 for( const potrace_dpoint_s& pt : cornersBuffer )
448 {
449 polyset_holes.Append( int( pt.x * m_ScaleX ),
450 int( pt.y * m_ScaleY ) );
451 }
452 }
453
454 cornersBuffer.clear();
455
456 // at the end of a group of a positive path and its negative children, fill.
457 if( paths->next == nullptr || paths->next->sign == '+' )
458 {
459 polyset_areas.Simplify();
460 polyset_holes.Simplify();
461 polyset_areas.BooleanSubtract( polyset_holes );
462
463 // Ensure there are no self intersecting polygons
464 if( polyset_areas.NormalizeAreaOutlines() )
465 {
466 // Convert polygon with holes to a unique polygon
467 polyset_areas.Fracture();
468
469 // Output current resulting polygon(s)
470 for( int ii = 0; ii < polyset_areas.OutlineCount(); ii++ )
471 {
472 SHAPE_LINE_CHAIN& poly = polyset_areas.Outline( ii );
473 outputOnePolygon( poly, aLayer );
474 }
475
476 polyset_areas.RemoveAllContours();
477 polyset_holes.RemoveAllContours();
478 main_outline = true;
479 }
480 }
481
482 paths = paths->next;
483 }
484
486}
487
488// a helper function to calculate a square value
489inline double square( double x )
490{
491 return x * x;
492}
493
494
495// a helper function to calculate a cube value
496inline double cube( double x )
497{
498 return x * x * x;
499}
500
501
502/* render a Bezier curve. */
503void BezierToPolyline( std::vector <potrace_dpoint_t>& aCornersBuffer,
504 potrace_dpoint_t p1,
505 potrace_dpoint_t p2,
506 potrace_dpoint_t p3,
507 potrace_dpoint_t p4 )
508{
509 double dd0, dd1, dd, delta, e2, epsilon, t;
510
511 // p1 = starting point
512
513 /* we approximate the curve by small line segments. The interval
514 * size, epsilon, is determined on the fly so that the distance
515 * between the true curve and its approximation does not exceed the
516 * desired accuracy delta. */
517
518 delta = 0.25; /* desired accuracy, in pixels */
519
520 /* let dd = maximal value of 2nd derivative over curve - this must
521 * occur at an endpoint. */
522 dd0 = square( p1.x - 2 * p2.x + p3.x ) + square( p1.y - 2 * p2.y + p3.y );
523 dd1 = square( p2.x - 2 * p3.x + p4.x ) + square( p2.y - 2 * p3.y + p4.y );
524 dd = 6 * sqrt( std::max( dd0, dd1 ) );
525 e2 = 8 * delta <= dd ? 8 * delta / dd : 1;
526 epsilon = sqrt( e2 ); /* necessary interval size */
527
528 for( t = epsilon; t<1; t += epsilon )
529 {
530 potrace_dpoint_t intermediate_point;
531 intermediate_point.x = p1.x * cube( 1 - t ) +
532 3* p2.x* square( 1 - t ) * t +
533 3 * p3.x * (1 - t) * square( t ) +
534 p4.x* cube( t );
535
536 intermediate_point.y = p1.y * cube( 1 - t ) +
537 3* p2.y* square( 1 - t ) * t +
538 3 * p3.y * (1 - t) * square( t ) + p4.y* cube( t );
539
540 aCornersBuffer.push_back( intermediate_point );
541 }
542
543 aCornersBuffer.push_back( p4 );
544}
constexpr double SCH_IU_PER_MM
Schematic internal units 1=100nm.
Definition base_units.h:70
constexpr double PCB_IU_PER_MM
Pcbnew IU is 1 nanometer.
Definition base_units.h:68
constexpr double PL_IU_PER_MM
Internal units in micron (should be enough).
Definition base_units.h:69
double square(double x)
static void BezierToPolyline(std::vector< potrace_dpoint_t > &aCornersBuffer, potrace_dpoint_t p1, potrace_dpoint_t p2, potrace_dpoint_t p3, potrace_dpoint_t p4)
double cube(double x)
static void bm_free(potrace_bitmap_t *bm)
#define SCH_LINE_THICKNESS_MM
OUTPUT_FMT_ID
@ DRAWING_SHEET_FMT
@ SYMBOL_FMT
@ SYMBOL_PASTE_FMT
@ POSTSCRIPT_FMT
@ FOOTPRINT_FMT
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:986
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
void outputDataEnd()
Function outputDataEnd write to file the last strings depending on file format.
std::string & m_Data
REPORTER & m_reporter
BITMAPCONV_INFO(std::string &aData, REPORTER &aReporter)
potrace_path_t * m_Paths
void outputOnePolygon(SHAPE_LINE_CHAIN &aPolygon, const wxString &aBrdLayerName)
Function outputOnePolygon write one polygon to output file.
std::string m_CmpName
void outputDataHeader(const wxString &aBrdLayerName)
Function outputDataHeader write to file the header depending on file format.
enum OUTPUT_FMT_ID m_Format
int ConvertBitmap(potrace_bitmap_t *aPotrace_bitmap, OUTPUT_FMT_ID aFormat, int aDpi_X, int aDpi_Y, const wxString &aLayer)
Run the conversion of the bitmap.
void createOutputData(const wxString &aBrdLayerName=wxT("F.SilkS"))
Creates the data specified by m_Format.
Definition kiid.h:44
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:71
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
int PointCount() const
Return the number of points (vertices) in this line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
Represent a set of closed polygons.
void RemoveAllContours()
Remove all outlines & holes (clears) the polygon set.
int NormalizeAreaOutlines()
Convert a self-intersecting polygon to one (or more) non self-intersecting polygon(s).
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
void Simplify()
Simplify the polyset (merges overlapping polys, eliminates degeneracy/self-intersections)
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
int NewOutline()
Creates a new empty polygon in the set and returns its index.
int OutlineCount() const
Return the number of outlines in the set.
void Fracture(bool aSimplify=true)
Convert a set of polygons with holes to a single outline with "slits"/"fractures" connecting the oute...
void BooleanSubtract(const SHAPE_POLY_SET &b)
Perform boolean polyset difference.
#define _(s)
This file contains miscellaneous commonly used macros and functions.
#define KI_FALLTHROUGH
The KI_FALLTHROUGH macro is to be used when switch statement cases should purposely fallthrough from ...
Definition macros.h:79
@ RPT_SEVERITY_ERROR
const double epsilon
int delta
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683