KiCad PCB EDA Suite
Loading...
Searching...
No Matches
dxf_import_plugin.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) 2019 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// The DXF reader lib (libdxfrw) comes from dxflib project used in QCAD
22// See http://www.ribbonsoft.com
23// Each time a dxf entity is read, a "call back" function is called
24// like void DXF_IMPORT_PLUGIN::addLine( const DL_LineData& data ) when a line is read.
25// this function just add the BOARD entity from dxf parameters (start and end point ...)
26
27
28#include "dxf_import_plugin.h"
29#include <wx/arrstr.h>
30#include <wx/regex.h>
31#include <geometry/ellipse.h>
32#include <bezier_curves.h>
33
34#include <trigo.h>
35#include <macros.h>
36#include <cmath> // isnan
37#include <vector>
38#include <board.h>
39#include "common.h"
40
41
42/*
43 * Important notes
44 * 1. All output coordinates of this importer are in mm
45 * 2. DXFs have a concept of world (WCS) and object coordinates (OCS)
46 3. The following objects are world coordinates:
47 - Line
48 - Point
49 - Polyline (3D)
50 - Vertex (3D)
51 - Polymesh
52 - Polyface
53 - Viewport
54 4. The following entities are object coordinates
55 - Circle
56 - Arc
57 - Solid
58 - Trace
59 - Attrib
60 - Shape
61 - Insert
62 - Polyline (2D)
63 - Vertex (2D)
64 - LWPolyline
65 - Hatch
66 - Image
67 - Text
68 * 5. Object coordinates must be run through the arbitrary axis
69 * translation even though they are 2D drawings and most of the time
70 * the import is fine. Sometimes, against all logic, CAD tools like
71 * SolidWorks may randomly insert circles "mirror" that must be unflipped
72 * by following the object to world conversion
73 * 6. Blocks are virtual groups, blocks must be placed by a INSERT entity
74 * 7. Blocks may be repeated multiple times
75 * 8. There is no sane way to make text look perfect like the original CAD.
76 * DXF simply does mpt specifying text/font enough to make it portable.
77 * We however make do try to get it somewhat close/visually appealing.
78 * 9. We silently drop the z coordinate on 3d polylines
79 */
80
81
82// minimum bulge value before resorting to a line segment;
83// the value 0.0218 is equivalent to about 5 degrees arc,
84#define MIN_BULGE 0.0218
85
86#define SCALE_FACTOR(x) (x)
87
88
90{
91 m_xOffset = 0.0; // X coord offset for conversion (in mm)
92 m_yOffset = 0.0; // Y coord offset for conversion (in mm)
93 m_version = 0; // the dxf version, not yet used
94 m_defaultThickness = 0.2; // default thickness (in mm)
95 m_brdLayer = Dwgs_User; // The default import layer
96 m_importAsFPShapes = true;
97 m_minX = m_minY = std::numeric_limits<double>::max();
98 m_maxX = m_maxY = std::numeric_limits<double>::lowest();
100
101 m_importCoordinatePrecision = 4; // initial value per dxf spec
102 m_importAnglePrecision = 0; // initial value per dxf spec
103
104 // placeholder layer so we can fallback to something later
105 auto layer0 = std::make_unique<DXF_IMPORT_LAYER>( "", DXF_IMPORT_LINEWEIGHT_BY_LW_DEFAULT );
106 m_layers.push_back( std::move( layer0 ) );
107
108 m_currentBlock = nullptr;
109}
110
111
115
116
117bool DXF_IMPORT_PLUGIN::Load( const wxString& aFileName )
118{
119 try
120 {
121 return ImportDxfFile( aFileName );
122 }
123 catch( const std::bad_alloc& )
124 {
125 m_layers.clear();
126 m_blocks.clear();
127 m_styles.clear();
128
129 m_internalImporter.ClearShapes();
130
131 ReportMsg( _( "Memory was exhausted trying to load the DXF, it may be too large." ) );
132 return false;
133 }
134}
135
136
138{
139 wxCHECK( m_importer, false );
140 m_internalImporter.ImportTo( *m_importer );
141
142 return true;
143}
144
145
147{
148 return m_maxX - m_minX;
149}
150
151
153{
154 return m_maxY - m_minY;
155}
156
157
159{
160 BOX2D bbox;
161 bbox.SetOrigin( m_minX, m_minY );
162 bbox.SetEnd( m_maxX, m_maxY );
163
164 return bbox;
165}
166
167
169{
171
172 if( m_importer )
173 SetDefaultLineWidthMM( m_importer->GetLineWidthMM() );
174}
175
176
177double DXF_IMPORT_PLUGIN::mapX( double aDxfCoordX )
178{
179 return SCALE_FACTOR( m_xOffset + ( aDxfCoordX * getCurrentUnitScale() ) );
180}
181
182
183double DXF_IMPORT_PLUGIN::mapY( double aDxfCoordY )
184{
185 return SCALE_FACTOR( m_yOffset - ( aDxfCoordY * getCurrentUnitScale() ) );
186}
187
188
189double DXF_IMPORT_PLUGIN::mapDim( double aDxfValue )
190{
191 return SCALE_FACTOR( aDxfValue * getCurrentUnitScale() );
192}
193
194
195bool DXF_IMPORT_PLUGIN::ImportDxfFile( const wxString& aFile )
196{
197 DL_Dxf dxf_reader;
198
199 // wxFopen takes care of unicode filenames across platforms
200 FILE* fp = wxFopen( aFile, wxT( "rt" ) );
201
202 if( fp == nullptr )
203 return false;
204
205 // The DXF reader closes the file after reading.
206 bool success = dxf_reader.in( fp, this );
207
208 return success;
209}
210
211
212void DXF_IMPORT_PLUGIN::ReportMsg( const wxString& aMessage )
213{
214 // Add message to keep trace of not handled dxf entities
215 m_messages += aMessage;
216 m_messages += '\n';
217}
218
219
220void DXF_IMPORT_PLUGIN::addSpline( const DL_SplineData& aData )
221{
222 // Called when starting reading a spline
223 m_curr_entity.Clear();
224 m_curr_entity.m_EntityParseStatus = 1;
225 m_curr_entity.m_EntityFlag = aData.flags;
226 m_curr_entity.m_EntityType = DL_ENTITY_SPLINE;
227 m_curr_entity.m_SplineDegree = aData.degree;
228 m_curr_entity.m_SplineTangentStartX = aData.tangentStartX;
229 m_curr_entity.m_SplineTangentStartY = aData.tangentStartY;
230 m_curr_entity.m_SplineTangentEndX = aData.tangentEndX;
231 m_curr_entity.m_SplineTangentEndY = aData.tangentEndY;
232 m_curr_entity.m_SplineKnotsCount = aData.nKnots;
233 m_curr_entity.m_SplineControlCount = aData.nControl;
234 m_curr_entity.m_SplineFitCount = aData.nFit;
235 m_curr_entity.m_LayerName = getDxfLayerName( attributes.getLayer() );
236}
237
238
239void DXF_IMPORT_PLUGIN::addControlPoint( const DL_ControlPointData& aData )
240{
241 // Called for every spline control point, when reading a spline entity
242 m_curr_entity.m_SplineControlPointList.emplace_back( aData.x , aData.y, aData.w );
243}
244
245
246void DXF_IMPORT_PLUGIN::addFitPoint( const DL_FitPointData& aData )
247{
248 // Called for every spline fit point, when reading a spline entity
249 // we store only the X,Y coord values in a VECTOR2D
250 m_curr_entity.m_SplineFitPointList.emplace_back( aData.x, aData.y );
251}
252
253
254void DXF_IMPORT_PLUGIN::addKnot( const DL_KnotData& aData)
255{
256 // Called for every spline knot value, when reading a spline entity
257 m_curr_entity.m_SplineKnotsList.push_back( aData.k );
258}
259
260
261void DXF_IMPORT_PLUGIN::addLayer( const DL_LayerData& aData )
262{
263 wxString name = wxString::FromUTF8( aData.name.c_str() );
264
265 int lw = attributes.getWidth();
266
269
270 std::unique_ptr<DXF_IMPORT_LAYER> layer = std::make_unique<DXF_IMPORT_LAYER>( name, lw );
271
272 m_layers.push_back( std::move( layer ) );
273}
274
275
276void DXF_IMPORT_PLUGIN::addLinetype( const DL_LinetypeData& data )
277{
278#if 0
279 wxString name = From_UTF8( data.name.c_str() );
280 wxString description = From_UTF8( data.description.c_str() );
281#endif
282}
283
284
286{
287 if( lw == DXF_IMPORT_LINEWEIGHT_BY_LAYER && aLayer != nullptr )
288 lw = aLayer->m_lineWeight;
289
290 // All lineweights >= 0 are always in 100ths of mm
291 double mm = m_defaultThickness;
292
293 if( lw >= 0 )
294 mm = lw / 100.0;
295
296 return SCALE_FACTOR( mm );
297}
298
299
301{
302 DXF_IMPORT_LAYER* layer = m_layers.front().get();
303 wxString layerName = wxString::FromUTF8( aLayerName.c_str() );
304
305 if( !layerName.IsEmpty() )
306 {
307 auto resultIt = std::find_if( m_layers.begin(), m_layers.end(),
308 [layerName]( const auto& it )
309 {
310 return it->m_layerName == layerName;
311 } );
312
313 if( resultIt != m_layers.end() )
314 layer = resultIt->get();
315 }
316
317 return layer;
318}
319
320
321wxString DXF_IMPORT_PLUGIN::getDxfLayerName( const std::string& aLayerName ) const
322{
323 wxString layerName = wxString::FromUTF8( aLayerName.c_str() );
324
325 if( layerName.IsEmpty() )
326 layerName = wxS( "0" );
327
328 return layerName;
329}
330
331
333{
334 DXF_IMPORT_BLOCK* block = nullptr;
335 wxString blockName = wxString::FromUTF8( aBlockName.c_str() );
336
337 if( !blockName.IsEmpty() )
338 {
339 auto resultIt = std::find_if( m_blocks.begin(), m_blocks.end(),
340 [blockName]( const auto& it )
341 {
342 return it->m_name == blockName;
343 } );
344
345 if( resultIt != m_blocks.end() )
346 block = resultIt->get();
347 }
348
349 return block;
350}
351
352
354{
355 DXF_IMPORT_STYLE* style = nullptr;
356 wxString styleName = wxString::FromUTF8( aStyleName.c_str() );
357
358 if( !styleName.IsEmpty() )
359 {
360 auto resultIt = std::find_if( m_styles.begin(), m_styles.end(),
361 [styleName]( const auto& it )
362 {
363 return it->m_name == styleName;
364 } );
365
366 if( resultIt != m_styles.end() )
367 style = resultIt->get();
368 }
369
370 return style;
371}
372
373
374void DXF_IMPORT_PLUGIN::addLine( const DL_LineData& aData )
375{
376 DXF_IMPORT_LAYER* layer = getImportLayer( attributes.getLayer() );
377 double lineWidth = lineWeightToWidth( attributes.getWidth(), layer );
378 wxString sourceLayer = getDxfLayerName( attributes.getLayer() );
379
380 VECTOR2D start( mapX( aData.x1 ), mapY( aData.y1 ) );
381 VECTOR2D end( mapX( aData.x2 ), mapY( aData.y2 ) );
382
383 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
385 bufferToUse->SetCurrentSourceLayer( sourceLayer );
386 bufferToUse->AddLine( start, end, lineWidth );
387
388 updateImageLimits( start );
390}
391
392
393void DXF_IMPORT_PLUGIN::addPolyline(const DL_PolylineData& aData )
394{
395 // Convert DXF Polylines into a series of KiCad Lines and Arcs.
396 // A Polyline (as opposed to a LWPolyline) may be a 3D line or
397 // even a 3D Mesh. The only type of Polyline which is guaranteed
398 // to import correctly is a 2D Polyline in X and Y, which is what
399 // we assume of all Polylines. The width used is the width of the Polyline.
400 // per-vertex line widths, if present, are ignored.
401 m_curr_entity.Clear();
402 m_curr_entity.m_EntityParseStatus = 1;
403 m_curr_entity.m_EntityFlag = aData.flags;
404 m_curr_entity.m_EntityType = DL_ENTITY_POLYLINE;
405 m_curr_entity.m_LayerName = getDxfLayerName( attributes.getLayer() );
406}
407
408
409void DXF_IMPORT_PLUGIN::addVertex( const DL_VertexData& aData )
410{
411 if( m_curr_entity.m_EntityParseStatus == 0 )
412 return; // Error
413
414 DXF_IMPORT_LAYER* layer = getImportLayer( attributes.getLayer() );
415 double lineWidth = lineWeightToWidth( attributes.getWidth(), layer );
416
417 /* support for per-vertex-encoded linewidth (Cadence uses it) */
418 /* linewidths are scaled by 100 in DXF */
419 if( aData.startWidth > 0.0 )
420 lineWidth = aData.startWidth / 100.0;
421 else if ( aData.endWidth > 0.0 )
422 lineWidth = aData.endWidth / 100.0;
423
424 const DL_VertexData* vertex = &aData;
425
426 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
427 VECTOR3D vertexCoords = ocsToWcs( arbAxis, VECTOR3D( vertex->x, vertex->y, vertex->z ) );
428
429 if( m_curr_entity.m_EntityParseStatus == 1 ) // This is the first vertex of an entity
430 {
431 m_curr_entity.m_LastCoordinate.x = mapX( vertexCoords.x );
432 m_curr_entity.m_LastCoordinate.y = mapY( vertexCoords.y );
433 m_curr_entity.m_PolylineStart = m_curr_entity.m_LastCoordinate;
434 m_curr_entity.m_BulgeVertex = vertex->bulge;
435 m_curr_entity.m_EntityParseStatus = 2;
436 return;
437 }
438
439 VECTOR2D seg_end( mapX( vertexCoords.x ), mapY( vertexCoords.y ) );
440
441 if( std::abs( m_curr_entity.m_BulgeVertex ) < MIN_BULGE )
442 insertLine( m_curr_entity.m_LastCoordinate, seg_end, lineWidth );
443 else
444 insertArc( m_curr_entity.m_LastCoordinate, seg_end, m_curr_entity.m_BulgeVertex,
445 lineWidth );
446
447 m_curr_entity.m_LastCoordinate = seg_end;
448 m_curr_entity.m_BulgeVertex = vertex->bulge;
449}
450
451
453{
454 DXF_IMPORT_LAYER* layer = getImportLayer( attributes.getLayer() );
455 double lineWidth = lineWeightToWidth( attributes.getWidth(), layer );
456
457 if( m_curr_entity.m_EntityType == DL_ENTITY_POLYLINE ||
458 m_curr_entity.m_EntityType == DL_ENTITY_LWPOLYLINE )
459 {
460 // Polyline flags bit 0 indicates closed (1) or open (0) polyline
461 if( m_curr_entity.m_EntityFlag & 1 )
462 {
463 if( std::abs( m_curr_entity.m_BulgeVertex ) < MIN_BULGE )
464 {
465 insertLine( m_curr_entity.m_LastCoordinate, m_curr_entity.m_PolylineStart,
466 lineWidth );
467 }
468 else
469 {
470 insertArc( m_curr_entity.m_LastCoordinate, m_curr_entity.m_PolylineStart,
471 m_curr_entity.m_BulgeVertex, lineWidth );
472 }
473 }
474 }
475
476 if( m_curr_entity.m_EntityType == DL_ENTITY_SPLINE )
477 insertSpline( lineWidth );
478
479 m_curr_entity.Clear();
480}
481
482
483void DXF_IMPORT_PLUGIN::addBlock( const DL_BlockData& aData )
484{
485 wxString name = wxString::FromUTF8( aData.name.c_str() );
486
487 std::unique_ptr<DXF_IMPORT_BLOCK> block = std::make_unique<DXF_IMPORT_BLOCK>( name, aData.bpx,
488 aData.bpy );
489
490 m_blocks.push_back( std::move( block ) );
491
492 m_currentBlock = m_blocks.back().get();
493}
494
495
497{
498 m_currentBlock = nullptr;
499}
500
501void DXF_IMPORT_PLUGIN::addInsert( const DL_InsertData& aData )
502{
503 DXF_IMPORT_BLOCK* block = getImportBlock( aData.name );
504
505 if( block == nullptr )
506 return;
507
508 wxString insertLayer = getDxfLayerName( attributes.getLayer() );
509
510 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
511
512 MATRIX3x3D rot;
513 rot.SetRotation( DEG2RAD( -aData.angle ) ); // DL_InsertData angle is in degrees
514
516 scale.SetScale( VECTOR2D( aData.sx, aData.sy ) );
517
518 MATRIX3x3D trans = ( arbAxis * rot ) * scale;
519 VECTOR3D insertCoords = ocsToWcs( arbAxis, VECTOR3D( aData.ipx, aData.ipy, aData.ipz ) );
520
521 VECTOR2D translation( mapX( insertCoords.x ), mapY( insertCoords.y ) );
522 translation -= VECTOR2D( mapX( block->m_baseX ), mapY( block->m_baseY ) );
523
524 for( const std::unique_ptr<IMPORTED_SHAPE>& shape : block->m_buffer.GetShapes() )
525 {
526 std::unique_ptr<IMPORTED_SHAPE> newShape = shape->clone();
527
528 newShape->Transform( trans, translation );
529
530 if( newShape->GetSourceLayer().IsEmpty() || newShape->GetSourceLayer() == wxS( "0" ) )
531 newShape->SetSourceLayer( insertLayer );
532
533 m_internalImporter.AddShape( newShape );
534 }
535}
536
537
538void DXF_IMPORT_PLUGIN::addCircle( const DL_CircleData& aData )
539{
540 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
541 VECTOR3D centerCoords = ocsToWcs( arbAxis, VECTOR3D( aData.cx, aData.cy, aData.cz ) );
542
543 VECTOR2D center( mapX( centerCoords.x ), mapY( centerCoords.y ) );
544 DXF_IMPORT_LAYER* layer = getImportLayer( attributes.getLayer() );
545 double lineWidth = lineWeightToWidth( attributes.getWidth(), layer );
546 wxString sourceLayer = getDxfLayerName( attributes.getLayer() );
547
548 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
550 bufferToUse->SetCurrentSourceLayer( sourceLayer );
551 bufferToUse->AddCircle( center, mapDim( aData.radius ), lineWidth, false );
552
553 VECTOR2D radiusDelta( mapDim( aData.radius ), mapDim( aData.radius ) );
554
555 updateImageLimits( center + radiusDelta );
556 updateImageLimits( center - radiusDelta );
557}
558
559
560void DXF_IMPORT_PLUGIN::addArc( const DL_ArcData& aData )
561{
562 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
563 VECTOR3D centerCoords = ocsToWcs( arbAxis, VECTOR3D( aData.cx, aData.cy, aData.cz ) );
564
565 // Init arc centre:
566 VECTOR2D center( mapX( centerCoords.x ), mapY( centerCoords.y ) );
567
568 // aData.anglex is in degrees.
569 EDA_ANGLE startangle( aData.angle1, DEGREES_T );
570 EDA_ANGLE endangle( aData.angle2, DEGREES_T );
571
572 if( ( arbAxis.GetScale().x < 0 ) != ( arbAxis.GetScale().y < 0 ) )
573 {
574 startangle = ANGLE_180 - startangle;
575 endangle = ANGLE_180 - endangle;
576 std::swap( startangle, endangle );
577 }
578
579 // Init arc start point
580 VECTOR2D startPoint( aData.radius, 0.0 );
581 RotatePoint( startPoint, -startangle );
582 VECTOR2D arcStart( mapX( startPoint.x + centerCoords.x ),
583 mapY( startPoint.y + centerCoords.y ) );
584
585 // calculate arc angle (arcs are CCW, and should be < 0 in Pcbnew)
586 EDA_ANGLE angle = -( endangle - startangle );
587
588 if( angle > ANGLE_0 )
589 angle -= ANGLE_360;
590
591 DXF_IMPORT_LAYER* layer = getImportLayer( attributes.getLayer() );
592 double lineWidth = lineWeightToWidth( attributes.getWidth(), layer );
593 wxString sourceLayer = getDxfLayerName( attributes.getLayer() );
594
595 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
597 bufferToUse->SetCurrentSourceLayer( sourceLayer );
598 bufferToUse->AddArc( center, arcStart, angle, lineWidth );
599
600 VECTOR2D radiusDelta( mapDim( aData.radius ), mapDim( aData.radius ) );
601
602 updateImageLimits( center + radiusDelta );
603 updateImageLimits( center - radiusDelta );
604}
605
606
607void DXF_IMPORT_PLUGIN::addEllipse( const DL_EllipseData& aData )
608{
609 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
610 VECTOR3D centerCoords = ocsToWcs( arbAxis, VECTOR3D( aData.cx, aData.cy, aData.cz ) );
611 VECTOR3D majorCoords = ocsToWcs( arbAxis, VECTOR3D( aData.mx, aData.my, aData.mz ) );
612
613 // DXF ellipses store the minor axis length as a ratio to the major axis.
614 // The major coords are relative to the center point.
615 // For now, we assume ellipses in the XY plane.
616
617 VECTOR2D center( mapX( centerCoords.x ), mapY( centerCoords.y ) );
618 VECTOR2D major( mapX( majorCoords.x ), mapY( majorCoords.y ) );
619
620 // DXF elliptical arcs store their angles in radians (unlike circular arcs which use degrees)
621 // The arcs wind CCW as in KiCad. The end angle must be greater than the start angle, and if
622 // the extrusion direction is negative, the arc winding is CW instead! Note that this is a
623 // simplification that assumes the DXF is representing a 2D drawing, and would need to be
624 // revisited if we want to import true 3D drawings and "flatten" them to the 2D KiCad plane
625 // internally.
626 EDA_ANGLE startAngle( aData.angle1, RADIANS_T );
627 EDA_ANGLE endAngle( aData.angle2, RADIANS_T );
628
629 if( startAngle > endAngle )
630 endAngle += ANGLE_360;
631
632 if( aData.ratio == 1.0 )
633 {
634 double radius = major.EuclideanNorm();
635
636 if( startAngle == endAngle )
637 {
638 DL_CircleData circle( aData.cx, aData.cy, aData.cz, radius );
639 addCircle( circle );
640 return;
641 }
642 else
643 {
644 // Angles are relative to major axis
645 startAngle -= EDA_ANGLE( major );
646 endAngle -= EDA_ANGLE( major );
647
648 DL_ArcData arc( aData.cx, aData.cy, aData.cz, radius, startAngle.AsDegrees(),
649 endAngle.AsDegrees() );
650 addArc( arc );
651 return;
652 }
653 }
654
655 // TODO: testcases for negative extrusion vector; handle it here
656
657 DXF_IMPORT_LAYER* layer = getImportLayer( attributes.getLayer() );
658 double lineWidth = lineWeightToWidth( attributes.getWidth(), layer );
659 wxString sourceLayer = getDxfLayerName( attributes.getLayer() );
660
661 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
663 bufferToUse->SetCurrentSourceLayer( sourceLayer );
664
665 double majorRadius = major.EuclideanNorm();
666 double minorRadius = majorRadius * aData.ratio;
667 EDA_ANGLE rotation( major );
668
669 if( startAngle == endAngle || std::abs( ( endAngle - startAngle ).AsDegrees() - 360.0 ) < 1e-9 )
670 {
671 bufferToUse->AddEllipse( center, majorRadius, minorRadius, rotation, lineWidth, false /* aFilled */ );
672 }
673 else
674 {
675 bufferToUse->AddEllipseArc( center, majorRadius, minorRadius, rotation, startAngle, endAngle, lineWidth );
676 }
677
678 // Naive bounding
679 updateImageLimits( center + major );
680 updateImageLimits( center - major );
681}
682
683
684void DXF_IMPORT_PLUGIN::addText( const DL_TextData& aData )
685{
686 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
687 VECTOR3D refPointCoords = ocsToWcs( arbAxis, VECTOR3D( aData.ipx, aData.ipy, aData.ipz ) );
688 VECTOR3D secPointCoords =
689 ocsToWcs( arbAxis, VECTOR3D( std::isnan( aData.apx ) ? 0 : aData.apx,
690 std::isnan( aData.apy ) ? 0 : aData.apy,
691 std::isnan( aData.apz ) ? 0 : aData.apz ) );
692
693 VECTOR2D refPoint( mapX( refPointCoords.x ), mapY( refPointCoords.y ) );
694 VECTOR2D secPoint( mapX( secPointCoords.x ), mapY( secPointCoords.y ) );
695
696 if( aData.vJustification != 0 || aData.hJustification != 0 || aData.hJustification == 4 )
697 {
698 if( aData.hJustification != 3 && aData.hJustification != 5 )
699 {
700 VECTOR2D tmp = secPoint;
701 secPoint = refPoint;
702 refPoint = tmp;
703 }
704 }
705
706 wxString text = toNativeString( wxString::FromUTF8( aData.text.c_str() ) );
707
708 DXF_IMPORT_STYLE* style = getImportStyle( aData.style.c_str() );
709
710 double textHeight = mapDim( aData.height );
711
712 // The 0.9 factor gives a better height/width base ratio with our font
713 double charWidth = textHeight * 0.9;
714
715 if( style != nullptr )
716 charWidth *= style->m_widthFactor;
717
718 double textWidth = charWidth * text.length(); // Rough approximation
719 double textThickness = textHeight / 8.0; // Use a reasonable line thickness for this text
720
721 VECTOR2D bottomLeft( 0.0, 0.0 );
722 VECTOR2D bottomRight( 0.0, 0.0 );
723 VECTOR2D topLeft( 0.0, 0.0 );
724 VECTOR2D topRight( 0.0, 0.0 );
725
728
729 switch( aData.vJustification )
730 {
731 case 0: //DRW_Text::VBaseLine:
732 case 1: //DRW_Text::VBottom:
733 vJustify = GR_TEXT_V_ALIGN_BOTTOM;
734
735 topLeft.y = textHeight;
736 topRight.y = textHeight;
737 break;
738
739 case 2: //DRW_Text::VMiddle:
740 vJustify = GR_TEXT_V_ALIGN_CENTER;
741
742 bottomRight.y = -textHeight / 2.0;
743 bottomLeft.y = -textHeight / 2.0;
744 topLeft.y = textHeight / 2.0;
745 topRight.y = textHeight / 2.0;
746 break;
747
748 case 3: //DRW_Text::VTop:
749 vJustify = GR_TEXT_V_ALIGN_TOP;
750
751 bottomLeft.y = -textHeight;
752 bottomRight.y = -textHeight;
753 break;
754 }
755
756 switch( aData.hJustification )
757 {
758 case 0: //DRW_Text::HLeft:
759 case 3: //DRW_Text::HAligned: // no equivalent options in text pcb.
760 case 5: //DRW_Text::HFit: // no equivalent options in text pcb.
761 hJustify = GR_TEXT_H_ALIGN_LEFT;
762
763 bottomRight.x = textWidth;
764 topRight.x = textWidth;
765 break;
766
767 case 1: //DRW_Text::HCenter:
768 case 4: //DRW_Text::HMiddle: // no equivalent options in text pcb.
769 hJustify = GR_TEXT_H_ALIGN_CENTER;
770
771 bottomLeft.x = -textWidth / 2.0;
772 topLeft.x = -textWidth / 2.0;
773 bottomRight.x = textWidth / 2.0;
774 topRight.x = textWidth / 2.0;
775 break;
776
777 case 2: //DRW_Text::HRight:
778 hJustify = GR_TEXT_H_ALIGN_RIGHT;
779
780 bottomLeft.x = -textWidth;
781 topLeft.x = -textWidth;
782 break;
783 }
784
785#if 0
786 wxString sty = wxString::FromUTF8( aData.style.c_str() );
787 sty = sty.ToLower();
788
789 if( aData.textgen == 2 )
790 {
791 // Text dir = left to right;
792 } else if( aData.textgen == 4 )
793 {
794 // Text dir = top to bottom;
795 } else
796 {
797 }
798#endif
799
800 // dxf_lib imports text angle in radians (although there are no comment about that.
801 // So, for the moment, convert this angle to degrees
802 double angle_degree = aData.angle * 180 / M_PI;
803
804 // We also need the angle in radians. so convert angle_degree to radians
805 // regardless the aData.angle unit
806 double angleInRads = angle_degree * M_PI / 180.0;
807 double cosine = cos(angleInRads);
808 double sine = sin(angleInRads);
809
810 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
812 bufferToUse->SetCurrentSourceLayer( getDxfLayerName( attributes.getLayer() ) );
813 bufferToUse->AddText( refPoint, text, textHeight, charWidth, textThickness, angle_degree,
814 hJustify, vJustify );
815
816 // Calculate the boundary box and update the image limits:
817 bottomLeft.x = bottomLeft.x * cosine - bottomLeft.y * sine;
818 bottomLeft.y = bottomLeft.x * sine + bottomLeft.y * cosine;
819
820 bottomRight.x = bottomRight.x * cosine - bottomRight.y * sine;
821 bottomRight.y = bottomRight.x * sine + bottomRight.y * cosine;
822
823 topLeft.x = topLeft.x * cosine - topLeft.y * sine;
824 topLeft.y = topLeft.x * sine + topLeft.y * cosine;
825
826 topRight.x = topRight.x * cosine - topRight.y * sine;
827 topRight.y = topRight.x * sine + topRight.y * cosine;
828
829 bottomLeft += refPoint;
830 bottomRight += refPoint;
831 topLeft += refPoint;
832 topRight += refPoint;
833
834 updateImageLimits( bottomLeft );
835 updateImageLimits( bottomRight );
836 updateImageLimits( topLeft );
837 updateImageLimits( topRight );
838}
839
840
841void DXF_IMPORT_PLUGIN::addMTextChunk( const std::string& text )
842{
843 // If the text string is greater than 250 characters, the string is divided into 250-character
844 // chunks, which appear in one or more group 3 codes. If group 3 codes are used, the last group
845 // is a group 1 and has fewer than 250 characters
846
847 m_mtextContent.append( text );
848}
849
850
851void DXF_IMPORT_PLUGIN::addMText( const DL_MTextData& aData )
852{
853 m_mtextContent.append( aData.text );
854
855 // TODO: determine control codes applied to the whole text?
856 wxString text = toNativeString( wxString::FromUTF8( m_mtextContent.c_str() ) );
857
858 DXF_IMPORT_STYLE* style = getImportStyle( aData.style.c_str() );
859 double textHeight = mapDim( aData.height );
860
861 // The 0.9 factor gives a better height/width base ratio with our font
862 double charWidth = textHeight * 0.9;
863
864 if( style != nullptr )
865 charWidth *= style->m_widthFactor;
866
867 double textWidth = charWidth * text.length(); // Rough approximation
868 double textThickness = textHeight/8.0; // Use a reasonable line thickness for this text
869
870 VECTOR2D bottomLeft(0.0, 0.0);
871 VECTOR2D bottomRight(0.0, 0.0);
872 VECTOR2D topLeft(0.0, 0.0);
873 VECTOR2D topRight(0.0, 0.0);
874
875 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
876 VECTOR3D textposCoords = ocsToWcs( arbAxis, VECTOR3D( aData.ipx, aData.ipy, aData.ipz ) );
877 VECTOR2D textpos( mapX( textposCoords.x ), mapY( textposCoords.y ) );
878
879 // Initialize text justifications:
882
883 if( aData.attachmentPoint <= 3 )
884 {
885 vJustify = GR_TEXT_V_ALIGN_TOP;
886
887 bottomLeft.y = -textHeight;
888 bottomRight.y = -textHeight;
889 }
890 else if( aData.attachmentPoint <= 6 )
891 {
892 vJustify = GR_TEXT_V_ALIGN_CENTER;
893
894 bottomRight.y = -textHeight / 2.0;
895 bottomLeft.y = -textHeight / 2.0;
896 topLeft.y = textHeight / 2.0;
897 topRight.y = textHeight / 2.0;
898 }
899 else
900 {
901 vJustify = GR_TEXT_V_ALIGN_BOTTOM;
902
903 topLeft.y = textHeight;
904 topRight.y = textHeight;
905 }
906
907 if( aData.attachmentPoint % 3 == 1 )
908 {
909 hJustify = GR_TEXT_H_ALIGN_LEFT;
910
911 bottomRight.x = textWidth;
912 topRight.x = textWidth;
913 }
914 else if( aData.attachmentPoint % 3 == 2 )
915 {
916 hJustify = GR_TEXT_H_ALIGN_CENTER;
917
918 bottomLeft.x = -textWidth / 2.0;
919 topLeft.x = -textWidth / 2.0;
920 bottomRight.x = textWidth / 2.0;
921 topRight.x = textWidth / 2.0;
922 }
923 else
924 {
925 hJustify = GR_TEXT_H_ALIGN_RIGHT;
926
927 bottomLeft.x = -textWidth;
928 topLeft.x = -textWidth;
929 }
930
931#if 0 // These setting have no meaning in Pcbnew
932 if( data.alignH == 1 )
933 {
934 // Text is left to right;
935 }
936 else if( data.alignH == 3 )
937 {
938 // Text is top to bottom;
939 }
940 else
941 {
942 // use ByStyle;
943 }
944
945 if( aData.alignV == 1 )
946 {
947 // use AtLeast;
948 }
949 else
950 {
951 // useExact;
952 }
953#endif
954
955 // dxf_lib imports text angle in radians (although there are no comment about that.
956 // So, for the moment, convert this angle to degrees
957 double angle_degree = aData.angle * 180/M_PI;
958
959 // We also need the angle in radians. so convert angle_degree to radians
960 // regardless the aData.angle unit
961 double angleInRads = angle_degree * M_PI / 180.0;
962 double cosine = cos(angleInRads);
963 double sine = sin(angleInRads);
964
965
966 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
968 bufferToUse->SetCurrentSourceLayer( getDxfLayerName( attributes.getLayer() ) );
969 bufferToUse->AddText( textpos, text, textHeight, charWidth, textThickness, angle_degree,
970 hJustify, vJustify );
971
972 bottomLeft.x = bottomLeft.x * cosine - bottomLeft.y * sine;
973 bottomLeft.y = bottomLeft.x * sine + bottomLeft.y * cosine;
974
975 bottomRight.x = bottomRight.x * cosine - bottomRight.y * sine;
976 bottomRight.y = bottomRight.x * sine + bottomRight.y * cosine;
977
978 topLeft.x = topLeft.x * cosine - topLeft.y * sine;
979 topLeft.y = topLeft.x * sine + topLeft.y * cosine;
980
981 topRight.x = topRight.x * cosine - topRight.y * sine;
982 topRight.y = topRight.x * sine + topRight.y * cosine;
983
984 bottomLeft += textpos;
985 bottomRight += textpos;
986 topLeft += textpos;
987 topRight += textpos;
988
989 updateImageLimits( bottomLeft );
990 updateImageLimits( bottomRight );
991 updateImageLimits( topLeft );
992 updateImageLimits( topRight );
993
994 m_mtextContent.clear();
995}
996
997
999{
1000 double scale = 1.0;
1001
1002 switch( m_currentUnit )
1003 {
1004 case DXF_IMPORT_UNITS::INCH: scale = 25.4; break;
1005 case DXF_IMPORT_UNITS::FEET: scale = 304.8; break;
1006 case DXF_IMPORT_UNITS::MM: scale = 1.0; break;
1007 case DXF_IMPORT_UNITS::CM: scale = 10.0; break;
1008 case DXF_IMPORT_UNITS::METERS: scale = 1000.0; break;
1009 case DXF_IMPORT_UNITS::MICROINCHES: scale = 2.54e-5; break;
1010 case DXF_IMPORT_UNITS::MILS: scale = 0.0254; break;
1011 case DXF_IMPORT_UNITS::YARDS: scale = 914.4; break;
1012 case DXF_IMPORT_UNITS::ANGSTROMS: scale = 1.0e-7; break;
1013 case DXF_IMPORT_UNITS::NANOMETERS: scale = 1.0e-6; break;
1014 case DXF_IMPORT_UNITS::MICRONS: scale = 1.0e-3; break;
1015 case DXF_IMPORT_UNITS::DECIMETERS: scale = 100.0; break;
1016
1017 default:
1018 // use the default of 1.0 for:
1019 // 0: Unspecified Units
1020 // 3: miles
1021 // 7: kilometers
1022 // 15: decameters
1023 // 16: hectometers
1024 // 17: gigameters
1025 // 18: AU
1026 // 19: lightyears
1027 // 20: parsecs
1028 break;
1029 }
1030
1031 return scale;
1032}
1033
1034
1035static std::vector<std::pair<DXF_IMPORT_UNITS, wxString>> dxfImportUnitChoices()
1036{
1037 // Dialog state saving persists the selection index, so this order must stay stable
1038 return { { DXF_IMPORT_UNITS::INCH, _( "Inches" ) },
1039 { DXF_IMPORT_UNITS::FEET, _( "Feet" ) },
1040 { DXF_IMPORT_UNITS::MM, _( "Millimeters" ) },
1041 { DXF_IMPORT_UNITS::CM, _( "Centimeter" ) },
1042 { DXF_IMPORT_UNITS::MILS, _( "Mils" ) } };
1043}
1044
1045
1047{
1048 wxArrayString names;
1049
1050 for( const std::pair<DXF_IMPORT_UNITS, wxString>& choice : dxfImportUnitChoices() )
1051 names.Add( choice.second );
1052
1053 return names;
1054}
1055
1056
1058{
1059 std::vector<std::pair<DXF_IMPORT_UNITS, wxString>> choices = dxfImportUnitChoices();
1060
1061 if( aSelection < 0 || aSelection >= (int) choices.size() )
1063
1064 return choices[aSelection].first;
1065}
1066
1067
1068void DXF_IMPORT_PLUGIN::setVariableInt( const std::string& key, int value, int code )
1069{
1070 // Called for every int variable in the DXF file (e.g. "$INSUNITS").
1071
1072 if( key == "$DWGCODEPAGE" )
1073 {
1074 m_codePage = value;
1075 return;
1076 }
1077
1078 if( key == "$AUPREC" )
1079 {
1080 m_importAnglePrecision = value;
1081 return;
1082 }
1083
1084 if( key == "$LUPREC" )
1085 {
1087 return;
1088 }
1089
1090 if( key == "$INSUNITS" ) // Drawing units
1091 {
1093
1094 switch( value )
1095 {
1096 case 1: m_currentUnit = DXF_IMPORT_UNITS::INCH; break;
1097 case 2: m_currentUnit = DXF_IMPORT_UNITS::FEET; break;
1098 case 4: m_currentUnit = DXF_IMPORT_UNITS::MM; break;
1099 case 5: m_currentUnit = DXF_IMPORT_UNITS::CM; break;
1100 case 6: m_currentUnit = DXF_IMPORT_UNITS::METERS; break;
1102 case 9: m_currentUnit = DXF_IMPORT_UNITS::MILS; break;
1103 case 10: m_currentUnit = DXF_IMPORT_UNITS::YARDS; break;
1106 case 13: m_currentUnit = DXF_IMPORT_UNITS::MICRONS; break;
1108
1109 default:
1110 // use the default for:
1111 // 0: Unspecified Units
1112 // 3: miles
1113 // 7: kilometers
1114 // 15: decameters
1115 // 16: hectometers
1116 // 17: gigameters
1117 // 18: AU
1118 // 19: lightyears
1119 // 20: parsecs
1120 break;
1121 }
1122
1123 return;
1124 }
1125}
1126
1127
1128void DXF_IMPORT_PLUGIN::setVariableString( const std::string& key, const std::string& value,
1129 int code )
1130{
1131 // Called for every string variable in the DXF file (e.g. "$ACADVER").
1132}
1133
1134
1135wxString DXF_IMPORT_PLUGIN::toDxfString( const wxString& aStr )
1136{
1137 wxString res;
1138 int j = 0;
1139
1140 for( unsigned i = 0; i<aStr.length(); ++i )
1141 {
1142 int c = aStr[i];
1143
1144 if( c > 175 || c < 11 )
1145 {
1146 res.append( aStr.Mid( j, i - j ) );
1147 j = i;
1148
1149 switch( c )
1150 {
1151 case 0x0A:
1152 res += wxT( "\\P" );
1153 break;
1154
1155 // diameter:
1156#ifdef _WIN32
1157 // windows, as always, is special.
1158 case 0x00D8:
1159#else
1160 case 0x2205:
1161#endif
1162 res += wxT( "%%C" );
1163 break;
1164
1165 // degree:
1166 case 0x00B0:
1167 res += wxT( "%%D" );
1168 break;
1169
1170 // plus/minus
1171 case 0x00B1:
1172 res += wxT( "%%P" );
1173 break;
1174
1175 default:
1176 j--;
1177 break;
1178 }
1179
1180 j++;
1181 }
1182 }
1183
1184 res.append( aStr.Mid( j ) );
1185 return res;
1186}
1187
1188
1189wxString DXF_IMPORT_PLUGIN::toNativeString( const wxString& aData )
1190{
1191 wxString res;
1192 size_t i = 0;
1193 int braces = 0;
1194 int overbarLevel = -1;
1195
1196 // For description, see:
1197 // https://ezdxf.readthedocs.io/en/stable/dxfinternals/entities/mtext.html
1198 // https://www.cadforum.cz/en/text-formatting-codes-in-mtext-objects-tip8640
1199
1200 for( i = 0; i < aData.length(); i++ )
1201 {
1202 switch( (wchar_t) aData[i] )
1203 {
1204 case '{': // Text area influenced by the code
1205 braces++;
1206 break;
1207
1208 case '}':
1209 if( overbarLevel == braces )
1210 {
1211 res << '}';
1212 overbarLevel = -1;
1213 }
1214 braces--;
1215 break;
1216
1217 case '^': // C0 control code
1218 if( ++i >= aData.length() )
1219 break;
1220
1221 switch( (wchar_t) aData[i] )
1222 {
1223 case 'I': res << '\t'; break;
1224 case 'J': res << '\b'; break;
1225 case ' ': res << '^'; break;
1226 default: break;
1227 }
1228 break;
1229
1230 case '\\':
1231 {
1232 if( ++i >= aData.length() )
1233 break;
1234
1235 switch( (wchar_t) aData[i] )
1236 {
1237 case 'P': // New paragraph (new line)
1238 case 'X': // Paragraph wrap on the dimension line (only in dimensions)
1239 res << '\n';
1240 break;
1241
1242 case '~': // Non-wrapping space, hard space
1243 res << L'\u00A0';
1244 break;
1245
1246 case 'U': // Unicode character, e.g. \U+ff08
1247 {
1248 i += 2;
1249 wxString codeHex;
1250
1251 for( ; codeHex.length() < 4 && i < aData.length(); i++ )
1252 codeHex << aData[i];
1253
1254 unsigned long codeVal = 0;
1255
1256 if( codeHex.ToCULong( &codeVal, 16 ) && codeVal != 0 )
1257 res << wxUniChar( codeVal );
1258
1259 i--;
1260 }
1261 break;
1262
1263 case 'S': // Stacking
1264 {
1265 i++;
1266 wxString stacked;
1267
1268 for( ; i < aData.length(); i++ )
1269 {
1270 if( aData[i] == ';' )
1271 break;
1272 else
1273 stacked << aData[i];
1274 }
1275
1276 if( stacked.Contains( wxS( "#" ) ) )
1277 {
1278 res << '^' << '{';
1279 res << stacked.BeforeFirst( '#' );
1280 res << '}' << '/' << '_' << '{';
1281 res << stacked.AfterFirst( '#' );
1282 res << '}';
1283 }
1284 else
1285 {
1286 stacked.Replace( wxS( "^ " ), wxS( "/" ) );
1287 res << stacked;
1288 }
1289 }
1290 break;
1291
1292 case 'O': // Start overstrike
1293 if( overbarLevel == -1 )
1294 {
1295 res << '~' << '{';
1296 overbarLevel = braces;
1297 }
1298 break;
1299 case 'o': // Stop overstrike
1300 if( overbarLevel == braces )
1301 {
1302 res << '}';
1303 overbarLevel = -1;
1304 }
1305 break;
1306
1307 case 'L': // Start underline
1308 case 'l': // Stop underline
1309 case 'K': // Start strike-through
1310 case 'k': // Stop strike-through
1311 case 'N': // New column
1312 // Ignore
1313 break;
1314
1315 case 'p': // Control codes for bullets, numbered paragraphs, tab stops and columns
1316 case 'Q': // Slanting (obliquing) text by angle
1317 case 'H': // Text height
1318 case 'W': // Text width
1319 case 'F': // Font selection
1320 case 'f': // Font selection (alternative)
1321 case 'A': // Alignment
1322 case 'C': // Color change (ACI colors)
1323 case 'c': // Color change (truecolor)
1324 case 'T': // Tracking, char.spacing
1325 // Skip to ;
1326 for( ; i < aData.length(); i++ )
1327 {
1328 if( aData[i] == ';' )
1329 break;
1330 }
1331 break;
1332
1333 default: // Escaped character
1334 if( ++i >= aData.length() )
1335 break;
1336
1337 res << aData[i];
1338 break;
1339 }
1340 }
1341 break;
1342
1343 default: res << aData[i];
1344 }
1345 }
1346
1347 if( overbarLevel != -1 )
1348 {
1349 res << '}';
1350 overbarLevel = -1;
1351 }
1352
1353#if 1
1354 wxRegEx regexp;
1355
1356 // diameter:
1357 regexp.Compile( wxT( "%%[cC]" ) );
1358#ifdef __WINDOWS__
1359 // windows, as always, is special.
1360 regexp.Replace( &res, wxChar( 0xD8 ) );
1361#else
1362 // Empty_set, diameter is 0x2300
1363 regexp.Replace( &res, wxChar( 0x2205 ) );
1364#endif
1365
1366 // degree:
1367 regexp.Compile( wxT( "%%[dD]" ) );
1368 regexp.Replace( &res, wxChar( 0x00B0 ) );
1369
1370 // plus/minus
1371 regexp.Compile( wxT( "%%[pP]" ) );
1372 regexp.Replace( &res, wxChar( 0x00B1 ) );
1373#endif
1374
1375 return res;
1376}
1377
1378
1379void DXF_IMPORT_PLUGIN::addTextStyle( const DL_StyleData& aData )
1380{
1381 wxString name = wxString::FromUTF8( aData.name.c_str() );
1382
1383 auto style = std::make_unique<DXF_IMPORT_STYLE>( name, aData.fixedTextHeight, aData.widthFactor,
1384 aData.bold, aData.italic );
1385
1386 m_styles.push_back( std::move( style ) );
1387}
1388
1389
1390void DXF_IMPORT_PLUGIN::addPoint( const DL_PointData& aData )
1391{
1392 MATRIX3x3D arbAxis = getArbitraryAxis( getExtrusion() );
1393 VECTOR3D centerCoords = ocsToWcs( arbAxis, VECTOR3D( aData.x, aData.y, aData.z ) );
1394 VECTOR2D center( mapX( centerCoords.x ), mapY( centerCoords.y ) );
1395
1396 // we emulate points with filled circles
1397 // set the linewidth to something that even small circles look good with
1398 // thickness is optional for dxf points
1399 // note: we had to modify the dxf library to grab the attribute for thickness
1400 double lineWidth = 0.0001;
1401 double thickness = mapDim( std::max( aData.thickness, 0.01 ) );
1402
1403 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
1405 bufferToUse->SetCurrentSourceLayer( getDxfLayerName( attributes.getLayer() ) );
1406 bufferToUse->AddCircle( center, thickness, lineWidth, true );
1407
1408 VECTOR2D radiusDelta( SCALE_FACTOR( thickness ), SCALE_FACTOR( thickness ) );
1409
1410 updateImageLimits( center + radiusDelta );
1411 updateImageLimits( center - radiusDelta );
1412}
1413
1414
1416 const VECTOR2D& aSegEnd, double aWidth )
1417{
1418 VECTOR2D origin( SCALE_FACTOR( aSegStart.x ), SCALE_FACTOR( aSegStart.y ) );
1419 VECTOR2D end( SCALE_FACTOR( aSegEnd.x ), SCALE_FACTOR( aSegEnd.y ) );
1420
1421 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
1423 bufferToUse->SetCurrentSourceLayer( m_curr_entity.m_LayerName );
1424 bufferToUse->AddLine( origin, end, aWidth );
1425
1426 updateImageLimits( origin );
1428}
1429
1430
1431void DXF_IMPORT_PLUGIN::insertArc( const VECTOR2D& aSegStart, const VECTOR2D& aSegEnd,
1432 double aBulge, double aWidth )
1433{
1434 VECTOR2D segment_startpoint( SCALE_FACTOR( aSegStart.x ), SCALE_FACTOR( aSegStart.y ) );
1435 VECTOR2D segment_endpoint( SCALE_FACTOR( aSegEnd.x ), SCALE_FACTOR( aSegEnd.y ) );
1436
1437 // ensure aBulge represents an angle from +/- ( 0 .. approx 359.8 deg )
1438 if( aBulge < -2000.0 )
1439 aBulge = -2000.0;
1440 else if( aBulge > 2000.0 )
1441 aBulge = 2000.0;
1442
1443 double ang = 4.0 * atan( aBulge );
1444
1445 // reflect the Y values to put everything in a RHCS
1446 VECTOR2D sp( aSegStart.x, -aSegStart.y );
1447 VECTOR2D ep( aSegEnd.x, -aSegEnd.y );
1448
1449 // angle from end->start
1450 double offAng = atan2( ep.y - sp.y, ep.x - sp.x );
1451
1452 // length of subtended segment = 1/2 distance between the 2 points
1453 double d = 0.5 * sqrt( ( sp.x - ep.x ) * ( sp.x - ep.x ) + ( sp.y - ep.y ) * ( sp.y - ep.y ) );
1454
1455 // midpoint of the subtended segment
1456 double xm = ( sp.x + ep.x ) * 0.5;
1457 double ym = ( sp.y + ep.y ) * 0.5;
1458 double radius = d / sin( ang * 0.5 );
1459
1460 if( radius < 0.0 )
1461 radius = -radius;
1462
1463 // calculate the height of the triangle with base d and hypotenuse r
1464 double dh2 = radius * radius - d * d;
1465
1466 // this should only ever happen due to rounding errors when r == d
1467 if( dh2 < 0.0 )
1468 dh2 = 0.0;
1469
1470 double h = sqrt( dh2 );
1471
1472 if( ang < 0.0 )
1473 offAng -= M_PI_2;
1474 else
1475 offAng += M_PI_2;
1476
1477 // for angles greater than 180 deg we need to flip the
1478 // direction in which the arc center is found relative
1479 // to the midpoint of the subtended segment.
1480 if( ang < -M_PI )
1481 offAng += M_PI;
1482 else if( ang > M_PI )
1483 offAng -= M_PI;
1484
1485 // center point
1486 double cx = h * cos( offAng ) + xm;
1487 double cy = h * sin( offAng ) + ym;
1488 VECTOR2D center( SCALE_FACTOR( cx ), SCALE_FACTOR( -cy ) );
1489 VECTOR2D arc_start;
1490 EDA_ANGLE angle( ang, RADIANS_T );
1491
1492 if( ang < 0.0 )
1493 {
1494 arc_start = VECTOR2D( SCALE_FACTOR( ep.x ), SCALE_FACTOR( -ep.y ) );
1495 }
1496 else
1497 {
1498 arc_start = VECTOR2D( SCALE_FACTOR( sp.x ), SCALE_FACTOR( -sp.y ) );
1499 angle = -angle;
1500 }
1501
1502 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
1504 bufferToUse->SetCurrentSourceLayer( m_curr_entity.m_LayerName );
1505 bufferToUse->AddArc( center, arc_start, angle, aWidth );
1506
1507 VECTOR2D radiusDelta( SCALE_FACTOR( radius ), SCALE_FACTOR( radius ) );
1508
1509 updateImageLimits( center + radiusDelta );
1510 updateImageLimits( center - radiusDelta );
1511}
1512
1513
1514#include "tinysplinecxx.h"
1515
1517{
1518#if 0 // Debug only
1519 wxLogMessage( "spl deg %d kn %d ctr %d fit %d",
1520 m_curr_entity.m_SplineDegree,
1521 m_curr_entity.m_SplineKnotsList.size(),
1522 m_curr_entity.m_SplineControlPointList.size(),
1523 m_curr_entity.m_SplineFitPointList.size() );
1524#endif
1525
1526 unsigned imax = m_curr_entity.m_SplineControlPointList.size();
1527
1528 if( imax < 2 ) // malformed spline
1529 return;
1530
1531#if 0 // set to 1 to approximate the spline by segments between 2 control points
1532 VECTOR2D startpoint( mapX( m_curr_entity.m_SplineControlPointList[0].m_x ),
1533 mapY( m_curr_entity.m_SplineControlPointList[0].m_y ) );
1534
1535 for( unsigned int ii = 1; ii < imax; ++ii )
1536 {
1537 VECTOR2D endpoint( mapX( m_curr_entity.m_SplineControlPointList[ii].m_x ),
1538 mapY( m_curr_entity.m_SplineControlPointList[ii].m_y ) );
1539
1540 if( startpoint != endpoint )
1541 {
1542 m_internalImporter.AddLine( startpoint, endpoint, aWidth );
1543
1544 updateImageLimits( startpoint );
1545 updateImageLimits( endpoint );
1546
1547 startpoint = endpoint;
1548 }
1549 }
1550#else // Use bezier curves, supported by pcbnew, to approximate the spline
1551 std::vector<double> ctrlp;
1552
1553 for( unsigned ii = 0; ii < imax; ++ii )
1554 {
1555 ctrlp.push_back( m_curr_entity.m_SplineControlPointList[ii].m_x );
1556 ctrlp.push_back( m_curr_entity.m_SplineControlPointList[ii].m_y );
1557 }
1558
1559 tinyspline::BSpline beziers;
1560 std::vector<double> coords;
1561
1562 try
1563 {
1564 tinyspline::BSpline dxfspline( m_curr_entity.m_SplineControlPointList.size(),
1565 /* coord dim */ 2, m_curr_entity.m_SplineDegree );
1566
1567 dxfspline.setControlPoints( ctrlp );
1568 dxfspline.setKnots( m_curr_entity.m_SplineKnotsList );
1569
1570 if( dxfspline.degree() < 3 )
1571 dxfspline = dxfspline.elevateDegree( 3 - dxfspline.degree() );
1572
1573 beziers = dxfspline.toBeziers();
1574 coords = beziers.controlPoints();
1575 }
1576 catch( const std::runtime_error& ) // tinyspline throws everything including data validation
1577 // as runtime errors
1578 {
1579 // invalid spline definition, drop this block
1580 ReportMsg( _( "Invalid spline definition encountered" ) );
1581 return;
1582 }
1583
1584 size_t order = beziers.order();
1585 size_t dim = beziers.dimension();
1586 size_t numBeziers = ( coords.size() / dim ) / order;
1587
1588 for( size_t i = 0; i < numBeziers; i++ )
1589 {
1590 size_t ii = i * dim * order;
1591 VECTOR2D start( mapX( coords[ ii ] ), mapY( coords[ ii + 1 ] ) );
1592 VECTOR2D bezierControl1( mapX( coords[ii + 2] ), mapY( coords[ii + 3] ) );
1593
1594 // not sure why this happens, but it seems to sometimes slip degree on the final bezier
1595 VECTOR2D bezierControl2;
1596
1597 if( ii + 5 >= coords.size() )
1598 bezierControl2 = bezierControl1;
1599 else
1600 bezierControl2 = VECTOR2D( mapX( coords[ii + 4] ), mapY( coords[ii + 5] ) );
1601
1602 VECTOR2D end;
1603
1604 if( ii + 7 >= coords.size() )
1605 end = bezierControl2;
1606 else
1607 end = VECTOR2D( mapX( coords[ii + 6] ), mapY( coords[ii + 7] ) );
1608
1609 GRAPHICS_IMPORTER_BUFFER* bufferToUse = m_currentBlock ? &m_currentBlock->m_buffer
1611 bufferToUse->SetCurrentSourceLayer( m_curr_entity.m_LayerName );
1612 bufferToUse->AddSpline( start, bezierControl1, bezierControl2, end, aWidth );
1613 }
1614#endif
1615}
1616
1617
1619{
1620 m_minX = std::min( aPoint.x, m_minX );
1621 m_maxX = std::max( aPoint.x, m_maxX );
1622
1623 m_minY = std::min( aPoint.y, m_minY );
1624 m_maxY = std::max( aPoint.y, m_maxY );
1625}
1626
1627
1629{
1630 VECTOR3D arbZ, arbX, arbY;
1631
1632 double direction[3];
1633 aData->getDirection( direction );
1634
1635 arbZ = VECTOR3D( direction[0], direction[1], direction[2] ).Normalize();
1636
1637 if( ( abs( arbZ.x ) < ( 1.0 / 64.0 ) ) && ( abs( arbZ.y ) < ( 1.0 / 64.0 ) ) )
1638 arbX = VECTOR3D( 0, 1, 0 ).Cross( arbZ ).Normalize();
1639 else
1640 arbX = VECTOR3D( 0, 0, 1 ).Cross( arbZ ).Normalize();
1641
1642 arbY = arbZ.Cross( arbX ).Normalize();
1643
1644 return MATRIX3x3D{ arbX, arbY, arbZ };
1645}
1646
1647
1649{
1650 return arbitraryAxis * point;
1651}
1652
1653
1655{
1656 VECTOR3D worldX = wcsToOcs( arbitraryAxis, VECTOR3D( 1, 0, 0 ) );
1657 VECTOR3D worldY = wcsToOcs( arbitraryAxis, VECTOR3D( 0, 1, 0 ) );
1658 VECTOR3D worldZ = wcsToOcs( arbitraryAxis, VECTOR3D( 0, 0, 1 ) );
1659
1660 MATRIX3x3 world( worldX, worldY, worldZ );
1661
1662 return world * point;
1663}
const char * name
BOX2< VECTOR2D > BOX2D
Definition box2.h:918
constexpr void SetOrigin(const Vec &pos)
Definition box2.h:240
constexpr void SetEnd(coord_type x, coord_type y)
Definition box2.h:300
A helper class to hold layer settings temporarily during import.
GRAPHICS_IMPORTER_BUFFER m_buffer
A helper class to hold layer settings temporarily during import.
DXF_IMPORT_UNITS m_currentUnit
virtual void addPolyline(const DL_PolylineData &aData) override
double mapY(double aDxfCoordY)
std::vector< std::unique_ptr< DXF_IMPORT_LAYER > > m_layers
void addEllipse(const DL_EllipseData &aData) override
static wxString toNativeString(const wxString &aData)
Convert a DXF encoded string into a native Unicode string.
virtual void setVariableInt(const std::string &key, int value, int code) override
Called for every int variable in the DXF file (e.g.
void insertSpline(double aWidth)
virtual void addLine(const DL_LineData &aData) override
VECTOR3D ocsToWcs(const MATRIX3x3D &arbitraryAxis, VECTOR3D point)
Convert a given object coordinate point to world coordinate using the given arbitrary axis vectors.
void insertLine(const VECTOR2D &aSegStart, const VECTOR2D &aSegEnd, double aWidth)
DXF_IMPORT_BLOCK * getImportBlock(const std::string &aBlockName)
Return the import layer block.
virtual void addBlock(const DL_BlockData &) override
Called for each BLOCK in the DXF file.
virtual void addLayer(const DL_LayerData &aData) override
virtual void addCircle(const DL_CircleData &aData) override
virtual void addMText(const DL_MTextData &aData) override
DXF_IMPORT_LAYER * getImportLayer(const std::string &aLayerName)
Return the import layer data.
static wxString toDxfString(const wxString &aStr)
Convert a native Unicode string into a DXF encoded string.
DXF_IMPORT_STYLE * getImportStyle(const std::string &aStyleName)
Return the import style.
virtual void addInsert(const DL_InsertData &aData) override
BOX2D GetImageBBox() const override
Return image bounding box from original imported file.
MATRIX3x3D getArbitraryAxis(DL_Extrusion *aData)
double GetImageWidth() const override
Return image width from original imported file.
double GetImageHeight() const override
Return image height from original imported file.
void updateImageLimits(const VECTOR2D &aPoint)
virtual void addTextStyle(const DL_StyleData &aData) override
virtual void addVertex(const DL_VertexData &aData) override
Called for every polyline vertex.
VECTOR3D wcsToOcs(const MATRIX3x3D &arbitraryAxis, VECTOR3D point)
Convert a given world coordinate point to object coordinate using the given arbitrary axis vectors.
virtual void addSpline(const DL_SplineData &aData) override
Called for every spline.
virtual void addText(const DL_TextData &aData) override
virtual void endBlock() override
virtual void setVariableString(const std::string &key, const std::string &value, int code) override
Called for every string variable in the DXF file (e.g.
virtual void addKnot(const DL_KnotData &aData) override
Called for every spline knot value.
bool ImportDxfFile(const wxString &aFile)
Implementation of the method used for communicate with this filter.
virtual void addArc(const DL_ArcData &aData) override
void SetDefaultLineWidthMM(double aWidth)
Set the default line width when importing dxf items like lines to Pcbnew.
virtual void addFitPoint(const DL_FitPointData &aData) override
Called for every spline fit point.
virtual void addPoint(const DL_PointData &aData) override
double mapDim(double aDxfValue)
void ReportMsg(const wxString &aMessage) override
double mapX(double aDxfCoordX)
double lineWeightToWidth(int lw, DXF_IMPORT_LAYER *aLayer)
void insertArc(const VECTOR2D &aSegStart, const VECTOR2D &aSegEnd, double aBulge, double aWidth)
std::vector< std::unique_ptr< DXF_IMPORT_BLOCK > > m_blocks
bool Import() override
Actually imports the file.
virtual void addMTextChunk(const std::string &text) override
virtual void endEntity() override
virtual void addControlPoint(const DL_ControlPointData &aData) override
Called for every spline control point.
GRAPHICS_IMPORTER_BUFFER m_internalImporter
std::vector< std::unique_ptr< DXF_IMPORT_STYLE > > m_styles
bool Load(const wxString &aFileName) override
Load file for import.
DXF_IMPORT_BLOCK * m_currentBlock
DXF2BRD_ENTITY_DATA m_curr_entity
wxString getDxfLayerName(const std::string &aLayerName) const
virtual void SetImporter(GRAPHICS_IMPORTER *aImporter) override
Set the receiver of the imported shapes.
virtual void addLinetype(const DL_LinetypeData &data) override
A helper class to hold style settings temporarily during import.
double AsDegrees() const
Definition eda_angle.h:115
std::list< std::unique_ptr< IMPORTED_SHAPE > > & GetShapes()
void AddCircle(const VECTOR2D &aCenter, double aRadius, const IMPORTED_STROKE &aStroke, bool aFilled, const COLOR4D &aFillColor=COLOR4D::UNSPECIFIED) override
Create an object representing a circle.
void AddSpline(const VECTOR2D &aStart, const VECTOR2D &aBezierControl1, const VECTOR2D &aBezierControl2, const VECTOR2D &aEnd, const IMPORTED_STROKE &aStroke) override
Create an object representing an arc.
void AddLine(const VECTOR2D &aStart, const VECTOR2D &aEnd, const IMPORTED_STROKE &aStroke) override
Create an object representing a line segment.
void AddEllipse(const VECTOR2D &aCenter, double aMajorRadius, double aMinorRadius, const EDA_ANGLE &aRotation, const IMPORTED_STROKE &aStroke, bool aFilled, const COLOR4D &aFillColor=COLOR4D::UNSPECIFIED) override
Create an object representing a closed ellipse.
void SetCurrentSourceLayer(const wxString &aSourceLayer) override
Set the source layer for the next buffered shape to be imported.
void AddArc(const VECTOR2D &aCenter, const VECTOR2D &aStart, const EDA_ANGLE &aAngle, const IMPORTED_STROKE &aStroke) override
Create an object representing an arc.
void AddText(const VECTOR2D &aOrigin, const wxString &aText, double aHeight, double aWidth, double aThickness, double aOrientation, GR_TEXT_H_ALIGN_T aHJustify, GR_TEXT_V_ALIGN_T aVJustify, const COLOR4D &aColor=COLOR4D::UNSPECIFIED) override
Create an object representing a text.
void AddEllipseArc(const VECTOR2D &aCenter, double aMajorRadius, double aMinorRadius, const EDA_ANGLE &aRotation, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aEndAngle, const IMPORTED_STROKE &aStroke) override
Create an object representing an elliptical arc.
Interface that creates objects representing shapes for a given data model.
GRAPHICS_IMPORTER * m_importer
Importer used to create objects representing the imported shapes.
virtual void SetImporter(GRAPHICS_IMPORTER *aImporter)
Set the receiver of the imported shapes.
MATRIX3x3 describes a general 3x3 matrix.
Definition matrix3x3.h:59
void SetRotation(T aAngle)
Set the rotation components of the matrix.
Definition matrix3x3.h:271
VECTOR2< T > GetScale() const
Get the scale components of the matrix.
Definition matrix3x3.h:291
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition vector2d.h:281
VECTOR3< T > Normalize()
Compute the normalized vector.
Definition vector3.h:160
VECTOR3< T > Cross(const VECTOR3< T > &aVector) const
Compute cross product of self with aVector.
Definition vector3.h:134
#define SCALE_FACTOR(x)
wxArrayString GetDxfImportUnitChoices()
static std::vector< std::pair< DXF_IMPORT_UNITS, wxString > > dxfImportUnitChoices()
DXF_IMPORT_UNITS DxfImportUnitFromChoice(int aSelection)
#define MIN_BULGE
#define DXF_IMPORT_LINEWEIGHT_BY_LW_DEFAULT
#define DXF_IMPORT_LINEWEIGHT_BY_LAYER
DXF_IMPORT_UNITS
DXF Units enum with values as specified in DXF 2012 Specification.
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
@ RADIANS_T
Definition eda_angle.h:31
@ DEGREES_T
Definition eda_angle.h:30
static constexpr EDA_ANGLE ANGLE_360
Definition eda_angle.h:478
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:476
@ Dwgs_User
Definition layer_ids.h:103
This file contains miscellaneous commonly used macros and functions.
MATRIX3x3< double > MATRIX3x3D
Definition matrix3x3.h:469
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
const int scale
wxString From_UTF8(const char *cstring)
nanodbc::result res
VECTOR2I center
int radius
VECTOR2I end
SHAPE_CIRCLE circle(c.m_circle_center, c.m_circle_radius)
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_V_ALIGN_T
This is API surface mapped to common.types.VertialAlignment.
@ GR_TEXT_V_ALIGN_BOTTOM
@ 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:227
double DEG2RAD(double deg)
Definition trigo.h:178
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
VECTOR3< double > VECTOR3D
Definition vector3.h:230