KiCad PCB EDA Suite
Loading...
Searching...
No Matches
cadstar_pcb_archive_loader.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-2021 Roberto Fernandez Bautista <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * 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
25
27
29#include <board_stackup_manager/stackup_predefined_prms.h> // KEY_COPPER, KEY_CORE, KEY_PREPREG
30#include <board.h>
33#include <pcb_dimension.h>
34#include <pcb_shape.h>
35#include <footprint.h>
36#include <pad.h>
37#include <pcb_group.h>
38#include <pcb_text.h>
39#include <project.h>
40#include <pcb_track.h>
41#include <progress_reporter.h>
42#include <zone.h>
44#include <trigo.h>
45#include <macros.h>
46#include <wx/debug.h>
47#include <font/fontconfig.h>
49#include <wx/log.h>
50
51#include <limits> // std::numeric_limits
52
53
55{
56 m_board = aBoard;
57 m_project = aProject;
58
60 m_progressReporter->SetNumPhases( 3 ); // (0) Read file, (1) Parse file, (2) Load file
61
62 Parse();
63
64 LONGPOINT designLimit = Assignments.Technology.DesignLimit;
65
66 //Note: can't use getKiCadPoint() due wxPoint being int - need long long to make the check
67 long long designSizeXkicad = (long long) designLimit.x * KiCadUnitMultiplier;
68 long long designSizeYkicad = (long long) designLimit.y * KiCadUnitMultiplier;
69
70 // Max size limited by the positive dimension of wxPoint (which is an int)
71 long long maxDesignSizekicad = std::numeric_limits<int>::max();
72
73 if( designSizeXkicad > maxDesignSizekicad || designSizeYkicad > maxDesignSizekicad )
74 {
75 // Note that we allow the floating point output here because this message is displayed to the user and should
76 // be in their locale.
77 THROW_IO_ERRORF( _( "The design is too large and cannot be imported into KiCad. \n"
78 "Please reduce the maximum design size in CADSTAR by navigating to: \n"
79 "Design Tab -> Properties -> Design Options -> Maximum Design Size. \n"
80 "Current Design size: %.2f, %.2f millimeters. \n" //format:allow
81 "Maximum permitted design size: %.2f, %.2f millimeters.\n" ), //format:allow
82 (double) designSizeXkicad / PCB_IU_PER_MM,
83 (double) designSizeYkicad / PCB_IU_PER_MM,
84 (double) maxDesignSizekicad / PCB_IU_PER_MM,
85 (double) maxDesignSizekicad / PCB_IU_PER_MM );
86 }
87
89 ( Assignments.Technology.DesignArea.first + Assignments.Technology.DesignArea.second )
90 / 2;
91
92 if( Layout.NetSynch == NETSYNCH::WARNING )
93 {
94 reportWarning( _( "The selected file indicates that nets might be out of synchronisation with the schematic. "
95 "It is recommended that you carry out an 'Align Nets' procedure in CADSTAR and re-import, "
96 "to avoid inconsistencies between the PCB and the schematic. " ) );
97 }
98
100 {
101 m_progressReporter->BeginPhase( 2 );
102
103 // Significantly most amount of time spent loading coppers compared to all the other steps
104 // (39 seconds vs max of 100ms in other steps). This is due to requirement of boolean
105 // operations to join them together into a single polygon.
106 long numSteps = Layout.Coppers.size();
107
108 // A large amount is also spent calculating zone priorities
109 numSteps += ( Layout.Templates.size() * Layout.Templates.size() ) / 2;
110
111 m_progressReporter->SetMaxProgress( numSteps );
112 }
113
118 loadGroups();
119 loadBoards();
120 loadFigures();
121 loadTexts();
123 loadAreas();
127 loadCoppers(); // Progress reporting is here as significantly most amount of time spent
128
130 {
131 if( !calculateZonePriorities( id ) )
132 {
133 reportError( wxString::Format( _( "Unable to determine zone fill priorities for layer '%s'. A best "
134 "attempt has been made but it is possible that DRC errors exist and "
135 "that manual editing of the zone priorities is required." ),
136 m_board->GetLayerName( id ) ) );
137 }
138 }
139
140 loadNets();
142
143 if( Layout.Trunks.size() > 0 )
144 {
145 reportWarning( _( "The CADSTAR design contains Trunk routing elements, which have no KiCad "
146 "equivalent. These elements were not loaded." ) );
147 }
148
149 if( Layout.VariantHierarchy.Variants.size() > 0 )
150 {
151 reportWarning( wxString::Format( _( "The CADSTAR design contains variants which has no KiCad equivalent. "
152 "Only the variant '%s' was loaded." ),
153 Layout.VariantHierarchy.Variants.begin()->second.Name ) );
154 }
155
156 if( Layout.ReuseBlocks.size() > 0 )
157 {
158 reportWarning( _( "The CADSTAR design contains re-use blocks which has no KiCad equivalent. The "
159 "re-use block information has been discarded during the import." ) );
160 }
161
162 reportWarning( _( "CADSTAR fonts are different to the ones in KiCad. This will likely result "
163 "in alignment issues that may cause DRC errors. Please review the imported "
164 "text elements carefully and correct manually if required." ) );
165
166 reportInfo( _( "The CADSTAR design has been imported successfully.\n"
167 "Please review the import errors and warnings (if any)." ) );
168}
169
171{
172 std::vector<FOOTPRINT*> retval;
173
174 for( std::pair<SYMDEF_ID, FOOTPRINT*> fpPair : m_libraryMap )
175 {
176 retval.push_back( static_cast<FOOTPRINT*>( fpPair.second->Clone() ) );
177 }
178
179 return retval;
180}
181
182
183std::vector<std::unique_ptr<FOOTPRINT>> CADSTAR_PCB_ARCHIVE_LOADER::LoadFpLibrary()
184{
185 // loading the library after parsing takes almost no time in comparison
187 m_progressReporter->SetNumPhases( 2 ); // (0) Read file, (1) Parse file
188
189 Parse( true /*aLibrary*/);
190
191 // Some memory handling
192 for( std::pair<SYMDEF_ID, FOOTPRINT*> libItem : m_libraryMap )
193 {
194 FOOTPRINT* footprint = libItem.second;
195
196 delete footprint;
197 }
198
199 m_libraryMap.clear();
200
201 delete m_board;
202
203 m_board = new BOARD(); // dummy board for loading
204 m_project = nullptr;
205 m_designCenter = { 0, 0 }; // load footprints at 0,0
206
210
211 std::vector<std::unique_ptr<FOOTPRINT>> retval;
212
213 for( auto& [id, footprint] : m_libraryMap )
214 {
215 footprint->SetParent( nullptr ); // remove association to m_board
216 retval.emplace_back( footprint );
217 }
218
219 delete m_board;
220
221 // Don't delete the generated footprints, but empty the map
222 // (the destructor of this class would end up deleting them if not)
223 m_libraryMap.clear();
224
225 return retval;
226}
227
228
229void CADSTAR_PCB_ARCHIVE_LOADER::logBoardStackupWarning( const wxString& aCadstarLayerName,
230 const PCB_LAYER_ID& aKiCadLayer )
231{
233 {
234 reportWarning( wxString::Format( _( "The CADSTAR layer '%s' has no KiCad equivalent. All elements on this "
235 "layer have been mapped to KiCad layer '%s' instead." ),
236 aCadstarLayerName,
237 LSET::Name( aKiCadLayer ) ) );
238 }
239}
240
241
242void CADSTAR_PCB_ARCHIVE_LOADER::logBoardStackupMessage( const wxString& aCadstarLayerName,
243 const PCB_LAYER_ID& aKiCadLayer )
244{
246 {
247 reportInfo( wxString::Format( _( "The CADSTAR layer '%s' has been assumed to be a technical layer. All "
248 "elements on this layer have been mapped to KiCad layer '%s'." ),
249 aCadstarLayerName,
250 LSET::Name( aKiCadLayer ) ) );
251 }
252}
253
254
256 int aDielectricSublayer )
257{
258 if( !aCadstarLayer.MaterialId.IsEmpty() )
259 {
260 MATERIAL material = Assignments.Layerdefs.Materials.at( aCadstarLayer.MaterialId );
261
262 aKiCadItem->SetMaterial( material.Name, aDielectricSublayer );
263 aKiCadItem->SetEpsilonR( material.Permittivity.GetDouble(), aDielectricSublayer );
264 aKiCadItem->SetLossTangent( material.LossTangent.GetDouble(), aDielectricSublayer );
265 //TODO add Resistivity when KiCad supports it
266 }
267
268 if( !aCadstarLayer.Name.IsEmpty() )
269 aKiCadItem->SetLayerName( aCadstarLayer.Name );
270
271 if( aCadstarLayer.Thickness != 0 )
272 aKiCadItem->SetThickness( getKiCadLength( aCadstarLayer.Thickness, 0.01 ), aDielectricSublayer );
273}
274
275
277{
278 // Structure describing an electrical layer with optional dielectric layers below it
279 // (construction layers in CADSTAR)
280 struct LAYER_BLOCK
281 {
282 LAYER_ID ElecLayerID = wxEmptyString; // Normally not empty, but could be empty if the
283 // first layer in the stackup is a construction
284 // layer
285 std::vector<LAYER_ID> ConstructionLayers; // Normally empty for the last electrical layer
286 // but it is possible to build a board in CADSTAR
287 // with no construction layers or with the bottom
288 // layer being a construction layer
289
290 bool IsInitialised() { return !ElecLayerID.IsEmpty() || ConstructionLayers.size() > 0; };
291 };
292
293 std::vector<LAYER_BLOCK> cadstarBoardStackup;
294 LAYER_BLOCK currentBlock;
295 bool first = true;
296
297 // Find the electrical and construction (dielectric) layers in the stackup
298 for( LAYER_ID cadstarLayerID : Assignments.Layerdefs.LayerStack )
299 {
300 LAYER cadstarLayer = Assignments.Layerdefs.Layers.at( cadstarLayerID );
301
302 if( cadstarLayer.Type == LAYER_TYPE::JUMPERLAYER ||
303 cadstarLayer.Type == LAYER_TYPE::POWER ||
304 cadstarLayer.Type == LAYER_TYPE::ELEC )
305 {
306 if( currentBlock.IsInitialised() )
307 {
308 cadstarBoardStackup.push_back( currentBlock );
309 currentBlock = LAYER_BLOCK(); // reset the block
310 }
311
312 currentBlock.ElecLayerID = cadstarLayerID;
313 first = false;
314 }
315 else if( cadstarLayer.Type == LAYER_TYPE::CONSTRUCTION )
316 {
317 if( first )
318 {
319 reportWarning( wxString::Format( _( "The CADSTAR construction layer '%s' is on the outer surface "
320 "of the board. It has been ignored." ),
321 cadstarLayer.Name ) );
322 }
323 else
324 {
325 currentBlock.ConstructionLayers.push_back( cadstarLayerID );
326 }
327 }
328 }
329
330 if( currentBlock.IsInitialised() )
331 cadstarBoardStackup.push_back( currentBlock );
332
333 m_numCopperLayers = cadstarBoardStackup.size();
334
335 // Special case: last layer in the stackup is a construction layer, drop it
336 if( cadstarBoardStackup.back().ConstructionLayers.size() > 0 )
337 {
338 for( const LAYER_ID& layerID : cadstarBoardStackup.back().ConstructionLayers )
339 {
340 LAYER cadstarLayer = Assignments.Layerdefs.Layers.at( layerID );
341
342 reportWarning( wxString::Format( _( "The CADSTAR construction layer '%s' is on the outer surface "
343 "of the board. It has been ignored." ),
344 cadstarLayer.Name ) );
345 }
346
347 cadstarBoardStackup.back().ConstructionLayers.clear();
348 }
349
350 const int sourceCopperLayers = m_numCopperLayers;
351
352 // Make sure it is an even number of layers (KiCad doesn't yet support unbalanced stack-ups)
353 if( cadstarBoardStackup.size() == 1 )
354 {
355 // Single-sided board gets an empty back copper layer
356 cadstarBoardStackup.emplace_back();
358 }
359 else if( ( m_numCopperLayers % 2 ) != 0 )
360 {
361 LAYER_BLOCK bottomLayer = cadstarBoardStackup.back();
362 cadstarBoardStackup.pop_back();
363
364 LAYER_BLOCK secondToLastLayer = cadstarBoardStackup.back();
365 cadstarBoardStackup.pop_back();
366
367 LAYER_BLOCK dummyLayer;
368
369 if( secondToLastLayer.ConstructionLayers.size() > 0 )
370 {
371 LAYER_ID lastConstruction = secondToLastLayer.ConstructionLayers.back();
372
373 if( secondToLastLayer.ConstructionLayers.size() > 1 )
374 {
375 // At least two construction layers, lets remove one here and use the
376 // other in the dummy layer
377 secondToLastLayer.ConstructionLayers.pop_back();
378 }
379 else
380 {
381 // There is only one construction layer, lets halve its thickness so it is split
382 // evenly between this layer and the dummy layer
383 Assignments.Layerdefs.Layers.at( lastConstruction ).Thickness /= 2;
384 }
385
386 dummyLayer.ConstructionLayers.push_back( lastConstruction );
387 }
388
389 cadstarBoardStackup.push_back( secondToLastLayer );
390 cadstarBoardStackup.push_back( dummyLayer );
391 cadstarBoardStackup.push_back( bottomLayer );
393 }
394
395 wxASSERT( m_numCopperLayers == (int) cadstarBoardStackup.size() );
396 wxASSERT( cadstarBoardStackup.back().ConstructionLayers.size() == 0 );
397
398 // Create a new stackup from default stackup list
399 BOARD_DESIGN_SETTINGS& boardDesignSettings = m_board->GetDesignSettings();
400 BOARD_STACKUP& stackup = boardDesignSettings.GetStackupDescriptor();
401 stackup.RemoveAll();
402 m_board->SetEnabledLayers( LSET::AllLayersMask() );
403 m_board->SetVisibleLayers( LSET::AllLayersMask() );
404 m_board->SetCopperLayerCount( m_numCopperLayers );
405 stackup.BuildDefaultStackupList( &m_board->GetDesignSettings(), m_numCopperLayers );
406
407 size_t stackIndex = 0;
408
409 for( BOARD_STACKUP_ITEM* item : stackup.GetList() )
410 {
411 if( item->GetType() == BOARD_STACKUP_ITEM_TYPE::BS_ITEM_TYPE_COPPER )
412 {
413 LAYER_ID layerID = cadstarBoardStackup.at( stackIndex ).ElecLayerID;
414
415 if( layerID.IsEmpty() )
416 {
417 // Loading a dummy layer. Make zero thickness so it doesn't affect overall stackup
418 item->SetThickness( 0 );
419 }
420 else
421 {
422 LAYER copperLayer = Assignments.Layerdefs.Layers.at( layerID );
423 initStackupItem( copperLayer, item, 0 );
424 LAYER_T copperType = LAYER_T::LT_SIGNAL;
425
426 switch( copperLayer.Type )
427 {
429 copperType = LAYER_T::LT_JUMPER;
430 break;
431
432 case LAYER_TYPE::ELEC:
433 copperType = LAYER_T::LT_SIGNAL;
434 break;
435
437 copperType = LAYER_T::LT_POWER;
438 m_powerPlaneLayers.push_back( copperLayer.ID ); //need to add a Copper zone
439 break;
440
441 default:
442 wxFAIL_MSG( wxT( "Unexpected Layer type. Was expecting an electrical type" ) );
443 break;
444 }
445
446 m_board->SetLayerType( item->GetBrdLayerId(), copperType );
447 m_board->SetLayerName( item->GetBrdLayerId(), item->GetLayerName() );
448 m_layermap.insert( { copperLayer.ID, item->GetBrdLayerId() } );
449 }
450 }
451 else if( item->GetType() == BOARD_STACKUP_ITEM_TYPE::BS_ITEM_TYPE_DIELECTRIC )
452 {
453 LAYER_BLOCK layerBlock = cadstarBoardStackup.at( stackIndex );
454 LAYER_BLOCK layerBlockBelow = cadstarBoardStackup.at( stackIndex + 1 );
455
456 if( layerBlock.ConstructionLayers.size() == 0 )
457 {
458 ++stackIndex;
459 continue; // Older cadstar designs have no construction layers - use KiCad defaults
460 }
461
462 int dielectricId = stackIndex + 1;
463 item->SetDielectricLayerId( dielectricId );
464
465 //Prepreg or core?
466 //Look at CADSTAR layer embedding (see LAYER->Embedding) to check whether the electrical
467 //layer embeds above and below to decide if current layer is prepreg or core
468 if( layerBlock.ElecLayerID.IsEmpty() )
469 {
470 //Dummy electrical layer, assume prepreg
471 item->SetTypeName( KEY_PREPREG );
472 }
473 else
474 {
475 LAYER copperLayer = Assignments.Layerdefs.Layers.at( layerBlock.ElecLayerID );
476
477 if( layerBlockBelow.ElecLayerID.IsEmpty() )
478 {
479 // Dummy layer below, just use current layer to decide
480
481 if( copperLayer.Embedding == EMBEDDING::ABOVE )
482 item->SetTypeName( KEY_CORE );
483 else
484 item->SetTypeName( KEY_PREPREG );
485 }
486 else
487 {
488 LAYER copperLayerBelow =
489 Assignments.Layerdefs.Layers.at( layerBlockBelow.ElecLayerID );
490
491 if( copperLayer.Embedding == EMBEDDING::ABOVE )
492 {
493 // Need to check layer below is embedding downwards
494 if( copperLayerBelow.Embedding == EMBEDDING::BELOW )
495 item->SetTypeName( KEY_CORE );
496 else
497 item->SetTypeName( KEY_PREPREG );
498 }
499 else
500 {
501 item->SetTypeName( KEY_PREPREG );
502 }
503 }
504 }
505
506 int dielectricSublayer = 0;
507
508 for( LAYER_ID constructionLaID : layerBlock.ConstructionLayers )
509 {
510 LAYER dielectricLayer = Assignments.Layerdefs.Layers.at( constructionLaID );
511
512 if( dielectricSublayer )
513 item->AddDielectricPrms( dielectricSublayer );
514
515 initStackupItem( dielectricLayer, item, dielectricSublayer );
516 m_board->SetLayerName( item->GetBrdLayerId(), item->GetLayerName() );
517 m_layermap.insert( { dielectricLayer.ID, item->GetBrdLayerId() } );
518 ++dielectricSublayer;
519 }
520
521 ++stackIndex;
522 }
523 else if( item->GetType() == BOARD_STACKUP_ITEM_TYPE::BS_ITEM_TYPE_SILKSCREEN )
524 {
525 item->SetColor( wxT( "White" ) );
526 }
527 else if( item->GetType() == BOARD_STACKUP_ITEM_TYPE::BS_ITEM_TYPE_SOLDERMASK )
528 {
529 item->SetColor( wxT( "Green" ) );
530 }
531 }
532
533 int thickness = stackup.BuildBoardThicknessFromStackup();
534 boardDesignSettings.SetBoardThickness( thickness );
535 boardDesignSettings.m_HasStackup = true;
536
537 int numElecLayersProcessed = 0;
538
539 // Non-electrical layers name their side through the physical layer they sit on
540 PHYSICAL_LAYER_ID bottomPhysicalLayer = 1;
541
542 for( const LAYER_ID& cadstarLayerID : Assignments.Layerdefs.LayerStack )
543 {
544 const LAYER& layer = Assignments.Layerdefs.Layers.at( cadstarLayerID );
545
546 if( layer.Type == LAYER_TYPE::ELEC || layer.Type == LAYER_TYPE::POWER )
547 bottomPhysicalLayer = std::max( bottomPhysicalLayer, layer.PhysicalLayer );
548 }
549
550 // Map CADSTAR documentation layers to KiCad "User layers"
551 int currentDocLayer = 0;
552 std::vector<PCB_LAYER_ID> docLayers = { Dwgs_User, Cmts_User, User_1, User_2, User_3, User_4,
554
555 for( const LAYER_ID& cadstarLayerID : Assignments.Layerdefs.LayerStack )
556 {
557 LAYER curLayer = Assignments.Layerdefs.Layers.at( cadstarLayerID );
559 wxString layerName = curLayer.Name.Lower();
560
561 enum class LOG_LEVEL
562 {
563 NONE,
564 MSG_LOG,
565 WARN
566 };
567
568 auto selectLayerID =
569 [&]( PCB_LAYER_ID aFront, PCB_LAYER_ID aBack, LOG_LEVEL aLogType )
570 {
571 // Padding layers have no CADSTAR counterpart to count
572 bool isBack = numElecLayersProcessed >= sourceCopperLayers;
573
574 // Stack order is only a fallback, it says nothing about the side
575 if( curLayer.Type == LAYER_TYPE::NONELEC && curLayer.PhysicalLayer != UNDEFINED_PHYSICAL_LAYER )
576 {
577 if( curLayer.PhysicalLayer <= 1 )
578 isBack = false;
579 else if( curLayer.PhysicalLayer >= bottomPhysicalLayer )
580 isBack = true;
581 }
582
583 kicadLayerID = isBack ? aBack : aFront;
584
585 switch( aLogType )
586 {
587 case LOG_LEVEL::NONE:
588 break;
589
590 case LOG_LEVEL::MSG_LOG:
591 logBoardStackupMessage( curLayer.Name, kicadLayerID );
592 break;
593
594 case LOG_LEVEL::WARN:
595 logBoardStackupWarning( curLayer.Name, kicadLayerID );
596 break;
597 }
598 };
599
600 switch( curLayer.Type )
601 {
607 //Shouldn't be here if CPA file is correctly parsed and not corrupt
608 THROW_IO_ERRORF( _( "Unexpected layer '%s' in layer stack." ), curLayer.Name );
609 break;
610
612 case LAYER_TYPE::ELEC:
614 ++numElecLayersProcessed;
617 //Already dealt with these when loading board stackup
618 break;
619
620 case LAYER_TYPE::DOC:
621
622 if( currentDocLayer >= (int) docLayers.size() )
623 currentDocLayer = 0;
624
625 kicadLayerID = docLayers.at( currentDocLayer++ );
626 logBoardStackupMessage( curLayer.Name, kicadLayerID );
627 break;
628
630 switch( curLayer.SubType )
631 {
633 selectLayerID( PCB_LAYER_ID::F_Fab, PCB_LAYER_ID::B_Fab, LOG_LEVEL::NONE );
634 break;
635
637 selectLayerID( PCB_LAYER_ID::F_CrtYd, PCB_LAYER_ID::B_CrtYd, LOG_LEVEL::NONE );
638 break;
639
641 // Generic Non-electrical layer (older CADSTAR versions).
642 // Attempt to detect technical layers by string matching.
643 if( layerName.Contains( wxT( "glue" ) ) || layerName.Contains( wxT( "adhesive" ) ) )
644 {
645 selectLayerID( PCB_LAYER_ID::F_Adhes, PCB_LAYER_ID::B_Adhes, LOG_LEVEL::MSG_LOG );
646 }
647 else if( layerName.Contains( wxT( "silk" ) ) || layerName.Contains( wxT( "legend" ) ) )
648 {
649 selectLayerID( PCB_LAYER_ID::F_SilkS, PCB_LAYER_ID::B_SilkS, LOG_LEVEL::MSG_LOG );
650 }
651 else if( layerName.Contains( wxT( "assembly" ) ) || layerName.Contains( wxT( "fabrication" ) ) )
652 {
653 selectLayerID( PCB_LAYER_ID::F_Fab, PCB_LAYER_ID::B_Fab, LOG_LEVEL::MSG_LOG );
654 }
655 else if( layerName.Contains( wxT( "resist" ) ) || layerName.Contains( wxT( "mask" ) ) )
656 {
657 selectLayerID( PCB_LAYER_ID::F_Mask, PCB_LAYER_ID::B_Mask, LOG_LEVEL::MSG_LOG );
658 }
659 else if( layerName.Contains( wxT( "paste" ) ) )
660 {
661 selectLayerID( PCB_LAYER_ID::F_Paste, PCB_LAYER_ID::B_Paste, LOG_LEVEL::MSG_LOG );
662 }
663 else
664 {
665 // Does not appear to be a technical layer - Map to Eco layers for now.
666 selectLayerID( PCB_LAYER_ID::Eco1_User, PCB_LAYER_ID::Eco2_User, LOG_LEVEL::WARN );
667 }
668 break;
669
671 selectLayerID( PCB_LAYER_ID::F_Paste, PCB_LAYER_ID::B_Paste, LOG_LEVEL::MSG_LOG );
672 break;
673
675 selectLayerID( PCB_LAYER_ID::F_SilkS, PCB_LAYER_ID::B_SilkS, LOG_LEVEL::MSG_LOG );
676 break;
677
679 selectLayerID( PCB_LAYER_ID::F_Mask, PCB_LAYER_ID::B_Mask, LOG_LEVEL::MSG_LOG );
680 break;
681
684 //Unsure what these layer types are used for. Map to Eco layers for now.
685 selectLayerID( PCB_LAYER_ID::Eco1_User, PCB_LAYER_ID::Eco2_User, LOG_LEVEL::WARN );
686 break;
687
688 default:
689 wxFAIL_MSG( wxT( "Unknown CADSTAR Layer Sub-type" ) );
690 break;
691 }
692 break;
693
694 default:
695 wxFAIL_MSG( wxT( "Unknown CADSTAR Layer Type" ) );
696 break;
697 }
698
699 m_layermap.insert( { curLayer.ID, kicadLayerID } );
700 }
701}
702
703
705{
706 LSET enabledLayers = m_board->GetEnabledLayers();
707 LSET validRemappingLayers = enabledLayers | LSET::AllBoardTechMask() |
709
710 std::vector<INPUT_LAYER_DESC> inputLayers;
711 std::map<wxString, LAYER_ID> cadstarLayerNameMap;
712
713 for( std::pair<LAYER_ID, PCB_LAYER_ID> layerPair : m_layermap )
714 {
715 LAYER* curLayer = &Assignments.Layerdefs.Layers.at( layerPair.first );
716
717 //Only remap documentation and non-electrical layers
718 if( curLayer->Type == LAYER_TYPE::NONELEC || curLayer->Type == LAYER_TYPE::DOC )
719 {
720 INPUT_LAYER_DESC iLdesc;
721 iLdesc.Name = curLayer->Name;
722 iLdesc.PermittedLayers = validRemappingLayers;
723 iLdesc.AutoMapLayer = layerPair.second;
724
725 inputLayers.push_back( iLdesc );
726 cadstarLayerNameMap.insert( { curLayer->Name, curLayer->ID } );
727 }
728 }
729
730 if( inputLayers.size() == 0 )
731 return;
732
733 // Callback:
734 std::map<wxString, PCB_LAYER_ID> reMappedLayers = m_layerMappingHandler( inputLayers );
735
736 for( std::pair<wxString, PCB_LAYER_ID> layerPair : reMappedLayers )
737 {
738 if( layerPair.second == PCB_LAYER_ID::UNDEFINED_LAYER )
739 {
740 wxFAIL_MSG( wxT( "Unexpected Layer ID" ) );
741 continue;
742 }
743
744 LAYER_ID cadstarLayerID = cadstarLayerNameMap.at( layerPair.first );
745 m_layermap.at( cadstarLayerID ) = layerPair.second;
746 enabledLayers |= LSET( { layerPair.second } );
747 }
748
749 m_board->SetEnabledLayers( enabledLayers );
750 m_board->SetVisibleLayers( enabledLayers );
751}
752
753
755{
756 BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
757 std::map<SPACINGCODE_ID, SPACINGCODE>& spacingCodes = Assignments.Codedefs.SpacingCodes;
758
759 auto applyRule =
760 [&]( const wxString& aID, int* aVal )
761 {
762 if( spacingCodes.find( aID ) == spacingCodes.end() )
763 reportWarning( wxString::Format( _( "Design rule %s was not found. This was ignored." ), aID ) );
764 else
765 *aVal = getKiCadLength( spacingCodes.at( aID ).Spacing, UNDEFINED_VALUE );
766 };
767
768 //Note: for details on the different spacing codes see SPACINGCODE::ID
769
770 applyRule( "T_T", &bds.m_MinClearance );
771 applyRule( "C_B", &bds.m_CopperEdgeClearance );
772 applyRule( "H_H", &bds.m_HoleToHoleMin );
773
774 bds.m_TrackMinWidth = getKiCadLength( Assignments.Technology.MinRouteWidth, 0.2 );
775 bds.m_ViasMinSize = bds.m_TrackMinWidth; // Not specified, assumed same as track width
776 bds.m_ViasMinAnnularWidth = bds.m_TrackMinWidth / 2; // Not specified, assumed half track width
777 bds.m_MinThroughDrill = PCB_IU_PER_MM * 0.0508; // CADSTAR does not specify a minimum hole size
778 // so set to minimum permitted in KiCad (2 mils)
779 bds.m_HoleClearance = 0; // Testing suggests cadstar might not have a copper-to-hole clearance
780
781 auto applyNetClassRule =
782 [&]( const wxString& aID, const std::shared_ptr<NETCLASS>& aNetClassPtr )
783 {
784 int value = UNDEFINED_VALUE;
785 applyRule( aID, &value );
786
787 if( value != UNDEFINED_VALUE )
788 aNetClassPtr->SetClearance( value );
789 };
790
791 applyNetClassRule( "T_T", bds.m_NetSettings->GetDefaultNetclass() );
792
793 reportWarning( _( "KiCad design rules are different from CADSTAR ones. Only the compatible "
794 "design rules were imported. It is recommended that you review the design "
795 "rules that have been applied." ) );
796}
797
798
800{
801 for( std::pair<SYMDEF_ID, SYMDEF_PCB> symPair : Library.ComponentDefinitions )
802 {
803 SYMDEF_ID key = symPair.first;
804 SYMDEF_PCB component = symPair.second;
805
806 // Check that we are not loading a documentation symbol.
807 // Documentation symbols in CADSTAR are graphical "footprints" that can be assigned
808 // to any layer. The definition in the library assigns all elements to an undefined layer.
809 LAYER_ID componentLayer;
810
811 if( component.Figures.size() > 0 )
812 {
813 FIGURE firstFigure = component.Figures.begin()->second;
814 componentLayer = firstFigure.LayerID;
815 }
816 else if( component.Texts.size() > 0 )
817 {
818 TEXT firstText = component.Texts.begin()->second;
819 componentLayer = firstText.LayerID;
820 }
821
822 if( !componentLayer.IsEmpty() && getLayerType( componentLayer ) == LAYER_TYPE::NOLAYER )
823 continue; // don't process documentation symbols
824
825 FOOTPRINT* footprint = new FOOTPRINT( m_board );
826 footprint->SetPosition( getKiCadPoint( component.Origin ) );
827
828 LIB_ID libID;
829 libID.Parse( component.BuildLibName(), true );
830
831 footprint->SetFPID( libID );
832 loadLibraryFigures( component, footprint );
833 loadLibraryAreas( component, footprint );
834 loadLibraryPads( component, footprint );
835 loadLibraryCoppers( component, footprint ); // Load coppers after pads to ensure correct
836 // ordering of pads in footprint->Pads()
837
838 footprint->SetPosition( { 0, 0 } ); // KiCad expects library footprints at 0,0
839 footprint->SetReference( wxT( "REF**" ) );
840 footprint->SetValue( libID.GetLibItemName() );
841 footprint->AutoPositionFields();
842 m_libraryMap.insert( std::make_pair( key, footprint ) );
843 }
844}
845
846
848 FOOTPRINT* aFootprint )
849{
850 for( std::pair<FIGURE_ID, FIGURE> figPair : aComponent.Figures )
851 {
852 FIGURE& fig = figPair.second;
853
854 for( const PCB_LAYER_ID& layer : getKiCadLayerSet( fig.LayerID ).Seq() )
855 {
857 wxString::Format( wxT( "Component %s:%s -> Figure %s" ),
858 aComponent.ReferenceName,
859 aComponent.Alternate,
860 fig.ID ),
861 aFootprint );
862 }
863 }
864}
865
866
868{
869 for( COMPONENT_COPPER compCopper : aComponent.ComponentCoppers )
870 {
871 int lineThickness = getKiCadLength( getCopperCode( compCopper.CopperCodeID ).CopperWidth, 0.2 );
872 LSET layers = getKiCadLayerSet( compCopper.LayerID );
873 LSET copperLayers = LSET::AllCuMask() & layers;
874 LSET remainingLayers = layers;
875
876 if( compCopper.AssociatedPadIDs.size() > 0
877 && copperLayers.count() > 0
878 && compCopper.Shape.Type == SHAPE_TYPE::SOLID )
879 {
880 // The copper is associated with pads and in an electrical layer which means it can
881 // have a net associated with it. Load as a pad instead.
882 // Note: we can only handle SOLID copper shapes. If the copper shape is an outline or
883 // hatched or outline, then we give up and load as a graphical shape instead.
884
885 // Find the first non-PCB-only pad. If there are none, use the first one
886 COMPONENT_PAD anchorPad;
887 bool found = false;
888
889 for( PAD_ID padID : compCopper.AssociatedPadIDs )
890 {
891 anchorPad = aComponent.ComponentPads.at( padID );
892
893 if( !anchorPad.PCBonlyPad )
894 {
895 found = true;
896 break;
897 }
898 }
899
900 if( !found )
901 anchorPad = aComponent.ComponentPads.at( compCopper.AssociatedPadIDs.front() );
902
903 std::unique_ptr<PAD> pad = std::make_unique<PAD>( aFootprint );
904 pad->SetAttribute( PAD_ATTRIB::SMD );
905 pad->SetLayerSet( copperLayers );
906 pad->SetNumber( anchorPad.Identifier.IsEmpty() ? wxString::Format( wxT( "%ld" ), anchorPad.ID )
907 : anchorPad.Identifier );
908
909 // Custom pad shape with an anchor at the position of one of the associated
910 // pads and same size as the pad. Shape circle as it fits inside a rectangle
911 // but not the other way round
912 PADCODE anchorpadcode = getPadCode( anchorPad.PadCodeID );
913 int anchorSize = getKiCadLength( anchorpadcode.Shape.Size, 0.6 );
914 VECTOR2I anchorPos = getKiCadPoint( anchorPad.Position );
915
916 if( anchorSize <= 0 )
917 anchorSize = 1;
918
919 pad->SetPadstackMode( PADSTACK::MODE::NORMAL );
921 pad->SetAnchorPadShape( PADSTACK::ALL_LAYERS, PAD_SHAPE::CIRCLE );
922 pad->SetSize( PADSTACK::ALL_LAYERS, { anchorSize, anchorSize } );
923 pad->SetPosition( anchorPos );
924
925 SHAPE_POLY_SET shapePolys = getPolySetFromCadstarShape( compCopper.Shape, lineThickness, aFootprint );
926 shapePolys.Move( -anchorPos );
927 pad->AddPrimitivePoly( PADSTACK::ALL_LAYERS, shapePolys, 0, true );
928
929 // Now renumber all the associated pads
930 COMPONENT_PAD associatedPad;
931
932 for( PAD_ID padID : compCopper.AssociatedPadIDs )
933 {
934 PAD* assocPad = getPadReference( aFootprint, padID );
935 assocPad->SetNumber( pad->GetNumber() );
936 }
937
938 aFootprint->Add( pad.release(), ADD_MODE::APPEND ); // Append so that we get the correct behaviour
939 // when finding pads by PAD_ID. See loadNets()
940
941 m_librarycopperpads[aComponent.ID][anchorPad.ID].push_back( aFootprint->Pads().size() );
942
943 remainingLayers ^= copperLayers; // don't process copper layers again!
944 }
945
946 if( remainingLayers.any() )
947 {
948 for( const PCB_LAYER_ID& layer : remainingLayers.Seq() )
949 {
950 drawCadstarShape( compCopper.Shape, layer, lineThickness, LINE_STYLE::SOLID,
951 wxString::Format( wxT( "Component %s:%s -> Copper element" ),
952 aComponent.ReferenceName, aComponent.Alternate ),
953 aFootprint );
954 }
955 }
956 }
957}
958
959
961{
962 for( std::pair<COMP_AREA_ID, COMPONENT_AREA> areaPair : aComponent.ComponentAreas )
963 {
964 COMPONENT_AREA& area = areaPair.second;
965
966 if( area.NoVias || area.NoTracks )
967 {
968 int lineThickness = 0; // CADSTAR areas only use the line width for display purpose
969 ZONE* zone = getZoneFromCadstarShape( area.Shape, lineThickness, aFootprint );
970
971 aFootprint->Add( zone, ADD_MODE::APPEND );
972
973 if( isLayerSet( area.LayerID ) )
974 zone->SetLayerSet( getKiCadLayerSet( area.LayerID ) );
975 else
976 zone->SetLayer( getKiCadLayer( area.LayerID ) );
977
978 zone->SetIsRuleArea( true ); //import all CADSTAR areas as Keepout zones
979 zone->SetDoNotAllowPads( false ); //no CADSTAR equivalent
980 zone->SetZoneName( area.ID );
981
982 //There is no distinction between tracks and copper pours in CADSTAR Keepout zones
983 zone->SetDoNotAllowTracks( area.NoTracks );
984 zone->SetDoNotAllowZoneFills( area.NoTracks );
985
986 zone->SetDoNotAllowVias( area.NoVias );
987 }
988 else
989 {
990 wxString libName = aComponent.ReferenceName;
991
992 if( !aComponent.Alternate.IsEmpty() )
993 libName << wxT( " (" ) << aComponent.Alternate << wxT( ")" );
994
995 reportError( wxString::Format( _( "The CADSTAR area '%s' in library component '%s' does not "
996 "have a KiCad equivalent. The area is neither a via nor "
997 "route keepout area. The area was not imported." ),
998 area.ID,
999 libName ) );
1000 }
1001 }
1002}
1003
1004
1006 FOOTPRINT* aFootprint )
1007{
1008 for( std::pair<PAD_ID, COMPONENT_PAD> padPair : aComponent.ComponentPads )
1009 {
1010 if( PAD* pad = getKiCadPad( padPair.second, aFootprint ) )
1011 {
1012 aFootprint->Add( pad, ADD_MODE::APPEND ); // Append so that we get correct behaviour
1013 // when finding pads by PAD_ID - see loadNets()
1014 }
1015 }
1016}
1017
1018
1020 const CADSTAR_PAD_SHAPE& aShape )
1021{
1022 // CADSTAR grows some shapes by a left and a right length, moving the centre off the pad origin
1023 VECTOR2I offset = { 0, 0 };
1024
1025 auto elongatedSize =
1026 [&]() -> VECTOR2I
1027 {
1028 return { getKiCadLength( aShape.Size, 0.6 ) + getKiCadLength( aShape.LeftLength, 0.0 )
1029 + getKiCadLength( aShape.RightLength, 0.0 ),
1030 getKiCadLength( aShape.Size, 0.6 ) };
1031 };
1032
1033 auto elongationOffset =
1034 [&]()
1035 {
1036 offset.x = getKiCadOffset( ( (long long) aShape.LeftLength / 2 )
1037 - ( (long long) aShape.RightLength / 2 ) );
1038 };
1039
1040 switch( aShape.ShapeType )
1041 {
1043 //todo fix: use custom shape instead (Donught shape, i.e. a circle with a hole)
1044 aPad->SetShape( aPadLayer, PAD_SHAPE::CIRCLE );
1045 aPad->SetSize( aPadLayer, { getKiCadLength( aShape.Size, 0.6 ),
1046 getKiCadLength( aShape.Size, 0.6 ) } );
1047 break;
1048
1050 aPad->SetShape( aPadLayer, PAD_SHAPE::CHAMFERED_RECT );
1051 aPad->SetSize( aPadLayer, elongatedSize() );
1052 aPad->SetChamferPositions( aPadLayer,
1055 aPad->SetRoundRectRadiusRatio( aPadLayer, 0.5 );
1056 aPad->SetChamferRectRatio( aPadLayer, 0.0 );
1057
1058 elongationOffset();
1059 break;
1060
1062 aPad->SetShape( aPadLayer, PAD_SHAPE::CIRCLE );
1063 aPad->SetSize( aPadLayer, { getKiCadLength( aShape.Size, 0.6 ),
1064 getKiCadLength( aShape.Size, 0.6 ) } );
1065 break;
1066
1068 {
1069 // Cadstar diamond shape is a square rotated 45 degrees
1070 // We convert it in KiCad to a square with chamfered edges
1071 int sizeOfSquare = (double) getKiCadLength( aShape.Size, 0.6 ) * sqrt(2.0);
1072 aPad->SetShape( aPadLayer, PAD_SHAPE::RECTANGLE );
1073 aPad->SetChamferRectRatio( aPadLayer, 0.5 );
1074 aPad->SetSize( aPadLayer, { sizeOfSquare, sizeOfSquare } );
1075
1076 elongationOffset();
1077 break;
1078 }
1079
1081 aPad->SetShape( aPadLayer, PAD_SHAPE::OVAL );
1082 aPad->SetSize( aPadLayer, elongatedSize() );
1083
1084 elongationOffset();
1085 break;
1086
1088 aPad->SetShape( aPadLayer, PAD_SHAPE::CHAMFERED_RECT );
1090 aPad->SetChamferRectRatio( aPadLayer, 0.25 );
1091 aPad->SetSize( aPadLayer, { getKiCadLength( aShape.Size, 0.6 ),
1092 getKiCadLength( aShape.Size, 0.6 ) } );
1093 break;
1094
1096 aPad->SetShape( aPadLayer, PAD_SHAPE::RECTANGLE );
1097 aPad->SetSize( aPadLayer, elongatedSize() );
1098
1099 elongationOffset();
1100 break;
1101
1103 aPad->SetShape( aPadLayer, PAD_SHAPE::ROUNDRECT );
1104 aPad->SetRoundRectCornerRadius( aPadLayer, getKiCadLength( aShape.InternalFeature, 0.0 ) );
1105 aPad->SetSize( aPadLayer, elongatedSize() );
1106
1107 elongationOffset();
1108 break;
1109
1111 aPad->SetShape( aPadLayer, PAD_SHAPE::RECTANGLE );
1112 aPad->SetSize( aPadLayer, { getKiCadLength( aShape.Size, 0.6 ),
1113 getKiCadLength( aShape.Size, 0.6 ) } );
1114 break;
1115
1116 default:
1117 wxFAIL_MSG( wxT( "Unknown Pad Shape" ) );
1118 }
1119
1120 return offset;
1121}
1122
1123
1125{
1126 PADCODE csPadcode = getPadCode( aCadstarPad.PadCodeID );
1127 wxString errorMSG;
1128
1129 std::unique_ptr<PAD> pad = std::make_unique<PAD>( aParent );
1130 LSET padLayerSet;
1131
1132 switch( aCadstarPad.Side )
1133 {
1134 case PAD_SIDE::MAXIMUM: //Bottom side
1135 padLayerSet |= LSET( { B_Cu, B_Paste, B_Mask } );
1136 break;
1137
1138 case PAD_SIDE::MINIMUM: //TOP side
1139 padLayerSet |= LSET( { F_Cu, F_Paste, F_Mask } );
1140 break;
1141
1143 padLayerSet = LSET::AllCuMask( m_numCopperLayers ) | LSET( { F_Mask, B_Mask, F_Paste, B_Paste } );
1144 break;
1145
1146 default:
1147 wxFAIL_MSG( wxT( "Unknown Pad type" ) );
1148 }
1149
1150 pad->SetAttribute( PAD_ATTRIB::SMD ); // assume SMD pad for now
1151 pad->SetLocalSolderMaskMargin( 0 );
1152 pad->SetLocalSolderPasteMargin( 0 );
1153 pad->SetLocalSolderPasteMarginRatio( 0.0 );
1154
1155 std::map<PCB_LAYER_ID, CADSTAR_PAD_SHAPE> copperReassigns;
1156
1157 for( auto& [layer, shape] : csPadcode.Reassigns )
1158 {
1159 PCB_LAYER_ID kiLayer = getKiCadLayer( layer );
1160
1161 if( shape.Size == 0 )
1162 {
1163 if( kiLayer > UNDEFINED_LAYER )
1164 padLayerSet.reset( kiLayer );
1165 }
1166 else
1167 {
1168 int newMargin = 0;
1169
1170 if( shape.Size != UNDEFINED_VALUE && csPadcode.Shape.Size != UNDEFINED_VALUE )
1171 newMargin = getKiCadOffset( shape.Size - csPadcode.Shape.Size ) / 2;
1172
1173 if( kiLayer == F_Mask || kiLayer == B_Mask )
1174 {
1175 std::optional<int> localMargin = pad->GetLocalSolderMaskMargin();
1176
1177 if( !localMargin.has_value() )
1178 pad->SetLocalSolderMaskMargin( newMargin );
1179 else if( std::abs( localMargin.value() ) < std::abs( newMargin ) )
1180 pad->SetLocalSolderMaskMargin( newMargin );
1181 }
1182 else if( kiLayer == F_Paste || kiLayer == B_Paste )
1183 {
1184 std::optional<int> localMargin = pad->GetLocalSolderPasteMargin();
1185
1186 if( !localMargin.has_value() )
1187 pad->SetLocalSolderPasteMargin( newMargin );
1188 else if( std::abs( localMargin.value() ) < std::abs( newMargin ) )
1189 pad->SetLocalSolderPasteMargin( newMargin );
1190 }
1191 else if( IsCopperLayer( kiLayer ) )
1192 {
1193 copperReassigns[kiLayer] = shape;
1194 }
1195 }
1196 }
1197
1198 pad->SetLayerSet( padLayerSet );
1199
1200 if( aCadstarPad.PCBonlyPad )
1201 {
1202 // PCB Only pads in CADSTAR do not have a representation in the schematic - they are
1203 // purely mechanical pads that have no net associated with them. Make the pad name
1204 // empty to avoid warnings when importing from the schematic
1205 pad->SetNumber( wxT( "" ) );
1206 }
1207 else
1208 {
1209 pad->SetNumber( aCadstarPad.Identifier.IsEmpty() ? wxString::Format( wxT( "%ld" ), aCadstarPad.ID )
1210 : aCadstarPad.Identifier );
1211 }
1212
1213 if( csPadcode.Shape.Size == 0 )
1214 {
1215 if( csPadcode.DrillDiameter == UNDEFINED_VALUE && aCadstarPad.Side == PAD_SIDE::THROUGH_HOLE )
1216 {
1217 // Through-hole, zero sized pad? Lets load this just on the F_Mask for now to
1218 // prevent DRC errors.
1219 // TODO: This could be a custom padstack
1220 pad->SetAttribute( PAD_ATTRIB::SMD );
1221 pad->SetLayerSet( LSET( { F_Mask } ) );
1222 }
1223
1224 // zero sized pads seems to break KiCad so lets make it very small instead
1225 csPadcode.Shape.Size = 1;
1226 }
1227
1228 VECTOR2I padOffset = applyPadShape( pad.get(), PADSTACK::ALL_LAYERS, csPadcode.Shape );
1229 VECTOR2I drillOffset = { 0, 0 }; // offset of the drill origin w.r.t. the pad (before rotating)
1230
1231 // A layer reassign needs a full-custom padstack. The shape centre can move per layer, so
1232 // the delta from the base shape becomes that layer's offset
1233 if( !copperReassigns.empty() )
1234 {
1235 pad->Padstack().SetMode( PADSTACK::MODE::CUSTOM );
1236
1237 for( const auto& [kiLayer, shape] : copperReassigns )
1238 {
1239 VECTOR2I layerOffset = applyPadShape( pad.get(), kiLayer, shape );
1240 pad->SetOffset( kiLayer, padOffset - layerOffset );
1241 }
1242 }
1243
1244 if( csPadcode.ReliefClearance != UNDEFINED_VALUE )
1245 pad->SetThermalGap( getKiCadLength( csPadcode.ReliefClearance, 0.5 ) );
1246
1247 if( csPadcode.ReliefWidth != UNDEFINED_VALUE )
1248 pad->SetLocalThermalSpokeWidthOverride( getKiCadLength( csPadcode.ReliefWidth, 0.5 ) );
1249
1250 if( csPadcode.DrillDiameter != UNDEFINED_VALUE )
1251 {
1252 if( csPadcode.SlotLength != UNDEFINED_VALUE )
1253 {
1254 pad->SetDrillShape( PAD_DRILL_SHAPE::OBLONG );
1255 pad->SetDrillSize( { getKiCadLength( csPadcode.DrillDiameter, 0.3 )
1256 + getKiCadLength( csPadcode.SlotLength, 0.0 ),
1257 getKiCadLength( csPadcode.DrillDiameter, 0.3 ) } );
1258 }
1259 else
1260 {
1261 pad->SetDrillShape( PAD_DRILL_SHAPE::CIRCLE );
1262 pad->SetDrillSize( { getKiCadLength( csPadcode.DrillDiameter, 0.3 ),
1263 getKiCadLength( csPadcode.DrillDiameter, 0.3 ) } );
1264 }
1265
1266 drillOffset.x = -getKiCadOffset( csPadcode.DrillXoffset );
1267 drillOffset.y = getKiCadOffset( csPadcode.DrillYoffset );
1268
1269 if( csPadcode.Plated )
1270 pad->SetAttribute( PAD_ATTRIB::PTH );
1271 else
1272 pad->SetAttribute( PAD_ATTRIB::NPTH );
1273 }
1274 else
1275 {
1276 pad->SetDrillSize( { 0, 0 } );
1277 }
1278
1279 if( csPadcode.SlotOrientation != 0 )
1280 {
1281 LSET lset = pad->GetLayerSet();
1282 lset &= LSET::AllCuMask();
1283
1284 if( lset.size() > 0 )
1285 {
1286 int maxError = m_board->GetDesignSettings().m_MaxError;
1287 EDA_ANGLE slotAngle = ANGLE_180 - getAngle( csPadcode.SlotOrientation );
1288 bool holeInsidePad = true;
1289
1290 pad->SetPosition( { 0, 0 } );
1291
1292 // Rotating the slot bakes the copper into a custom primitive, so each padstack
1293 // layer needs its own
1294 std::map<PCB_LAYER_ID, std::unique_ptr<PCB_SHAPE>> slotShapes;
1295
1296 for( PCB_LAYER_ID padLayer : pad->Padstack().UniqueLayers() )
1297 {
1298 SHAPE_POLY_SET padOutline;
1299 pad->TransformShapeToPolygon( padOutline, padLayer, 0, maxError, ERROR_INSIDE );
1300
1301 auto padShape = std::make_unique<PCB_SHAPE>();
1302 padShape->SetShape( SHAPE_T::POLY );
1303 padShape->SetFilled( true );
1304 padShape->SetPolyShape( padOutline );
1305 padShape->SetStroke( STROKE_PARAMS( 0 ) );
1306 padShape->Move( padOffset - drillOffset );
1307 padShape->Rotate( VECTOR2I( 0, 0 ), slotAngle );
1308
1309 if( !padShape->GetPolyShape().Contains( { 0, 0 } ) )
1310 holeInsidePad = false;
1311
1312 slotShapes[padLayer] = std::move( padShape );
1313 }
1314
1315 if( holeInsidePad )
1316 {
1317 for( auto& [padLayer, padShape] : slotShapes )
1318 {
1319 pad->SetAnchorPadShape( padLayer, PAD_SHAPE::RECTANGLE );
1320 pad->SetSize( padLayer, VECTOR2I( { 4, 4 } ) );
1321 pad->SetShape( padLayer, PAD_SHAPE::CUSTOM );
1322
1323 // The outline already includes the layer offset; leaving it set shifts twice
1324 pad->SetOffset( padLayer, { 0, 0 } );
1325 pad->AddPrimitive( padLayer, padShape.release() );
1326 }
1327
1328 padOffset = { 0, 0 };
1329 }
1330 else
1331 {
1332 // The CADSTAR pad has the hole shape outside the pad shape
1333 // Lets just put the hole in the center of the pad instead
1334 csPadcode.SlotOrientation = 0;
1335 drillOffset = { 0, 0 };
1336
1337 errorMSG += wxT( "\n - " )
1338 + wxString::Format( _( "The CADSTAR pad definition '%s' has the hole shape outside the "
1339 "pad shape. The hole has been moved to the center of the pad." ),
1340 csPadcode.Name );
1341 }
1342 }
1343 else
1344 {
1345 wxFAIL_MSG( wxT( "No copper layers defined in the pad?" ) );
1346 csPadcode.SlotOrientation = 0;
1347 pad->SetOffset( PADSTACK::ALL_LAYERS, drillOffset );
1348 }
1349 }
1350 else
1351 {
1352 // The reassigned layers already carry the offset that centres their own copper
1353 for( PCB_LAYER_ID padLayer : pad->Padstack().UniqueLayers() )
1354 pad->SetOffset( padLayer, pad->GetOffset( padLayer ) + drillOffset );
1355 }
1356
1357 EDA_ANGLE padOrientation = getAngle( aCadstarPad.OrientAngle )
1358 + getAngle( csPadcode.Shape.OrientAngle );
1359
1360 RotatePoint( padOffset, padOrientation );
1361 RotatePoint( drillOffset, padOrientation );
1362 pad->SetPosition( getKiCadPoint( aCadstarPad.Position ) - padOffset - drillOffset );
1363 pad->SetOrientation( padOrientation + getAngle( csPadcode.SlotOrientation ) );
1364
1365 //log warnings:
1366 if( m_padcodesTested.find( csPadcode.ID ) == m_padcodesTested.end() && !errorMSG.IsEmpty() )
1367 {
1368 reportError( wxString::Format( _( "The CADSTAR pad definition '%s' has import errors: %s" ),
1369 csPadcode.Name,
1370 errorMSG ) );
1371
1372 m_padcodesTested.insert( csPadcode.ID );
1373 }
1374
1375 return pad.release();
1376}
1377
1378
1380{
1381 size_t index = aCadstarPadID - (long) 1;
1382
1383 if( !( index < aFootprint->Pads().size() ) )
1384 {
1385 THROW_IO_ERRORF( _( "Unable to find pad index '%ld' in footprint '%s'." ),
1386 (long) aCadstarPadID, aFootprint->GetReference() );
1387 }
1388
1389 return aFootprint->Pads().at( index );
1390}
1391
1392
1394{
1395 for( std::pair<GROUP_ID, GROUP> groupPair : Layout.Groups )
1396 {
1397 GROUP& csGroup = groupPair.second;
1398
1399 PCB_GROUP* kiGroup = new PCB_GROUP( m_board );
1400
1401 m_board->Add( kiGroup );
1402 kiGroup->SetName( csGroup.Name );
1403 kiGroup->SetLocked( csGroup.Fixed );
1404
1405 m_groupMap.insert( { csGroup.ID, kiGroup } );
1406 }
1407
1408 //now add any groups to their parent group
1409 for( std::pair<GROUP_ID, GROUP> groupPair : Layout.Groups )
1410 {
1411 GROUP& csGroup = groupPair.second;
1412
1413 if( !csGroup.GroupID.IsEmpty() )
1414 {
1415 if( m_groupMap.find( csGroup.ID ) == m_groupMap.end() )
1416 {
1417 THROW_IO_ERRORF( _( "Unable to find group ID %s in the group definitions." ), csGroup.ID );
1418 }
1419 else if( m_groupMap.find( csGroup.ID ) == m_groupMap.end() )
1420 {
1421 THROW_IO_ERRORF( _( "Unable to find sub group %s in the group map (parent group ID=%s, Name=%s)." ),
1422 csGroup.GroupID,
1423 csGroup.ID,
1424 csGroup.Name );
1425 }
1426 else
1427 {
1428 PCB_GROUP* kiCadGroup = m_groupMap.at( csGroup.ID );
1429 PCB_GROUP* parentGroup = m_groupMap.at( csGroup.GroupID );
1430 parentGroup->AddItem( kiCadGroup );
1431 }
1432 }
1433 }
1434}
1435
1436
1438{
1439 for( std::pair<BOARD_ID, CADSTAR_BOARD> boardPair : Layout.Boards )
1440 {
1441 CADSTAR_BOARD& board = boardPair.second;
1442 GROUP_ID boardGroup = createUniqueGroupID( wxT( "Board" ) );
1443
1445 getLineStyle( board.LineCodeID ), wxString::Format( wxT( "BOARD %s" ), board.ID ),
1446 m_board, boardGroup );
1447
1448 if( !board.GroupID.IsEmpty() )
1449 addToGroup( board.GroupID, getKiCadGroup( boardGroup ) );
1450
1451 //TODO process board attributes when KiCad supports them
1452 }
1453}
1454
1455
1457{
1458 for( std::pair<FIGURE_ID, FIGURE> figPair : Layout.Figures )
1459 {
1460 FIGURE& fig = figPair.second;
1461
1462 for( const PCB_LAYER_ID& layer : getKiCadLayerSet( fig.LayerID ).Seq() )
1463 {
1465 wxString::Format( wxT( "FIGURE %s" ), fig.ID ), m_board, fig.GroupID );
1466 }
1467
1468 //TODO process "swaprule" (doesn't seem to apply to Layout Figures?)
1469 //TODO process re-use block when KiCad Supports it
1470 //TODO process attributes when KiCad Supports attributes in figures
1471 }
1472}
1473
1474
1476{
1477 for( std::pair<TEXT_ID, TEXT> txtPair : Layout.Texts )
1478 {
1479 TEXT& csTxt = txtPair.second;
1480 drawCadstarText( csTxt, m_board );
1481 }
1482}
1483
1484
1486{
1487 for( std::pair<DIMENSION_ID, DIMENSION> dimPair : Layout.Dimensions )
1488 {
1489 DIMENSION& csDim = dimPair.second;
1490
1491 switch( csDim.Type )
1492 {
1493 case DIMENSION::TYPE::LINEARDIM:
1494 switch( csDim.Subtype )
1495 {
1496 case DIMENSION::SUBTYPE::ANGLED:
1497 reportWarning( wxString::Format( _( "Dimension ID %s is an angled dimension, which has no KiCad "
1498 "equivalent. An aligned dimension was loaded instead." ),
1499 csDim.ID ) );
1501 case DIMENSION::SUBTYPE::DIRECT:
1502 case DIMENSION::SUBTYPE::ORTHOGONAL:
1503 {
1504 if( csDim.Line.Style == DIMENSION::LINE::STYLE::EXTERNAL )
1505 {
1506 reportWarning( wxString::Format( _( "Dimension ID %s has 'External' style in CADSTAR. External "
1507 "dimension styles are not yet supported in KiCad. The "
1508 "dimension object was imported with an internal dimension "
1509 "style instead." ),
1510 csDim.ID ) );
1511 }
1512
1513 PCB_DIM_ALIGNED* dimension = nullptr;
1514
1515 if( csDim.Subtype == DIMENSION::SUBTYPE::ORTHOGONAL )
1516 {
1517 dimension = new PCB_DIM_ORTHOGONAL( m_board );
1518 PCB_DIM_ORTHOGONAL* orDim = static_cast<PCB_DIM_ORTHOGONAL*>( dimension );
1519
1520 if( csDim.ExtensionLineParams.Start.x == csDim.Line.Start.x )
1522 else
1524 }
1525 else
1526 {
1527 dimension = new PCB_DIM_ALIGNED( m_board, PCB_DIM_ALIGNED_T );
1528 }
1529
1530 m_board->Add( dimension, ADD_MODE::APPEND );
1531 applyDimensionSettings( csDim, dimension );
1532
1534
1535 // Calculate height:
1536 VECTOR2I crossbarStart = getKiCadPoint( csDim.Line.Start );
1537 VECTOR2I crossbarEnd = getKiCadPoint( csDim.Line.End );
1538 VECTOR2I crossbarVector = crossbarEnd - crossbarStart;
1539 VECTOR2I heightVector = crossbarStart - dimension->GetStart();
1540 double height = 0.0;
1541
1542 if( csDim.Subtype == DIMENSION::SUBTYPE::ORTHOGONAL )
1543 {
1544 if( csDim.ExtensionLineParams.Start.x == csDim.Line.Start.x )
1545 height = heightVector.y;
1546 else
1547 height = heightVector.x;
1548 }
1549 else
1550 {
1551 EDA_ANGLE angle( crossbarVector );
1552 angle += ANGLE_90;
1553 height = heightVector.x * angle.Cos() + heightVector.y * angle.Sin();
1554 }
1555
1556 dimension->SetHeight( height );
1557 }
1558 break;
1559
1560 default:
1561 // Radius and diameter dimensions are LEADERDIM (even if not actually leader)
1562 // Angular dimensions are always ANGLEDIM
1563 reportError( wxString::Format( _( "Unexpected Dimension type (ID %s). This was not imported." ),
1564 csDim.ID ) );
1565 continue;
1566 }
1567 break;
1568
1569 case DIMENSION::TYPE::LEADERDIM:
1570 //TODO: update import when KiCad supports radius and diameter dimensions
1571
1572 if( csDim.Line.Style == DIMENSION::LINE::STYLE::INTERNAL )
1573 {
1574 // "internal" is a simple double sided arrow from start to end (no extension lines)
1576 m_board->Add( dimension, ADD_MODE::APPEND );
1577 applyDimensionSettings( csDim, dimension );
1578
1579 // Lets set again start/end:
1580 dimension->SetStart( getKiCadPoint( csDim.Line.Start ) );
1581 dimension->SetEnd( getKiCadPoint( csDim.Line.End ) );
1582
1583 // Do not use any extension lines:
1584 dimension->SetExtensionOffset( 0 );
1585 dimension->SetExtensionHeight( 0 );
1586 dimension->SetHeight( 0 );
1587 }
1588 else
1589 {
1590 // "external" is a "leader" style dimension
1591 PCB_DIM_LEADER* leaderDim = new PCB_DIM_LEADER( m_board );
1592 m_board->Add( leaderDim, ADD_MODE::APPEND );
1593
1594 applyDimensionSettings( csDim, leaderDim );
1595 leaderDim->SetStart( getKiCadPoint( csDim.Line.End ) );
1596
1597 /*
1598 * In CADSTAR, the resulting shape orientation of the leader dimension depends on
1599 * on the positions of the #Start (S) and #End (E) points as shown below. In the
1600 * diagrams below, the leader angle (angRad) is represented by HEV
1601 *
1602 * Orientation 1: (orientX = -1, | Orientation 2: (orientX = 1,
1603 * orientY = 1) | orientY = 1)
1604 * |
1605 * --------V | V----------
1606 * \ | /
1607 * \ | /
1608 * H _E/ | \E_ H
1609 * |
1610 * S | S
1611 * |
1612 *
1613 * Orientation 3: (orientX = -1, | Orientation 4: (orientX = 1,
1614 * orientY = -1) | orientY = -1)
1615 * |
1616 * S | S
1617 * _ | _
1618 * H E\ | /E H
1619 * / | \
1620 * / | \
1621 * ----------V | V-----------
1622 * |
1623 *
1624 * Corner cases:
1625 *
1626 * It is not possible to generate a leader object with start and end point being
1627 * identical. Assume Orientation 2 if start and end points are identical.
1628 *
1629 * If start and end points are aligned vertically (i.e. S.x == E.x):
1630 * - If E.y > S.y - Orientation 2
1631 * - If E.y < S.y - Orientation 4
1632 *
1633 * If start and end points are aligned horitontally (i.e. S.y == E.y):
1634 * - If E.x > S.x - Orientation 2
1635 * - If E.x < S.x - Orientation 1
1636 */
1637 double angRad = DEG2RAD( getAngleDegrees( csDim.Line.LeaderAngle ) );
1638
1639 double orientX = 1;
1640 double orientY = 1;
1641
1642 if( csDim.Line.End.x >= csDim.Line.Start.x )
1643 {
1644 if( csDim.Line.End.y >= csDim.Line.Start.y )
1645 {
1646 //Orientation 2
1647 orientX = 1;
1648 orientY = 1;
1649 }
1650 else
1651 {
1652 //Orientation 4
1653 orientX = 1;
1654 orientY = -1;
1655 }
1656 }
1657 else
1658 {
1659 if( csDim.Line.End.y >= csDim.Line.Start.y )
1660 {
1661 //Orientation 1
1662 orientX = -1;
1663 orientY = 1;
1664 }
1665 else
1666 {
1667 //Orientation 3
1668 orientX = -1;
1669 orientY = -1;
1670 }
1671 }
1672
1673 VECTOR2I endOffset( csDim.Line.LeaderLineLength * cos( angRad ) * orientX,
1674 csDim.Line.LeaderLineLength * sin( angRad ) * orientY );
1675
1676 VECTOR2I endPoint = VECTOR2I( csDim.Line.End ) + endOffset;
1677 VECTOR2I txtPoint( endPoint.x + ( csDim.Line.LeaderLineExtensionLength * orientX ),
1678 endPoint.y );
1679
1680 leaderDim->SetEnd( getKiCadPoint( endPoint ) );
1681 leaderDim->SetTextPos( getKiCadPoint( txtPoint ) );
1682 leaderDim->SetOverrideText( ParseTextFields( csDim.Text.Text, &m_context ) );
1683 leaderDim->SetPrefix( wxEmptyString );
1684 leaderDim->SetSuffix( wxEmptyString );
1686
1687 if( orientX == 1 )
1689 else
1691
1692 leaderDim->SetExtensionOffset( 0 );
1693 }
1694 break;
1695
1696 case DIMENSION::TYPE::ANGLEDIM:
1697 //TODO: update import when KiCad supports angular dimensions
1698 reportError( wxString::Format( _( "Dimension %s is an angular dimension which has no KiCad equivalent. "
1699 "The object was not imported." ),
1700 csDim.ID ) );
1701 break;
1702 }
1703 }
1704}
1705
1706
1708{
1709 for( std::pair<AREA_ID, AREA> areaPair : Layout.Areas )
1710 {
1711 AREA& area = areaPair.second;
1712
1713 if( area.NoVias || area.NoTracks || area.Keepout || area.Routing )
1714 {
1715 int lineThickness = 0; // CADSTAR areas only use the line width for display purpose
1716 ZONE* zone = getZoneFromCadstarShape( area.Shape, lineThickness, m_board );
1717
1718 m_board->Add( zone, ADD_MODE::APPEND );
1719
1720 if( isLayerSet( area.LayerID ) )
1721 zone->SetLayerSet( getKiCadLayerSet( area.LayerID ) );
1722 else
1723 zone->SetLayer( getKiCadLayer( area.LayerID ) );
1724
1725 zone->SetIsRuleArea( true ); //import all CADSTAR areas as Keepout zones
1726 zone->SetDoNotAllowPads( false ); //no CADSTAR equivalent
1727 zone->SetZoneName( area.Name );
1728
1729 zone->SetDoNotAllowFootprints( area.Keepout );
1730
1731 zone->SetDoNotAllowTracks( area.NoTracks );
1732 zone->SetDoNotAllowZoneFills( area.NoTracks );
1733
1734 zone->SetDoNotAllowVias( area.NoVias );
1735
1736 if( area.Placement )
1737 {
1738 reportWarning( wxString::Format( _( "The CADSTAR area '%s' is marked as a placement area in "
1739 "CADSTAR. Placement areas are not supported in KiCad. Only "
1740 "the supported elements for the area were imported." ),
1741 area.Name ) );
1742 }
1743 }
1744 else
1745 {
1746 reportError( wxString::Format( _( "The CADSTAR area '%s' does not have a KiCad equivalent. Pure "
1747 "Placement areas are not supported." ),
1748 area.Name ) );
1749 }
1750
1751 //todo Process area.AreaHeight when KiCad supports 3D design rules
1752 //TODO process attributes
1753 //TODO process addition to a group
1754 //TODO process "swaprule"
1755 //TODO process re-use block
1756 }
1757}
1758
1759
1761{
1762 for( std::pair<COMPONENT_ID, COMPONENT> compPair : Layout.Components )
1763 {
1764 COMPONENT& comp = compPair.second;
1765
1766 if( !comp.VariantID.empty() && comp.VariantParentComponentID != comp.ID )
1767 continue; // Only load master Variant
1768
1769 auto fpIter = m_libraryMap.find( comp.SymdefID );
1770
1771 if( fpIter == m_libraryMap.end() )
1772 {
1773 THROW_IO_ERRORF( _( "Unable to find component '%s' in the library (Symdef ID: '%s')" ),
1774 comp.Name,
1775 comp.SymdefID );
1776 }
1777
1778 FOOTPRINT* libFootprint = fpIter->second;
1779
1780 // Use Duplicate() to ensure unique KIID for all objects
1781 FOOTPRINT* footprint = static_cast<FOOTPRINT*>( libFootprint->Duplicate( IGNORE_PARENT_GROUP ) );
1782
1783 m_board->Add( footprint, ADD_MODE::APPEND );
1784
1785 // First lets fix the pad names on the footprint.
1786 // CADSTAR defines the pad name in the PART definition and the SYMDEF (i.e. the PCB
1787 // footprint definition) uses a numerical sequence. COMP is the only object that has
1788 // visibility of both the SYMDEF and PART.
1789 if( Parts.PartDefinitions.find( comp.PartID ) != Parts.PartDefinitions.end() )
1790 {
1791 PART part = Parts.PartDefinitions.at( comp.PartID );
1792
1793 // Only do this when the number of pins in the part definition equals the number of
1794 // pads in the footprint.
1795 if( part.Definition.Pins.size() == footprint->Pads().size() )
1796 {
1797 for( std::pair<PART_DEFINITION_PIN_ID, PART::DEFINITION::PIN> pinPair :
1798 part.Definition.Pins )
1799 {
1800 PART::DEFINITION::PIN pin = pinPair.second;
1801 wxString pinName = pin.Name;
1802
1803 if( pinName.empty() )
1804 pinName = pin.Identifier;
1805
1806 if( pinName.empty() )
1807 pinName = wxString::Format( wxT( "%ld" ), pin.ID );
1808
1809 getPadReference( footprint, pin.ID )->SetNumber( pinName );
1810 }
1811 }
1812 }
1813
1814 //Override pads with pad exceptions
1815 if( comp.PadExceptions.size() > 0 )
1816 {
1817 SYMDEF_PCB fpLibEntry = Library.ComponentDefinitions.at( comp.SymdefID );
1818
1819 for( std::pair<PAD_ID, PADEXCEPTION> padPair : comp.PadExceptions )
1820 {
1821 PADEXCEPTION& padEx = padPair.second;
1822 COMPONENT_PAD csPad = fpLibEntry.ComponentPads.at( padPair.first );
1823
1824 // Reset the pad to be around 0,0
1825 csPad.Position -= fpLibEntry.Origin;
1826 csPad.Position += m_designCenter;
1827
1828 if( !padEx.PadCode.IsEmpty() )
1829 csPad.PadCodeID = padEx.PadCode;
1830
1831 if( padEx.OverrideExits )
1832 csPad.Exits = padEx.Exits;
1833
1834 if( padEx.OverrideOrientation )
1835 csPad.OrientAngle = padEx.OrientAngle;
1836
1837 if( padEx.OverrideSide )
1838 csPad.Side = padEx.Side;
1839
1840 // Find the pad in the footprint definition
1841 PAD* kiPad = getPadReference( footprint, padEx.ID );
1842
1843 wxString padNumber = kiPad->GetNumber();
1844
1845 delete kiPad;
1846
1847 if( ( kiPad = getKiCadPad( csPad, footprint ) ) )
1848 {
1849 kiPad->SetNumber( padNumber );
1850
1851 // Change the pointer in the footprint to the newly created pad
1852 getPadReference( footprint, padEx.ID ) = kiPad;
1853 }
1854 }
1855 }
1856
1857 //set to empty string to avoid duplication when loading attributes:
1858 footprint->SetValue( wxEmptyString );
1859
1860 footprint->SetPosition( getKiCadPoint( comp.Origin ) );
1861 footprint->SetOrientation( getAngle( comp.OrientAngle ) );
1862 footprint->SetReference( comp.Name );
1863
1864 if( comp.Mirror )
1865 {
1866 EDA_ANGLE mirroredAngle = - getAngle( comp.OrientAngle );
1867 mirroredAngle.Normalize180();
1868 footprint->SetOrientation( mirroredAngle );
1869 footprint->Flip( getKiCadPoint( comp.Origin ), FLIP_DIRECTION::LEFT_RIGHT );
1870 }
1871
1872 loadComponentAttributes( comp, footprint );
1873
1874 if( !comp.PartID.IsEmpty() && comp.PartID != wxT( "NO_PART" ) )
1875 footprint->SetLibDescription( getPart( comp.PartID ).Definition.Name );
1876
1877 m_componentMap.insert( { comp.ID, footprint } );
1878 }
1879}
1880
1881
1883{
1884 //No KiCad equivalent. Loaded as graphic and text elements instead
1885
1886 for( std::pair<DOCUMENTATION_SYMBOL_ID, DOCUMENTATION_SYMBOL> docPair : Layout.DocumentationSymbols )
1887 {
1888 DOCUMENTATION_SYMBOL& docSymInstance = docPair.second;
1889
1890
1891 auto docSymIter = Library.ComponentDefinitions.find( docSymInstance.SymdefID );
1892
1893 if( docSymIter == Library.ComponentDefinitions.end() )
1894 {
1895 THROW_IO_ERRORF( _( "Unable to find documentation symbol in the library (Symdef ID: '%s')" ),
1896 docSymInstance.SymdefID );
1897 }
1898
1899 SYMDEF_PCB& docSymDefinition = ( *docSymIter ).second;
1900 VECTOR2I moveVector = getKiCadPoint( docSymInstance.Origin ) - getKiCadPoint( docSymDefinition.Origin );
1901 double rotationAngle = getAngleTenthDegree( docSymInstance.OrientAngle );
1902 double scalingFactor = (double) docSymInstance.ScaleRatioNumerator
1903 / (double) docSymInstance.ScaleRatioDenominator;
1904 VECTOR2I centreOfTransform = getKiCadPoint( docSymDefinition.Origin );
1905 bool mirrorInvert = docSymInstance.Mirror;
1906
1907 //create a group to store the items in
1908 wxString groupName = docSymDefinition.ReferenceName;
1909
1910 if( !docSymDefinition.Alternate.IsEmpty() )
1911 groupName += wxT( " (" ) + docSymDefinition.Alternate + wxT( ")" );
1912
1913 GROUP_ID groupID = createUniqueGroupID( groupName );
1914
1915 LSEQ layers = getKiCadLayerSet( docSymInstance.LayerID ).Seq();
1916
1917 for( PCB_LAYER_ID layer : layers )
1918 {
1919 for( std::pair<FIGURE_ID, FIGURE> figPair : docSymDefinition.Figures )
1920 {
1921 FIGURE fig = figPair.second;
1923 wxString::Format( wxT( "DOCUMENTATION SYMBOL %s, FIGURE %s" ),
1924 docSymDefinition.ReferenceName,
1925 fig.ID ),
1926 m_board, groupID, moveVector, rotationAngle, scalingFactor,
1927 centreOfTransform, mirrorInvert );
1928 }
1929 }
1930
1931 for( std::pair<TEXT_ID, TEXT> textPair : docSymDefinition.Texts )
1932 {
1933 TEXT txt = textPair.second;
1934 drawCadstarText( txt, m_board, groupID, docSymInstance.LayerID, moveVector, rotationAngle,
1935 scalingFactor, centreOfTransform, mirrorInvert );
1936 }
1937 }
1938}
1939
1940
1942{
1943 for( std::pair<TEMPLATE_ID, TEMPLATE> tempPair : Layout.Templates )
1944 {
1945 TEMPLATE& csTemplate = tempPair.second;
1946
1947 int zonelinethickness = 0; // The line thickness in CADSTAR is only for display purposes but
1948 // does not affect the end copper result.
1949 ZONE* zone = getZoneFromCadstarShape( csTemplate.Shape, zonelinethickness, m_board );
1950
1951 m_board->Add( zone, ADD_MODE::APPEND );
1952
1953 zone->SetZoneName( csTemplate.Name );
1954 zone->SetLayer( getKiCadLayer( csTemplate.LayerID ) );
1955 zone->SetAssignedPriority( 1 ); // initially 1, we will increase in calculateZonePriorities
1956
1957 if( !( csTemplate.NetID.IsEmpty() || csTemplate.NetID == wxT( "NONE" ) ) )
1958 zone->SetNet( getKiCadNet( csTemplate.NetID ) );
1959
1960 if( csTemplate.Pouring.AllowInNoRouting )
1961 {
1962 reportWarning( wxString::Format( _( "The CADSTAR template '%s' has the setting 'Allow in No Routing "
1963 "Areas' enabled. This setting has no KiCad equivalent, so it has "
1964 "been ignored." ),
1965 csTemplate.Name ) );
1966 }
1967
1968 if( csTemplate.Pouring.BoxIsolatedPins )
1969 {
1970 reportWarning( wxString::Format( _( "The CADSTAR template '%s' has the setting 'Box Isolated Pins' "
1971 "enabled. This setting has no KiCad equivalent, so it has been "
1972 "ignored." ),
1973 csTemplate.Name ) );
1974 }
1975
1976 if( csTemplate.Pouring.AutomaticRepour )
1977 {
1978 reportWarning( wxString::Format( _( "The CADSTAR template '%s' has the setting 'Automatic Repour' "
1979 "enabled. This setting has no KiCad equivalent, so it has been "
1980 "ignored." ),
1981 csTemplate.Name ) );
1982 }
1983
1984 // Sliver width has different behaviour to KiCad Zone's minimum thickness
1985 // In Cadstar 'Sliver width' has to be greater than the Copper thickness, whereas in
1986 // Kicad it is the opposite.
1987 if( csTemplate.Pouring.SliverWidth != 0 )
1988 {
1989 reportWarning( wxString::Format( _( "The CADSTAR template '%s' has a non-zero value defined for the "
1990 "'Sliver Width' setting. There is no KiCad equivalent for "
1991 "this, so this setting was ignored." ),
1992 csTemplate.Name ) );
1993 }
1994
1995
1996 if( csTemplate.Pouring.MinIsolatedCopper != csTemplate.Pouring.MinDisjointCopper )
1997 {
1998 reportWarning( wxString::Format( _( "The CADSTAR template '%s' has different settings for "
1999 "'Retain Poured Copper - Disjoint' and "
2000 "'Retain Poured Copper - Isolated'. KiCad does not distinguish "
2001 "between these two settings. The setting for disjoint copper "
2002 "has been applied as the minimum island area of the KiCad Zone." ),
2003 csTemplate.Name ) );
2004 }
2005
2006 long long minIslandArea = -1;
2007
2008 if( csTemplate.Pouring.MinDisjointCopper != UNDEFINED_VALUE )
2009 {
2010 minIslandArea = (long long) getKiCadLength( csTemplate.Pouring.MinDisjointCopper, 0.2 )
2011 * (long long) getKiCadLength( csTemplate.Pouring.MinDisjointCopper, 0.2 );
2012
2014 }
2015 else
2016 {
2018 }
2019
2020 zone->SetMinIslandArea( minIslandArea );
2021
2022 // In cadstar zone clearance is in addition to the global clearance.
2023 // TODO: need to create custom rules for individual items: zone to pad, zone to track, etc.
2024 int clearance = getKiCadLength( csTemplate.Pouring.AdditionalIsolation, 0.0005 );
2025 clearance += m_board->GetDesignSettings().m_MinClearance;
2026
2028
2029 COPPERCODE pouringCopperCode = getCopperCode( csTemplate.Pouring.CopperCodeID );
2030 int minThickness = getKiCadLength( pouringCopperCode.CopperWidth, 0.25 );
2031 zone->SetMinThickness( minThickness );
2032
2033 if( csTemplate.Pouring.FillType == TEMPLATE::POURING::COPPER_FILL_TYPE::HATCHED )
2034 {
2036 zone->SetHatchGap( getKiCadHatchCodeGap( csTemplate.Pouring.HatchCodeID ) );
2039 }
2040 else
2041 {
2043 }
2044
2045 if( csTemplate.Pouring.ThermalReliefOnPads != csTemplate.Pouring.ThermalReliefOnVias
2046 || csTemplate.Pouring.ThermalReliefPadsAngle
2047 != csTemplate.Pouring.ThermalReliefViasAngle )
2048 {
2049 reportWarning( wxString::Format( _( "The CADSTAR template '%s' has different settings for thermal relief "
2050 "in pads and vias. KiCad only supports one single setting for both. "
2051 "The setting for pads has been applied." ),
2052 csTemplate.Name ) );
2053 }
2054
2055 COPPERCODE reliefCopperCode = getCopperCode( csTemplate.Pouring.ReliefCopperCodeID );
2056 int spokeWidth = getKiCadLength( reliefCopperCode.CopperWidth, 0.5 );
2057 int reliefWidth = getKiCadLength( csTemplate.Pouring.ClearanceWidth, 0.5 );
2058
2059 // Cadstar supports having a spoke width thinner than the minimum thickness of the zone, but
2060 // this is not permitted in KiCad. We load it as solid fill instead.
2061 if( csTemplate.Pouring.ThermalReliefOnPads && reliefWidth > 0 )
2062 {
2063 if( spokeWidth < minThickness )
2064 {
2065 reportWarning( wxString::Format( _( "The CADSTAR template '%s' has thermal reliefs in the original "
2066 "design but the spoke width (%.2f mm) is thinner " //format:allow
2067 "than the minimum thickness of the zone (%.2f mm). " //format:allow
2068 "KiCad requires the minimum thickness of the zone to be preserved. "
2069 "Therefore the minimum thickness has been applied as the new "
2070 "spoke width and will be applied next time the zones are filled." ),
2071 csTemplate.Name, (double) getKiCadLength( spokeWidth, 0.5 ) / 1E6,
2072 (double) getKiCadLength( minThickness, 0.25 ) / 1E6 ) );
2073
2074 spokeWidth = minThickness;
2075 }
2076
2077 zone->SetThermalReliefGap( reliefWidth );
2078 zone->SetThermalReliefSpokeWidth( spokeWidth );
2080 }
2081 else
2082 {
2084 }
2085
2086 m_zonesMap.insert( { csTemplate.ID, zone } );
2087 }
2088
2089 //Now create power plane layers:
2090 for( const LAYER_ID& layer : m_powerPlaneLayers )
2091 {
2092 wxASSERT( Assignments.Layerdefs.Layers.find( layer ) != Assignments.Layerdefs.Layers.end() );
2093
2094 //The net name will equal the layer name
2095 wxString powerPlaneLayerName = Assignments.Layerdefs.Layers.at( layer ).Name;
2096 NET_ID netid = wxEmptyString;
2097
2098 for( std::pair<NET_ID, NET_PCB> netPair : Layout.Nets )
2099 {
2100 NET_PCB net = netPair.second;
2101
2102 if( net.Name == powerPlaneLayerName )
2103 {
2104 netid = net.ID;
2105 break;
2106 }
2107 }
2108
2109 if( netid.IsEmpty() )
2110 {
2111 reportError( wxString::Format( _( "The CADSTAR layer '%s' is defined as a power plane layer. "
2112 "However no net with such name exists. The layer has been loaded "
2113 "but no copper zone was created." ),
2114 powerPlaneLayerName ) );
2115 }
2116 else
2117 {
2118 for( std::pair<BOARD_ID, CADSTAR_BOARD> boardPair : Layout.Boards )
2119 {
2120 //create a zone in each board shape
2121 BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
2122 CADSTAR_BOARD& board = boardPair.second;
2123 int defaultLineThicknesss = bds.GetLineThickness( PCB_LAYER_ID::Edge_Cuts );
2124 ZONE* zone = getZoneFromCadstarShape( board.Shape, defaultLineThicknesss, m_board );
2125
2126 m_board->Add( zone, ADD_MODE::APPEND );
2127
2128 zone->SetZoneName( powerPlaneLayerName );
2129 zone->SetLayer( getKiCadLayer( layer ) );
2132 zone->SetMinIslandArea( -1 );
2133 zone->SetAssignedPriority( 0 ); // Priority always 0 (lowest priority) for implied power planes.
2134 zone->SetNet( getKiCadNet( netid ) );
2135 }
2136 }
2137 }
2138}
2139
2140
2142{
2143 for( std::pair<COPPER_ID, COPPER> copPair : Layout.Coppers )
2144 {
2145 COPPER& csCopper = copPair.second;
2146 int copperWidth = getKiCadLength( getCopperCode( csCopper.CopperCodeID ).CopperWidth, 0.2 );
2147
2148
2149 checkPoint();
2150
2151 if( !csCopper.PouredTemplateID.IsEmpty() )
2152 {
2153 ZONE* pouredZone = m_zonesMap.at( csCopper.PouredTemplateID );
2154 SHAPE_POLY_SET fill;
2155
2156 if( csCopper.Shape.Type == SHAPE_TYPE::OPENSHAPE )
2157 {
2158 // This is usually for themal reliefs. They are lines of copper with a thickness.
2159 // We convert them to an oval in most cases, but handle also the possibility of
2160 // encountering arcs in here.
2161
2162 std::vector<PCB_SHAPE*> outlineShapes = getShapesFromVertices( csCopper.Shape.Vertices );
2163
2164 for( PCB_SHAPE* shape : outlineShapes )
2165 {
2166 SHAPE_POLY_SET poly;
2167
2168 if( shape->GetShape() == SHAPE_T::ARC )
2169 {
2170 TransformArcToPolygon( poly, shape->GetStart(), shape->GetArcMid(), shape->GetEnd(),
2171 copperWidth, pouredZone->GetMaxError(), ERROR_LOC::ERROR_INSIDE );
2172 }
2173 else
2174 {
2175 TransformOvalToPolygon( poly, shape->GetStart(), shape->GetEnd(), copperWidth,
2176 pouredZone->GetMaxError(), ERROR_LOC::ERROR_INSIDE );
2177 }
2178
2179 poly.ClearArcs();
2180 fill.BooleanAdd( poly );
2181 }
2182
2183 }
2184 else
2185 {
2186 fill = getPolySetFromCadstarShape( csCopper.Shape, -1 );
2187 fill.ClearArcs();
2188 fill.Inflate( copperWidth / 2, CORNER_STRATEGY::ROUND_ALL_CORNERS, pouredZone->GetMaxError() );
2189 }
2190
2191 if( pouredZone->HasFilledPolysForLayer( getKiCadLayer( csCopper.LayerID ) ) )
2192 fill.BooleanAdd( *pouredZone->GetFill( getKiCadLayer( csCopper.LayerID ) ) );
2193
2194 fill.Fracture();
2195
2196 pouredZone->SetFilledPolysList( getKiCadLayer( csCopper.LayerID ), fill );
2197 pouredZone->SetIsFilled( true );
2198 pouredZone->SetNeedRefill( false );
2199 continue;
2200 }
2201
2202 // For now we are going to load coppers to a KiCad zone however this isn't perfect
2203 //TODO: Load onto a graphical polygon with a net
2204
2205 if( !m_doneCopperWarning )
2206 {
2207 reportWarning( _( "The CADSTAR design contains COPPER elements, which have no direct KiCad "
2208 "equivalent. These have been imported as a KiCad Zone if solid or hatch "
2209 "filled, or as a KiCad Track if the shape was an unfilled outline (open or "
2210 "closed)." ) );
2211 m_doneCopperWarning = true;
2212 }
2213
2214
2215 if( csCopper.Shape.Type == SHAPE_TYPE::OPENSHAPE
2216 || csCopper.Shape.Type == SHAPE_TYPE::OUTLINE )
2217 {
2218 std::vector<PCB_SHAPE*> outlineShapes = getShapesFromVertices( csCopper.Shape.Vertices );
2219
2220 std::vector<PCB_TRACK*> outlineTracks = makeTracksFromShapes( outlineShapes, m_board,
2221 getKiCadNet( csCopper.NetRef.NetID ),
2222 getKiCadLayer( csCopper.LayerID ), copperWidth );
2223
2224 //cleanup
2225 for( PCB_SHAPE* shape : outlineShapes )
2226 delete shape;
2227
2228 for( const CUTOUT& cutout : csCopper.Shape.Cutouts )
2229 {
2230 std::vector<PCB_SHAPE*> cutoutShapes = getShapesFromVertices( cutout.Vertices );
2231
2232 std::vector<PCB_TRACK*> cutoutTracks = makeTracksFromShapes( cutoutShapes, m_board,
2233 getKiCadNet( csCopper.NetRef.NetID ),
2234 getKiCadLayer( csCopper.LayerID ), copperWidth );
2235
2236 //cleanup
2237 for( PCB_SHAPE* shape : cutoutShapes )
2238 delete shape;
2239 }
2240 }
2241 else
2242 {
2243 ZONE* zone = getZoneFromCadstarShape( csCopper.Shape, copperWidth, m_board );
2244
2245 m_board->Add( zone, ADD_MODE::APPEND );
2246
2247 zone->SetZoneName( csCopper.ID );
2248 zone->SetLayer( getKiCadLayer( csCopper.LayerID ) );
2250
2251 if( csCopper.Shape.Type == SHAPE_TYPE::HATCHED )
2252 {
2257 }
2258 else
2259 {
2261 }
2262
2265 zone->SetNet( getKiCadNet( csCopper.NetRef.NetID ) );
2266 zone->SetAssignedPriority( m_zonesMap.size() + 1 ); // Highest priority (always fill first)
2267
2268 SHAPE_POLY_SET fill( *zone->Outline() );
2269 fill.Fracture();
2270
2271 zone->SetFilledPolysList( getKiCadLayer( csCopper.LayerID ), fill );
2272 }
2273 }
2274}
2275
2276
2278{
2279 for( std::pair<NET_ID, NET_PCB> netPair : Layout.Nets )
2280 {
2281 NET_PCB net = netPair.second;
2282 wxString netnameForErrorReporting = net.Name;
2283
2284 std::map<NETELEMENT_ID, long> netelementSizes;
2285
2286 if( netnameForErrorReporting.IsEmpty() )
2287 netnameForErrorReporting = wxString::Format( wxT( "$%ld" ), net.SignalNum );
2288
2289 for( std::pair<NETELEMENT_ID, NET_PCB::VIA> viaPair : net.Vias )
2290 {
2291 NET_PCB::VIA via = viaPair.second;
2292
2293 // viasize is used for calculating route offset (as done in CADSTAR post processor)
2294 int viaSize = loadNetVia( net.ID, via );
2295 netelementSizes.insert( { viaPair.first, viaSize } );
2296 }
2297
2298 for( std::pair<NETELEMENT_ID, NET_PCB::PIN> pinPair : net.Pins )
2299 {
2300 NET_PCB::PIN pin = pinPair.second;
2301 FOOTPRINT* footprint = getFootprintFromCadstarID( pin.ComponentID );
2302
2303 if( footprint == nullptr )
2304 {
2305 reportWarning( wxString::Format( _( "The net '%s' references component ID '%s' which does not exist. "
2306 "This has been ignored." ),
2307 netnameForErrorReporting, pin.ComponentID ) );
2308 }
2309 else if( pin.PadID <= 0 || static_cast<size_t>( pin.PadID ) > footprint->Pads().size() )
2310 {
2311 // Pad IDs are one-based, so the valid range is [1, Pads().size()]. Anything
2312 // else would throw out of getPadReference() and abort the whole import.
2313 reportWarning( wxString::Format( _( "The net '%s' references non-existent pad index '%ld' in "
2314 "component '%s'. This has been ignored." ),
2315 netnameForErrorReporting,
2316 pin.PadID,
2317 footprint->GetReference() ) );
2318 }
2319 else
2320 {
2321 // The below works because we have added the pads in the correct order to the
2322 // footprint and the PAD_ID in Cadstar is a sequential, numerical ID
2323 PAD* pad = getPadReference( footprint, pin.PadID );
2324 pad->SetNet( getKiCadNet( net.ID ) );
2325
2326 // also set the net to any copper pads (i.e. copper elements that we have imported
2327 // as pads instead:
2328 SYMDEF_ID symdefid = Layout.Components.at( pin.ComponentID ).SymdefID;
2329
2330 if( m_librarycopperpads.find( symdefid ) != m_librarycopperpads.end() )
2331 {
2332 ASSOCIATED_COPPER_PADS assocPads = m_librarycopperpads.at( symdefid );
2333
2334 if( assocPads.find( pin.PadID ) != assocPads.end() )
2335 {
2336 for( PAD_ID copperPadID : assocPads.at( pin.PadID ) )
2337 {
2338 PAD* copperpad = getPadReference( footprint, copperPadID );
2339 copperpad->SetNet( getKiCadNet( net.ID ) );
2340 }
2341 }
2342 }
2343
2344 // padsize is used for calculating route offset (as done in CADSTAR post processor)
2345 int padsize = std::min( pad->GetSize( PADSTACK::TEMP_ALL_LAYERS ).x,
2346 pad->GetSize( PADSTACK::TEMP_ALL_LAYERS ).y );
2347 netelementSizes.insert( { pinPair.first, padsize } );
2348 }
2349 }
2350
2351 // For junction points we need to find out the biggest size of the other routes connecting
2352 // at the junction in order to correctly apply the same "route offset" operation that the
2353 // CADSTAR post processor applies when generating Manufacturing output. The only exception
2354 // is if there is just a single route at the junction point, we use that route width
2355 // Optimal width of a route code, falling back to the default netclass track width when the
2356 // route code is missing or specifies no usable width. Unlike getRouteCode() this tolerates
2357 // an absent route code silently, as expected for CADSTAR Revision 7 routes that omit
2358 // ROUTEWIDTH, and never yields a non-positive track width.
2359 auto getRouteCodeWidth =
2360 [&]( const ROUTECODE_ID& aRouteCodeID ) -> long
2361 {
2362 auto rcIt = Assignments.Codedefs.RouteCodes.find( aRouteCodeID );
2363
2364 if( rcIt != Assignments.Codedefs.RouteCodes.end() && rcIt->second.OptimalWidth > 0 )
2365 return rcIt->second.OptimalWidth;
2366
2367 long defaultWidth =
2368 m_board->GetDesignSettings().m_NetSettings->GetDefaultNetclass()->GetTrackWidth();
2369
2370 return defaultWidth / KiCadUnitMultiplier;
2371 };
2372
2373 // Resolve a vertex width, falling back to the connection's route code when the
2374 // ROUTEWIDTH node was omitted (CADSTAR Revision 7 format).
2375 auto getVertexWidth =
2376 [&]( const NET_PCB::ROUTE_VERTEX& aVertex, const ROUTECODE_ID& aRouteCodeID ) -> long
2377 {
2378 if( aVertex.RouteWidthIsExplicit )
2379 return aVertex.RouteWidth;
2380
2381 return getRouteCodeWidth( aRouteCodeID );
2382 };
2383
2384 auto getJunctionSize =
2385 [&]( const NETELEMENT_ID& aJptNetElemId, const NET_PCB::CONNECTION_PCB& aConnectionToIgnore ) -> int
2386 {
2387 int jptsize = 0;
2388
2389 for( NET_PCB::CONNECTION_PCB connection : net.Connections )
2390 {
2391 if( connection.Route.RouteVertices.size() == 0 )
2392 continue;
2393
2394 if( connection.StartNode == aConnectionToIgnore.StartNode
2395 && connection.EndNode == aConnectionToIgnore.EndNode )
2396 {
2397 continue;
2398 }
2399
2400 if( connection.StartNode == aJptNetElemId )
2401 {
2402 int s = getKiCadLength( getVertexWidth( connection.Route.RouteVertices.front(),
2403 connection.RouteCodeID ), 0.0 );
2404 jptsize = std::max( jptsize, s );
2405 }
2406 else if( connection.EndNode == aJptNetElemId )
2407 {
2408 int s = getKiCadLength( getVertexWidth( connection.Route.RouteVertices.back(),
2409 connection.RouteCodeID ), 0.0 );
2410 jptsize = std::max( jptsize, s );
2411 }
2412 }
2413
2414 if( jptsize == 0 && !aConnectionToIgnore.Route.RouteVertices.empty() )
2415 {
2416 // aConnectionToIgnore is actually the only one that has a route, so lets use that
2417 // to determine junction size
2418 NET_PCB::ROUTE_VERTEX vertex = aConnectionToIgnore.Route.RouteVertices.front();
2419
2420 if( aConnectionToIgnore.EndNode == aJptNetElemId )
2421 vertex = aConnectionToIgnore.Route.RouteVertices.back();
2422
2423 jptsize = getKiCadLength( getVertexWidth( vertex, aConnectionToIgnore.RouteCodeID ), 0.0 );
2424 }
2425
2426 if( jptsize == 0 )
2427 jptsize = getKiCadLength( UNDEFINED_VALUE, 0.2 );
2428
2429 return jptsize;
2430 };
2431
2432 for( const NET_PCB::CONNECTION_PCB& connection : net.Connections )
2433 {
2434 int startSize = std::numeric_limits<int>::max();
2435 int endSize = std::numeric_limits<int>::max();
2436
2437 if( netelementSizes.find( connection.StartNode ) != netelementSizes.end() )
2438 startSize = netelementSizes.at( connection.StartNode );
2439 else if( net.Junctions.find( connection.StartNode ) != net.Junctions.end() )
2440 startSize = getJunctionSize( connection.StartNode, connection );
2441
2442 if( netelementSizes.find( connection.EndNode ) != netelementSizes.end() )
2443 endSize = netelementSizes.at( connection.EndNode );
2444 else if( net.Junctions.find( connection.EndNode ) != net.Junctions.end() )
2445 endSize = getJunctionSize( connection.EndNode, connection );
2446
2447 startSize /= KiCadUnitMultiplier;
2448 endSize /= KiCadUnitMultiplier;
2449
2450 if( !connection.Unrouted )
2451 {
2452 loadNetTracks( net.ID, connection.Route, getRouteCodeWidth( connection.RouteCodeID ),
2453 startSize, endSize );
2454 }
2455 }
2456 }
2457}
2458
2459
2461{
2462 auto findAndReplaceTextField =
2463 [&]( TEXT_FIELD_NAME aField, const wxString& aValue )
2464 {
2465 if( m_context.TextFieldToValuesMap.find( aField ) != m_context.TextFieldToValuesMap.end() )
2466 {
2467 if( m_context.TextFieldToValuesMap.at( aField ) != aValue )
2468 {
2469 m_context.TextFieldToValuesMap.at( aField ) = aValue;
2470 m_context.InconsistentTextFields.insert( aField );
2471 return false;
2472 }
2473 }
2474 else
2475 {
2476 m_context.TextFieldToValuesMap.insert( { aField, aValue } );
2477 }
2478
2479 return true;
2480 };
2481
2482 if( m_project )
2483 {
2484 std::map<wxString, wxString>& txtVars = m_project->GetTextVars();
2485
2486 // Most of the design text fields can be derived from other elements
2487 if( Layout.VariantHierarchy.Variants.size() > 0 )
2488 {
2489 VARIANT loadedVar = Layout.VariantHierarchy.Variants.begin()->second;
2490
2491 findAndReplaceTextField( TEXT_FIELD_NAME::VARIANT_NAME, loadedVar.Name );
2492 findAndReplaceTextField( TEXT_FIELD_NAME::VARIANT_DESCRIPTION, loadedVar.Description );
2493 }
2494
2495 findAndReplaceTextField( TEXT_FIELD_NAME::DESIGN_TITLE, Header.JobTitle );
2496
2497 for( std::pair<TEXT_FIELD_NAME, wxString> txtvalue : m_context.TextFieldToValuesMap )
2498 {
2499 wxString varName = CADSTAR_TO_KICAD_FIELDS.at( txtvalue.first );
2500 wxString varValue = txtvalue.second;
2501
2502 txtVars.insert( { varName, varValue } );
2503 }
2504
2505 for( std::pair<wxString, wxString> txtvalue : m_context.FilenamesToTextMap )
2506 {
2507 wxString varName = txtvalue.first;
2508 wxString varValue = txtvalue.second;
2509
2510 txtVars.insert( { varName, varValue } );
2511 }
2512 }
2513 else
2514 {
2515 reportError( _( "Text Variables could not be set as there is no project loaded." ) );
2516 }
2517}
2518
2519
2521 FOOTPRINT* aFootprint )
2522{
2523 for( std::pair<ATTRIBUTE_ID, ATTRIBUTE_VALUE> attrPair : aComponent.AttributeValues )
2524 {
2525 ATTRIBUTE_VALUE& attrval = attrPair.second;
2526
2527 if( attrval.HasLocation ) //only import attributes with location. Ignore the rest
2528 addAttribute( attrval.AttributeLocation, attrval.AttributeID, aFootprint, attrval.Value );
2529 }
2530
2531 for( std::pair<ATTRIBUTE_ID, TEXT_LOCATION> textlocPair : aComponent.TextLocations )
2532 {
2533 TEXT_LOCATION& textloc = textlocPair.second;
2534 wxString attrval;
2535
2536 if( textloc.AttributeID == COMPONENT_NAME_ATTRID )
2537 attrval = wxEmptyString; // Designator is loaded separately
2538 else if( textloc.AttributeID == COMPONENT_NAME_2_ATTRID )
2539 attrval = wxT( "${REFERENCE}" );
2540 else if( textloc.AttributeID == PART_NAME_ATTRID )
2541 attrval = getPart( aComponent.PartID ).Name;
2542 else
2543 attrval = getAttributeValue( textloc.AttributeID, aComponent.AttributeValues );
2544
2545 addAttribute( textloc, textloc.AttributeID, aFootprint, attrval );
2546 }
2547}
2548
2549
2551 const NET_PCB::ROUTE& aCadstarRoute,
2552 long aDefaultRouteWidth,
2553 long aStartWidth, long aEndWidth )
2554{
2555 if( aCadstarRoute.RouteVertices.size() == 0 )
2556 return;
2557
2558 std::vector<PCB_SHAPE*> shapes;
2559 std::vector<NET_PCB::ROUTE_VERTEX> routeVertices = aCadstarRoute.RouteVertices;
2560
2561 // Fill in default route width for vertices that don't have explicit widths (CADSTAR Revision 7)
2562 for( NET_PCB::ROUTE_VERTEX& v : routeVertices )
2563 {
2564 if( !v.RouteWidthIsExplicit )
2565 v.RouteWidth = aDefaultRouteWidth;
2566 }
2567
2568 // Add thin route at front so that route offsetting works as expected
2569 if( aStartWidth < routeVertices.front().RouteWidth )
2570 {
2571 NET_PCB::ROUTE_VERTEX newFrontVertex = aCadstarRoute.RouteVertices.front();
2572 newFrontVertex.RouteWidth = aStartWidth;
2573 newFrontVertex.Vertex.End = aCadstarRoute.StartPoint;
2574 routeVertices.insert( routeVertices.begin(), newFrontVertex );
2575 }
2576
2577 // Add thin route at the back if required
2578 if( aEndWidth < routeVertices.back().RouteWidth )
2579 {
2580 NET_PCB::ROUTE_VERTEX newBackVertex = aCadstarRoute.RouteVertices.back();
2581 newBackVertex.RouteWidth = aEndWidth;
2582 routeVertices.push_back( newBackVertex );
2583 }
2584
2585 POINT prevEnd = aCadstarRoute.StartPoint;
2586
2587 for( const NET_PCB::ROUTE_VERTEX& v : routeVertices )
2588 {
2589 PCB_SHAPE* shape = getShapeFromVertex( prevEnd, v.Vertex );
2590 shape->SetLayer( getKiCadLayer( aCadstarRoute.LayerID ) );
2591 shape->SetStroke( STROKE_PARAMS( getKiCadLength( v.RouteWidth, 0.2 ), LINE_STYLE::SOLID ) );
2592 shape->SetLocked( v.Fixed );
2593 shapes.push_back( shape );
2594 prevEnd = v.Vertex.End;
2595
2596 if( !m_doneTearDropWarning && ( v.TeardropAtEnd || v.TeardropAtStart ) )
2597 {
2598 // TODO: load teardrops
2599 reportError( _( "The CADSTAR design contains teardrops. This importer does not yet support them, "
2600 "so the teardrops in the design have been ignored." ) );
2601
2602 m_doneTearDropWarning = true;
2603 }
2604 }
2605
2606 NETINFO_ITEM* net = getKiCadNet( aCadstarNetID );
2607 std::vector<PCB_TRACK*> tracks = makeTracksFromShapes( shapes, m_board, net );
2608
2609 //cleanup
2610 for( PCB_SHAPE* shape : shapes )
2611 delete shape;
2612}
2613
2614
2615int CADSTAR_PCB_ARCHIVE_LOADER::loadNetVia( const NET_ID& aCadstarNetID, const NET_PCB::VIA& aCadstarVia )
2616{
2617 PCB_VIA* via = new PCB_VIA( m_board );
2618 m_board->Add( via, ADD_MODE::APPEND );
2619
2620 VIACODE csViaCode = getViaCode( aCadstarVia.ViaCodeID );
2621 LAYERPAIR csLayerPair = getLayerPair( aCadstarVia.LayerPairID );
2622
2623 via->SetPadstackMode( PADSTACK::MODE::NORMAL );
2624 via->SetPosition( getKiCadPoint( aCadstarVia.Location ) );
2625 via->SetDrill( getKiCadLength( csViaCode.DrillDiameter, 0.3 ) );
2626 via->SetLocked( aCadstarVia.Fixed );
2627
2628 if( csViaCode.Shape.ShapeType != PAD_SHAPE_TYPE::CIRCLE )
2629 {
2630 reportError( wxString::Format( _( "The CADSTAR via code '%s' has different shape from a circle defined. "
2631 "KiCad only supports circular vias so this via type has been changed to "
2632 "be a via with circular shape of %.2f mm diameter." ), //format:allow
2633 csViaCode.Name,
2634 (double) getKiCadLength( csViaCode.Shape.Size, 0.5 ) / 1E6 ) );
2635 }
2636
2637 via->SetWidth( PADSTACK::ALL_LAYERS, getKiCadLength( csViaCode.Shape.Size, 0.5 ) );
2638
2639 // A via code can reassign copper per layer, which KiCad holds as a full-custom padstack
2640 for( const auto& [layer, shape] : csViaCode.Reassigns )
2641 {
2642 PCB_LAYER_ID kiLayer = getKiCadLayer( layer );
2643
2644 if( !IsCopperLayer( kiLayer ) || shape.Size <= 0 )
2645 continue;
2646
2647 via->SetPadstackMode( PADSTACK::MODE::CUSTOM );
2648 via->SetWidth( kiLayer, getKiCadLength( shape.Size, 0.5 ) );
2649 }
2650
2651 bool start_layer_outside = csLayerPair.PhysicalLayerStart == 1
2652 || csLayerPair.PhysicalLayerStart == Assignments.Technology.MaxPhysicalLayer;
2653 bool end_layer_outside = csLayerPair.PhysicalLayerEnd == 1
2654 || csLayerPair.PhysicalLayerEnd == Assignments.Technology.MaxPhysicalLayer;
2655
2656 if( start_layer_outside && end_layer_outside )
2657 via->SetViaType( VIATYPE::THROUGH );
2658 else if( ( !start_layer_outside ) && ( !end_layer_outside ) )
2659 via->SetViaType( VIATYPE::BURIED );
2660 else
2661 via->SetViaType( VIATYPE::BLIND );
2662
2663 via->SetLayerPair( getKiCadCopperLayerID( csLayerPair.PhysicalLayerStart ),
2664 getKiCadCopperLayerID( csLayerPair.PhysicalLayerEnd ) );
2665 via->SetNet( getKiCadNet( aCadstarNetID ) );
2666
2667 return via->GetWidth( PADSTACK::ALL_LAYERS );
2668}
2669
2670
2672 BOARD_ITEM_CONTAINER* aContainer,
2673 const GROUP_ID& aCadstarGroupID,
2674 const LAYER_ID& aCadstarLayerOverride,
2675 const VECTOR2I& aMoveVector,
2676 double aRotationAngle, double aScalingFactor,
2677 const VECTOR2I& aTransformCentre,
2678 bool aMirrorInvert )
2679{
2680 PCB_TEXT* txt = new PCB_TEXT( aContainer );
2681 aContainer->Add( txt );
2682 txt->SetText( aCadstarText.Text );
2683
2684 EDA_ANGLE rotationAngle( aRotationAngle, TENTHS_OF_A_DEGREE_T );
2685 VECTOR2I rotatedTextPos = getKiCadPoint( aCadstarText.Position );
2686 RotatePoint( rotatedTextPos, aTransformCentre, rotationAngle );
2687 rotatedTextPos.x = KiROUND( ( rotatedTextPos.x - aTransformCentre.x ) * aScalingFactor );
2688 rotatedTextPos.y = KiROUND( ( rotatedTextPos.y - aTransformCentre.y ) * aScalingFactor );
2689 rotatedTextPos += aTransformCentre;
2690 txt->SetTextPos( rotatedTextPos );
2691 txt->SetPosition( rotatedTextPos );
2692
2693 txt->SetTextAngle( getAngle( aCadstarText.OrientAngle ) + rotationAngle );
2694
2695 txt->SetMirrored( aCadstarText.Mirror );
2696
2697 applyTextCode( txt, aCadstarText.TextCodeID );
2698
2699 switch( aCadstarText.Alignment )
2700 {
2701 case ALIGNMENT::NO_ALIGNMENT: // Default for Single line text is Bottom Left
2705 break;
2706
2710 break;
2711
2715 break;
2716
2720 break;
2721
2725 break;
2726
2730 break;
2731
2732 case ALIGNMENT::TOPLEFT:
2735 break;
2736
2740 break;
2741
2745 break;
2746
2747 default:
2748 wxFAIL_MSG( wxT( "Unknown Alignment - needs review!" ) );
2749 }
2750
2751 if( aMirrorInvert )
2752 txt->Flip( aTransformCentre, FLIP_DIRECTION::LEFT_RIGHT );
2753
2754 //scale it after flipping:
2755 if( aScalingFactor != 1.0 )
2756 {
2757 VECTOR2I unscaledTextSize = txt->GetTextSize();
2758 int unscaledThickness = txt->GetTextThickness();
2759
2760 VECTOR2I scaledTextSize;
2761 scaledTextSize.x = KiROUND( (double) unscaledTextSize.x * aScalingFactor );
2762 scaledTextSize.y = KiROUND( (double) unscaledTextSize.y * aScalingFactor );
2763
2764 txt->SetTextSize( scaledTextSize );
2765 txt->SetTextThickness( KiROUND( (double) unscaledThickness * aScalingFactor ) );
2766 }
2767
2768 txt->Move( aMoveVector );
2769
2770 if( aCadstarText.Alignment == ALIGNMENT::NO_ALIGNMENT )
2772
2773 LAYER_ID layersToDrawOn = aCadstarLayerOverride;
2774
2775 if( layersToDrawOn.IsEmpty() )
2776 layersToDrawOn = aCadstarText.LayerID;
2777
2778 if( isLayerSet( layersToDrawOn ) )
2779 {
2780 //Make a copy on each layer
2781 for( PCB_LAYER_ID layer : getKiCadLayerSet( layersToDrawOn ).Seq() )
2782 {
2783 txt->SetLayer( layer );
2784 PCB_TEXT* newtxt = static_cast<PCB_TEXT*>( txt->Duplicate( IGNORE_PARENT_GROUP ) );
2785 m_board->Add( newtxt, ADD_MODE::APPEND );
2786
2787 if( !aCadstarGroupID.IsEmpty() )
2788 addToGroup( aCadstarGroupID, newtxt );
2789 }
2790
2791 m_board->Remove( txt );
2792 delete txt;
2793 }
2794 else
2795 {
2796 txt->SetLayer( getKiCadLayer( layersToDrawOn ) );
2797
2798 if( !aCadstarGroupID.IsEmpty() )
2799 addToGroup( aCadstarGroupID, txt );
2800 }
2801}
2802
2803
2804void CADSTAR_PCB_ARCHIVE_LOADER::drawCadstarShape( const SHAPE& aCadstarShape, const PCB_LAYER_ID& aKiCadLayer,
2805 int aLineThickness, LINE_STYLE aLineStyle,
2806 const wxString& aShapeName, BOARD_ITEM_CONTAINER* aContainer,
2807 const GROUP_ID& aCadstarGroupID, const VECTOR2I& aMoveVector,
2808 double aRotationAngle, double aScalingFactor,
2809 const VECTOR2I& aTransformCentre, bool aMirrorInvert )
2810{
2811 auto drawAsOutline =
2812 [&]()
2813 {
2814 drawCadstarVerticesAsShapes( aCadstarShape.Vertices, aKiCadLayer, aLineThickness, aLineStyle,
2815 aContainer, aCadstarGroupID, aMoveVector, aRotationAngle,
2816 aScalingFactor, aTransformCentre, aMirrorInvert );
2817 drawCadstarCutoutsAsShapes( aCadstarShape.Cutouts, aKiCadLayer, aLineThickness, aContainer,
2818 aCadstarGroupID, aMoveVector, aRotationAngle, aScalingFactor,
2819 aTransformCentre, aMirrorInvert );
2820 };
2821
2822 if( aCadstarShape.Type == SHAPE_TYPE::OPENSHAPE || aCadstarShape.Type == SHAPE_TYPE::OUTLINE )
2823 {
2824 drawAsOutline();
2825 return;
2826 }
2827
2828 // Special case solid shapes that are effectively a single line
2829 if( aCadstarShape.Vertices.size() < 3 )
2830 {
2831 drawAsOutline();
2832 return;
2833 }
2834
2835 PCB_SHAPE* shape = new PCB_SHAPE( aContainer, SHAPE_T::POLY );
2836
2837 if( aCadstarShape.Type == SHAPE_TYPE::SOLID )
2839 else if( getHatchCodeAngle( aCadstarShape.HatchCodeID ) > ANGLE_90 )
2841 else
2842 shape->SetFillMode( FILL_T::HATCH );
2843
2844 SHAPE_POLY_SET shapePolys = getPolySetFromCadstarShape( aCadstarShape, -1, aContainer, aMoveVector,
2845 aRotationAngle, aScalingFactor, aTransformCentre,
2846 aMirrorInvert );
2847
2848 shapePolys.Fracture();
2849
2850 shape->SetPolyShape( shapePolys );
2851 shape->SetStroke( STROKE_PARAMS( aLineThickness, aLineStyle ) );
2852 shape->SetLayer( aKiCadLayer );
2853 aContainer->Add( shape, ADD_MODE::APPEND );
2854
2855 if( !aCadstarGroupID.IsEmpty() )
2856 addToGroup( aCadstarGroupID, shape );
2857}
2858
2859
2860void CADSTAR_PCB_ARCHIVE_LOADER::drawCadstarCutoutsAsShapes( const std::vector<CUTOUT>& aCutouts,
2861 const PCB_LAYER_ID& aKiCadLayer,
2862 int aLineThickness,
2863 BOARD_ITEM_CONTAINER* aContainer,
2864 const GROUP_ID& aCadstarGroupID,
2865 const VECTOR2I& aMoveVector,
2866 double aRotationAngle,
2867 double aScalingFactor,
2868 const VECTOR2I& aTransformCentre,
2869 bool aMirrorInvert )
2870{
2871 for( const CUTOUT& cutout : aCutouts )
2872 {
2873 drawCadstarVerticesAsShapes( cutout.Vertices, aKiCadLayer, aLineThickness, LINE_STYLE::SOLID, aContainer,
2874 aCadstarGroupID, aMoveVector, aRotationAngle, aScalingFactor, aTransformCentre,
2875 aMirrorInvert );
2876 }
2877}
2878
2879
2880void CADSTAR_PCB_ARCHIVE_LOADER::drawCadstarVerticesAsShapes( const std::vector<VERTEX>& aCadstarVertices,
2881 const PCB_LAYER_ID& aKiCadLayer,
2882 int aLineThickness, LINE_STYLE aLineStyle,
2883 BOARD_ITEM_CONTAINER* aContainer,
2884 const GROUP_ID& aCadstarGroupID,
2885 const VECTOR2I& aMoveVector, double aRotationAngle,
2886 double aScalingFactor, const VECTOR2I& aTransformCentre,
2887 bool aMirrorInvert )
2888{
2889 std::vector<PCB_SHAPE*> shapes = getShapesFromVertices( aCadstarVertices, aContainer, aCadstarGroupID,
2890 aMoveVector, aRotationAngle, aScalingFactor,
2891 aTransformCentre, aMirrorInvert );
2892
2893 for( PCB_SHAPE* shape : shapes )
2894 {
2895 shape->SetStroke( STROKE_PARAMS( aLineThickness, aLineStyle ) );
2896 shape->SetLayer( aKiCadLayer );
2897 shape->SetParent( aContainer );
2898 aContainer->Add( shape, ADD_MODE::APPEND );
2899 }
2900}
2901
2902
2903std::vector<PCB_SHAPE*>
2904CADSTAR_PCB_ARCHIVE_LOADER::getShapesFromVertices( const std::vector<VERTEX>& aCadstarVertices,
2905 BOARD_ITEM_CONTAINER* aContainer,
2906 const GROUP_ID& aCadstarGroupID,
2907 const VECTOR2I& aMoveVector,
2908 double aRotationAngle, double aScalingFactor,
2909 const VECTOR2I& aTransformCentre,
2910 bool aMirrorInvert )
2911{
2912 std::vector<PCB_SHAPE*> shapes;
2913
2914 if( aCadstarVertices.size() < 2 )
2915 //need at least two points to draw a segment! (unlikely but possible to have only one)
2916 return shapes;
2917
2918 const VERTEX* prev = &aCadstarVertices.at( 0 ); // first one should always be a point vertex
2919 const VERTEX* cur;
2920
2921 for( size_t i = 1; i < aCadstarVertices.size(); i++ )
2922 {
2923 cur = &aCadstarVertices.at( i );
2924 shapes.push_back( getShapeFromVertex( prev->End, *cur, aContainer, aCadstarGroupID, aMoveVector,
2925 aRotationAngle, aScalingFactor, aTransformCentre, aMirrorInvert ) );
2926 prev = cur;
2927 }
2928
2929 return shapes;
2930}
2931
2932
2934 const VERTEX& aCadstarVertex,
2935 BOARD_ITEM_CONTAINER* aContainer,
2936 const GROUP_ID& aCadstarGroupID,
2937 const VECTOR2I& aMoveVector,
2938 double aRotationAngle,
2939 double aScalingFactor,
2940 const VECTOR2I& aTransformCentre,
2941 bool aMirrorInvert )
2942{
2943 PCB_SHAPE* shape = nullptr;
2944 bool cw = false;
2945
2946 VECTOR2I startPoint = getKiCadPoint( aCadstarStartPoint );
2947 VECTOR2I endPoint = getKiCadPoint( aCadstarVertex.End );
2948 VECTOR2I centerPoint;
2949
2950 if( aCadstarVertex.Type == VERTEX_TYPE::ANTICLOCKWISE_SEMICIRCLE
2951 || aCadstarVertex.Type == VERTEX_TYPE::CLOCKWISE_SEMICIRCLE )
2952 {
2953 centerPoint = ( startPoint + endPoint ) / 2;
2954 }
2955 else
2956 {
2957 centerPoint = getKiCadPoint( aCadstarVertex.Center );
2958 }
2959
2960 switch( aCadstarVertex.Type )
2961 {
2962
2964 shape = new PCB_SHAPE( aContainer, SHAPE_T::SEGMENT );
2965
2966 shape->SetStart( startPoint );
2967 shape->SetEnd( endPoint );
2968 break;
2969
2972 cw = true;
2974
2977 {
2978 shape = new PCB_SHAPE( aContainer, SHAPE_T::ARC );
2979
2980 shape->SetCenter( centerPoint );
2981 shape->SetStart( startPoint );
2982
2983 EDA_ANGLE arcStartAngle( startPoint - centerPoint );
2984 EDA_ANGLE arcEndAngle( endPoint - centerPoint );
2985 EDA_ANGLE arcAngle = ( arcEndAngle - arcStartAngle ).Normalize();
2986 //TODO: detect if we are supposed to draw a circle instead (i.e. two SEMICIRCLEs with opposite
2987 // start/end points and same centre point)
2988
2989 if( !cw )
2990 arcAngle.NormalizeNegative(); // anticlockwise arc
2991
2992 shape->SetArcAngleAndEnd( arcAngle, true );
2993
2994 break;
2995 }
2996 }
2997
2998 //Apply transforms
2999 if( aMirrorInvert )
3000 shape->Flip( aTransformCentre, FLIP_DIRECTION::LEFT_RIGHT );
3001
3002 if( aScalingFactor != 1.0 )
3003 {
3004 shape->Move( -1*aTransformCentre );
3005 shape->Scale( aScalingFactor );
3006 shape->Move( aTransformCentre );
3007 }
3008
3009 if( aRotationAngle != 0.0 )
3010 shape->Rotate( aTransformCentre, EDA_ANGLE( aRotationAngle, TENTHS_OF_A_DEGREE_T ) );
3011
3012 if( aMoveVector != VECTOR2I{ 0, 0 } )
3013 shape->Move( aMoveVector );
3014
3015 if( !aCadstarGroupID.IsEmpty() )
3016 addToGroup( aCadstarGroupID, shape );
3017
3018 return shape;
3019}
3020
3021
3022ZONE* CADSTAR_PCB_ARCHIVE_LOADER::getZoneFromCadstarShape( const SHAPE& aCadstarShape, const int& aLineThickness,
3023 BOARD_ITEM_CONTAINER* aParentContainer )
3024{
3025 ZONE* zone = new ZONE( aParentContainer );
3026
3027 if( aCadstarShape.Type == SHAPE_TYPE::HATCHED )
3028 {
3031 }
3032 else
3033 {
3035 }
3036
3037 SHAPE_POLY_SET polygon = getPolySetFromCadstarShape( aCadstarShape, aLineThickness );
3038
3039 zone->AddPolygon( polygon.COutline( 0 ) );
3040
3041 for( int i = 0; i < polygon.HoleCount( 0 ); i++ )
3042 zone->AddPolygon( polygon.CHole( 0, i ) );
3043
3044 return zone;
3045}
3046
3047
3049 int aLineThickness,
3050 BOARD_ITEM_CONTAINER* aContainer,
3051 const VECTOR2I& aMoveVector,
3052 double aRotationAngle,
3053 double aScalingFactor,
3054 const VECTOR2I& aTransformCentre,
3055 bool aMirrorInvert )
3056{
3057 GROUP_ID noGroup = wxEmptyString;
3058
3059 std::vector<PCB_SHAPE*> outlineShapes = getShapesFromVertices( aCadstarShape.Vertices, aContainer, noGroup,
3060 aMoveVector, aRotationAngle, aScalingFactor,
3061 aTransformCentre, aMirrorInvert );
3062
3063 SHAPE_POLY_SET polySet( getLineChainFromShapes( outlineShapes ) );
3064
3065 //cleanup
3066 for( PCB_SHAPE* shape : outlineShapes )
3067 delete shape;
3068
3069 for( const CUTOUT& cutout : aCadstarShape.Cutouts )
3070 {
3071 std::vector<PCB_SHAPE*> cutoutShapes = getShapesFromVertices( cutout.Vertices, aContainer, noGroup,
3072 aMoveVector, aRotationAngle, aScalingFactor,
3073 aTransformCentre, aMirrorInvert );
3074
3075 polySet.AddHole( getLineChainFromShapes( cutoutShapes ) );
3076
3077 //cleanup
3078 for( PCB_SHAPE* shape : cutoutShapes )
3079 delete shape;
3080 }
3081
3082 polySet.ClearArcs();
3083
3084 if( aLineThickness > 0 )
3085 {
3086 polySet.Inflate( aLineThickness / 2, CORNER_STRATEGY::ROUND_ALL_CORNERS,
3087 m_board->GetDesignSettings().m_MaxError );
3088 }
3089
3090#ifdef DEBUG
3091 for( int i = 0; i < polySet.OutlineCount(); ++i )
3092 {
3093 wxASSERT( polySet.Outline( i ).PointCount() > 2 );
3094
3095 for( int j = 0; j < polySet.HoleCount( i ); ++j )
3096 wxASSERT( polySet.Hole( i, j ).PointCount() > 2 );
3097 }
3098#endif
3099
3100 return polySet;
3101}
3102
3103
3105{
3106 SHAPE_LINE_CHAIN lineChain;
3107
3108 for( PCB_SHAPE* shape : aShapes )
3109 {
3110 switch( shape->GetShape() )
3111 {
3112 case SHAPE_T::ARC:
3113 {
3114 SHAPE_ARC arc( shape->GetCenter(), shape->GetStart(), shape->GetArcAngle() );
3115
3116 if( shape->EndsSwapped() )
3117 arc.Reverse();
3118
3119 lineChain.Append( arc );
3120 break;
3121 }
3122
3123 case SHAPE_T::SEGMENT:
3124 lineChain.Append( shape->GetStartX(), shape->GetStartY() );
3125 lineChain.Append( shape->GetEndX(), shape->GetEndY() );
3126 break;
3127
3128 default:
3129 wxFAIL_MSG( wxT( "Drawsegment type is unexpected. Ignored." ) );
3130 }
3131 }
3132
3133 // Shouldn't have less than 3 points to make a closed shape!
3134 wxASSERT( lineChain.PointCount() > 2 );
3135
3136 // Check if it is closed
3137 if( lineChain.GetPoint( 0 ) != lineChain.GetPoint( lineChain.PointCount() - 1 ) )
3138 lineChain.Append( lineChain.GetPoint( 0 ) );
3139
3140 lineChain.SetClosed( true );
3141
3142 return lineChain;
3143}
3144
3145
3146std::vector<PCB_TRACK*> CADSTAR_PCB_ARCHIVE_LOADER::makeTracksFromShapes( const std::vector<PCB_SHAPE*>& aShapes,
3147 BOARD_ITEM_CONTAINER* aParentContainer,
3148 NETINFO_ITEM* aNet,
3149 PCB_LAYER_ID aLayerOverride,
3150 int aWidthOverride )
3151{
3152 std::vector<PCB_TRACK*> tracks;
3153 PCB_TRACK* prevTrack = nullptr;
3154 PCB_TRACK* track = nullptr;
3155
3156 auto addTrack =
3157 [&]( PCB_TRACK* aTrack )
3158 {
3159 // Ignore zero length tracks in the same way as the CADSTAR postprocessor does
3160 // when generating gerbers. Note that CADSTAR reports these as "Route offset
3161 // errors" when running a DRC within CADSTAR, so we shouldn't be getting this in
3162 // general, however it is used to remove any synthetic points added to
3163 // aDrawSegments by the caller of this function.
3164 if( aTrack->GetLength() != 0 )
3165 {
3166 tracks.push_back( aTrack );
3167 aParentContainer->Add( aTrack, ADD_MODE::APPEND );
3168 }
3169 else
3170 {
3171 delete aTrack;
3172 }
3173 };
3174
3175 for( PCB_SHAPE* shape : aShapes )
3176 {
3177 switch( shape->GetShape() )
3178 {
3179 case SHAPE_T::ARC:
3180 {
3181 SHAPE_ARC arc( shape->GetStart(), shape->GetArcMid(), shape->GetEnd(), 0 );
3182
3183 if( shape->EndsSwapped() )
3184 arc.Reverse();
3185
3186 track = new PCB_ARC( aParentContainer, &arc );
3187 break;
3188 }
3189
3190 case SHAPE_T::SEGMENT:
3191 track = new PCB_TRACK( aParentContainer );
3192 track->SetStart( shape->GetStart() );
3193 track->SetEnd( shape->GetEnd() );
3194 break;
3195
3196 default:
3197 wxFAIL_MSG( wxT( "Drawsegment type is unexpected. Ignored." ) );
3198 continue;
3199 }
3200
3201 if( aWidthOverride == -1 )
3202 track->SetWidth( shape->GetWidth() );
3203 else
3204 track->SetWidth( aWidthOverride );
3205
3206 if( aLayerOverride == PCB_LAYER_ID::UNDEFINED_LAYER )
3207 track->SetLayer( shape->GetLayer() );
3208 else
3209 track->SetLayer( aLayerOverride );
3210
3211 if( aNet != nullptr )
3212 track->SetNet( aNet );
3213 else
3214 track->SetNetCode( -1 );
3215
3216 track->SetLocked( shape->IsLocked() );
3217
3218 // Apply route offsetting, mimmicking the behaviour of the CADSTAR post processor
3219 if( prevTrack != nullptr )
3220 {
3221 int offsetAmount = ( track->GetWidth() / 2 ) - ( prevTrack->GetWidth() / 2 );
3222
3223 if( offsetAmount > 0 )
3224 {
3225 // modify the start of the current track
3226 VECTOR2I newStart = track->GetStart();
3227 applyRouteOffset( &newStart, track->GetEnd(), offsetAmount );
3228 track->SetStart( newStart );
3229 }
3230 else if( offsetAmount < 0 )
3231 {
3232 // amend the end of the previous track
3233 VECTOR2I newEnd = prevTrack->GetEnd();
3234 applyRouteOffset( &newEnd, prevTrack->GetStart(), -offsetAmount );
3235 prevTrack->SetEnd( newEnd );
3236 } // don't do anything if offsetAmount == 0
3237
3238 // Add a synthetic track of the thinnest width between the tracks
3239 // to ensure KiCad features works as expected on the imported design
3240 // (KiCad expects tracks are contiguous segments)
3241 if( track->GetStart() != prevTrack->GetEnd() )
3242 {
3243 int minWidth = std::min( track->GetWidth(), prevTrack->GetWidth() );
3244 PCB_TRACK* synthTrack = new PCB_TRACK( aParentContainer );
3245 synthTrack->SetStart( prevTrack->GetEnd() );
3246 synthTrack->SetEnd( track->GetStart() );
3247 synthTrack->SetWidth( minWidth );
3248 synthTrack->SetLocked( track->IsLocked() );
3249 synthTrack->SetNet( track->GetNet() );
3250 synthTrack->SetLayer( track->GetLayer() );
3251 addTrack( synthTrack );
3252 }
3253 }
3254
3255 if( prevTrack )
3256 addTrack( prevTrack );
3257
3258 prevTrack = track;
3259 }
3260
3261 if( track )
3262 addTrack( track );
3263
3264 return tracks;
3265}
3266
3267
3269 const ATTRIBUTE_ID& aCadstarAttributeID,
3270 FOOTPRINT* aFootprint, const wxString& aAttributeValue )
3271{
3272 PCB_FIELD* field;
3273
3274 if( aCadstarAttributeID == COMPONENT_NAME_ATTRID )
3275 {
3276 field = &aFootprint->Reference(); //text should be set outside this function
3277 }
3278 else if( aCadstarAttributeID == PART_NAME_ATTRID )
3279 {
3280 if( aFootprint->Value().GetText().IsEmpty() )
3281 {
3282 // Use PART_NAME_ATTRID as the value is value field is blank
3283 aFootprint->SetValue( aAttributeValue );
3284 field = &aFootprint->Value();
3285 }
3286 else
3287 {
3288 field = new PCB_FIELD( aFootprint, FIELD_T::USER, aCadstarAttributeID );
3289 aFootprint->Add( field );
3290 field->SetText( aAttributeValue );
3291 }
3292 field->SetVisible( false ); //make invisible to avoid clutter.
3293 }
3294 else if( aCadstarAttributeID != COMPONENT_NAME_2_ATTRID
3295 && getAttributeName( aCadstarAttributeID ) == wxT( "Value" ) )
3296 {
3297 if( !aFootprint->Value().GetText().IsEmpty() )
3298 {
3299 //copy the object
3300 aFootprint->Add( aFootprint->Value().Duplicate( IGNORE_PARENT_GROUP ) );
3301 }
3302
3303 aFootprint->SetValue( aAttributeValue );
3304 field = &aFootprint->Value();
3305 field->SetVisible( false ); //make invisible to avoid clutter.
3306 }
3307 else
3308 {
3309 field = new PCB_FIELD( aFootprint, FIELD_T::USER, aCadstarAttributeID );
3310 aFootprint->Add( field );
3311 field->SetText( aAttributeValue );
3312 field->SetVisible( false ); //make all user attributes invisible to avoid clutter.
3313 }
3314
3315 field->SetPosition( getKiCadPoint( aCadstarAttrLoc.Position ) );
3316 field->SetLayer( getKiCadLayer( aCadstarAttrLoc.LayerID ) );
3317 field->SetMirrored( aCadstarAttrLoc.Mirror );
3318 field->SetTextAngle( getAngle( aCadstarAttrLoc.OrientAngle ) );
3319
3320 if( aCadstarAttrLoc.Mirror ) // If mirroring, invert angle to match CADSTAR
3321 field->SetTextAngle( -field->GetTextAngle() );
3322
3323 applyTextCode( field, aCadstarAttrLoc.TextCodeID );
3324
3325 field->SetKeepUpright( false ); //Keeping it upright seems to result in incorrect orientation
3326
3327 switch( aCadstarAttrLoc.Alignment )
3328 {
3329 case ALIGNMENT::NO_ALIGNMENT: // Default for Single line text is Bottom Left
3335 break;
3336
3340 break;
3341
3345 break;
3346
3350 break;
3351
3355 break;
3356
3360 break;
3361
3362 case ALIGNMENT::TOPLEFT:
3365 break;
3366
3370 break;
3371
3375 break;
3376
3377 default:
3378 wxFAIL_MSG( wxT( "Unknown Alignment - needs review!" ) );
3379 }
3380}
3381
3382
3384 const VECTOR2I& aRefPoint,
3385 const long& aOffsetAmount )
3386{
3387 VECTOR2I v( *aPointToOffset - aRefPoint );
3388 int newLength = v.EuclideanNorm() - aOffsetAmount;
3389
3390 if( newLength > 0 )
3391 {
3392 VECTOR2I offsetted = v.Resize( newLength ) + VECTOR2I( aRefPoint );
3393 aPointToOffset->x = offsetted.x;
3394 aPointToOffset->y = offsetted.y;
3395 }
3396 else
3397 {
3398 *aPointToOffset = aRefPoint; // zero length track. Needs to be removed to mimmick
3399 // cadstar behaviour
3400 }
3401}
3402
3403
3404void CADSTAR_PCB_ARCHIVE_LOADER:: applyTextCode( EDA_TEXT* aKiCadText, const TEXTCODE_ID& aCadstarTextCodeID )
3405{
3406 TEXTCODE tc = getTextCode( aCadstarTextCodeID );
3407
3408 aKiCadText->SetTextThickness( getKiCadLength( tc.LineWidth, 0.08 ) );
3409
3410 if( tc.Font.Modifier1 == FONT_BOLD )
3411 aKiCadText->SetBold( true );
3412
3413 if( tc.Font.Italic )
3414 aKiCadText->SetItalic( true );
3415
3416 VECTOR2I textSize;
3417 textSize.x = getKiCadLength( tc.Width, 0.8 );
3418
3419 // The width is zero for all non-cadstar fonts. Using a width equal to the height seems
3420 // to work well for most fonts.
3421 if( textSize.x == 0 )
3422 textSize.x = getKiCadLength( tc.Height, 0.8 );
3423
3424 textSize.y = KiROUND( TXT_HEIGHT_RATIO * (double) getKiCadLength( tc.Height, 0.8 ) );
3425
3426 if( textSize.x == 0 || textSize.y == 0 )
3427 {
3428 // Make zero sized text not visible
3429
3432 }
3433 else
3434 {
3435 aKiCadText->SetTextSize( textSize );
3436 }
3437
3438 KIFONT::FONT* font;
3439
3440 if( tc.Font.Name == CADSTAR_FONT_NAME )
3441 {
3442 // Kicad currently only supports a single stroke font, so even if we had a facsimile of the CADSTAR stroke
3443 // font we wouldn't be able to use it.
3444 // So, substitute the Kicad stroke font. (We could default to a similarly-named outline font, but the
3445 // performance penalty on some designs would be large. Better to let the user do that if they want.)
3446
3447 fontconfig::FONTCONFIG::GetReporter().Report( wxString::Format( _( "Font '%s' not found; substituting '%s'." ),
3449
3451 }
3452 else
3453 {
3455 }
3456
3457 if( font )
3458 aKiCadText->SetFont( font );
3459
3460 // The line width is the intended rendered stroke; store the base so Bold doesn't double
3461 // it. Must run after SetFont() so the stroke-vs-outline check below sees the real font.
3462 aKiCadText->MigrateLegacyBoldStrokeWidth();
3463}
3464
3465
3467{
3468 wxCHECK( Assignments.Codedefs.LineCodes.find( aCadstarLineCodeID ) != Assignments.Codedefs.LineCodes.end(),
3470
3471 return getKiCadLength( Assignments.Codedefs.LineCodes.at( aCadstarLineCodeID ).Width, 0.05 );
3472}
3473
3474
3476{
3477 wxCHECK( Assignments.Codedefs.LineCodes.find( aCadstarLineCodeID ) != Assignments.Codedefs.LineCodes.end(),
3479
3480 switch( Assignments.Codedefs.LineCodes.at( aCadstarLineCodeID ).Style )
3481 {
3482 case LINESTYLE::DASH: return LINE_STYLE::DASH;
3485 case LINESTYLE::DOT: return LINE_STYLE::DOT;
3487 default: return LINE_STYLE::DEFAULT;
3488 }
3489}
3490
3491
3493 const COPPERCODE_ID& aCadstaCopperCodeID )
3494{
3495 wxCHECK( Assignments.Codedefs.CopperCodes.find( aCadstaCopperCodeID ) != Assignments.Codedefs.CopperCodes.end(),
3496 COPPERCODE() );
3497
3498 return Assignments.Codedefs.CopperCodes.at( aCadstaCopperCodeID );
3499}
3500
3501
3503{
3504 wxCHECK( Assignments.Codedefs.TextCodes.find( aCadstarTextCodeID ) != Assignments.Codedefs.TextCodes.end(),
3505 TEXTCODE() );
3506
3507 return Assignments.Codedefs.TextCodes.at( aCadstarTextCodeID );
3508}
3509
3510
3512{
3513 wxCHECK( Assignments.Codedefs.PadCodes.find( aCadstarPadCodeID ) != Assignments.Codedefs.PadCodes.end(),
3514 PADCODE() );
3515
3516 return Assignments.Codedefs.PadCodes.at( aCadstarPadCodeID );
3517}
3518
3519
3521{
3522 wxCHECK( Assignments.Codedefs.ViaCodes.find( aCadstarViaCodeID ) != Assignments.Codedefs.ViaCodes.end(),
3523 VIACODE() );
3524
3525 return Assignments.Codedefs.ViaCodes.at( aCadstarViaCodeID );
3526}
3527
3528
3530{
3531 wxCHECK( Assignments.Codedefs.LayerPairs.find( aCadstarLayerPairID ) != Assignments.Codedefs.LayerPairs.end(),
3532 LAYERPAIR() );
3533
3534 return Assignments.Codedefs.LayerPairs.at( aCadstarLayerPairID );
3535}
3536
3537
3539{
3540 wxCHECK( Assignments.Codedefs.AttributeNames.find( aCadstarAttributeID )
3541 != Assignments.Codedefs.AttributeNames.end(),
3542 wxEmptyString );
3543
3544 return Assignments.Codedefs.AttributeNames.at( aCadstarAttributeID ).Name;
3545}
3546
3547
3549 const std::map<ATTRIBUTE_ID, ATTRIBUTE_VALUE>& aCadstarAttrMap )
3550{
3551 wxCHECK( aCadstarAttrMap.find( aCadstarAttributeID ) != aCadstarAttrMap.end(), wxEmptyString );
3552
3553 return aCadstarAttrMap.at( aCadstarAttributeID ).Value;
3554}
3555
3556
3559{
3560 if( Assignments.Layerdefs.Layers.find( aCadstarLayerID ) != Assignments.Layerdefs.Layers.end() )
3561 return Assignments.Layerdefs.Layers.at( aCadstarLayerID ).Type;
3562
3563 return LAYER_TYPE::UNDEFINED;
3564}
3565
3566
3568{
3569 wxCHECK( Parts.PartDefinitions.find( aCadstarPartID ) != Parts.PartDefinitions.end(), PART() );
3570
3571 return Parts.PartDefinitions.at( aCadstarPartID );
3572}
3573
3574
3576 const ROUTECODE_ID& aCadstarRouteCodeID )
3577{
3578 wxCHECK( Assignments.Codedefs.RouteCodes.find( aCadstarRouteCodeID ) != Assignments.Codedefs.RouteCodes.end(),
3579 ROUTECODE() );
3580
3581 return Assignments.Codedefs.RouteCodes.at( aCadstarRouteCodeID );
3582}
3583
3584
3586 const HATCHCODE_ID& aCadstarHatchcodeID )
3587{
3588 wxCHECK( Assignments.Codedefs.HatchCodes.find( aCadstarHatchcodeID ) != Assignments.Codedefs.HatchCodes.end(),
3589 HATCHCODE() );
3590
3591 return Assignments.Codedefs.HatchCodes.at( aCadstarHatchcodeID );
3592}
3593
3594
3596{
3597 checkAndLogHatchCode( aCadstarHatchcodeID );
3598 HATCHCODE hcode = getHatchCode( aCadstarHatchcodeID );
3599
3600 if( hcode.Hatches.size() < 1 )
3601 return m_board->GetDesignSettings().GetDefaultZoneSettings().m_HatchOrientation;
3602 else
3603 return getAngle( hcode.Hatches.at( 0 ).OrientAngle );
3604}
3605
3606
3608{
3609 checkAndLogHatchCode( aCadstarHatchcodeID );
3610 HATCHCODE hcode = getHatchCode( aCadstarHatchcodeID );
3611
3612 if( hcode.Hatches.size() < 1 || hcode.Hatches.at( 0 ).LineWidth == UNDEFINED_VALUE )
3613 return m_board->GetDesignSettings().GetDefaultZoneSettings().m_HatchThickness;
3614 else
3615 return getKiCadLength( hcode.Hatches.at( 0 ).LineWidth, 1.0 );
3616}
3617
3618
3620{
3621 checkAndLogHatchCode( aCadstarHatchcodeID );
3622 HATCHCODE hcode = getHatchCode( aCadstarHatchcodeID );
3623
3624 if( hcode.Hatches.size() < 1 || hcode.Hatches.at( 0 ).Step == UNDEFINED_VALUE )
3625 return m_board->GetDesignSettings().GetDefaultZoneSettings().m_HatchGap;
3626 else
3627 return getKiCadLength( hcode.Hatches.at( 0 ).Step, 1.5 );
3628}
3629
3630
3632{
3633 wxCHECK( m_groupMap.find( aCadstarGroupID ) != m_groupMap.end(), nullptr );
3634
3635 return m_groupMap.at( aCadstarGroupID );
3636}
3637
3638
3640{
3641 if( m_hatchcodesTested.find( aCadstarHatchcodeID ) != m_hatchcodesTested.end() )
3642 {
3643 return; //already checked
3644 }
3645 else
3646 {
3647 HATCHCODE hcode = getHatchCode( aCadstarHatchcodeID );
3648
3649 if( hcode.Hatches.size() != 2 )
3650 {
3651 reportWarning( wxString::Format( _( "The CADSTAR Hatching code '%s' has %d hatches defined. "
3652 "KiCad only supports 2 hatches (crosshatching) 90 degrees apart. "
3653 "The imported hatching is crosshatched." ),
3654 hcode.Name,
3655 (int) hcode.Hatches.size() ) );
3656 }
3657 else
3658 {
3659 if( hcode.Hatches.at( 0 ).LineWidth != hcode.Hatches.at( 1 ).LineWidth )
3660 {
3661 reportWarning( wxString::Format( _( "The CADSTAR Hatching code '%s' has different line widths for "
3662 "each hatch. KiCad only supports one width for the hatching. The "
3663 "imported hatching uses the width defined in the first hatch "
3664 "definition, i.e. %.2f mm." ), //format:allow
3665 hcode.Name,
3666 (double) getKiCadLength( hcode.Hatches.at( 0 ).LineWidth, 1.0 ) / 1E6 ) );
3667 }
3668
3669 if( hcode.Hatches.at( 0 ).Step != hcode.Hatches.at( 1 ).Step )
3670 {
3671 reportWarning( wxString::Format( _( "The CADSTAR Hatching code '%s' has different step sizes for "
3672 "each hatch. KiCad only supports one step size for the hatching. "
3673 "The imported hatching uses the step size defined in the first "
3674 "hatching definition, i.e. %.2f mm." ), //format:allow
3675 hcode.Name,
3676 (double) getKiCadLength( hcode.Hatches.at( 0 ).Step, 1.5 ) / 1E6 ) );
3677 }
3678
3679 if( abs( hcode.Hatches.at( 0 ).OrientAngle - hcode.Hatches.at( 1 ).OrientAngle ) != 90000 )
3680 {
3681 reportWarning( wxString::Format( _( "The hatches in CADSTAR Hatching code '%s' have an angle "
3682 "difference of %.1f degrees. KiCad only supports hatching 90 " //format:allow
3683 "degrees apart. The imported hatching has two hatches 90 "
3684 "degrees apart, oriented %.1f degrees from horizontal." ), //format:allow
3685 hcode.Name,
3686 getAngle( abs( hcode.Hatches.at( 0 ).OrientAngle
3687 - hcode.Hatches.at( 1 ).OrientAngle ) ).AsDegrees(),
3688 getAngle( hcode.Hatches.at( 0 ).OrientAngle ).AsDegrees() ) );
3689 }
3690 }
3691
3692 m_hatchcodesTested.insert( aCadstarHatchcodeID );
3693 }
3694}
3695
3696
3698{
3699 UNITS dimensionUnits = aCadstarDim.LinearUnits;
3700 LINECODE linecode = Assignments.Codedefs.LineCodes.at( aCadstarDim.Line.LineCodeID );
3701
3702 aKiCadDim->SetLayer( getKiCadLayer( aCadstarDim.LayerID ) );
3703 aKiCadDim->SetPrecision( static_cast<DIM_PRECISION>( aCadstarDim.Precision ) );
3704 aKiCadDim->SetStart( getKiCadPoint( aCadstarDim.ExtensionLineParams.Start ) );
3705 aKiCadDim->SetEnd( getKiCadPoint( aCadstarDim.ExtensionLineParams.End ) );
3706 aKiCadDim->SetExtensionOffset( getKiCadOffset( aCadstarDim.ExtensionLineParams.Offset ) );
3707 aKiCadDim->SetLineThickness( getKiCadLength( linecode.Width, 0.05 ) );
3708
3709 applyTextCode( aKiCadDim, aCadstarDim.Text.TextCodeID );
3710
3711 // Find prefix and suffix:
3712 wxString prefix = wxEmptyString;
3713 wxString suffix = wxEmptyString;
3714 int startpos = aCadstarDim.Text.Text.Find( wxT( "<@DISTANCE" ) );
3715
3716 if( startpos != wxNOT_FOUND )
3717 {
3718 prefix = ParseTextFields( aCadstarDim.Text.Text.SubString( 0, startpos - 1 ), &m_context );
3719 wxString remainingStr = aCadstarDim.Text.Text.Mid( startpos );
3720 int endpos = remainingStr.Find( "@>" );
3721 suffix = ParseTextFields( remainingStr.Mid( endpos + 2 ), &m_context );
3722 }
3723
3724 if( suffix.StartsWith( wxT( "mm" ) ) )
3725 {
3727 suffix = suffix.Mid( 2 );
3728 }
3729 else
3730 {
3732 }
3733
3734 aKiCadDim->SetPrefix( prefix );
3735 aKiCadDim->SetSuffix( suffix );
3736
3737 if( aCadstarDim.LinearUnits == UNITS::DESIGN )
3738 {
3739 // For now we will hardcode the units as per the original CADSTAR design.
3740 // TODO: update this when KiCad supports design units
3741 aKiCadDim->SetPrecision( static_cast<DIM_PRECISION>( Assignments.Technology.UnitDisplPrecision ) );
3742 dimensionUnits = Assignments.Technology.Units;
3743 }
3744
3745 switch( dimensionUnits )
3746 {
3747 case UNITS::METER:
3748 case UNITS::CENTIMETER:
3749 case UNITS::MICROMETRE:
3750 reportWarning( wxString::Format( _( "Dimension ID %s uses a type of unit that is not supported in KiCad. "
3751 "Millimeters were applied instead." ),
3752 aCadstarDim.ID ) );
3754 case UNITS::MM:
3755 aKiCadDim->SetUnitsMode( DIM_UNITS_MODE::MM );
3756 break;
3757
3758 case UNITS::INCH:
3759 aKiCadDim->SetUnitsMode( DIM_UNITS_MODE::INCH );
3760 break;
3761
3762 case UNITS::THOU:
3763 aKiCadDim->SetUnitsMode( DIM_UNITS_MODE::MILS );
3764 break;
3765
3766 case UNITS::DESIGN:
3767 wxFAIL_MSG( wxT( "We should have handled design units before coming here!" ) );
3768 break;
3769 }
3770}
3771
3772
3774{
3775 std::map<TEMPLATE_ID, std::set<TEMPLATE_ID>> winningOverlaps;
3776
3777 auto inflateValue =
3778 [&]( ZONE* aZoneA, ZONE* aZoneB )
3779 {
3780 int extra = getKiCadLength( Assignments.Codedefs.SpacingCodes.at( wxT( "C_C" ) ).Spacing, 0.2 )
3781 - m_board->GetDesignSettings().m_MinClearance;
3782
3783 int retval = std::max( aZoneA->GetLocalClearance().value(), aZoneB->GetLocalClearance().value() );
3784
3785 retval += extra;
3786
3787 return retval;
3788 };
3789
3790 // Find the error in fill area when guessing that aHigherZone gets filled before aLowerZone
3791 auto errorArea =
3792 [&]( ZONE* aLowerZone, ZONE* aHigherZone ) -> double
3793 {
3794 SHAPE_POLY_SET intersectShape( *aHigherZone->Outline() );
3795 intersectShape.Inflate( inflateValue( aLowerZone, aHigherZone ), CORNER_STRATEGY::ROUND_ALL_CORNERS,
3796 aLowerZone->GetMaxError() );
3797
3798 SHAPE_POLY_SET lowerZoneFill( *aLowerZone->GetFilledPolysList( aLayer ) );
3799 SHAPE_POLY_SET lowerZoneOutline( *aLowerZone->Outline() );
3800
3801 lowerZoneOutline.BooleanSubtract( intersectShape );
3802
3803 lowerZoneFill.BooleanSubtract( lowerZoneOutline );
3804
3805 double leftOverArea = lowerZoneFill.Area();
3806
3807 return leftOverArea;
3808 };
3809
3810 auto intersectionAreaOfZoneOutlines =
3811 [&]( ZONE* aZoneA, ZONE* aZoneB ) -> double
3812 {
3813 SHAPE_POLY_SET outLineA( *aZoneA->Outline() );
3814 outLineA.Inflate( inflateValue( aZoneA, aZoneB ), CORNER_STRATEGY::ROUND_ALL_CORNERS,
3815 aZoneA->GetMaxError() );
3816
3817 SHAPE_POLY_SET outLineB( *aZoneB->Outline() );
3818 outLineB.Inflate( inflateValue( aZoneA, aZoneB ), CORNER_STRATEGY::ROUND_ALL_CORNERS,
3819 aZoneA->GetMaxError() );
3820
3821 outLineA.BooleanIntersection( outLineB );
3822
3823 return outLineA.Area();
3824 };
3825
3826 // Lambda to determine if the zone with template ID 'a' is lower priority than 'b'
3827 auto isLowerPriority =
3828 [&]( const TEMPLATE_ID& a, const TEMPLATE_ID& b ) -> bool
3829 {
3830 return winningOverlaps[b].count( a ) > 0;
3831 };
3832
3833 for( std::map<TEMPLATE_ID, ZONE*>::iterator it1 = m_zonesMap.begin(); it1 != m_zonesMap.end(); ++it1 )
3834 {
3835 TEMPLATE& thisTemplate = Layout.Templates.at( it1->first );
3836 ZONE* thisZone = it1->second;
3837
3838 if( !thisZone->GetLayerSet().Contains( aLayer ) )
3839 continue;
3840
3841 for( std::map<TEMPLATE_ID, ZONE*>::iterator it2 = it1;
3842 it2 != m_zonesMap.end(); ++it2 )
3843 {
3844 TEMPLATE& otherTemplate = Layout.Templates.at( it2->first );
3845 ZONE* otherZone = it2->second;
3846
3847 if( thisTemplate.ID == otherTemplate.ID )
3848 continue;
3849
3850 if( !otherZone->GetLayerSet().Contains( aLayer ) )
3851 {
3852 checkPoint();
3853 continue;
3854 }
3855
3856 if( intersectionAreaOfZoneOutlines( thisZone, otherZone ) == 0 )
3857 {
3858 checkPoint();
3859 continue; // The zones do not interact in any way
3860 }
3861
3862 SHAPE_POLY_SET thisZonePolyFill = *thisZone->GetFilledPolysList( aLayer );
3863 SHAPE_POLY_SET otherZonePolyFill = *otherZone->GetFilledPolysList( aLayer );
3864
3865 if( thisZonePolyFill.Area() > 0.0 && otherZonePolyFill.Area() > 0.0 )
3866 {
3867 // Test if this zone were lower priority than other zone, what is the error?
3868 double areaThis = errorArea( thisZone, otherZone );
3869 // Vice-versa
3870 double areaOther = errorArea( otherZone, thisZone );
3871
3872 if( areaThis > areaOther )
3873 {
3874 // thisTemplate is filled before otherTemplate
3875 winningOverlaps[thisTemplate.ID].insert( otherTemplate.ID );
3876 }
3877 else
3878 {
3879 // thisTemplate is filled AFTER otherTemplate
3880 winningOverlaps[otherTemplate.ID].insert( thisTemplate.ID );
3881 }
3882 }
3883 else if( thisZonePolyFill.Area() > 0.0 )
3884 {
3885 // The other template is not filled, this one wins
3886 winningOverlaps[thisTemplate.ID].insert( otherTemplate.ID );
3887 }
3888 else if( otherZonePolyFill.Area() > 0.0 )
3889 {
3890 // This template is not filled, the other one wins
3891 winningOverlaps[otherTemplate.ID].insert( thisTemplate.ID );
3892 }
3893 else
3894 {
3895 // Neither of the templates is poured - use zone outlines instead (bigger outlines
3896 // get a lower priority)
3897 if( intersectionAreaOfZoneOutlines( thisZone, otherZone ) != 0 )
3898 {
3899 if( thisZone->Outline()->Area() > otherZone->Outline()->Area() )
3900 winningOverlaps[otherTemplate.ID].insert( thisTemplate.ID );
3901 else
3902 winningOverlaps[thisTemplate.ID].insert( otherTemplate.ID );
3903 }
3904 }
3905
3906 checkPoint();
3907 }
3908 }
3909
3910 // Build a set of unique TEMPLATE_IDs of all the zones that intersect with another one
3911 std::set<TEMPLATE_ID> intersectingIDs;
3912
3913 for( const auto& idPair : winningOverlaps )
3914 {
3915 intersectingIDs.insert( idPair.first );
3916 intersectingIDs.insert( idPair.second.begin(), idPair.second.end() );
3917 }
3918
3919 // Now store them in a vector
3920 std::vector<TEMPLATE_ID> sortedIDs;
3921
3922 for( const TEMPLATE_ID& id : intersectingIDs )
3923 {
3924 sortedIDs.push_back( id );
3925 }
3926
3927 // sort by priority
3928 std::sort( sortedIDs.begin(), sortedIDs.end(), isLowerPriority );
3929
3930 TEMPLATE_ID prevID = wxEmptyString;
3931
3932 for( const TEMPLATE_ID& id : sortedIDs )
3933 {
3934 if( prevID.IsEmpty() )
3935 {
3936 prevID = id;
3937 continue;
3938 }
3939
3940 wxASSERT( !isLowerPriority( id, prevID ) );
3941
3942 int newPriority = m_zonesMap.at( prevID )->GetAssignedPriority();
3943
3944 // Only increase priority of the current zone
3945 if( isLowerPriority( prevID, id ) )
3946 newPriority++;
3947
3948 m_zonesMap.at( id )->SetAssignedPriority( newPriority );
3949 prevID = id;
3950 }
3951
3952 // Verify
3953 for( const auto& idPair : winningOverlaps )
3954 {
3955 const TEMPLATE_ID& winningID = idPair.first;
3956
3957 for( const TEMPLATE_ID& losingID : idPair.second )
3958 {
3959 if( m_zonesMap.at( losingID )->GetAssignedPriority() > m_zonesMap.at( winningID )->GetAssignedPriority() )
3960 return false;
3961 }
3962 }
3963
3964 return true;
3965}
3966
3967
3969{
3970 if( m_componentMap.find( aCadstarComponentID ) == m_componentMap.end() )
3971 return nullptr;
3972 else
3973 return m_componentMap.at( aCadstarComponentID );
3974}
3975
3976
3978{
3979 VECTOR2I retval;
3980
3981 retval.x = ( aCadstarPoint.x - m_designCenter.x ) * KiCadUnitMultiplier;
3982 retval.y = -( aCadstarPoint.y - m_designCenter.y ) * KiCadUnitMultiplier;
3983
3984 return retval;
3985}
3986
3987
3989{
3990 if( aCadstarNetID.IsEmpty() )
3991 {
3992 return nullptr;
3993 }
3994 else if( m_netMap.find( aCadstarNetID ) != m_netMap.end() )
3995 {
3996 return m_netMap.at( aCadstarNetID );
3997 }
3998 else
3999 {
4000 wxCHECK( Layout.Nets.find( aCadstarNetID ) != Layout.Nets.end(), nullptr );
4001
4002 NET_PCB csNet = Layout.Nets.at( aCadstarNetID );
4003 wxString newName = csNet.Name;
4004
4005 if( csNet.Name.IsEmpty() )
4006 {
4007 if( csNet.Pins.size() > 0 )
4008 {
4009 // Create default KiCad net naming:
4010
4011 NET_PCB::PIN firstPin = ( *csNet.Pins.begin() ).second;
4012 //we should have already loaded the component with loadComponents() :
4013 FOOTPRINT* m = getFootprintFromCadstarID( firstPin.ComponentID );
4014 newName = wxT( "Net-(" );
4015 newName << m->Reference().GetText();
4016 newName << wxT( "-Pad" ) << wxString::Format( wxT( "%ld" ), firstPin.PadID );
4017 newName << wxT( ")" );
4018 }
4019 else
4020 {
4021 wxFAIL_MSG( wxT( "A net with no pins associated?" ) );
4022 newName = wxT( "csNet-" );
4023 newName << wxString::Format( wxT( "%i" ), csNet.SignalNum );
4024 }
4025 }
4026
4027 if( !m_doneNetClassWarning && !csNet.NetClassID.IsEmpty() && csNet.NetClassID != wxT( "NONE" ) )
4028 {
4029 reportInfo( _( "The CADSTAR design contains nets with a 'Net Class' assigned. KiCad "
4030 "does not have an equivalent to CADSTAR's Net Class so these elements "
4031 "were not imported. Note: KiCad's version of 'Net Class' is closer to "
4032 "CADSTAR's 'Net Route Code' (which has been imported for all nets)." ) );
4033 m_doneNetClassWarning = true;
4034 }
4035
4036 if( !m_doneSpacingClassWarning && !csNet.SpacingClassID.IsEmpty() && csNet.SpacingClassID != wxT( "NONE" ) )
4037 {
4038 reportWarning( _( "The CADSTAR design contains nets with a 'Spacing Class' assigned. "
4039 "KiCad does not have an equivalent to CADSTAR's Spacing Class so "
4040 "these elements were not imported. Please review the design rules as "
4041 "copper pours may be affected by this." ) );
4043 }
4044
4045 std::shared_ptr<NET_SETTINGS>& netSettings = m_board->GetDesignSettings().m_NetSettings;
4046 NETINFO_ITEM* netInfo = m_board->FindOrAddNet( newName, ++m_numNets, ADD_MODE::APPEND );
4047 std::shared_ptr<NETCLASS> netclass;
4048
4049 std::tuple<ROUTECODE_ID, NETCLASS_ID, SPACING_CLASS_ID> key = { csNet.RouteCodeID,
4050 csNet.NetClassID,
4051 csNet.SpacingClassID };
4052
4053 if( m_netClassMap.find( key ) != m_netClassMap.end() )
4054 {
4055 netclass = m_netClassMap.at( key );
4056 }
4057 else if( auto rcIt = Assignments.Codedefs.RouteCodes.find( csNet.RouteCodeID );
4058 !csNet.RouteCodeID.IsEmpty() && rcIt != Assignments.Codedefs.RouteCodes.end()
4059 && rcIt->second.OptimalWidth > 0 )
4060 {
4061 wxString netClassName;
4062
4063 ROUTECODE rc = getRouteCode( csNet.RouteCodeID );
4064 netClassName += wxT( "Route code: " ) + rc.Name;
4065
4066 if( !csNet.NetClassID.IsEmpty() )
4067 {
4068 CADSTAR_NETCLASS nc = Assignments.Codedefs.NetClasses.at( csNet.NetClassID );
4069 netClassName += wxT( " | Net class: " ) + nc.Name;
4070 }
4071
4072 if( !csNet.SpacingClassID.IsEmpty() )
4073 {
4074 SPCCLASSNAME sp = Assignments.Codedefs.SpacingClassNames.at( csNet.SpacingClassID );
4075 netClassName += wxT( " | Spacing class: " ) + sp.Name;
4076 }
4077
4078 netclass.reset( new NETCLASS( netClassName ) );
4079 netSettings->SetNetclass( netClassName, netclass );
4080 netclass->SetTrackWidth( getKiCadLength( rc.OptimalWidth, 0.2 ) );
4081 m_netClassMap.insert( { key, netclass } );
4082 }
4083 else
4084 {
4085 // No route code specified, route code not found, or it has no usable width; use the
4086 // default netclass
4087 netclass = netSettings->GetDefaultNetclass();
4088 }
4089
4090 m_board->GetDesignSettings().m_NetSettings->SetNetclassPatternAssignment( newName, netclass->GetName() );
4091
4092 netInfo->SetNetClass( netclass );
4093 m_netMap.insert( { aCadstarNetID, netInfo } );
4094 return netInfo;
4095 }
4096}
4097
4098
4099PCB_LAYER_ID CADSTAR_PCB_ARCHIVE_LOADER::getKiCadCopperLayerID( unsigned int aLayerNum, bool aDetectMaxLayer )
4100{
4101 if( aDetectMaxLayer && aLayerNum == (unsigned int) m_numCopperLayers )
4102 return PCB_LAYER_ID::B_Cu;
4103
4104 switch( aLayerNum )
4105 {
4106 case 1: return PCB_LAYER_ID::F_Cu;
4107 case 2: return PCB_LAYER_ID::In1_Cu;
4108 case 3: return PCB_LAYER_ID::In2_Cu;
4109 case 4: return PCB_LAYER_ID::In3_Cu;
4110 case 5: return PCB_LAYER_ID::In4_Cu;
4111 case 6: return PCB_LAYER_ID::In5_Cu;
4112 case 7: return PCB_LAYER_ID::In6_Cu;
4113 case 8: return PCB_LAYER_ID::In7_Cu;
4114 case 9: return PCB_LAYER_ID::In8_Cu;
4115 case 10: return PCB_LAYER_ID::In9_Cu;
4116 case 11: return PCB_LAYER_ID::In10_Cu;
4117 case 12: return PCB_LAYER_ID::In11_Cu;
4118 case 13: return PCB_LAYER_ID::In12_Cu;
4119 case 14: return PCB_LAYER_ID::In13_Cu;
4120 case 15: return PCB_LAYER_ID::In14_Cu;
4121 case 16: return PCB_LAYER_ID::In15_Cu;
4122 case 17: return PCB_LAYER_ID::In16_Cu;
4123 case 18: return PCB_LAYER_ID::In17_Cu;
4124 case 19: return PCB_LAYER_ID::In18_Cu;
4125 case 20: return PCB_LAYER_ID::In19_Cu;
4126 case 21: return PCB_LAYER_ID::In20_Cu;
4127 case 22: return PCB_LAYER_ID::In21_Cu;
4128 case 23: return PCB_LAYER_ID::In22_Cu;
4129 case 24: return PCB_LAYER_ID::In23_Cu;
4130 case 25: return PCB_LAYER_ID::In24_Cu;
4131 case 26: return PCB_LAYER_ID::In25_Cu;
4132 case 27: return PCB_LAYER_ID::In26_Cu;
4133 case 28: return PCB_LAYER_ID::In27_Cu;
4134 case 29: return PCB_LAYER_ID::In28_Cu;
4135 case 30: return PCB_LAYER_ID::In29_Cu;
4136 case 31: return PCB_LAYER_ID::In30_Cu;
4137 case 32: return PCB_LAYER_ID::B_Cu;
4138 }
4139
4141}
4142
4143
4145{
4146 wxCHECK( Assignments.Layerdefs.Layers.find( aCadstarLayerID ) != Assignments.Layerdefs.Layers.end(), false );
4147
4148 LAYER& layer = Assignments.Layerdefs.Layers.at( aCadstarLayerID );
4149
4150 switch( layer.Type )
4151 {
4152 case LAYER_TYPE::ALLDOC:
4155 return true;
4156
4157 default:
4158 return false;
4159 }
4160}
4161
4162
4164{
4165 if( getLayerType( aCadstarLayerID ) == LAYER_TYPE::NOLAYER )
4166 {
4167 //The "no layer" is common for CADSTAR documentation symbols
4168 //map it to undefined layer for later processing
4170 }
4171
4172 wxCHECK( m_layermap.find( aCadstarLayerID ) != m_layermap.end(), PCB_LAYER_ID::UNDEFINED_LAYER );
4173
4174 return m_layermap.at( aCadstarLayerID );
4175}
4176
4177
4179{
4180 LAYER_TYPE layerType = getLayerType( aCadstarLayerID );
4181
4182 switch( layerType )
4183 {
4184 case LAYER_TYPE::ALLDOC:
4185 return LSET( { PCB_LAYER_ID::Dwgs_User,
4190
4193
4202
4203 default:
4204 return LSET( { getKiCadLayer( aCadstarLayerID ) } );
4205 }
4206}
4207
4208
4209void CADSTAR_PCB_ARCHIVE_LOADER::addToGroup( const GROUP_ID& aCadstarGroupID, BOARD_ITEM* aKiCadItem )
4210{
4211 wxCHECK( m_groupMap.find( aCadstarGroupID ) != m_groupMap.end(), );
4212
4213 PCB_GROUP* parentGroup = m_groupMap.at( aCadstarGroupID );
4214 parentGroup->AddItem( aKiCadItem );
4215}
4216
4217
4219{
4220 wxString groupName = aName;
4221 int num = 0;
4222
4223 while( m_groupMap.find( groupName ) != m_groupMap.end() )
4224 groupName = aName + wxT( "_" ) + wxString::Format( wxT( "%i" ), ++num );
4225
4226 PCB_GROUP* docSymGroup = new PCB_GROUP( m_board );
4227 m_board->Add( docSymGroup );
4228 docSymGroup->SetName( groupName );
4229 GROUP_ID groupID( groupName );
4230 m_groupMap.insert( { groupID, docSymGroup } );
4231
4232 return groupID;
4233}
int index
@ ERROR_INSIDE
constexpr double PCB_IU_PER_MM
Pcbnew IU is 1 nanometer.
Definition base_units.h:68
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
LAYER_T
The allowed types of layers, same as Specctra DSN spec.
Definition board.h:243
@ LT_POWER
Definition board.h:246
@ LT_JUMPER
Definition board.h:248
@ LT_SIGNAL
Definition board.h:245
@ BS_ITEM_TYPE_COPPER
@ BS_ITEM_TYPE_SILKSCREEN
@ BS_ITEM_TYPE_DIELECTRIC
@ BS_ITEM_TYPE_SOLDERMASK
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
#define CADSTAR_FONT_NAME
file: cadstar_archive_objects.h Contains common object definitions
#define COMPONENT_NAME_2_ATTRID
Component Name 2 Attribute ID - typically used for indicating the placement of designators in placeme...
#define COMPONENT_NAME_ATTRID
Component Name Attribute ID - typically used for placement of designators on silk screen.
#define PART_NAME_ATTRID
Loads a cpa file into a KiCad BOARD object.
#define UNDEFINED_PHYSICAL_LAYER
BASE_SET & reset(size_t pos)
Definition base_set.h:153
virtual bool SetNetCode(int aNetCode, bool aNoAssert)
Set net using a net code.
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
virtual void SetNet(NETINFO_ITEM *aNetInfo)
Set a NET_INFO object for the item.
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
NETINFO_ITEM * GetNet() const
Return NETINFO_ITEM object for a given item.
Container for design settings for a BOARD object.
std::shared_ptr< NET_SETTINGS > m_NetSettings
BOARD_STACKUP & GetStackupDescriptor()
void SetBoardThickness(int aThickness)
int GetLineThickness(PCB_LAYER_ID aLayer) const
Return the default graphic segment thickness from the layer class for the given layer.
Abstract interface for BOARD_ITEMs capable of storing other items inside.
virtual void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false)=0
Adds an item to the container.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
virtual BOARD_ITEM * Duplicate(bool addToParentGroup, BOARD_COMMIT *aCommit=nullptr) const
Create a copy of this BOARD_ITEM.
void SetLocked(bool aLocked) override
Definition board_item.h:441
bool IsLocked() const override
virtual void SetLayer(PCB_LAYER_ID aLayer)
Set the layer this item is on.
Definition board_item.h:397
int GetMaxError() const
Manage one layer needed to make a physical board.
void SetThickness(int aThickness, int aDielectricSubLayer=0)
void SetMaterial(const wxString &aName, int aDielectricSubLayer=0)
void SetLossTangent(double aTg, int aDielectricSubLayer=0)
void SetEpsilonR(double aEpsilon, int aDielectricSubLayer=0)
void SetLayerName(const wxString &aName)
Manage layers needed to make a physical board.
void RemoveAll()
Delete all items in list and clear the list.
const std::vector< BOARD_STACKUP_ITEM * > & GetList() const
int BuildBoardThicknessFromStackup() const
void BuildDefaultStackupList(const BOARD_DESIGN_SETTINGS *aSettings, int aActiveCopperLayersCount=0)
Create a default stackup, according to the current BOARD_DESIGN_SETTINGS settings.
static const std::map< TEXT_FIELD_NAME, wxString > CADSTAR_TO_KICAD_FIELDS
Map between CADSTAR fields and KiCad text variables.
TEXT_FIELD_NAME
These are special fields in text objects enclosed between the tokens '<@' and '>' such as <@[FIELD_NA...
@ NO_ALIGNMENT
NO_ALIGNMENT has different meaning depending on the object type.
static wxString ParseTextFields(const wxString &aTextString, PARSER_CONTEXT *aParserContext)
Replaces CADSTAR fields for the equivalent in KiCad and stores the field values in aParserContext.
wxString LAYER_ID
ID of a Sheet (if schematic) or board Layer (if PCB)
static void FixTextPositionNoAlignment(EDA_TEXT *aKiCadTextItem)
Correct the position of a text element that had NO_ALIGNMENT in CADSTAR.
@ OPENSHAPE
Unfilled open shape. Cannot have cutouts.
@ SOLID
Filled closed shape (solid fill).
@ HATCHED
Filled closed shape (hatch fill).
static const double TXT_HEIGHT_RATIO
CADSTAR fonts are drawn on a 24x24 integer matrix, where the each axis goes from 0 to 24.
void checkPoint()
Updates m_progressReporter or throws if user canceled.
@ DESIGN
Inherits from design units (assumed Assignments->Technology->Units)
PROGRESS_REPORTER * m_progressReporter
std::map< TEMPLATE_ID, ZONE * > m_zonesMap
Map between Cadstar and KiCad zones.
std::map< std::tuple< ROUTECODE_ID, NETCLASS_ID, SPACING_CLASS_ID >, std::shared_ptr< NETCLASS > > m_netClassMap
Map between Cadstar and KiCad classes.
bool m_doneCopperWarning
Used by loadCoppers() to avoid multiple duplicate warnings.
std::vector< std::unique_ptr< FOOTPRINT > > LoadFpLibrary()
Parse a CADSTAR PCB Archive and load the footprints contained within.
std::set< PADCODE_ID > m_padcodesTested
Used by getKiCadPad() to avoid multiple duplicate warnings.
void drawCadstarVerticesAsShapes(const std::vector< VERTEX > &aCadstarVertices, const PCB_LAYER_ID &aKiCadLayer, int aLineThickness, LINE_STYLE aLineStyle, BOARD_ITEM_CONTAINER *aContainer, const GROUP_ID &aCadstarGroupID=wxEmptyString, const VECTOR2I &aMoveVector={ 0, 0 }, double aRotationAngle=0.0, double aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, bool aMirrorInvert=false)
Uses PCB_SHAPE to draw the vertices on m_board object.
void initStackupItem(const LAYER &aCadstarLayer, BOARD_STACKUP_ITEM *aKiCadItem, int aDielectricSublayer)
int m_numCopperLayers
Number of layers in the design.
void reportError(const wxString &aMsg) const
Report an import issue the user can act on.
std::vector< LAYER_ID > m_powerPlaneLayers
List of layers that are marked as power plane in CADSTAR.
void drawCadstarText(const TEXT &aCadstarText, BOARD_ITEM_CONTAINER *aContainer, const GROUP_ID &aCadstarGroupID=wxEmptyString, const LAYER_ID &aCadstarLayerOverride=wxEmptyString, const VECTOR2I &aMoveVector={ 0, 0 }, double aRotationAngle=0.0, double aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, bool aMirrorInvert=false)
bool isLayerSet(const LAYER_ID &aCadstarLayerID)
LAYERPAIR getLayerPair(const LAYERPAIR_ID &aCadstarLayerPairID)
FOOTPRINT * getFootprintFromCadstarID(const COMPONENT_ID &aCadstarComponentID)
PADCODE getPadCode(const PADCODE_ID &aCadstarPadCodeID)
int loadNetVia(const NET_ID &aCadstarNetID, const NET_PCB::VIA &aCadstarVia)
Load via and return via size.
EDA_ANGLE getAngle(const long long &aCadstarAngle)
std::vector< PCB_SHAPE * > getShapesFromVertices(const std::vector< VERTEX > &aCadstarVertices, BOARD_ITEM_CONTAINER *aContainer=nullptr, const GROUP_ID &aCadstarGroupID=wxEmptyString, const VECTOR2I &aMoveVector={ 0, 0 }, double aRotationAngle=0.0, double aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, bool aMirrorInvert=false)
Returns a vector of pointers to PCB_SHAPE objects.
void applyTextCode(EDA_TEXT *aKiCadText, const TEXTCODE_ID &aCadstarTextCodeID)
Apply cadstar textcode parameters to a KiCad text object.
std::map< COMPONENT_ID, FOOTPRINT * > m_componentMap
Map between Cadstar and KiCad components on the board.
SHAPE_LINE_CHAIN getLineChainFromShapes(const std::vector< PCB_SHAPE * > &aShapes)
Returns a SHAPE_LINE_CHAIN object from a series of PCB_SHAPE objects.
std::map< PAD_ID, std::vector< PAD_ID > > ASSOCIATED_COPPER_PADS
Map of pad anchor points (first) to copper pads (second).
void applyDimensionSettings(const DIMENSION &aCadstarDim, PCB_DIMENSION_BASE *aKiCadDim)
ZONE * getZoneFromCadstarShape(const SHAPE &aCadstarShape, const int &aLineThickness, BOARD_ITEM_CONTAINER *aParentContainer)
void drawCadstarShape(const SHAPE &aCadstarShape, const PCB_LAYER_ID &aKiCadLayer, int aLineThickness, LINE_STYLE aLineStyle, const wxString &aShapeName, BOARD_ITEM_CONTAINER *aContainer, const GROUP_ID &aCadstarGroupID=wxEmptyString, const VECTOR2I &aMoveVector={ 0, 0 }, double aRotationAngle=0.0, double aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, bool aMirrorInvert=false)
PCB_LAYER_ID getKiCadCopperLayerID(unsigned int aLayerNum, bool aDetectMaxLayer=true)
void reportInfo(const wxString &aMsg) const
std::vector< PCB_TRACK * > makeTracksFromShapes(const std::vector< PCB_SHAPE * > &aShapes, BOARD_ITEM_CONTAINER *aParentContainer, NETINFO_ITEM *aNet=nullptr, PCB_LAYER_ID aLayerOverride=UNDEFINED_LAYER, int aWidthOverride=-1)
Returns a vector of pointers to TRACK/ARC objects.
VIACODE getViaCode(const VIACODE_ID &aCadstarViaCodeID)
VECTOR2I m_designCenter
Used for calculating the required offset to apply to the Cadstar design so that it fits in KiCad canv...
void Load(BOARD *aBoard, PROJECT *aProject)
Loads a CADSTAR PCB Archive file into the KiCad BOARD object given.
void drawCadstarCutoutsAsShapes(const std::vector< CUTOUT > &aCutouts, const PCB_LAYER_ID &aKiCadLayer, int aLineThickness, BOARD_ITEM_CONTAINER *aContainer, const GROUP_ID &aCadstarGroupID=wxEmptyString, const VECTOR2I &aMoveVector={ 0, 0 }, double aRotationAngle=0.0, double aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, bool aMirrorInvert=false)
Uses PCB_SHAPEs to draw the cutouts on m_board object.
void logBoardStackupWarning(const wxString &aCadstarLayerName, const PCB_LAYER_ID &aKiCadLayer)
VECTOR2I applyPadShape(PAD *aPad, PCB_LAYER_ID aPadLayer, const CADSTAR_PAD_SHAPE &aShape)
Apply a CADSTAR pad shape to a single layer of a KiCad padstack.
std::vector< FOOTPRINT * > GetLoadedLibraryFootpints() const
Return a copy of the loaded library footprints (caller owns the objects)
PCB_SHAPE * getShapeFromVertex(const POINT &aCadstarStartPoint, const VERTEX &aCadstarVertex, BOARD_ITEM_CONTAINER *aContainer=nullptr, const GROUP_ID &aCadstarGroupID=wxEmptyString, const VECTOR2I &aMoveVector={ 0, 0 }, double aRotationAngle=0.0, double aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, bool aMirrorInvert=false)
Returns a pointer to a PCB_SHAPE object.
void checkAndLogHatchCode(const HATCHCODE_ID &aCadstarHatchcodeID)
bool m_doneSpacingClassWarning
Used by getKiCadNet() to avoid multiple duplicate warnings.
int m_numNets
Number of nets loaded so far.
void loadLibraryPads(const SYMDEF_PCB &aComponent, FOOTPRINT *aFootprint)
PAD * getKiCadPad(const COMPONENT_PAD &aCadstarPad, FOOTPRINT *aParent)
NETINFO_ITEM * getKiCadNet(const NET_ID &aCadstarNetID)
Searches m_netMap and returns the NETINFO_ITEM pointer if exists.
void logBoardStackupMessage(const wxString &aCadstarLayerName, const PCB_LAYER_ID &aKiCadLayer)
int getLineThickness(const LINECODE_ID &aCadstarLineCodeID)
std::map< NET_ID, NETINFO_ITEM * > m_netMap
Map between Cadstar and KiCad Nets.
void loadComponentAttributes(const COMPONENT &aComponent, FOOTPRINT *aFootprint)
void loadNetTracks(const NET_ID &aCadstarNetID, const NET_PCB::ROUTE &aCadstarRoute, long aDefaultRouteWidth, long aStartWidth=std::numeric_limits< long >::max(), long aEndWidth=std::numeric_limits< long >::max())
PCB_GROUP * getKiCadGroup(const GROUP_ID &aCadstarGroupID)
bool m_logLayerWarnings
Used in loadBoardStackup()
HATCHCODE getHatchCode(const HATCHCODE_ID &aCadstarHatchcodeID)
void loadLibraryCoppers(const SYMDEF_PCB &aComponent, FOOTPRINT *aFootprint)
LAYER_TYPE getLayerType(const LAYER_ID aCadstarLayerID)
void loadLibraryFigures(const SYMDEF_PCB &aComponent, FOOTPRINT *aFootprint)
TEXTCODE getTextCode(const TEXTCODE_ID &aCadstarTextCodeID)
void reportWarning(const wxString &aMsg) const
wxString getAttributeName(const ATTRIBUTE_ID &aCadstarAttributeID)
int getKiCadOffset(long long aCadstarLength)
wxString getAttributeValue(const ATTRIBUTE_ID &aCadstarAttributeID, const std::map< ATTRIBUTE_ID, ATTRIBUTE_VALUE > &aCadstarAttributeMap)
void applyRouteOffset(VECTOR2I *aPointToOffset, const VECTOR2I &aRefPoint, const long &aOffsetAmount)
CADSTAR's Post Processor does an action called "Route Offset" which is applied when a route is wider ...
VECTOR2I getKiCadPoint(const VECTOR2I &aCadstarPoint)
Scales, offsets and inverts y axis to make the point usable directly in KiCad.
void remapUnsureLayers()
Callback m_layerMappingHandler for layers we aren't sure of.
double getAngleTenthDegree(const long long &aCadstarAngle)
LSET getKiCadLayerSet(const LAYER_ID &aCadstarLayerID)
void addToGroup(const GROUP_ID &aCadstarGroupID, BOARD_ITEM *aKiCadItem)
std::map< SYMDEF_ID, FOOTPRINT * > m_libraryMap
Map between Cadstar and KiCad components in the library.
COPPERCODE getCopperCode(const COPPERCODE_ID &aCadstaCopperCodeID)
SHAPE_POLY_SET getPolySetFromCadstarShape(const SHAPE &aCadstarShape, int aLineThickness=-1, BOARD_ITEM_CONTAINER *aContainer=nullptr, const VECTOR2I &aMoveVector={ 0, 0 }, double aRotationAngle=0.0, double aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, bool aMirrorInvert=false)
Returns a SHAPE_POLY_SET object from a Cadstar SHAPE.
EDA_ANGLE getHatchCodeAngle(const HATCHCODE_ID &aCadstarHatchcodeID)
int getKiCadHatchCodeThickness(const HATCHCODE_ID &aCadstarHatchcodeID)
PCB_LAYER_ID getKiCadLayer(const LAYER_ID &aCadstarLayerID)
std::set< HATCHCODE_ID > m_hatchcodesTested
Used by checkAndLogHatchCode() to avoid multiple duplicate warnings.
void loadLibraryAreas(const SYMDEF_PCB &aComponent, FOOTPRINT *aFootprint)
GROUP_ID createUniqueGroupID(const wxString &aName)
Adds a new PCB_GROUP* to m_groupMap.
LINE_STYLE getLineStyle(const LINECODE_ID &aCadstarLineCodeID)
int getKiCadHatchCodeGap(const HATCHCODE_ID &aCadstarHatchcodeID)
ROUTECODE getRouteCode(const ROUTECODE_ID &aCadstarRouteCodeID)
int getKiCadLength(long long aCadstarLength, double aDefaultInMM)
void addAttribute(const ATTRIBUTE_LOCATION &aCadstarAttrLoc, const ATTRIBUTE_ID &aCadstarAttributeID, FOOTPRINT *aFootprint, const wxString &aAttributeValue)
Adds a CADSTAR Attribute to a KiCad footprint.
std::map< GROUP_ID, PCB_GROUP * > m_groupMap
Map between Cadstar and KiCad groups.
bool calculateZonePriorities(PCB_LAYER_ID &aLayer)
Tries to make a best guess as to the zone priorities based on the pour status.
std::map< LAYER_ID, PCB_LAYER_ID > m_layermap
Map between Cadstar and KiCad Layers.
PAD *& getPadReference(FOOTPRINT *aFootprint, const PAD_ID aCadstarPadID)
bool m_doneNetClassWarning
Used by getKiCadNet() to avoid multiple duplicate warnings.
double getAngleDegrees(const long long &aCadstarAngle)
PART getPart(const PART_ID &aCadstarPartID)
LAYER_MAPPING_HANDLER m_layerMappingHandler
Callback to get layer mapping.
std::map< SYMDEF_ID, ASSOCIATED_COPPER_PADS > m_librarycopperpads
Associated copper pads (if any) for each component library definition.
long PAD_ID
Pad identifier (pin) in the PCB.
void Parse(bool aLibrary=false)
Parses the file.
int KiCadUnitMultiplier
Use this value to convert units in this CPA file to KiCad units.
@ ALLELEC
Inbuilt layer type (cannot be assigned to user layers)
@ ALLDOC
Inbuilt layer type (cannot be assigned to user layers)
@ NOLAYER
Inbuilt layer type (cannot be assigned to user layers)
@ JUMPERLAYER
Inbuilt layer type (cannot be assigned to user layers)
@ ALLLAYER
Inbuilt layer type (cannot be assigned to user layers)
@ ASSCOMPCOPP
Inbuilt layer type (cannot be assigned to user layers)
@ MAXIMUM
The highest PHYSICAL_LAYER_ID currently defined (i.e.
@ THROUGH_HOLE
All physical layers currently defined.
EDA_ANGLE NormalizeNegative()
Definition eda_angle.h:247
double Sin() const
Definition eda_angle.h:177
EDA_ANGLE Normalize180()
Definition eda_angle.h:273
double Cos() const
Definition eda_angle.h:196
void AddItem(EDA_ITEM *aItem)
Add item to group.
Definition eda_group.cpp:58
void SetName(const wxString &aName)
Definition eda_group.h:76
void SetFillMode(FILL_T aFill)
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
virtual void SetTextSize(VECTOR2I aNewSize, bool aEnforceMinTextSize=true)
Definition eda_text.cpp:513
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
virtual void SetTextPos(const VECTOR2I &aPoint)
Definition eda_text.cpp:557
void SetMirrored(bool isMirrored)
Definition eda_text.cpp:355
void SetVertJustify(GR_TEXT_V_ALIGN_T aType)
Definition eda_text.cpp:379
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
void MigrateLegacyBoldStrokeWidth()
Migrate a pre-v11 bold stroke text so its stored thickness holds the base (non-bold) width.
Definition eda_text.cpp:333
virtual void SetTextThickness(int aWidth)
The TextThickness is that set by the user.
Definition eda_text.cpp:251
void SetBold(bool aBold)
Set the text to be bold - this will also update the font if needed.
Definition eda_text.cpp:311
void SetKeepUpright(bool aKeepUpright)
Definition eda_text.cpp:387
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
void SetItalic(bool aItalic)
Set the text to be italic - this will also update the font if needed.
Definition eda_text.cpp:291
void SetFont(KIFONT::FONT *aFont)
Definition eda_text.cpp:472
void SetHorizJustify(GR_TEXT_H_ALIGN_T aType)
Definition eda_text.cpp:371
void SetPosition(const VECTOR2I &aPos) override
void SetFPID(const LIB_ID &aFPID)
Definition footprint.h:418
void SetOrientation(const EDA_ANGLE &aNewAngle)
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:831
std::deque< PAD * > & Pads()
Definition footprint.h:355
void SetReference(const wxString &aReference)
Definition footprint.h:799
void SetValue(const wxString &aValue)
Definition footprint.h:822
PCB_FIELD & Reference()
Definition footprint.h:832
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Adds an item to the container.
void AutoPositionFields()
Position Reference and Value fields at the top and bottom of footprint's bounding box.
void Flip(const VECTOR2I &aCentre, FLIP_DIRECTION aFlipDirection) override
Flip this object, i.e.
BOARD_ITEM * Duplicate(bool addToParentGroup, BOARD_COMMIT *aCommit=nullptr) const override
Create a copy of this BOARD_ITEM.
void SetLibDescription(const wxString &aDesc)
Definition footprint.h:450
const wxString & GetReference() const
Definition footprint.h:793
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
static FONT * GetFont(const wxString &aFontName=wxEmptyString, bool aBold=false, bool aItalic=false, const std::vector< wxString > *aEmbeddedFiles=nullptr, bool aForDrawingSheet=false)
Definition font.cpp:144
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
Definition lib_id.cpp:65
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
LSEQ is a sequence (and therefore also a set) of PCB_LAYER_IDs.
Definition lseq.h:47
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
static const LSET & AllBoardTechMask()
Return a mask holding board technical layers (no CU layer) on both side.
Definition lset.cpp:679
static const LSET & AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
Definition lset.cpp:604
static const LSET & UserMask()
Definition lset.cpp:686
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
static const LSET & AllLayersMask()
Definition lset.cpp:637
static LSET UserDefinedLayersMask(int aUserDefinedLayerCount=MAX_USER_DEFINED_LAYERS)
Return a mask with the requested number of user defined layers.
Definition lset.cpp:700
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:184
bool Contains(PCB_LAYER_ID aLayer) const
See if the layer set contains a PCB layer.
Definition lset.h:63
Handle the data for a net.
Definition netinfo.h:50
void SetNetClass(const std::shared_ptr< NETCLASS > &aNetClass)
std::shared_ptr< NETCLASS > GetDefaultNetclass() const
Gets the default netclass for the project.
@ NORMAL
Shape is the same on all layers.
Definition padstack.h:175
@ CUSTOM
Shapes can be defined on arbitrary layers.
Definition padstack.h:177
static constexpr PCB_LAYER_ID ALL_LAYERS
! The layer identifier to use for the single defintion on normal padstacks
Definition padstack.h:184
static constexpr PCB_LAYER_ID TEMP_ALL_LAYERS
! Temporary layer identifier to identify code that is not padstack-aware
Definition padstack.h:181
Definition pad.h:61
const wxString & GetNumber() const
Definition pad.h:143
void SetShape(PCB_LAYER_ID aLayer, PAD_SHAPE aShape)
Set the new shape of this pad.
Definition pad.h:196
void SetNumber(const wxString &aNumber)
Set the pad number (note that it can be alphanumeric, such as the array reference "AA12").
Definition pad.h:142
void SetChamferRectRatio(PCB_LAYER_ID aLayer, double aChamferScale)
Has meaning only for chamfered rectangular pads.
Definition pad.cpp:1103
void SetSize(PCB_LAYER_ID aLayer, const VECTOR2I &aSize)
Definition pad.cpp:264
void SetRoundRectCornerRadius(PCB_LAYER_ID aLayer, double aRadius)
Definition pad.cpp:1059
void SetChamferPositions(PCB_LAYER_ID aLayer, int aPositions)
Has meaning only for chamfered rectangular pads.
Definition pad.h:873
void SetRoundRectRadiusRatio(PCB_LAYER_ID aLayer, double aRadiusScale)
Has meaning only for rounded rectangle pads.
Definition pad.cpp:1065
Abstract dimension API.
virtual void SetEnd(const VECTOR2I &aPoint)
void SetUnitsFormat(const DIM_UNITS_FORMAT aFormat)
virtual void SetStart(const VECTOR2I &aPoint)
void SetPrefix(const wxString &aPrefix)
void SetExtensionOffset(int aOffset)
void SetSuffix(const wxString &aSuffix)
void SetLineThickness(int aWidth)
void SetPrecision(DIM_PRECISION aPrecision)
void SetOverrideText(const wxString &aValue)
virtual VECTOR2I GetStart() const
The dimension's origin is the first feature point for the dimension.
void SetUnitsMode(DIM_UNITS_MODE aMode)
For better understanding of the points that make a dimension:
void SetExtensionHeight(int aHeight)
void SetHeight(int aHeight)
Set the distance from the feature points to the crossbar line.
A leader is a dimension-like object pointing to a specific point.
An orthogonal dimension is like an aligned dimension, but the extension lines are locked to the X or ...
void SetOrientation(DIR aOrientation)
Set the orientation of the dimension line (so, perpendicular to the feature lines).
A set of BOARD_ITEMs (i.e., without duplicates).
Definition pcb_group.h:51
void SetLocked(bool aLocked) override
void SetCenter(const VECTOR2I &aCenter) override
void Rotate(const VECTOR2I &aRotCentre, const EDA_ANGLE &aAngle) override
Rotate this object.
void SetArcAngleAndEnd(const EDA_ANGLE &aAngle, bool aCheckNegativeAngle=false)
Definition pcb_shape.h:109
void SetEnd(const VECTOR2I &aEnd) override
void Flip(const VECTOR2I &aCentre, FLIP_DIRECTION aFlipDirection) override
Flip this object, i.e.
void SetPolyShape(const SHAPE_POLY_SET &aShape) override
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
void Move(const VECTOR2I &aMoveVector) override
Move this object.
void SetStart(const VECTOR2I &aStart) override
void Scale(double aScale)
void SetStroke(const STROKE_PARAMS &aStroke) override
void SetTextThickness(int aWidth) override
The TextThickness is that set by the user.
Definition pcb_text.cpp:514
void Flip(const VECTOR2I &aCentre, FLIP_DIRECTION aFlipDirection) override
Flip this object, i.e.
Definition pcb_text.cpp:643
EDA_ANGLE GetTextAngle() const override
Definition pcb_text.cpp:562
void SetTextSize(VECTOR2I aNewSize, bool aEnforceMinTextSize=true) override
Definition pcb_text.cpp:486
void SetPosition(const VECTOR2I &aPos) override
Definition pcb_text.h:103
void Move(const VECTOR2I &aMoveVector) override
Move this object.
Definition pcb_text.h:105
int GetTextThickness() const override
Definition pcb_text.cpp:499
void SetTextAngle(const EDA_ANGLE &aAngle) override
Definition pcb_text.cpp:574
VECTOR2I GetTextSize() const override
Definition pcb_text.cpp:472
void SetEnd(const VECTOR2I &aEnd)
Definition pcb_track.h:96
void SetStart(const VECTOR2I &aStart)
Definition pcb_track.h:99
const VECTOR2I & GetStart() const
Definition pcb_track.h:100
const VECTOR2I & GetEnd() const
Definition pcb_track.h:97
virtual void SetWidth(int aWidth)
Definition pcb_track.h:93
virtual int GetWidth() const
Definition pcb_track.h:94
Container for project specific data.
Definition project.h:63
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
void Reverse()
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
virtual const VECTOR2I GetPoint(int aIndex) const override
void SetClosed(bool aClosed)
Mark the line chain as closed (i.e.
int PointCount() const
Return the number of points (vertices) in this line chain.
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
Represent a set of closed polygons.
void BooleanAdd(const SHAPE_POLY_SET &b)
Perform boolean polyset union.
void ClearArcs()
Removes all arc references from all the outlines and holes in the polyset.
double Area()
Return the area of this poly set.
void Inflate(int aAmount, CORNER_STRATEGY aCornerStrategy, int aMaxError, bool aSimplify=false)
Perform outline inflation/deflation.
int HoleCount(int aOutline) const
Returns the number of holes in a given outline.
int AddHole(const SHAPE_LINE_CHAIN &aHole, int aOutline=-1)
Adds a new hole to the given outline (default: last) and returns its index.
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
SHAPE_LINE_CHAIN & Hole(int aOutline, int aHole)
Return the reference to aHole-th hole in the aIndex-th outline.
void BooleanIntersection(const SHAPE_POLY_SET &b)
Perform boolean polyset intersection.
int OutlineCount() const
Return the number of outlines in the set.
void Move(const VECTOR2I &aVector) override
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.
virtual VECTOR2I GetStart() const
Definition shape.h:296
Simple container to manage line stroke parameters.
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition vector2d.h:281
VECTOR2< T > Resize(T aNewLength) const
Return a vector of the same direction, but length specified in aNewLength.
Definition vector2d.h:406
Handle a list of polygons defining a copper zone.
Definition zone.h:70
void SetHatchThickness(int aThickness)
Definition zone.h:326
void SetNeedRefill(bool aNeedRefill)
Definition zone.h:310
void SetDoNotAllowPads(bool aEnable)
Definition zone.h:860
std::optional< int > GetLocalClearance() const override
Definition zone.cpp:1099
void SetLocalClearance(std::optional< int > aClearance)
Definition zone.h:183
void AddPolygon(std::vector< VECTOR2I > &aPolygon)
Add a polygon to the zone outline.
Definition zone.cpp:1502
std::shared_ptr< SHAPE_POLY_SET > GetFilledPolysList(PCB_LAYER_ID aLayer) const
Definition zone.h:701
void SetMinThickness(int aMinThickness)
Definition zone.h:316
void SetHatchOrientation(const EDA_ANGLE &aStep)
Definition zone.h:332
void SetThermalReliefSpokeWidth(int aThermalReliefSpokeWidth)
Definition zone.h:251
virtual void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
Definition zone.cpp:677
SHAPE_POLY_SET * Outline()
Definition zone.h:421
void SetHatchStyle(ZONE_BORDER_DISPLAY_STYLE aStyle)
Definition zone.h:690
SHAPE_POLY_SET * GetFill(PCB_LAYER_ID aLayer)
Definition zone.h:708
void SetIsRuleArea(bool aEnable)
Definition zone.h:835
void SetDoNotAllowTracks(bool aEnable)
Definition zone.h:859
void SetFilledPolysList(PCB_LAYER_ID aLayer, const SHAPE_POLY_SET &aPolysList)
Set the list of filled polygons.
Definition zone.h:748
void SetIsFilled(bool isFilled)
Definition zone.h:307
void SetFillMode(ZONE_FILL_MODE aFillMode)
Definition zone.cpp:683
bool HasFilledPolysForLayer(PCB_LAYER_ID aLayer) const
Definition zone.h:692
void SetLayerSet(const LSET &aLayerSet) override
Definition zone.cpp:702
void SetDoNotAllowVias(bool aEnable)
Definition zone.h:858
void SetNet(NETINFO_ITEM *aNetInfo) override
Override that drops aNetInfo when this zone is in copper-thieving fill mode.
Definition zone.cpp:668
void SetThermalReliefGap(int aThermalReliefGap)
Definition zone.h:240
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
void SetDoNotAllowFootprints(bool aEnable)
Definition zone.h:861
void SetDoNotAllowZoneFills(bool aEnable)
Definition zone.h:857
void SetAssignedPriority(unsigned aPriority)
Definition zone.h:117
void SetPadConnection(ZONE_CONNECTION aPadConnection)
Definition zone.h:313
void SetZoneName(const wxString &aName)
Definition zone.h:161
void SetIslandRemovalMode(ISLAND_REMOVAL_MODE aRemove)
Definition zone.h:864
void SetMinIslandArea(long long int aArea)
Definition zone.h:867
void SetHatchGap(int aStep)
Definition zone.h:329
static REPORTER & GetReporter()
Get the current reporter used for font substitution warnings.
void TransformArcToPolygon(SHAPE_POLY_SET &aBuffer, const VECTOR2I &aStart, const VECTOR2I &aMid, const VECTOR2I &aEnd, int aWidth, int aError, ERROR_LOC aErrorLoc)
Convert arc to multiple straight segments.
void TransformOvalToPolygon(SHAPE_POLY_SET &aBuffer, const VECTOR2I &aStart, const VECTOR2I &aEnd, int aWidth, int aError, ERROR_LOC aErrorLoc, int aMinSegCount=0)
Convert a oblong shape to a polygon, using multiple segments.
@ ROUND_ALL_CORNERS
All angles are rounded.
#define _(s)
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
@ TENTHS_OF_A_DEGREE_T
Definition eda_angle.h:29
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:476
@ REVERSE_HATCH
Definition eda_fill.h:35
@ HATCH
Definition eda_fill.h:34
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
#define IGNORE_PARENT_GROUP
Definition eda_item.h:55
@ SEGMENT
Definition eda_shape.h:57
#define DEFAULT_SIZE_TEXT
This is the "default-of-the-default" hardcoded text size; individual application define their own def...
Definition eda_text.h:84
#define THROW_IO_ERRORF(msg,...)
#define KICAD_FONT_NAME
bool IsCopperLayer(int aLayerId)
Test whether a layer is a copper layer.
Definition layer_ids.h:744
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ In22_Cu
Definition layer_ids.h:83
@ In11_Cu
Definition layer_ids.h:72
@ In29_Cu
Definition layer_ids.h:90
@ In30_Cu
Definition layer_ids.h:91
@ User_8
Definition layer_ids.h:127
@ F_CrtYd
Definition layer_ids.h:112
@ In17_Cu
Definition layer_ids.h:78
@ B_Adhes
Definition layer_ids.h:99
@ Edge_Cuts
Definition layer_ids.h:108
@ Dwgs_User
Definition layer_ids.h:103
@ F_Paste
Definition layer_ids.h:100
@ In9_Cu
Definition layer_ids.h:70
@ Cmts_User
Definition layer_ids.h:104
@ User_6
Definition layer_ids.h:125
@ User_7
Definition layer_ids.h:126
@ In19_Cu
Definition layer_ids.h:80
@ In7_Cu
Definition layer_ids.h:68
@ In28_Cu
Definition layer_ids.h:89
@ In26_Cu
Definition layer_ids.h:87
@ F_Adhes
Definition layer_ids.h:98
@ B_Mask
Definition layer_ids.h:94
@ B_Cu
Definition layer_ids.h:61
@ User_5
Definition layer_ids.h:124
@ Eco1_User
Definition layer_ids.h:105
@ F_Mask
Definition layer_ids.h:93
@ In21_Cu
Definition layer_ids.h:82
@ In23_Cu
Definition layer_ids.h:84
@ B_Paste
Definition layer_ids.h:101
@ In15_Cu
Definition layer_ids.h:76
@ In2_Cu
Definition layer_ids.h:63
@ User_9
Definition layer_ids.h:128
@ F_Fab
Definition layer_ids.h:115
@ In10_Cu
Definition layer_ids.h:71
@ F_SilkS
Definition layer_ids.h:96
@ In4_Cu
Definition layer_ids.h:65
@ B_CrtYd
Definition layer_ids.h:111
@ UNDEFINED_LAYER
Definition layer_ids.h:57
@ Eco2_User
Definition layer_ids.h:106
@ In16_Cu
Definition layer_ids.h:77
@ In24_Cu
Definition layer_ids.h:85
@ In1_Cu
Definition layer_ids.h:62
@ User_3
Definition layer_ids.h:122
@ User_1
Definition layer_ids.h:120
@ B_SilkS
Definition layer_ids.h:97
@ In13_Cu
Definition layer_ids.h:74
@ User_4
Definition layer_ids.h:123
@ In8_Cu
Definition layer_ids.h:69
@ In14_Cu
Definition layer_ids.h:75
@ User_2
Definition layer_ids.h:121
@ In12_Cu
Definition layer_ids.h:73
@ In27_Cu
Definition layer_ids.h:88
@ In6_Cu
Definition layer_ids.h:67
@ In5_Cu
Definition layer_ids.h:66
@ In3_Cu
Definition layer_ids.h:64
@ In20_Cu
Definition layer_ids.h:81
@ F_Cu
Definition layer_ids.h:60
@ In18_Cu
Definition layer_ids.h:79
@ In25_Cu
Definition layer_ids.h:86
@ B_Fab
Definition layer_ids.h:114
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
@ LEFT_RIGHT
Flip left to right (around the Y axis)
Definition mirror.h:27
constexpr int Mils2IU(const EDA_IU_SCALE &aIuScale, int mils)
Definition eda_units.h:169
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
@ NPTH
like PAD_PTH, but not plated mechanical use only, no connection allowed
Definition padstack.h:104
@ SMD
Smd pad, appears on the solder paste layer (default)
Definition padstack.h:100
@ PTH
Plated through hole pad.
Definition padstack.h:99
@ CHAMFERED_RECT
Definition padstack.h:61
@ ROUNDRECT
Definition padstack.h:58
@ RECTANGLE
Definition padstack.h:55
DIM_PRECISION
Class to handle a set of BOARD_ITEMs.
#define KEY_PREPREG
#define KEY_CORE
LINE_STYLE
Dashed line types.
ALIGNMENT Alignment
In CADSTAR The default alignment for a TEXT object (when "(No Alignment()" is selected) Bottom Left o...
bool HasLocation
Flag to know if this ATTRIBUTE_VALUE has a location i.e.
Represent a cutout in a closed shape (e.g.
long ScaleRatioNumerator
Documentation symbols can be arbitrarily scaled when added to a design.
long ScaleRatioDenominator
Documentation symbols can be arbitrarily scaled when added to a design.
POINT Origin
Origin of the component (this is used as the reference point when placing the component in the design...
LAYER_ID LayerID
Move all objects in the Symdef to this layer.
SYMDEF_ID SymdefID
Normally documentation symbols only have TEXT, FIGURE and TEXT_LOCATION objects which are all drawn o...
SHAPE Shape
Uses the component's coordinate frame if within a component definition, otherwise uses the design's c...
GROUP_ID GroupID
If not empty, this FIGURE is part of a group.
long Modifier1
It seems this is related to weight. 400=Normal, 700=Bold.
GROUP_ID GroupID
If not empty, this GROUP is part of another GROUP.
ROUTECODE_ID RouteCodeID
"NETCODE" subnode
wxString Name
This is undefined (wxEmptyString) if the net is unnamed.
NETCLASS_ID NetClassID
The net might not have a net class, in which case it will be wxEmptyString subnode="NETCLASSREF".
SPACING_CLASS_ID SpacingClassID
The net might not have a spacing class, in which case it will be wxEmptyString subnode="SPACINGCLASS"...
long SignalNum
This is undefined if the net has been given a name.
wxString Name
This name can be different to the PART name.
std::map< PART_DEFINITION_PIN_ID, PIN > Pins
Represent a point in x,y coordinates.
wxString HatchCodeID
Only Applicable for HATCHED Type.
std::vector< CUTOUT > Cutouts
Not Applicable to OPENSHAPE Type.
std::map< FIGURE_ID, FIGURE > Figures
POINT Origin
Origin of the component (this is used as the reference point when placing the component in the design...
wxString Alternate
This is in addition to ReferenceName.
wxString ReferenceName
This is the name which identifies the symbol in the library.
long Width
Defaults to 0 if using system fonts or, if using CADSTAR font, defaults to equal height (1:1 aspect r...
ALIGNMENT Alignment
In CADSTAR The default alignment for a TEXT object (when "(No Alignment)" is selected) Bottom Left of...
< Nodename = "VARIANT" or "VMASTER" (master variant
Represents a vertex in a shape.
From CADSTAR Help: "Area is for creating areas within which, and nowhere else, certain operations are...
bool Keepout
From CADSTAR Help: "Auto Placement cannot place components within this area.
bool Placement
From CADSTAR Help: "Auto Placement can place components within this area.
bool NoVias
From CADSTAR Help: "No vias will be placed within this area by the automatic router.
bool Routing
From CADSTAR Help: "Area can be used to place routes during Automatic Routing.
bool NoTracks
From CADSTAR Help: "Area cannot be used to place routes during automatic routing.
GROUP_ID GroupID
Normally CADSTAR_BOARD cannot be part of a reuseblock, but included for completeness.
From CADSTAR Help: "Area is for creating areas within which, and nowhere else, certain operations are...
bool NoVias
From CADSTAR Help: "Check this button to specify that any area created by the Rectangle,...
bool NoTracks
From CADSTAR Help: "Check this button to specify that any area created by the Rectangle,...
A shape of copper in the component footprint.
bool PCBonlyPad
From CADSTAR Help: "The PCB Only Pad property can be used to stop ECO Update, Back Annotation,...
POINT Position
Pad position within the component's coordinate frame.
wxString Identifier
This is an identifier that is displayed to the user.
std::map< ATTRIBUTE_ID, ATTRIBUTE_VALUE > AttributeValues
std::map< ATTRIBUTE_ID, TEXT_LOCATION > TextLocations
This contains location of any attributes, including designator position.
TEMPLATE_ID PouredTemplateID
If not empty, it means this COPPER is part of a poured template.
long Overshoot
Overshoot of the extension line past the arrow line.
long LeaderLineExtensionLength
Only for TYPE=LEADERLINE Length of the horizontal part of the leader line [param6].
long LeaderLineLength
Only for TYPE=LEADERLINE Length of the angled part of the leader line [param5].
long LeaderAngle
Only for TYPE=LEADERLINE subnode "LEADERANG".
Linear, leader (radius/diameter) or angular dimension.
LAYER_ID LayerID
ID on which to draw this [param1].
EXTENSION_LINE ExtensionLineParams
Not applicable to TYPE=LEADERDIM.
DIMENSION_ID ID
Some ID (doesn't seem to be used) subnode="DIMREF".
long Precision
Number of decimal points to display in the measurement [param3].
PHYSICAL_LAYER_ID PhysicalLayer
If UNDEFINED, no physical layer is assigned (e.g.
long Thickness
Note: Units of length are defined in file header.
std::map< NETELEMENT_ID, JUNCTION_PCB > Junctions
long ReliefWidth
if undefined inherits from design
std::map< LAYER_ID, CADSTAR_PAD_SHAPE > Reassigns
long ReliefClearance
if undefined inherits from design
PADCODE_ID PadCode
If not empty, override padcode.
std::map< PAD_ID, COMPONENT_PAD > ComponentPads
std::vector< COMPONENT_COPPER > ComponentCoppers
std::map< COMP_AREA_ID, COMPONENT_AREA > ComponentAreas
long AdditionalIsolation
This is the gap to apply in routes and pads in addition to the existing pad-to-copper or route-to-cop...
bool ThermalReliefOnVias
false when subnode "NOVIARELIEF" is present
HATCHCODE_ID HatchCodeID
Only for FillType = HATCHED.
bool ThermalReliefOnPads
false when subnode "NOPINRELIEF" is present
long ThermalReliefPadsAngle
Orientation for the thermal reliefs.
long MinDisjointCopper
The value is the length of one side of a notional square.
bool AutomaticRepour
true when subnode "REGENERATE" is present
bool AllowInNoRouting
true when subnode "IGNORETRN" is present
bool BoxIsolatedPins
true when subnode "BOXPINS" is present
long ClearanceWidth
Specifies the space around pads when pouring (i.e.
COPPERCODE_ID ReliefCopperCodeID
From CADSTAR Help: "Relief Copper Code is forselecting the width of line used to draw thethermal reli...
COPPERCODE_ID CopperCodeID
From CADSTAR Help: "Copper Code is for selecting the width of the line used to draw the outline and f...
long ThermalReliefViasAngle
Disabled when !ThermalReliefOnVias (param6)
long MinIsolatedCopper
The value is the length of one side of a notional square.
long SliverWidth
Minimum width of copper that may be created.
Templates are CADSTAR's equivalent to a "filled zone".
POURING Pouring
Copper pour settings (e.g. relief / hatching /etc.)
std::map< LAYER_ID, CADSTAR_PAD_SHAPE > Reassigns
Describes an imported layer and how it could be mapped to KiCad Layers.
PCB_LAYER_ID AutoMapLayer
Best guess as to what the equivalent KiCad layer might be.
LSET PermittedLayers
KiCad layers that the imported layer can be mapped onto.
wxString Name
Imported layer name as displayed in original application.
@ USER
The field ID hasn't been set yet; field is invalid.
static void addTrack(BOARD &aBoard, int aNetCode, PCB_LAYER_ID aLayer, const VECTOR2I &aStart, const VECTOR2I &aEnd)
KIBIS_COMPONENT * comp
KIBIS_PIN * pin
bool cw
int clearance
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
@ 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)
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
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition typeinfo.h:94
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
static PIECE polygon(std::vector< VIA_CROSS_SECTION_GEOMETRY::POINT > aPoints, bool aMixed=false)
@ THERMAL
Use thermal relief for pads.
Definition zones.h:46
@ FULL
pads are covered by copper
Definition zones.h:47