KiCad PCB EDA Suite
Loading...
Searching...
No Matches
cadstar_sch_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
28
29#include <bus_alias.h>
30#include <core/mirror.h>
31#include <core/kicad_algo.h>
32#include <eda_text.h>
33#include <macros.h>
34#include <progress_reporter.h>
35#include <string_utils.h>
36#include <sch_bus_entry.h>
37#include <sch_edit_frame.h> //SYMBOL_ORIENTATION_T
38#include <sch_io/sch_io_mgr.h>
40#include <sch_junction.h>
41#include <sch_line.h>
42#include <sch_screen.h>
43#include <sch_shape.h>
44#include <sch_sheet.h>
45#include <sch_sheet_path.h>
46#include <sch_sheet_pin.h>
47#include <sch_label.h>
48#include <schematic.h>
49#include <sim/sim_model.h>
50#include <trigo.h>
52
53
54const wxString PartNameFieldName = "Part Name";
55const wxString PartNumberFieldName = "Part Number";
56const wxString PartVersionFieldName = "Part Version";
57const wxString PartAcceptanceFieldName = "Part Acceptance";
58
59
60wxString CADSTAR_SCH_ARCHIVE_LOADER::CreateLibName( const wxFileName& aFileName,
61 const SCH_SHEET* aRootSheet )
62{
63 wxString libName = aFileName.GetName();
64
65 if( libName.IsEmpty() && aRootSheet )
66 {
67 wxFileName fn( aRootSheet->GetFileName() );
68 libName = fn.GetName();
69 }
70
71 if( libName.IsEmpty() )
72 libName = "noname";
73
74 libName = LIB_ID::FixIllegalChars( libName, true ).wx_str();
75
76 return libName;
77}
78
79
80std::vector<LIB_SYMBOL*> CADSTAR_SCH_ARCHIVE_LOADER::LoadPartsLib( const wxString& aFilename )
81{
83 m_progressReporter->SetNumPhases( 3 ); // (0) Read csa, (1) Parse csa, (3) Load lib
84
85 Parse();
86
88
89 if( !p.CheckFileHeader( aFilename.utf8_string() ) )
90 THROW_IO_ERROR( _( "File does not appear to be a CADSTAR parts Library file" ) );
91
92 // TODO: we could add progress reporting for reading .lib
93 CADSTAR_PARTS_LIB_MODEL csLib = p.ReadFile( aFilename.utf8_string() );
94
96 {
97 m_progressReporter->BeginPhase( 2 );
98 long numSteps = csLib.m_PartEntries.size();
99 m_progressReporter->SetMaxProgress( numSteps );
100 }
101
102 std::vector<LIB_SYMBOL*> retVal;
103
104 for( const CADSTAR_PART_ENTRY& part : csLib.m_PartEntries )
105 {
106 std::unique_ptr<LIB_SYMBOL> loadedPart = loadLibPart( part );
107
108 checkPoint();
109
110 if( loadedPart )
111 retVal.push_back( loadedPart.release() );
112 }
113
114 return retVal;
115}
116
117
118std::unique_ptr<LIB_SYMBOL>
120{
121 wxString escapedPartName = EscapeString( aPart.m_Name, CTX_LIBID );
122 std::unique_ptr<LIB_SYMBOL> retSym;
123
124 int unit = 0;
125
126 for( const CADSTAR_PART_SYMBOL_ENTRY& sym : aPart.m_Symbols )
127 {
128 ++unit;
129 wxString alternateName = sym.m_SymbolAlternateName.value_or( "" );
130 SYMDEF_ID symbolID = getSymDefFromName( sym.m_SymbolName, alternateName );
131
132 if( !Library.SymbolDefinitions.count( symbolID ) )
133 {
134 m_reporter->Report( wxString::Format( _( "Unable to find symbol %s, referenced by part "
135 "%s. The part was not loaded." ),
136 generateLibName( sym.m_SymbolName, alternateName ),
137 aPart.m_Name ),
139
140 return nullptr;
141 }
142
143 // Load the graphical symbol for this gate
144 std::unique_ptr<LIB_SYMBOL> kiSymDef( loadSymdef( symbolID )->Duplicate() );
145
146 if( (int)sym.m_Pins.size() != kiSymDef->GetPinCount() )
147 {
148 m_reporter->Report( wxString::Format( _( "Inconsistent pin numbers in symbol %s "
149 "compared to the one defined in part %s. The "
150 "part was not loaded." ),
151 generateLibName( sym.m_SymbolName, alternateName ),
152 aPart.m_Name ),
154
155 return nullptr;
156 }
157
158 wxASSERT( m_symDefTerminalsMap.count( symbolID ) ); //loadSymDef should have populated this
159
160
161 // Update the pin numbers to match those defined in the Cadstar part
162 for( auto& [storedPinNum, termID] : m_symDefTerminalsMap[symbolID] )
163 {
164 wxCHECK( termID > 0 && sym.m_Pins.size() >= size_t( termID ), nullptr );
165 std::vector<SCH_PIN*> pins = kiSymDef->GetPinsByNumber( storedPinNum );
166 size_t termIdx = size_t( termID ) - 1;
167
168 // For now leave numerical pin number. Otherwise, when loading the
169 // .cpa file we won't be able to link up to the footprint pads, but if
170 // we solve this, we could then load alphanumeric pin numbers as below:
171 //
172 // if( aPart.m_PinNamesMap.count( termID ) )
173 // partPinNum = wxString( aPart.m_PinNamesMap.at( termID ) );
174 //
175 wxString partPinNum = wxString::Format( "%ld", sym.m_Pins[termIdx].m_Identifier );
176
177 for( SCH_PIN* pin : pins )
178 {
179 pin->SetNumber( partPinNum );
180
181 if( aPart.m_PinNamesMap.count( termID ) )
182 pin->SetName( HandleTextOverbar( aPart.m_PinNamesMap.at( termID ) ) );
183 else if( aPart.m_PinLabelsMap.count( termID ) )
184 pin->SetName( HandleTextOverbar( aPart.m_PinLabelsMap.at( termID ) ) );
185
186 pin->SetType( getKiCadPinType( sym.m_Pins[termIdx].m_Type ) );
187 }
188
189 // @todo: Load pin/gate swapping information once kicad supports this
190 }
191
192 if( unit == 1 )
193 {
194 wxCHECK( kiSymDef->GetUnitCount() == 1, nullptr );
195 // The first unit can just be moved to the part symbol
196 retSym = std::move( kiSymDef );
197
198 retSym->SetUnitCount( aPart.m_Symbols.size(), true );
199
200 retSym->SetName( escapedPartName );
201 retSym->GetReferenceField().SetText( aPart.m_ComponentStem );
202 retSym->GetValueField().SetText( aPart.m_Value.value_or( "" ) );
203 addNewFieldToSymbol( PartNameFieldName, retSym.get() )->SetText( aPart.m_Name );
204 retSym->SetDescription( aPart.m_Description.value_or( "" ) );
205
206 auto addFieldIfHasValue =
207 [&]( const wxString& name, const std::optional<std::string>& value )
208 {
209 if( value.has_value() )
210 addNewFieldToSymbol( name, retSym.get() )->SetText( value.value() );
211 };
212
213 addFieldIfHasValue( PartNumberFieldName, aPart.m_Number );
214 addFieldIfHasValue( PartVersionFieldName, aPart.m_Version );
215 addFieldIfHasValue( PartAcceptanceFieldName, aPart.m_AcceptancePartName );
216
217 setFootprintOnSymbol( retSym.get(), aPart.m_Pcb_component,
218 aPart.m_Pcb_alternate.value_or( "" ) );
219
220 if( aPart.m_SpiceModel.has_value() )
221 {
222 wxString modelVal = wxString::Format( "model=\"%s\"", aPart.m_SpiceModel.value() );
223 addNewFieldToSymbol( SIM_DEVICE_FIELD, retSym.get() )->SetText( "SPICE" );
224 addNewFieldToSymbol( SIM_PARAMS_FIELD, retSym.get() )->SetText( modelVal );
225 }
226
227 // Load all part attributes, regardless of original cadstar type, to the symbol
228
229 // @todo some cadstar part attributes have a "read-only" flag. We should load this
230 // when KiCad supports read-only fields.
231
232 for( auto& [fieldName, value] : aPart.m_UserAttributes )
233 addNewFieldToSymbol( fieldName, retSym.get() )->SetText( value );
234
235 for( auto& [fieldName, attrValue] : aPart.m_SchAttributes )
236 addNewFieldToSymbol( fieldName, retSym.get() )->SetText( attrValue.m_Value );
237
238 for( auto& [fieldName, attrValue] : aPart.m_PcbAttributes )
239 addNewFieldToSymbol( fieldName, retSym.get() )->SetText( attrValue.m_Value );
240
241 for( auto& [fieldName, attrValue] : aPart.m_SchAndPcbAttributes )
242 addNewFieldToSymbol( fieldName, retSym.get() )->SetText( attrValue.m_Value );
243
244 for( auto& [fieldName, attrValue] : aPart.m_PartAttributes )
245 addNewFieldToSymbol( fieldName, retSym.get() )->SetText( attrValue.m_Value );
246
247 // Load all hidden pins onto the first unit of the symbol in KiCad
248 // We load them in a spiral sequence, starting at the center of the symbol BBOX
249 VECTOR2I symCenter = retSym->GetBodyBoundingBox( unit, 0, false, false ).GetCenter();
250 symCenter.y = -symCenter.y; // need to invert the y coord for lib symbols.
251
252 VECTOR2I delta( 0, 1 );
253 VECTOR2I direction( 0, -1 );
254 int spacing = schIUScale.MilsToIU( 50 ); // for now, place on a 50mil grid
255
256 for( auto& [signalName, csPinVector] : aPart.m_HiddenPins )
257 {
258 for( const CADSTAR_PART_PIN& csPin : csPinVector )
259 {
260 std::unique_ptr<SCH_PIN> pin = std::make_unique<SCH_PIN>( retSym.get() );
261
262 long pinNum = csPin.m_Identifier;
263 pin->SetNumber( wxString::Format( "%ld", pinNum ) );
264 pin->SetName( signalName );
266
267 pin->SetVisible( false );
268
269 // Generate the coordinate for the pin. We don't want overlapping pins
270 // and ideally close to the center of the symbol, so we load pins in a
271 // spiral sequence around the center
272 if( delta.x == delta.y
273 || ( delta.x < 0 && delta.x == -delta.y )
274 || ( delta.x > 0 && delta.x == 1 - delta.y ) )
275 {
276 // change direction
277 direction = { -direction.y, direction.x };
278 }
279
280 delta += direction;
281 VECTOR2I offset = delta * spacing;
282 pin->SetPosition( symCenter + offset );
283 pin->SetLength( 0 ); //CADSTAR Pins are just a point (have no length)
284 pin->SetShape( GRAPHIC_PINSHAPE::LINE );
285 pin->SetUnit( unit );
286 retSym->AddDrawItem( pin.release() );
287 }
288 }
289 }
290 else
291 { // Source: Dest:
292 copySymbolItems( kiSymDef.get(), retSym.get(), unit, false /* aOverrideFields */ );
293 }
294
295
296 retSym->SetShowPinNames( aPart.m_PinsVisible );
297 retSym->SetShowPinNumbers( aPart.m_PinsVisible );
298 }
299
300
301 return retSym;
302}
303
304
306 int aDestUnit, bool aOverrideFields )
307{
308 // Ensure there are no items on the unit we want to load onto
309 for( SCH_ITEM* item : aDestSym->GetUnitDrawItems( aDestUnit, ALL_BODY_STYLES ) )
310 aDestSym->RemoveDrawItem( item );
311
312 // Copy all draw items
313 for( SCH_ITEM* newItem : aSourceSym->GetUnitDrawItems( 1, ALL_BODY_STYLES ) )
314 {
315 SCH_ITEM* itemCopy = static_cast<SCH_ITEM*>( newItem->Clone() );
316 itemCopy->SetParent( aDestSym );
317 itemCopy->SetUnit( aDestUnit );
318 aDestSym->AddDrawItem( itemCopy );
319 }
320
321 //Copy / override all fields
322 if( aOverrideFields )
323 {
324 std::vector<SCH_FIELD*> fieldsToCopy;
325 aSourceSym->GetFields( fieldsToCopy );
326
327 for( SCH_FIELD* templateField : fieldsToCopy )
328 {
329 SCH_FIELD* appliedField = addNewFieldToSymbol( templateField->GetName(), aDestSym );
330 templateField->Copy( appliedField );
331 }
332 }
333}
334
335
337{
338 wxCHECK( aSchematic, /* void */ );
339
341 m_progressReporter->SetNumPhases( 3 ); // (0) Read file, (1) Parse file, (2) Load file
342
343 Parse();
344
345 checkDesignLimits(); // Throws if error found
346
347 // Assume the center at 0,0 since we are going to be translating the design afterwards anyway
348 m_designCenter = { 0, 0 };
349
350 m_schematic = aSchematic;
351 m_rootSheet = aRootSheet;
352
354 {
355 m_progressReporter->BeginPhase( 2 );
356 long numSteps = 11; // one step for each of below functions + one at the end of import
357
358 // Step 4 is by far the longest - add granularity in reporting
359 numSteps += Parts.PartDefinitions.size();
360
361 m_progressReporter->SetMaxProgress( numSteps );
362 }
363
364 loadTextVariables(); // Load text variables right at the start to ensure bounding box
365 // calculations work correctly for text items
366 checkPoint(); // Step 1
367 loadSheets();
368 checkPoint(); // Step 2
370 checkPoint(); // Step 3
372 checkPoint(); // Step 4, Subdivided into extra steps
374 checkPoint(); // Step 5
375 loadBusses();
376 checkPoint(); // Step 6
377 loadNets();
378 checkPoint(); // Step 7
379 loadFigures();
380 checkPoint(); // Step 8
381 loadTexts();
382 checkPoint(); // Step 9
384 checkPoint(); // Step 10
385
386 if( Schematic.VariantHierarchy.Variants.size() > 0 )
387 {
388 // TODO: implement variant importing
389 m_reporter->Report( wxString::Format( _( "The CADSTAR design contains variants are not currently "
390 "supported. Only the master variant ('%s') was loaded." ),
391 Schematic.VariantHierarchy.Variants.at( "V0" ).Name ),
393 }
394
395 if( Schematic.Groups.size() > 0 )
396 {
397 // TODO: implement group importing
398 m_reporter->Report( _( "The CADSTAR design contains grouped items which are not currently supported. "
399 "Any grouped items have been ungrouped." ),
401 }
402
403 if( Schematic.ReuseBlocks.size() > 0 )
404 {
405 // TODO: implement design block importing
406 m_reporter->Report( _( "The CADSTAR design contains re-use blocks which are not curretly supported. "
407 "The re-use block information has been discarded during the import." ),
409 }
410
411
412 // For all sheets, center all elements and re calculate the page size:
413 for( std::pair<LAYER_ID, SCH_SHEET*> sheetPair : m_sheetMap )
414 {
415 SCH_SHEET* sheet = sheetPair.second;
416
417 // Calculate the new sheet size.
418 BOX2I sheetBoundingBox;
419
420 for( SCH_ITEM* item : sheet->GetScreen()->Items() )
421 {
422 BOX2I bbox;
423
424 // Only use the visible fields of the symbols to calculate their bounding box
425 // (hidden fields could be very long and artificially enlarge the sheet bounding box)
426 if( item->Type() == SCH_SYMBOL_T )
427 {
428 SCH_SYMBOL* comp = static_cast<SCH_SYMBOL*>( item );
429 bbox = comp->GetBodyAndPinsBoundingBox();
430
431 for( const SCH_FIELD& field : comp->GetFields() )
432 {
433 if( field.IsVisible() )
434 bbox.Merge( field.GetBoundingBox() );
435 }
436 }
437 else if( item->Type() == SCH_TEXT_T )
438 {
439 SCH_TEXT* txtItem = static_cast<SCH_TEXT*>( item );
440 wxString txt = txtItem->GetText();
441
442 if( txt.Contains( "${" ) )
443 continue; // We can't calculate bounding box of text items with variables
444 else
445 bbox = txtItem->GetBoundingBox();
446 }
447 else
448 {
449 bbox = item->GetBoundingBox();
450 }
451
452 sheetBoundingBox.Merge( bbox );
453 }
454
455 // Find the screen grid of the original CADSTAR design
456 int grid = UNDEFINED_VALUE;
457
458 if( Assignments.Grids.ScreenGrid.Param1 != UNDEFINED_VALUE )
459 grid = Assignments.Grids.ScreenGrid.Param1;
460
461 if( Assignments.Grids.ScreenGrid.Param2 != UNDEFINED_VALUE )
462 {
463 if( Assignments.Grids.ScreenGrid.Type == GRID_TYPE::FRACTIONALGRID )
464 grid = grid / Assignments.Grids.ScreenGrid.Param2;
465 else if( Assignments.Grids.ScreenGrid.Param2 > grid )
466 grid = Assignments.Grids.ScreenGrid.Param2;
467 }
468
469 grid = getKiCadLength( grid, 50.0 );
470
471 auto roundToNearestGrid =
472 [&]( int aNumber ) -> int
473 {
474 int error = aNumber % grid;
475 int absError = sign( error ) * error;
476
477 if( absError > ( grid / 2 ) )
478 return aNumber + ( sign( error ) * grid ) - error;
479 else
480 return aNumber - error;
481 };
482
483 // When exporting to pdf, CADSTAR applies a margin of 3percent of the longest dimension (height
484 // or width) to all 4 sides (top, bottom, left right). For the import, we are also rounding
485 // the margin to the nearest grid, ensuring all items remain on the grid.
486 VECTOR2I targetSheetSize = sheetBoundingBox.GetSize();
487 int longestSide = std::max( targetSheetSize.x, targetSheetSize.y );
488 int margin = ( (double) longestSide * 0.03 );
489 margin = roundToNearestGrid( margin );
490 targetSheetSize += margin * 2;
491
492 // Update page size always
493 PAGE_INFO pageInfo = sheet->GetScreen()->GetPageSettings();
494 pageInfo.SetWidthMils( schIUScale.IUToMils( targetSheetSize.x ) );
495 pageInfo.SetHeightMils( schIUScale.IUToMils( targetSheetSize.y ) );
496
497 // Set the new sheet size.
498 sheet->GetScreen()->SetPageSettings( pageInfo );
499
500 VECTOR2I pageSizeIU = sheet->GetScreen()->GetPageSettings().GetSizeIU( schIUScale.IU_PER_MILS );
501 VECTOR2I sheetcentre( pageSizeIU.x / 2, pageSizeIU.y / 2 );
502 VECTOR2I itemsCentre = sheetBoundingBox.Centre();
503
504 // round the translation to nearest point on the grid
505 VECTOR2I translation = sheetcentre - itemsCentre;
506 translation.x = roundToNearestGrid( translation.x );
507 translation.y = roundToNearestGrid( translation.y );
508
509 // Translate the items.
510 std::vector<SCH_ITEM*> allItems;
511
512 std::copy( sheet->GetScreen()->Items().begin(), sheet->GetScreen()->Items().end(),
513 std::back_inserter( allItems ) );
514
515 for( SCH_ITEM* item : allItems )
516 {
517 item->Move( translation );
518 item->ClearFlags();
519 sheet->GetScreen()->Update( item );
520 }
521 }
522
523 checkPoint();
524
525 m_reporter->Report( _( "CADSTAR fonts are different to the ones in KiCad. This will likely "
526 "result in alignment issues. Please review the imported text elements "
527 "carefully and correct manually if required." ),
529
530 m_reporter->Report( _( "The CADSTAR design has been imported successfully.\n"
531 "Please review the import errors and warnings (if any)." ) );
532}
533
534
536{
537 LONGPOINT designLimit = Assignments.Settings.DesignLimit;
538
539 //Note: can't use getKiCadPoint() due VECTOR2I being int - need long long to make the check
540 long long designSizeXkicad = (long long) designLimit.x / KiCadUnitDivider;
541 long long designSizeYkicad = (long long) designLimit.y / KiCadUnitDivider;
542
543 // Max size limited by the positive dimension of VECTOR2I (which is an int)
544 constexpr long long maxDesignSizekicad = std::numeric_limits<int>::max();
545
546 if( designSizeXkicad > maxDesignSizekicad || designSizeYkicad > maxDesignSizekicad )
547 {
548 THROW_IO_ERRORF( _( "The design is too large and cannot be imported into KiCad. \n"
549 "Please reduce the maximum design size in CADSTAR by navigating to: \n"
550 "Design Tab -> Properties -> Design Options -> Maximum Design Size. \n"
551 "Current Design size: %.2f, %.2f millimeters. \n" //format:allow
552 "Maximum permitted design size: %.2f, %.2f millimeters.\n" ), //format:allow
553 (double) designSizeXkicad / SCH_IU_PER_MM,
554 (double) designSizeYkicad / SCH_IU_PER_MM,
555 (double) maxDesignSizekicad / SCH_IU_PER_MM,
556 (double) maxDesignSizekicad / SCH_IU_PER_MM );
557 }
558}
559
560
562{
563 const std::vector<LAYER_ID>& orphanSheets = findOrphanSheets();
564 SCH_SHEET_PATH rootPath;
565 rootPath.push_back( m_rootSheet );
566 rootPath.SetPageNumber( wxT( "1" ) );
567
568 if( orphanSheets.size() > 1 )
569 {
570 int x = 1;
571 int y = 1;
572
573 for( LAYER_ID sheetID : orphanSheets )
574 {
575 VECTOR2I pos( x * schIUScale.MilsToIU( 1000 ), y * schIUScale.MilsToIU( 1000 ) );
576 VECTOR2I siz( schIUScale.MilsToIU( 1000 ), schIUScale.MilsToIU( 1000 ) );
577
578 loadSheetAndChildSheets( sheetID, pos, siz, rootPath );
579
580 x += 2;
581
582 if( x > 10 ) // start next row
583 {
584 x = 1;
585 y += 2;
586 }
587 }
588 }
589 else if( orphanSheets.size() > 0 )
590 {
591 LAYER_ID rootSheetID = orphanSheets.at( 0 );
592
593 wxFileName loadedFilePath = wxFileName( Filename );
594
595 std::string filename = wxString::Format( "%s_%02d", loadedFilePath.GetName(),
596 getSheetNumber( rootSheetID ) )
597 .ToStdString();
598 ReplaceIllegalFileNameChars( filename );
599 filename += wxT( "." ) + wxString( FILEEXT::KiCadSchematicFileExtension );
600
601 wxFileName fn( m_schematic->Project().GetProjectPath() + filename );
602 m_rootSheet->GetScreen()->SetFileName( fn.GetFullPath() );
603
604 m_sheetMap.insert( { rootSheetID, m_rootSheet } );
605 loadChildSheets( rootSheetID, rootPath );
606 }
607 else if( Header.Format.Type == "SYMBOL" )
608 {
609 THROW_IO_ERROR( _( "The selected file is a CADSTAR symbol library. It does not contain a "
610 "schematic design so cannot be imported/opened in this way." ) );
611 }
612 else
613 {
614 THROW_IO_ERROR( _( "The CADSTAR schematic might be corrupt: there is no root sheet." ) );
615 }
616}
617
618
620{
621 for( std::pair<BLOCK_ID, BLOCK> blockPair : Schematic.Blocks )
622 {
623 BLOCK& block = blockPair.second;
624 LAYER_ID sheetID = "";
625
626 if( block.Type == BLOCK::TYPE::PARENT )
627 sheetID = block.LayerID;
628 else if( block.Type == BLOCK::TYPE::CHILD )
629 sheetID = block.AssocLayerID;
630 else
631 continue;
632
633 if( m_sheetMap.find( sheetID ) != m_sheetMap.end() )
634 {
635 SCH_SHEET* sheet = m_sheetMap.at( sheetID );
636
637 for( std::pair<TERMINAL_ID, TERMINAL> termPair : block.Terminals )
638 {
639 TERMINAL term = termPair.second;
640 wxString name = "YOU SHOULDN'T SEE THIS TEXT. THIS IS A BUG.";
641
642 SCH_HIERLABEL* sheetPin = nullptr;
643
644 if( block.Type == BLOCK::TYPE::PARENT )
645 sheetPin = new SCH_HIERLABEL();
646 else if( block.Type == BLOCK::TYPE::CHILD )
647 sheetPin = new SCH_SHEET_PIN( sheet );
648
649 sheetPin->SetText( name );
651 sheetPin->SetSpinStyle( getSpinStyle( term.OrientAngle, false ) );
652 sheetPin->SetPosition( getKiCadPoint( term.Position ) );
653
654 if( sheetPin->Type() == SCH_SHEET_PIN_T )
655 sheet->AddPin( (SCH_SHEET_PIN*) sheetPin );
656 else
657 sheet->GetScreen()->Append( sheetPin );
658
659 BLOCK_PIN_ID blockPinID = std::make_pair( block.ID, term.ID );
660 m_sheetPinMap.insert( { blockPinID, sheetPin } );
661 }
662 }
663 }
664}
665
666
668{
669 for( std::pair<PART_ID, PART> partPair : Parts.PartDefinitions )
670 {
671 PART_ID partID = partPair.first;
672 PART part = partPair.second;
673
674 wxString escapedPartName = EscapeString( part.Name, CTX_LIBID );
675 std::unique_ptr<LIB_SYMBOL> kiSym = std::make_unique<LIB_SYMBOL>( escapedPartName );
676
677 kiSym->SetUnitCount( part.Definition.GateSymbols.size(), true );
678 bool ok = true;
679
680 for( std::pair<GATE_ID, PART::DEFINITION::GATE> gatePair : part.Definition.GateSymbols )
681 {
682 GATE_ID gateID = gatePair.first;
683 PART::DEFINITION::GATE gate = gatePair.second;
684 SYMDEF_ID symbolID = getSymDefFromName( gate.Name, gate.Alternate );
685
686 if( symbolID.IsEmpty() )
687 {
688 m_reporter->Report( wxString::Format( _( "Part definition '%s' references symbol "
689 "'%s' (alternate '%s') which could not be "
690 "found in the symbol library. The part has "
691 "not been loaded into the KiCad library." ),
692 part.Name,
693 gate.Name,
694 gate.Alternate ),
696
697 ok = false;
698 break;
699 }
700
701 m_partSymbolsMap.insert( { { partID, gateID }, symbolID } );
702 loadSymbolGateAndPartFields( symbolID, part, gateID, kiSym.get() );
703 }
704
705 bool saveInLibrary = ok && part.Definition.GateSymbols.size() != 0;
706
707 if( !saveInLibrary )
708 {
709 if( part.Definition.GateSymbols.size() == 0 )
710 {
711 m_reporter->Report( wxString::Format( _( "Part definition '%s' has an incomplete "
712 "definition (no symbol definitions are "
713 "associated with it). The part has not "
714 "been loaded into the KiCad library." ),
715 part.Name ),
717 }
718
719 // Don't save in the library, but still keep it cached as some of the units might have
720 // been loaded correctly (saving us time later on), plus the part definition contains
721 // the part name, which is important to load
722 }
723
724 // The loader owns the symbol for the rest of the load; the maps below only hold aliases
725 LIB_SYMBOL* symbol = kiSym.get();
726 m_ownedSymbols.push_back( std::move( kiSym ) );
727
728 bool inserted = m_partMap.insert( { partID, symbol } ).second;
729 wxCHECK2( inserted, continue );
730
731 if( saveInLibrary )
732 m_loadedSymbols.push_back( symbol );
733
734 checkPoint();
735 }
736}
737
738
740{
741 for( std::pair<SYMBOL_ID, SYMBOL> symPair : Schematic.Symbols )
742 {
743 SYMBOL sym = symPair.second;
744
745 if( !sym.VariantID.empty() && sym.VariantParentSymbolID != sym.ID )
746 continue; // Only load master Variant
747
748 if( sym.IsComponent )
749 {
750 if( m_partMap.find( sym.PartRef.RefID ) == m_partMap.end() )
751 {
752 m_reporter->Report( wxString::Format( _( "Symbol '%s' references part '%s' which could not be "
753 "found in the library. The symbol was not loaded." ),
755 sym.PartRef.RefID ),
757
758 continue;
759 }
760
761 if( sym.GateID.IsEmpty() )
762 sym.GateID = wxT( "A" ); // Assume Gate "A" if unspecified
763
764 PART_GATE_ID partSymbolID = { sym.PartRef.RefID, sym.GateID };
765 LIB_SYMBOL* kiSym = m_partMap.at( sym.PartRef.RefID );
766 std::unique_ptr<LIB_SYMBOL> kiSymCopy;
767
768 // The symbol definition in the part either does not exist for this gate number
769 // or is different to the symbol instance. We need to reload the gate for this
770 // symbol
771 if( m_partSymbolsMap.find( partSymbolID ) == m_partSymbolsMap.end()
772 || m_partSymbolsMap.at( partSymbolID ) != sym.SymdefID )
773 {
774 kiSymCopy = std::make_unique<LIB_SYMBOL>( *kiSym );
775 kiSym = kiSymCopy.get();
776 const PART& part = Parts.PartDefinitions.at( sym.PartRef.RefID );
777 loadSymbolGateAndPartFields( sym.SymdefID, part, sym.GateID, kiSym );
778 }
779
780 std::unique_ptr<LIB_SYMBOL> scaledPart( getScaledLibPart( kiSym, sym.ScaleRatioNumerator,
781 sym.ScaleRatioDenominator ) );
782
783 EDA_ANGLE symOrient = ANGLE_0;
784 SCH_SYMBOL* symbol = loadSchematicSymbol( sym, *scaledPart, symOrient );
785
786 if( !symbol )
787 continue;
788
789 SCH_FIELD* refField = symbol->GetField( FIELD_T::REFERENCE );
790
791 sym.ComponentRef.Designator.Replace( wxT( "\n" ), wxT( "\\n" ) );
792 sym.ComponentRef.Designator.Replace( wxT( "\r" ), wxT( "\\r" ) );
793 sym.ComponentRef.Designator.Replace( wxT( "\t" ), wxT( "\\t" ) );
794 sym.ComponentRef.Designator.Replace( wxT( " " ), wxT( "_" ) );
795
796 refField->SetText( sym.ComponentRef.Designator );
797 loadSymbolFieldAttribute( sym.ComponentRef.AttrLoc, symOrient, sym.Mirror, refField );
798
799 if( sym.HasPartRef )
800 {
801 SCH_FIELD* partField = symbol->GetField( PartNameFieldName );
802
803 if( !partField )
804 partField = symbol->AddField( SCH_FIELD( symbol, FIELD_T::USER, PartNameFieldName ) );
805
806 wxASSERT( partField->GetName() == PartNameFieldName );
807
808 wxString partname = getPart( sym.PartRef.RefID ).Name;
809 partname.Replace( wxT( "\n" ), wxT( "\\n" ) );
810 partname.Replace( wxT( "\r" ), wxT( "\\r" ) );
811 partname.Replace( wxT( "\t" ), wxT( "\\t" ) );
812 partField->SetText( partname );
813
814 loadSymbolFieldAttribute( sym.PartRef.AttrLoc, symOrient, sym.Mirror, partField );
815
816 partField->SetVisible( SymbolPartNameColor.IsVisible );
817 }
818
819 for( auto& attr : sym.AttributeValues )
820 {
821 ATTRIBUTE_VALUE attrVal = attr.second;
822
823 if( attrVal.HasLocation )
824 {
825 wxString attrName = getAttributeName( attrVal.AttributeID );
826 SCH_FIELD* attrField = symbol->GetField( attrName );
827
828 if( !attrField )
829 attrField = symbol->AddField( SCH_FIELD( symbol, FIELD_T::USER, attrName ) );
830
831 wxASSERT( attrField->GetName() == attrName );
832
833 attrVal.Value.Replace( wxT( "\n" ), wxT( "\\n" ) );
834 attrVal.Value.Replace( wxT( "\r" ), wxT( "\\r" ) );
835 attrVal.Value.Replace( wxT( "\t" ), wxT( "\\t" ) );
836 attrField->SetText( attrVal.Value );
837
838 loadSymbolFieldAttribute( attrVal.AttributeLocation, symOrient, sym.Mirror,
839 attrField );
840 attrField->SetVisible( isAttributeVisible( attrVal.AttributeID ) );
841 }
842 }
843 }
844 else if( sym.IsSymbolVariant )
845 {
846 if( Library.SymbolDefinitions.find( sym.SymdefID ) == Library.SymbolDefinitions.end() )
847 {
848 THROW_IO_ERRORF( _( "Symbol ID '%s' references library symbol '%s' which could not be found "
849 "in the library. Did you export all items of the design?" ),
850 sym.ID,
851 sym.PartRef.RefID );
852 }
853
854 SYMDEF_SCM libSymDef = Library.SymbolDefinitions.at( sym.SymdefID );
855
856 if( libSymDef.Terminals.size() != 1 )
857 {
858 THROW_IO_ERRORF( _( "Symbol ID '%s' is a signal reference or global signal but it has too "
859 "many pins. The expected number of pins is 1 but %d were found." ),
860 sym.ID,
861 libSymDef.Terminals.size() );
862 }
863
864 if( sym.SymbolVariant.Type == SYMBOLVARIANT::TYPE::GLOBALSIGNAL )
865 {
866 SYMDEF_ID symID = sym.SymdefID;
867 LIB_SYMBOL* kiPart = nullptr;
868
869 // In CADSTAR "GlobalSignal" is a special type of symbol which defines
870 // a Power Symbol. The "Alternate" name defines the default net name of
871 // the power symbol but this can be overridden in the design itself.
872 wxString libraryNetName = Library.SymbolDefinitions.at( symID ).Alternate;
873
874 // Name of the net that the symbol instance in CADSTAR refers to:
875 wxString symbolInstanceNetName = sym.SymbolVariant.Reference;
876 symbolInstanceNetName = EscapeString( symbolInstanceNetName, CTX_LIBID );
877
878 // Name of the symbol we will use for saving the part in KiCad
879 // Note: In CADSTAR all power symbols will start have the reference name be
880 // "GLOBALSIGNAL" followed by the default net name, so it makes sense to save
881 // the symbol in KiCad as the default net name as well.
882 wxString libPartName = libraryNetName;
883
884 // In CADSTAR power symbol instances can refer to a different net to that defined
885 // in the library. This causes problems in KiCad v6 as it breaks connectivity when
886 // the user decides to update all symbols from library. We handle this by creating
887 // individual versions of the power symbol for each net name.
888 if( libPartName != symbolInstanceNetName )
889 {
890 libPartName += wxT( " (" ) + symbolInstanceNetName + wxT( ")" );
891 }
892
893 if( m_powerSymLibMap.find( libPartName ) == m_powerSymLibMap.end() )
894 {
895 const LIB_SYMBOL* templatePart = loadSymdef( symID );
896 wxCHECK( templatePart, /*void*/ );
897
898 auto ownedPart = std::make_unique<LIB_SYMBOL>( *templatePart );
899 kiPart = ownedPart.get();
900 m_ownedSymbols.push_back( std::move( ownedPart ) );
901
902 kiPart->SetGlobalPower();
903 kiPart->SetName( libPartName );
904 kiPart->GetValueField().SetText( symbolInstanceNetName );
905 kiPart->SetShowPinNames( false );
906 kiPart->SetShowPinNumbers( false );
907
908 std::vector<SCH_PIN*> pins = kiPart->GetGraphicalPins( 0, 0 );
909 wxCHECK( pins.size() == 1, /*void*/ );
910
911 pins.at( 0 )->SetType( ELECTRICAL_PINTYPE::PT_POWER_IN );
912 pins.at( 0 )->SetName( symbolInstanceNetName );
913
914 if( libSymDef.TextLocations.find( SIGNALNAME_ORIGIN_ATTRID )
915 != libSymDef.TextLocations.end() )
916 {
917 TEXT_LOCATION& txtLoc =
919
920 VECTOR2I valPos = getKiCadLibraryPoint( txtLoc.Position, libSymDef.Origin );
921
922 kiPart->GetValueField().SetPosition( valPos );
923 kiPart->GetValueField().SetVisible( true );
924 }
925 else
926 {
927 kiPart->GetValueField().SetVisible( false );
928 }
929
930 kiPart->GetReferenceField().SetText( "#PWR" );
931 kiPart->GetReferenceField().SetVisible( false );
932 m_loadedSymbols.push_back( kiPart );
933 m_powerSymLibMap.insert( { libPartName, kiPart } );
934 }
935 else
936 {
937 kiPart = m_powerSymLibMap.at( libPartName );
938 wxASSERT( kiPart->GetValueField().GetText() == symbolInstanceNetName );
939 }
940
941 std::unique_ptr<LIB_SYMBOL> scaledPart( getScaledLibPart( kiPart, sym.ScaleRatioNumerator,
942 sym.ScaleRatioDenominator ) );
943
944 EDA_ANGLE returnedOrient = ANGLE_0;
945
946 if( SCH_SYMBOL* symbol = loadSchematicSymbol( sym, *scaledPart, returnedOrient ) )
947 m_powerSymMap.insert( { sym.ID, symbol } );
948 }
949 else if( sym.SymbolVariant.Type == SYMBOLVARIANT::TYPE::SIGNALREF )
950 {
951 // There should only be one pin and we'll use that to set the position
952 TERMINAL& symbolTerminal = libSymDef.Terminals.begin()->second;
953 VECTOR2I terminalPosOffset = symbolTerminal.Position - libSymDef.Origin;
954 EDA_ANGLE rotate = getAngle( sym.OrientAngle );
955
956 if( sym.Mirror )
957 rotate += ANGLE_180;
958
959 RotatePoint( terminalPosOffset, -rotate );
960
961 SCH_GLOBALLABEL* netLabel = new SCH_GLOBALLABEL;
962 netLabel->SetPosition( getKiCadPoint( VECTOR2I( sym.Origin.x, sym.Origin.y ) + terminalPosOffset ) );
963 netLabel->SetText( "***UNKNOWN NET****" ); // This should be later updated when we load the netlist
964 netLabel->SetTextSize( VECTOR2I( schIUScale.MilsToIU( 50 ), schIUScale.MilsToIU( 50 ) ) );
965
966 SYMDEF_SCM symbolDef = Library.SymbolDefinitions.at( sym.SymdefID );
967
968 if( symbolDef.TextLocations.count( LINK_ORIGIN_ATTRID ) )
969 {
970 TEXT_LOCATION linkOrigin = symbolDef.TextLocations.at( LINK_ORIGIN_ATTRID );
971 applyTextSettings( netLabel, linkOrigin.TextCodeID, linkOrigin.Alignment,
972 linkOrigin.Justification );
973 }
974
975 netLabel->SetSpinStyle( getSpinStyle( sym.OrientAngle, sym.Mirror ) );
976
977 if( libSymDef.Alternate.Lower().Contains( "in" ) )
979 else if( libSymDef.Alternate.Lower().Contains( "bi" ) )
981 else if( libSymDef.Alternate.Lower().Contains( "out" ) )
983 else
985
986 SCH_SCREEN* screen = m_sheetMap.at( sym.LayerID )->GetScreen();
987
988 // autoplace intersheet refs
989 netLabel->AutoplaceFields( screen, AUTOPLACE_AUTO );
990
991 screen->Append( netLabel );
992 m_globalLabelsMap.insert( { sym.ID, netLabel } );
993 }
994 else
995 {
996 wxASSERT_MSG( false, "Unknown Symbol Variant." );
997 }
998 }
999 else
1000 {
1001 m_reporter->Report( wxString::Format( _( "Symbol ID '%s' is of an unknown type. It is neither a "
1002 "symbol or a net power / symbol. The symbol was not loaded." ),
1003 sym.ID ),
1005 }
1006
1007 if( sym.ScaleRatioDenominator != 1 || sym.ScaleRatioNumerator != 1 )
1008 {
1009 wxString symbolName = sym.ComponentRef.Designator;
1010
1011 if( symbolName.empty() )
1012 symbolName = wxString::Format( "ID: %s", sym.ID );
1013 else
1014 symbolName += sym.GateID;
1015
1016 m_reporter->Report( wxString::Format( _( "Symbol '%s' is scaled in the original CADSTAR schematic "
1017 "but this is not supported in KiCad. When the symbol is "
1018 "reloaded from the library, it will revert to the original "
1019 "1:1 scale." ),
1020 symbolName,
1021 sym.PartRef.RefID ),
1023 }
1024 }
1025}
1026
1027
1029{
1030 for( std::pair<BUS_ID, BUS> busPair : Schematic.Buses )
1031 {
1032 BUS bus = busPair.second;
1033 bool firstPt = true;
1034 VERTEX last;
1035
1036 if( bus.LayerID != wxT( "NO_SHEET" ) )
1037 {
1038 SCH_SCREEN* screen = m_sheetMap.at( bus.LayerID )->GetScreen();
1039 std::shared_ptr<BUS_ALIAS> kiBusAlias = std::make_shared<BUS_ALIAS>();
1040
1041 kiBusAlias->SetName( bus.Name );
1042 screen->AddBusAlias( kiBusAlias );
1043 m_busesMap.insert( { bus.ID, kiBusAlias } );
1044
1045 SCH_LABEL* label = new SCH_LABEL();
1046
1047 wxString busname = HandleTextOverbar( bus.Name );
1048
1049 label->SetText( wxT( "{" ) + busname + wxT( "}" ) );
1050 label->SetVisible( true );
1051 screen->Append( label );
1052
1053 SHAPE_LINE_CHAIN busLineChain; // to compute nearest segment to bus label
1054
1055 for( const VERTEX& cur : bus.Shape.Vertices )
1056 {
1057 busLineChain.Append( getKiCadPoint( cur.End ) );
1058
1059 if( firstPt )
1060 {
1061 last = cur;
1062 firstPt = false;
1063
1064 if( !bus.HasBusLabel )
1065 {
1066 // Add a bus label on the starting point if the original CADSTAR design
1067 // does not have an explicit label
1068 label->SetPosition( getKiCadPoint( last.End ) );
1069 }
1070
1071 continue;
1072 }
1073
1074
1075 SCH_LINE* kiBus = new SCH_LINE();
1076
1077 kiBus->SetStartPoint( getKiCadPoint( last.End ) );
1078 kiBus->SetEndPoint( getKiCadPoint( cur.End ) );
1079 kiBus->SetLayer( LAYER_BUS );
1080 kiBus->SetLineWidth( getLineThickness( bus.LineCodeID ) );
1081 screen->Append( kiBus );
1082
1083 last = cur;
1084 }
1085
1086 if( bus.HasBusLabel )
1087 {
1088 //lets find the closest point in the busline to the label
1089 VECTOR2I busLabelLoc = getKiCadPoint( bus.BusLabel.Position );
1090 VECTOR2I nearestPt = busLineChain.NearestPoint( busLabelLoc );
1091
1092 label->SetPosition( nearestPt );
1093
1095 bus.BusLabel.Justification );
1096
1097 // Re-set bus name as it might have been "double-escaped" after applyTextSettings
1098 label->SetText( wxT( "{" ) + busname + wxT( "}" ) );
1099
1100 // Note orientation of the bus label will be determined in loadNets
1101 // (the position of the wire will determine how best to place the bus label)
1102 }
1103 }
1104 }
1105}
1106
1107
1109{
1110 // Every pin is an obstacle for wires of other nets, the terminals of a net carry its identity
1111 std::map<LAYER_ID, SCH_IO_WIRE_DETOUR> detours;
1112 std::map<NET_ID, int> netIds;
1113 std::set<std::pair<LAYER_ID, VECTOR2I>> terminalPoints;
1114
1115 for( const auto& [netID, net] : Schematic.Nets )
1116 {
1117 const int netIndex = netIds.try_emplace( netID, static_cast<int>( netIds.size() ) + 1 ).first->second;
1118
1119 for( const auto& [termID, term] : net.Terminals )
1120 {
1121 auto symIt = Schematic.Symbols.find( term.SymbolID );
1122 POINT pos = getLocationOfNetElement( net, termID );
1123
1124 if( symIt == Schematic.Symbols.end() || pos.x == UNDEFINED_VALUE )
1125 continue;
1126
1127 const VECTOR2I kiPos = getKiCadPoint( pos );
1128
1129 detours[symIt->second.LayerID].AddContact( kiPos, netIndex );
1130 terminalPoints.emplace( symIt->second.LayerID, kiPos );
1131 }
1132 }
1133
1134 for( const auto& [layerID, sheet] : m_sheetMap )
1135 {
1136 for( SCH_ITEM* item : sheet->GetScreen()->Items().OfType( SCH_SYMBOL_T ) )
1137 {
1138 SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( item );
1139
1140 for( const SCH_PIN* pin : symbol->GetLibPins() )
1141 {
1142 if( symbol->GetUnit() && pin->GetUnit() && pin->GetUnit() != symbol->GetUnit() )
1143 continue;
1144
1145 const VECTOR2I pos = symbol->GetPinPhysicalPosition( pin );
1146
1147 if( !terminalPoints.count( { layerID, pos } ) )
1148 detours[layerID].AddContact( pos, detours[layerID].AnonymousNet() );
1149 }
1150 }
1151 }
1152
1153 auto getHierarchicalLabel =
1154 [&]( const NET_SCH& aNet, const NETELEMENT_ID& aNode ) -> SCH_HIERLABEL*
1155 {
1156 if( aNode.Contains( "BLKT" ) )
1157 {
1158 NET_SCH::BLOCK_TERM blockTerm = aNet.BlockTerminals.at( aNode );
1159 BLOCK_PIN_ID blockPinID = std::make_pair( blockTerm.BlockID, blockTerm.TerminalID );
1160
1161 if( m_sheetPinMap.find( blockPinID ) != m_sheetPinMap.end() )
1162 return m_sheetPinMap.at( blockPinID );
1163 }
1164
1165 return nullptr;
1166 };
1167
1168 // Connections are routed once every net has registered its geometry
1169 struct PENDING_CONNECTION
1170 {
1171 NET_ID NetID;
1172 NET_SCH::CONNECTION_SCH Conn;
1173 SHAPE_LINE_CHAIN Chain;
1174 std::map<NETELEMENT_ID, SCH_LABEL*> Labels;
1175 };
1176
1177 std::vector<PENDING_CONNECTION> pending;
1178
1179 for( std::pair<NET_ID, NET_SCH> netPair : Schematic.Nets )
1180 {
1181 const int netIndex = netIds.at( netPair.first );
1182 NET_SCH net = netPair.second;
1183 wxString netName = net.Name;
1184 std::map<NETELEMENT_ID, SCH_LABEL*> netlabels;
1185
1186 if( netName.IsEmpty() )
1187 netName = wxString::Format( "$%ld", net.SignalNum );
1188
1189 netName = HandleTextOverbar( netName );
1190
1191 for( std::pair<NETELEMENT_ID, NET_SCH::SYM_TERM> terminalPair : net.Terminals )
1192 {
1193 NET_SCH::SYM_TERM netTerm = terminalPair.second;
1194
1195 if( m_powerSymMap.find( netTerm.SymbolID ) != m_powerSymMap.end() )
1196 {
1197 SCH_FIELD* val = m_powerSymMap.at( netTerm.SymbolID )->GetField( FIELD_T::VALUE );
1198 val->SetText( netName );
1199 val->SetBold( false );
1200 val->SetVisible( false );
1201
1202 if( netTerm.HasNetLabel )
1203 {
1204 val->SetVisible( true );
1205 val->SetPosition( getKiCadPoint( netTerm.NetLabel.Position ) );
1206
1207 applyTextSettings( val, netTerm.NetLabel.TextCodeID, netTerm.NetLabel.Alignment,
1208 netTerm.NetLabel.Justification, netTerm.NetLabel.OrientAngle,
1209 netTerm.NetLabel.Mirror );
1210 }
1211 }
1212 else if( m_globalLabelsMap.find( netTerm.SymbolID ) != m_globalLabelsMap.end() )
1213 {
1214 m_globalLabelsMap.at( netTerm.SymbolID )->SetText( netName );
1215
1216 LAYER_ID sheet = Schematic.Symbols.at( netTerm.SymbolID ).LayerID;
1217
1218 if( m_sheetMap.count( sheet ) )
1219 {
1220 SCH_SCREEN* screen = m_sheetMap.at( sheet )->GetScreen();
1221
1222 // autoplace intersheet refs again since we've changed the name
1223 m_globalLabelsMap.at( netTerm.SymbolID )->AutoplaceFields( screen, AUTOPLACE_AUTO );
1224 }
1225 }
1226 else if( !net.Name.IsEmpty() && Schematic.Symbols.count( netTerm.SymbolID )
1227 && netTerm.HasNetLabel )
1228 {
1229 // This is a named net that connects to a schematic symbol pin - we need to put a label
1230 SCH_LABEL* label = new SCH_LABEL();
1231 label->SetText( netName );
1232
1233 POINT pinLocation = getLocationOfNetElement( net, netTerm.ID );
1234 label->SetPosition( getKiCadPoint( pinLocation ) );
1235 label->SetVisible( true );
1236
1237 applyTextSettings( label, netTerm.NetLabel.TextCodeID, netTerm.NetLabel.Alignment,
1238 netTerm.NetLabel.Justification );
1239
1240 netlabels.insert( { netTerm.ID, label } );
1241
1242 LAYER_ID sheet = Schematic.Symbols.at( netTerm.SymbolID ).LayerID;
1243 m_sheetMap.at( sheet )->GetScreen()->Append( label );
1244 }
1245 }
1246
1247 //Add net name to all hierarchical pins (block terminals in CADSTAR)
1248 for( std::pair<NETELEMENT_ID, NET_SCH::BLOCK_TERM> blockPair : net.BlockTerminals )
1249 {
1250 SCH_HIERLABEL* label = getHierarchicalLabel( net, blockPair.first );
1251
1252 if( label )
1253 label->SetText( netName );
1254
1255 // Terminals a connection ends on are registered after their position is fixed up below
1256 const bool connected = std::any_of( net.Connections.begin(), net.Connections.end(),
1257 [&]( const NET_SCH::CONNECTION_SCH& aConn )
1258 {
1259 return aConn.LayerID != wxT( "NO_SHEET" )
1260 && ( aConn.StartNode == blockPair.first
1261 || aConn.EndNode == blockPair.first );
1262 } );
1263
1264 if( label && !connected )
1265 {
1266 detours[Schematic.Blocks.at( blockPair.second.BlockID ).LayerID].AddContact( label->GetPosition(),
1267 netIndex );
1268 }
1269 }
1270
1271 // Load all bus entries and add net label if required
1272 for( std::pair<NETELEMENT_ID, NET_SCH::BUS_TERM> busPair : net.BusTerminals )
1273 {
1274 NET_SCH::BUS_TERM busTerm = busPair.second;
1275 BUS bus = Schematic.Buses.at( busTerm.BusID );
1276
1277 if( !alg::contains( m_busesMap.at( bus.ID )->Members(), netName ) )
1278 m_busesMap.at( bus.ID )->AddMember( netName );
1279
1280 SCH_BUS_WIRE_ENTRY* busEntry = new SCH_BUS_WIRE_ENTRY( getKiCadPoint( busTerm.FirstPoint ), false );
1281
1282 VECTOR2I size = getKiCadPoint( busTerm.SecondPoint ) - getKiCadPoint( busTerm.FirstPoint );
1283 busEntry->SetSize( VECTOR2I( size.x, size.y ) );
1284
1285 m_sheetMap.at( bus.LayerID )->GetScreen()->Append( busEntry );
1286
1287 // Always add a label at bus terminals to ensure connectivity.
1288 // If the original design does not have a label, just make it very small
1289 // to keep connectivity but make the design look visually similar to
1290 // the original.
1291 SCH_LABEL* label = new SCH_LABEL();
1292 label->SetText( netName );
1293 label->SetPosition( getKiCadPoint( busTerm.SecondPoint ) );
1294 label->SetVisible( true );
1295
1296 if( busTerm.HasNetLabel )
1297 {
1298 applyTextSettings( label, busTerm.NetLabel.TextCodeID, busTerm.NetLabel.Alignment,
1299 busTerm.NetLabel.Justification );
1300 }
1301 else
1302 {
1304 }
1305
1306 netlabels.insert( { busTerm.ID, label } );
1307 detours[bus.LayerID].AddContact( label->GetPosition(), netIndex );
1308 m_sheetMap.at( bus.LayerID )->GetScreen()->Append( label );
1309 }
1310
1311 for( std::pair<NETELEMENT_ID, NET_SCH::DANGLER> danglerPair : net.Danglers )
1312 {
1313 NET_SCH::DANGLER dangler = danglerPair.second;
1314
1315 SCH_LABEL* label = new SCH_LABEL();
1316 label->SetPosition( getKiCadPoint( dangler.Position ) );
1317 label->SetVisible( true );
1318
1319 if( dangler.HasNetLabel )
1320 {
1321 applyTextSettings( label, dangler.NetLabel.TextCodeID, dangler.NetLabel.Alignment,
1322 dangler.NetLabel.Justification );
1323 }
1324
1325 label->SetText( netName ); // set text after applying settings to avoid double-escaping
1326 netlabels.insert( { dangler.ID, label } );
1327 detours[dangler.LayerID].AddContact( label->GetPosition(), netIndex );
1328
1329 m_sheetMap.at( dangler.LayerID )->GetScreen()->Append( label );
1330 }
1331
1332 for( NET_SCH::CONNECTION_SCH conn : net.Connections )
1333 {
1334 if( conn.LayerID == wxT( "NO_SHEET" ) )
1335 continue; // No point loading virtual connections. KiCad handles that internally
1336
1337 POINT start = getLocationOfNetElement( net, conn.StartNode );
1338 POINT end = getLocationOfNetElement( net, conn.EndNode );
1339
1340 if( start.x == UNDEFINED_VALUE || end.x == UNDEFINED_VALUE )
1341 continue;
1342
1343 // Connections in CADSTAR are always implied between symbols even if the route
1344 // doesn't start and end exactly at the connection points
1345 if( conn.Path.size() < 1 || conn.Path.front().End != start )
1346 conn.Path.insert( conn.Path.begin(), VERTEX( VERTEX_TYPE::VT_POINT, start ) );
1347
1348 if( conn.Path.size() < 2 || conn.Path.back().End != end )
1349 conn.Path.push_back( VERTEX( VERTEX_TYPE::VT_POINT, end ) );
1350
1351 SHAPE_LINE_CHAIN wireChain; // Create a temp. line chain representing the connection
1352
1353 auto cadstarToKicadPoint = [this]( const VECTOR2I& aPoint ) -> VECTOR2I
1354 {
1355 return getKiCadPoint( aPoint );
1356 };
1357
1358 for( const VERTEX& vertex : conn.Path )
1359 vertex.AppendToChain( &wireChain, cadstarToKicadPoint, ARC_ACCURACY );
1360
1361 // AUTO-FIX SHEET PINS
1362 //--------------------
1363 // KiCad constrains the sheet pin on the edge of the sheet object whereas in
1364 // CADSTAR it can be anywhere. Let's find the intersection of the wires with the sheet
1365 // and place the hierarchical
1366 std::vector<NETELEMENT_ID> nodes;
1367 nodes.push_back( conn.StartNode );
1368 nodes.push_back( conn.EndNode );
1369
1370 for( const NETELEMENT_ID& node : nodes )
1371 {
1372 SCH_HIERLABEL* sheetPin = getHierarchicalLabel( net, node );
1373
1374 if( sheetPin )
1375 {
1376 if( sheetPin->Type() == SCH_SHEET_PIN_T
1377 && SCH_SHEET::ClassOf( sheetPin->GetParent() ) )
1378 {
1379 SCH_SHEET* parentSheet = static_cast<SCH_SHEET*>( sheetPin->GetParent() );
1380 VECTOR2I sheetSize = parentSheet->GetSize();
1381 VECTOR2I sheetPosition = parentSheet->GetPosition();
1382
1383 int leftSide = sheetPosition.x;
1384 int rightSide = sheetPosition.x + sheetSize.x;
1385 int topSide = sheetPosition.y;
1386 int botSide = sheetPosition.y + sheetSize.y;
1387
1388 SHAPE_LINE_CHAIN sheetEdge;
1389
1390 sheetEdge.Append( leftSide, topSide );
1391 sheetEdge.Append( rightSide, topSide );
1392 sheetEdge.Append( rightSide, botSide );
1393 sheetEdge.Append( leftSide, botSide );
1394 sheetEdge.Append( leftSide, topSide );
1395
1396 std::vector<SHAPE_LINE_CHAIN::INTERSECTION> wireToSheetIntersects;
1397
1398 if( !wireChain.Intersect( sheetEdge, wireToSheetIntersects ) )
1399 {
1400 // The block terminal is outside the block shape in the original
1401 // CADSTAR design. Since KiCad's Sheet Pin will already be constrained
1402 // on the edge, we will simply join to it with a straight line.
1403 if( node == conn.StartNode )
1404 wireChain = wireChain.Reverse();
1405
1406 wireChain.Append( sheetPin->GetPosition() );
1407
1408 if( node == conn.StartNode )
1409 wireChain = wireChain.Reverse();
1410 }
1411 else
1412 {
1413 // The block terminal is either inside or on the shape edge. Lets use
1414 // the first intersection point.
1415 VECTOR2I intsctPt = wireToSheetIntersects.at( 0 ).p;
1416 int intsctIndx = wireChain.FindSegment( intsctPt );
1417 wxASSERT_MSG( intsctIndx != -1, "Can't find intersecting segment" );
1418
1419 if( node == conn.StartNode )
1420 wireChain.Replace( 0, intsctIndx, intsctPt );
1421 else
1422 wireChain.Replace( intsctIndx + 1, /*end index*/ -1, intsctPt );
1423
1424 sheetPin->SetPosition( intsctPt );
1425 }
1426 }
1427 }
1428 }
1429
1430 for( int i = 1; i < wireChain.PointCount(); i++ )
1431 detours[conn.LayerID].AddWire( SEG( wireChain.CPoint( i - 1 ), wireChain.CPoint( i ) ), netIndex );
1432
1433 for( const NETELEMENT_ID& node : nodes )
1434 {
1435 if( SCH_HIERLABEL* sheetPin = getHierarchicalLabel( net, node ) )
1436 detours[conn.LayerID].AddContact( sheetPin->GetPosition(), netIndex );
1437 }
1438
1439 pending.push_back( { netPair.first, conn, wireChain, netlabels } );
1440 }
1441
1442 for( std::pair<NETELEMENT_ID, NET_SCH::JUNCTION_SCH> juncPair : net.Junctions )
1443 {
1444 NET_SCH::JUNCTION_SCH junc = juncPair.second;
1445
1446 SCH_JUNCTION* kiJunc = new SCH_JUNCTION();
1447
1448 kiJunc->SetPosition( getKiCadPoint( junc.Location ) );
1449 detours[junc.LayerID].AddContact( kiJunc->GetPosition(), netIndex );
1450 m_sheetMap.at( junc.LayerID )->GetScreen()->Append( kiJunc );
1451
1452 if( junc.HasNetLabel )
1453 {
1454 // In CADSTAR the label can be placed anywhere, but in KiCad it has to be placed
1455 // in the same location as the junction for it to be connected to it.
1456 SCH_LABEL* label = new SCH_LABEL();
1457 label->SetText( netName );
1458 label->SetPosition( getKiCadPoint( junc.Location ) );
1459 label->SetVisible( true );
1460
1461 EDA_ANGLE labelAngle = getAngle( junc.NetLabel.OrientAngle );
1462 SPIN_STYLE spin = getSpinStyle( labelAngle );
1463
1464 label->SetSpinStyle( spin );
1465
1466 m_sheetMap.at( junc.LayerID )->GetScreen()->Append( label );
1467 }
1468 }
1469 }
1470
1471 for( PENDING_CONNECTION& pend : pending )
1472 {
1473 const NET_SCH& net = Schematic.Nets.at( pend.NetID );
1474 const NET_SCH::CONNECTION_SCH& conn = pend.Conn;
1475 SCH_IO_WIRE_DETOUR& detour = detours[conn.LayerID];
1476 const int netIndex = netIds.at( pend.NetID );
1477 SHAPE_LINE_CHAIN wireChain;
1478 bool detourFailed = false;
1479
1480 for( int i = 0; i < pend.Chain.PointCount(); i++ )
1481 {
1482 if( i == 0 )
1483 {
1484 wireChain.Append( pend.Chain.CPoint( 0 ) );
1485 continue;
1486 }
1487
1489 detour.Route( SEG( pend.Chain.CPoint( i - 1 ), pend.Chain.CPoint( i ) ), netIndex );
1490
1491 detourFailed |= result.Failed;
1492
1493 // A bend lying on another net's pin cannot be detoured by moving one segment
1494 if( i + 1 < pend.Chain.PointCount() && detour.TouchesOtherNet( pend.Chain.CPoint( i ), netIndex ) )
1495 detourFailed = true;
1496
1497 for( const SEG& piece : result.Pieces )
1498 wireChain.Append( piece.B );
1499 }
1500
1501 if( detourFailed )
1502 {
1503 m_reporter->Report( wxString::Format( _( "A connection of net %s passes over a pin or wire of another "
1504 "net and could not be rerouted. The nets may be joined and "
1505 "require manual fixing." ),
1506 getNetName( net ) ),
1508 }
1509
1510 auto fixNetLabelsAndSheetPins =
1511 [&]( const EDA_ANGLE& aWireAngle, const NETELEMENT_ID& aNetEleID )
1512 {
1513 SPIN_STYLE spin = getSpinStyle( aWireAngle );
1514
1515 if( pend.Labels.find( aNetEleID ) != pend.Labels.end() )
1516 pend.Labels.at( aNetEleID )->SetSpinStyle( spin.MirrorY() );
1517
1518 SCH_HIERLABEL* sheetPin = getHierarchicalLabel( net, aNetEleID );
1519
1520 if( sheetPin )
1521 sheetPin->SetSpinStyle( spin.MirrorX() );
1522 };
1523
1524 bool firstPt = true;
1525 bool secondPt = false;
1526 VECTOR2I last;
1527 SCH_LINE* wire = nullptr;
1528
1529 // Now we can load the wires and fix the label orientations
1530 for( const VECTOR2I& pt : wireChain.CPoints() )
1531 {
1532 if( firstPt )
1533 {
1534 last = pt;
1535 firstPt = false;
1536 secondPt = true;
1537 continue;
1538 }
1539
1540 if( secondPt )
1541 {
1542 secondPt = false;
1543
1544 EDA_ANGLE wireAngle( last - pt );
1545 fixNetLabelsAndSheetPins( wireAngle, conn.StartNode );
1546 }
1547
1548 wire = new SCH_LINE();
1549
1550 wire->SetStartPoint( last );
1551 wire->SetEndPoint( pt );
1552 wire->SetLayer( LAYER_WIRE );
1553
1554 if( !conn.ConnectionLineCode.IsEmpty() )
1555 wire->SetLineWidth( getLineThickness( conn.ConnectionLineCode ) );
1556
1557 last = pt;
1558
1559 m_sheetMap.at( conn.LayerID )->GetScreen()->Append( wire );
1560 }
1561
1562 //Fix labels on the end wire
1563 if( wire )
1564 {
1565 EDA_ANGLE wireAngle( wire->GetEndPoint() - wire->GetStartPoint() );
1566 fixNetLabelsAndSheetPins( wireAngle, conn.EndNode );
1567 }
1568 }
1569}
1570
1571
1573{
1574 for( std::pair<FIGURE_ID, FIGURE> figPair : Schematic.Figures )
1575 {
1576 FIGURE fig = figPair.second;
1577
1578 loadFigure( fig, fig.LayerID, LAYER_NOTES );
1579 }
1580}
1581
1582
1584{
1585 for( std::pair<TEXT_ID, TEXT> textPair : Schematic.Texts )
1586 {
1587 TEXT txt = textPair.second;
1588
1589 SCH_TEXT* kiTxt = getKiCadSchText( txt );
1590 loadItemOntoKiCadSheet( txt.LayerID, kiTxt );
1591 }
1592}
1593
1594
1596{
1597 for( std::pair<DOCUMENTATION_SYMBOL_ID, DOCUMENTATION_SYMBOL> docSymPair :
1598 Schematic.DocumentationSymbols )
1599 {
1600 DOCUMENTATION_SYMBOL docSym = docSymPair.second;
1601
1602 if( Library.SymbolDefinitions.find( docSym.SymdefID ) == Library.SymbolDefinitions.end() )
1603 {
1604 m_reporter->Report( wxString::Format( _( "Documentation Symbol '%s' refers to symbol definition "
1605 "ID '%s' which does not exist in the library. The symbol "
1606 "was not loaded." ),
1607 docSym.ID,
1608 docSym.SymdefID ),
1610 continue;
1611 }
1612
1613 SYMDEF_SCM docSymDef = Library.SymbolDefinitions.at( docSym.SymdefID );
1614 VECTOR2I moveVector = getKiCadPoint( docSym.Origin ) - getKiCadPoint( docSymDef.Origin );
1615 EDA_ANGLE rotationAngle = getAngle( docSym.OrientAngle );
1616 double scalingFactor = (double) docSym.ScaleRatioNumerator
1617 / (double) docSym.ScaleRatioDenominator;
1618 VECTOR2I centreOfTransform = getKiCadPoint( docSymDef.Origin );
1619 bool mirrorInvert = docSym.Mirror;
1620
1621 for( std::pair<FIGURE_ID, FIGURE> figPair : docSymDef.Figures )
1622 {
1623 FIGURE fig = figPair.second;
1624
1625 loadFigure( fig, docSym.LayerID, LAYER_NOTES, moveVector, rotationAngle, scalingFactor,
1626 centreOfTransform, mirrorInvert );
1627 }
1628
1629 for( std::pair<TEXT_ID, TEXT> textPair : docSymDef.Texts )
1630 {
1631 TEXT txt = textPair.second;
1632
1633 txt.Mirror = ( txt.Mirror ) ? !mirrorInvert : mirrorInvert;
1634 txt.OrientAngle = docSym.OrientAngle - txt.OrientAngle;
1635
1636 SCH_TEXT* kiTxt = getKiCadSchText( txt );
1637
1638 VECTOR2I newPosition = applyTransform( kiTxt->GetPosition(), moveVector, rotationAngle,
1639 scalingFactor, centreOfTransform, mirrorInvert );
1640
1641 int newTxtWidth = KiROUND( kiTxt->GetTextWidth() * scalingFactor );
1642 int newTxtHeight = KiROUND( kiTxt->GetTextHeight() * scalingFactor );
1643 int newTxtThickness = KiROUND( kiTxt->GetTextThickness() * scalingFactor );
1644
1645 kiTxt->SetPosition( newPosition );
1646 kiTxt->SetTextWidth( newTxtWidth );
1647 kiTxt->SetTextHeight( newTxtHeight );
1648 kiTxt->SetTextThickness( newTxtThickness );
1649
1650 loadItemOntoKiCadSheet( docSym.LayerID, kiTxt );
1651 }
1652 }
1653}
1654
1655
1657{
1658 auto findAndReplaceTextField =
1659 [&]( TEXT_FIELD_NAME aField, wxString aValue )
1660 {
1661 if( m_context.TextFieldToValuesMap.find( aField ) != m_context.TextFieldToValuesMap.end() )
1662 {
1663 if( m_context.TextFieldToValuesMap.at( aField ) != aValue )
1664 {
1665 m_context.TextFieldToValuesMap.at( aField ) = aValue;
1666 m_context.InconsistentTextFields.insert( aField );
1667 return false;
1668 }
1669 }
1670 else
1671 {
1672 m_context.TextFieldToValuesMap.insert( { aField, aValue } );
1673 }
1674
1675 return true;
1676 };
1677
1678 PROJECT* pj = &m_schematic->Project();
1679
1680 if( pj )
1681 {
1682 std::map<wxString, wxString>& txtVars = pj->GetTextVars();
1683
1684 // Most of the design text fields can be derived from other elements
1685 if( Schematic.VariantHierarchy.Variants.size() > 0 )
1686 {
1687 VARIANT loadedVar = Schematic.VariantHierarchy.Variants.begin()->second;
1688
1689 findAndReplaceTextField( TEXT_FIELD_NAME::VARIANT_NAME, loadedVar.Name );
1690 findAndReplaceTextField( TEXT_FIELD_NAME::VARIANT_DESCRIPTION, loadedVar.Description );
1691 }
1692
1693 findAndReplaceTextField( TEXT_FIELD_NAME::DESIGN_TITLE, Header.JobTitle );
1694
1695 for( std::pair<TEXT_FIELD_NAME, wxString> txtvalue : m_context.TextFieldToValuesMap )
1696 {
1697 wxString varName = CADSTAR_TO_KICAD_FIELDS.at( txtvalue.first );
1698 wxString varValue = txtvalue.second;
1699
1700 txtVars.insert( { varName, varValue } );
1701 }
1702
1703 for( std::pair<wxString, wxString> txtvalue : m_context.FilenamesToTextMap )
1704 {
1705 wxString varName = txtvalue.first;
1706 wxString varValue = txtvalue.second;
1707
1708 txtVars.insert( { varName, varValue } );
1709 }
1710 }
1711 else
1712 {
1713 m_reporter->Report( _( "Text Variables could not be set as there is no project attached." ),
1715 }
1716}
1717
1718
1720 LIB_SYMBOL* aKiCadSymbol )
1721{
1722 // First Check if field already exists
1723 if( SCH_FIELD* existingField = aKiCadSymbol->GetField( aFieldName ) )
1724 return existingField;
1725
1726 SCH_FIELD* newfield = new SCH_FIELD( aKiCadSymbol, FIELD_T::USER, aFieldName );
1727 newfield->SetVisible( false );
1728 aKiCadSymbol->AddField( newfield );
1729 /*
1730 @todo we should load that a field is a URL by checking if it starts with "Link"
1731 e.g.:
1732 if( aFieldName.Lower().StartsWith( "link" ) )
1733 newfield->SetAsURL*/
1734
1735 return newfield;
1736}
1737
1738
1740{
1741 wxCHECK( Library.SymbolDefinitions.find( aSymdefID ) != Library.SymbolDefinitions.end(), nullptr );
1742
1743 if( m_symDefMap.count( aSymdefID ) )
1744 return m_symDefMap.at( aSymdefID ).get(); // return a non-owning ptr
1745
1746 SYMDEF_SCM csSym = Library.SymbolDefinitions.at( aSymdefID );
1747 std::unique_ptr<LIB_SYMBOL> kiSym = std::make_unique<LIB_SYMBOL>( csSym.BuildLibName() );
1748 const int gateNumber = 1; // Always load to gate "A" - we will change the unit later
1749
1750 // Load Graphical Figures
1751 for( std::pair<FIGURE_ID, FIGURE> figPair : csSym.Figures )
1752 {
1753 FIGURE fig = figPair.second;
1754 int lineThickness = getLineThickness( fig.LineCodeID );
1755 LINE_STYLE linestyle = getLineStyle( fig.LineCodeID );
1756
1757 if( fig.Shape.Type == SHAPE_TYPE::OPENSHAPE )
1758 {
1759 loadLibrarySymbolShapeVertices( fig.Shape.Vertices, csSym.Origin, kiSym.get(), gateNumber,
1760 lineThickness, linestyle );
1761 }
1762 else
1763 {
1765
1766 shape->SetPolyShape( fig.Shape.ConvertToPolySet( [&]( const VECTOR2I& aPt )
1767 {
1768 return getKiCadLibraryPoint( aPt, csSym.Origin );
1769 },
1770 ARC_ACCURACY ) );
1771
1772 shape->SetUnit( gateNumber );
1773
1774 shape->SetStroke( STROKE_PARAMS( lineThickness, linestyle ) );
1775
1776 if( fig.Shape.Type == SHAPE_TYPE::SOLID )
1778 else if( fig.Shape.Type == SHAPE_TYPE::OUTLINE )
1779 shape->SetFillMode( FILL_T::NO_FILL );
1780 else if( fig.Shape.Type == SHAPE_TYPE::HATCHED ) // We don't have an equivalent
1782
1783 kiSym->AddDrawItem( shape );
1784 }
1785 }
1786
1787 PINNUM_TO_TERMINAL_MAP pinNumToTerminals;
1788
1789 // Load Pins
1790 for( std::pair<TERMINAL_ID, TERMINAL> termPair : csSym.Terminals )
1791 {
1792 TERMINAL term = termPair.second;
1793 wxString pinNum = wxString::Format( "%ld", term.ID );
1794 wxString pinName = wxEmptyString;
1795 std::unique_ptr<SCH_PIN> pin = std::make_unique<SCH_PIN>( kiSym.get() );
1796
1797 // Assume passive pin for now (we will set it later once we load the parts)
1799
1800 pin->SetPosition( getKiCadLibraryPoint( term.Position, csSym.Origin ) );
1801 pin->SetLength( 0 ); //CADSTAR Pins are just a point (have no length)
1802 pin->SetShape( GRAPHIC_PINSHAPE::LINE );
1803 pin->SetUnit( gateNumber );
1804 pin->SetNumber( pinNum );
1805 pin->SetName( pinName );
1806
1807 // TC0 is the default CADSTAR text size for name/number if none specified
1808 int pinNumberHeight = getTextHeightFromTextCode( wxT( "TC0" ) );
1809 int pinNameHeight = getTextHeightFromTextCode( wxT( "TC0" ) );
1810
1811 if( csSym.PinNumberLocations.count( term.ID ) )
1812 {
1813 PIN_NUM_LABEL_LOC pinNumLocation = csSym.PinNumberLocations.at( term.ID );
1814 pinNumberHeight = getTextHeightFromTextCode( pinNumLocation.TextCodeID );
1815 }
1816
1817 if( csSym.PinLabelLocations.count( term.ID ) )
1818 {
1819 PIN_NUM_LABEL_LOC pinNameLocation = csSym.PinLabelLocations.at( term.ID );
1820 pinNameHeight = getTextHeightFromTextCode( pinNameLocation.TextCodeID );
1821 }
1822
1823 pin->SetNumberTextSize( pinNumberHeight );
1824 pin->SetNameTextSize( pinNameHeight );
1825
1826 pinNumToTerminals.insert( { pin->GetNumber(), term.ID } );
1827 kiSym->AddDrawItem( pin.release() );
1828 }
1829
1830 m_symDefTerminalsMap.insert( { aSymdefID, pinNumToTerminals } );
1831 fixUpLibraryPins( kiSym.get(), gateNumber );
1832
1833
1834 // Load Text items
1835 for( std::pair<TEXT_ID, TEXT> textPair : csSym.Texts )
1836 {
1837 TEXT csText = textPair.second;
1838 VECTOR2I pos = getKiCadLibraryPoint( csText.Position, csSym.Origin );
1839 auto libtext = std::make_unique<SCH_TEXT>( pos, csText.Text, LAYER_DEVICE );
1840
1841 libtext->SetUnit( gateNumber );
1842 libtext->SetPosition( getKiCadLibraryPoint( csText.Position, csSym.Origin ) );
1843 libtext->SetMultilineAllowed( true ); // temporarily so that we calculate bbox correctly
1844
1845 applyTextSettings( libtext.get(), csText.TextCodeID, csText.Alignment, csText.Justification,
1846 csText.OrientAngle, csText.Mirror );
1847
1848 // Split out multi line text items into individual text elements
1849 if( csText.Text.Contains( "\n" ) )
1850 {
1851 wxArrayString strings;
1852 wxStringSplit( csText.Text, strings, '\n' );
1853
1854 for( size_t ii = 0; ii < strings.size(); ++ii )
1855 {
1856 BOX2I bbox = libtext->GetTextBox( nullptr, ii );
1857 VECTOR2I linePos = { bbox.GetLeft(), -bbox.GetBottom() };
1858
1859 RotatePoint( linePos, libtext->GetTextPos(), -libtext->GetTextAngle() );
1860
1861 SCH_TEXT* textLine = static_cast<SCH_TEXT*>( libtext->Duplicate( IGNORE_PARENT_GROUP ) );
1862 textLine->SetText( strings[ii] );
1865 textLine->SetTextPos( linePos );
1866
1867 // Multiline text not allowed in LIB_TEXT
1868 textLine->SetMultilineAllowed( false );
1869 kiSym->AddDrawItem( textLine );
1870 }
1871 }
1872 else
1873 {
1874 // Multiline text not allowed in LIB_TEXT
1875 libtext->SetMultilineAllowed( false );
1876 kiSym->AddDrawItem( libtext.release() );
1877 }
1878 }
1879
1880 // CADSTAR uses TC1 when fields don't have explicit text/attribute location
1881 static const TEXTCODE_ID defaultTextCode = "TC1";
1882
1883 // Load field locations (Attributes in CADSTAR)
1884
1885 // Symbol name (e.g. R1)
1886 if( csSym.TextLocations.count( SYMBOL_NAME_ATTRID ) )
1887 {
1888 TEXT_LOCATION& textLoc = csSym.TextLocations.at( SYMBOL_NAME_ATTRID );
1889 applyToLibraryFieldAttribute( textLoc, csSym.Origin, &kiSym->GetReferenceField() );
1890 }
1891 else
1892 {
1893 applyTextCodeIfExists( &kiSym->GetReferenceField(), defaultTextCode );
1894 }
1895
1896 // Always add the part name field (even if it doesn't have a specific location defined)
1897 SCH_FIELD* partField = addNewFieldToSymbol( PartNameFieldName, kiSym.get() );
1898 wxCHECK( partField, nullptr );
1899 wxASSERT( partField->GetName() == PartNameFieldName );
1900
1901 if( csSym.TextLocations.count( PART_NAME_ATTRID ) )
1902 {
1903 TEXT_LOCATION& textLoc = csSym.TextLocations.at( PART_NAME_ATTRID );
1904 applyToLibraryFieldAttribute( textLoc, csSym.Origin, partField );
1905 }
1906 else
1907 {
1908 applyTextCodeIfExists( partField, defaultTextCode );
1909 }
1910
1911 partField->SetVisible( SymbolPartNameColor.IsVisible );
1912
1913
1914 for( auto& [attributeId, textLocation] : csSym.TextLocations )
1915 {
1916 if( attributeId == PART_NAME_ATTRID || attributeId == SYMBOL_NAME_ATTRID
1917 || attributeId == SIGNALNAME_ORIGIN_ATTRID || attributeId == LINK_ORIGIN_ATTRID )
1918 {
1919 continue;
1920 }
1921
1922 wxString attributeName = getAttributeName( attributeId );
1923 SCH_FIELD* field = addNewFieldToSymbol( attributeName, kiSym.get() );
1924 applyToLibraryFieldAttribute( textLocation, csSym.Origin, field );
1925 }
1926
1927
1928 for( auto& [attributeId, attrValue] : csSym.AttributeValues )
1929 {
1930 if( attributeId == PART_NAME_ATTRID || attributeId == SYMBOL_NAME_ATTRID
1931 || attributeId == SIGNALNAME_ORIGIN_ATTRID || attributeId == LINK_ORIGIN_ATTRID )
1932 {
1933 continue;
1934 }
1935
1936 wxString attributeName = getAttributeName( attributeId );
1937 SCH_FIELD* field = addNewFieldToSymbol( attributeName, kiSym.get() );
1938
1939 if( attrValue.HasLocation )
1940 applyToLibraryFieldAttribute( attrValue.AttributeLocation, csSym.Origin, field );
1941 else
1942 applyTextCodeIfExists( field, defaultTextCode );
1943 }
1944
1945
1946 m_symDefMap.insert( { aSymdefID, std::move( kiSym ) } );
1947
1948 return m_symDefMap.at( aSymdefID ).get(); // return a non-owning ptr
1949}
1950
1951
1953 const PART& aCadstarPart,
1954 const GATE_ID& aGateID,
1955 LIB_SYMBOL* aSymbol )
1956{
1957 wxCHECK( Library.SymbolDefinitions.find( aSymdefID ) != Library.SymbolDefinitions.end(), /*void*/ );
1958
1959 std::unique_ptr<LIB_SYMBOL> kiSymDef( loadSymdef( aSymdefID )->Duplicate() );
1960 wxCHECK( kiSymDef, /*void*/ );
1961
1962 // Update the pin numbers to match those defined in the Cadstar part
1963 TERMINAL_TO_PINNUM_MAP pinNumMap;
1964
1965 for( auto&& [storedPinNum, termID] : m_symDefTerminalsMap[aSymdefID] )
1966 {
1967 PART::DEFINITION::PIN csPin = getPartDefinitionPin( aCadstarPart, aGateID, termID );
1968 std::vector<SCH_PIN*> pins = kiSymDef->GetPinsByNumber( storedPinNum );
1969
1970 wxString pinName = HandleTextOverbar( csPin.Label );
1971 wxString pinNum = HandleTextOverbar( csPin.Name );
1972
1973 if( pinNum.IsEmpty() )
1974 {
1975 if( !csPin.Identifier.IsEmpty() )
1976 pinNum = csPin.Identifier;
1977 else if( csPin.ID == UNDEFINED_VALUE )
1978 pinNum = wxString::Format( "%ld", termID );
1979 else
1980 pinNum = wxString::Format( "%ld", csPin.ID );
1981 }
1982
1983 for( SCH_PIN* pin : pins )
1984 {
1985 pin->SetType( getKiCadPinType( csPin.Type ) );
1986 pin->SetNumber( pinNum );
1987 pin->SetName( pinName );
1988 }
1989
1990 pinNumMap.insert( { termID, pinNum } );
1991 }
1992
1993 m_pinNumsMap.insert( { aCadstarPart.ID + aGateID, pinNumMap } );
1994
1995 // COPY ITEMS
1996 int gateNumber = getKiCadUnitNumberFromGate( aGateID );
1997 copySymbolItems( kiSymDef.get(), aSymbol, gateNumber );
1998
1999 // Hide the value field for now (it might get unhidden if an attribute exists in the cadstar
2000 // design with the text "Value"
2001 aSymbol->GetValueField().SetVisible( false );
2002
2003
2004 if( SCH_FIELD* partNameField = aSymbol->GetField( PartNameFieldName ) )
2005 partNameField->SetText( EscapeFieldText( aCadstarPart.Name ) );
2006
2007 const POINT& symDefOrigin = Library.SymbolDefinitions.at( aSymdefID ).Origin;
2008 wxString footprintRefName = wxEmptyString;
2009 wxString footprintAlternateName = wxEmptyString;
2010
2011 auto loadLibraryField = [&]( const ATTRIBUTE_VALUE& aAttributeVal )
2012 {
2013 wxString attrName = getAttributeName( aAttributeVal.AttributeID );
2014
2015 // Remove invalid field characters
2016 wxString attributeValue = aAttributeVal.Value;
2017 attributeValue.Replace( wxT( "\n" ), wxT( "\\n" ) );
2018 attributeValue.Replace( wxT( "\r" ), wxT( "\\r" ) );
2019 attributeValue.Replace( wxT( "\t" ), wxT( "\\t" ) );
2020
2021 //TODO: Handle "links": In cadstar a field can be a "link" if its name starts
2022 // with the characters "Link ". Need to figure out how to convert them to
2023 // equivalent in KiCad.
2024
2025 if( attrName == wxT( "(PartDefinitionNameStem)" ) )
2026 {
2027 //Space not allowed in Reference field
2028 attributeValue.Replace( wxT( " " ), "_" );
2029 aSymbol->GetReferenceField().SetText( attributeValue );
2030 return;
2031 }
2032 else if( attrName == wxT( "(PartDescription)" ) )
2033 {
2034 aSymbol->SetDescription( attributeValue );
2035 return;
2036 }
2037 else if( attrName == wxT( "(PartDefinitionReferenceName)" ) )
2038 {
2039 footprintRefName = attributeValue;
2040 return;
2041 }
2042 else if( attrName == wxT( "(PartDefinitionAlternateName)" ) )
2043 {
2044 footprintAlternateName = attributeValue;
2045 return;
2046 }
2047
2048 bool attrIsNew = aSymbol->GetField( attrName ) == nullptr;
2049 SCH_FIELD* attrField = addNewFieldToSymbol( attrName, aSymbol );
2050
2051 wxASSERT( attrField->GetName() == attrName );
2052 attrField->SetText( attributeValue );
2053 attrField->SetUnit( gateNumber );
2054
2055 const ATTRIBUTE_ID& attrid = aAttributeVal.AttributeID;
2056 attrField->SetVisible( isAttributeVisible( attrid ) );
2057
2058 if( aAttributeVal.HasLocation )
2059 {
2060 // Check if the part itself defined a location for the field
2061 applyToLibraryFieldAttribute( aAttributeVal.AttributeLocation, symDefOrigin, attrField );
2062 }
2063 else if( attrIsNew )
2064 {
2065 attrField->SetVisible( false );
2066 applyTextSettings( attrField, wxT( "TC1" ), ALIGNMENT::NO_ALIGNMENT, JUSTIFICATION::LEFT, false, true );
2067 }
2068 };
2069
2070 // Load all attributes in the Part Definition
2071 for( auto& [attrId, attrVal] : aCadstarPart.Definition.AttributeValues )
2072 loadLibraryField( attrVal );
2073
2074 // Load all attributes in the Part itself.
2075 for( auto& [attrId, attrVal] : aCadstarPart.AttributeValues )
2076 loadLibraryField( attrVal );
2077
2078 setFootprintOnSymbol( aSymbol, footprintRefName, footprintAlternateName );
2079
2080 if( aCadstarPart.Definition.HidePinNames )
2081 {
2082 aSymbol->SetShowPinNames( false );
2083 aSymbol->SetShowPinNumbers( false );
2084 }
2085}
2086
2087
2089 const wxString& aFootprintName,
2090 const wxString& aFootprintAlternate )
2091{
2092 wxString fpNameInLibrary = generateLibName( aFootprintName, aFootprintAlternate );
2093
2094 if( !fpNameInLibrary.IsEmpty() )
2095 {
2096 wxArrayString fpFilters;
2097 fpFilters.Add( aFootprintName ); // In cadstar one footprint has several "alternates"
2098
2099 if( !aFootprintAlternate.IsEmpty() )
2100 fpFilters.Add( fpNameInLibrary );
2101
2102 aKiCadSymbol->SetFPFilters( fpFilters );
2103
2104 LIB_ID libID( m_footprintLibName, fpNameInLibrary );
2105 aKiCadSymbol->GetFootprintField().SetText( libID.Format() );
2106 }
2107}
2108
2109
2110void CADSTAR_SCH_ARCHIVE_LOADER::loadLibrarySymbolShapeVertices( const std::vector<VERTEX>& aCadstarVertices,
2111 const VECTOR2I& aSymbolOrigin,
2112 LIB_SYMBOL* aSymbol, int aGateNumber,
2113 int aLineThickness, LINE_STYLE aLineStyle )
2114{
2115 const VERTEX* prev = aCadstarVertices.empty() ? nullptr : &aCadstarVertices.at( 0 );
2116 const VERTEX* cur;
2117
2118 wxASSERT_MSG( prev && prev->Type == VERTEX_TYPE::VT_POINT, "First vertex should always be a point." );
2119
2120 for( size_t i = 1; i < aCadstarVertices.size(); i++ )
2121 {
2122 cur = &aCadstarVertices.at( i );
2123
2124 SCH_SHAPE* shape = nullptr;
2125 bool cw = false;
2126 VECTOR2I startPoint = getKiCadLibraryPoint( prev->End, aSymbolOrigin );
2127 VECTOR2I endPoint = getKiCadLibraryPoint( cur->End, aSymbolOrigin );
2128 VECTOR2I centerPoint;
2129
2131 centerPoint = ( startPoint + endPoint ) / 2;
2132 else
2133 centerPoint = getKiCadLibraryPoint( cur->Center, aSymbolOrigin );
2134
2135 switch( cur->Type )
2136 {
2138 shape = new SCH_SHAPE( SHAPE_T::POLY, LAYER_DEVICE );
2139 shape->AddPoint( startPoint );
2140 shape->AddPoint( endPoint );
2141 break;
2142
2145 cw = true;
2147
2150 shape = new SCH_SHAPE( SHAPE_T::ARC, LAYER_DEVICE );
2151
2152 shape->SetPosition( centerPoint );
2153
2154 if( cw )
2155 {
2156 shape->SetStart( endPoint );
2157 shape->SetEnd( startPoint );
2158 }
2159 else
2160 {
2161 shape->SetStart( startPoint );
2162 shape->SetEnd( endPoint );
2163 }
2164
2165 break;
2166 }
2167
2168 shape->SetUnit( aGateNumber );
2169 shape->SetStroke( STROKE_PARAMS( aLineThickness, aLineStyle ) );
2170 aSymbol->AddDrawItem( shape, false );
2171
2172 prev = cur;
2173 }
2174
2175 aSymbol->GetDrawItems().sort();
2176}
2177
2178
2180 const VECTOR2I& aSymbolOrigin,
2181 SCH_FIELD* aKiCadField )
2182{
2183 aKiCadField->SetTextPos( getKiCadLibraryPoint( aCadstarAttrLoc.Position, aSymbolOrigin ) );
2184
2185 applyTextSettings( aKiCadField, aCadstarAttrLoc.TextCodeID, aCadstarAttrLoc.Alignment,
2186 aCadstarAttrLoc.Justification, aCadstarAttrLoc.OrientAngle,
2187 aCadstarAttrLoc.Mirror );
2188}
2189
2190
2192 const LIB_SYMBOL& aKiCadPart,
2193 EDA_ANGLE& aComponentOrientation )
2194{
2195 wxString libName = CreateLibName( m_footprintLibName, m_rootSheet );
2196
2197 LIB_ID libId;
2198 libId.SetLibItemName( aKiCadPart.GetName() );
2199 libId.SetLibNickname( libName );
2200
2201 int unit = getKiCadUnitNumberFromGate( aCadstarSymbol.GateID );
2202
2203 if( m_sheetMap.find( aCadstarSymbol.LayerID ) == m_sheetMap.end() )
2204 {
2205 m_reporter->Report( wxString::Format( _( "Symbol '%s' references sheet ID '%s' which does not exist "
2206 "in the design. The symbol was not loaded." ),
2207 aCadstarSymbol.ComponentRef.Designator,
2208 aCadstarSymbol.LayerID ),
2210
2211 return nullptr;
2212 }
2213
2214 SCH_SHEET_PATH sheetpath;
2215 SCH_SHEET* kiSheet = m_sheetMap.at( aCadstarSymbol.LayerID );
2216 m_rootSheet->LocatePathOfScreen( kiSheet->GetScreen(), &sheetpath );
2217
2218 SCH_SYMBOL* symbol = new SCH_SYMBOL( aKiCadPart, libId, &sheetpath, unit );
2219
2220 if( aCadstarSymbol.IsComponent )
2221 symbol->SetRef( &sheetpath, aCadstarSymbol.ComponentRef.Designator );
2222
2223 symbol->SetPosition( getKiCadPoint( aCadstarSymbol.Origin ) );
2224
2225 EDA_ANGLE compAngle = getAngle( aCadstarSymbol.OrientAngle );
2226 int compOrientation = 0;
2227
2228 if( aCadstarSymbol.Mirror )
2229 {
2230 compAngle = -compAngle;
2231 compOrientation += SYMBOL_ORIENTATION_T::SYM_MIRROR_Y;
2232 }
2233
2234 compOrientation += getComponentOrientation( compAngle, aComponentOrientation );
2235 EDA_ANGLE test1( compAngle );
2236 EDA_ANGLE test2( aComponentOrientation );
2237
2238 if( test1.Normalize180() != test2.Normalize180() )
2239 {
2240 m_reporter->Report( wxString::Format( _( "Symbol '%s' is rotated by an angle of %.1f " //format:allow
2241 "degrees in the original CADSTAR design but "
2242 "KiCad only supports rotation angles multiples "
2243 "of 90 degrees. The connecting wires will need "
2244 "manual fixing." ),
2245 aCadstarSymbol.ComponentRef.Designator,
2246 compAngle.AsDegrees() ),
2248 }
2249
2250 symbol->SetOrientation( compOrientation );
2251
2252 wxString gate = ( aCadstarSymbol.GateID.IsEmpty() ) ? wxString( wxT( "A" ) ) : aCadstarSymbol.GateID;
2253 wxString partGateIndex = aCadstarSymbol.PartRef.RefID + gate;
2254
2255 //Handle pin swaps
2256 if( m_pinNumsMap.find( partGateIndex ) != m_pinNumsMap.end() )
2257 {
2258 TERMINAL_TO_PINNUM_MAP termNumMap = m_pinNumsMap.at( partGateIndex );
2259
2260 std::map<wxString, std::vector<SCH_PIN*>> pinNumToLibPinsMap;
2261
2262 for( auto& term : termNumMap )
2263 {
2264 wxString pinNum = term.second;
2265 std::vector<SCH_PIN*> pins =
2266 symbol->GetLibSymbolRef()->GetPinsByNumber( term.second );
2267 pinNumToLibPinsMap.insert( { pinNum, pins } );
2268 }
2269
2270 auto replacePinNumber =
2271 [&]( const wxString& aOldPinNum, const wxString& aNewPinNum )
2272 {
2273 if( aOldPinNum == aNewPinNum )
2274 return;
2275
2276 for( SCH_PIN* libpin : pinNumToLibPinsMap.at( aOldPinNum ) )
2277 libpin->SetNumber( HandleTextOverbar( aNewPinNum ) );
2278 };
2279
2280 //Older versions of Cadstar used pin numbers
2281 for( auto& pinPair : aCadstarSymbol.PinNumbers )
2282 {
2283 SYMBOL::PIN_NUM pin = pinPair.second;
2284
2285 replacePinNumber( termNumMap.at( pin.TerminalID ),
2286 wxString::Format( "%ld", pin.PinNum ) );
2287 }
2288
2289 //Newer versions of Cadstar use pin names
2290 for( auto& pinPair : aCadstarSymbol.PinNames )
2291 {
2292 SYMPINNAME_LABEL pin = pinPair.second;
2293 replacePinNumber( termNumMap.at( pin.TerminalID ), pin.NameOrLabel );
2294 }
2295
2296 symbol->UpdatePins();
2297 }
2298
2299 kiSheet->GetScreen()->Append( symbol );
2300
2301 return symbol;
2302}
2303
2304
2306 const EDA_ANGLE& aComponentOrientation,
2307 bool aIsMirrored,
2308 SCH_FIELD* aKiCadField )
2309{
2310 aKiCadField->SetPosition( getKiCadPoint( aCadstarAttrLoc.Position ) );
2311 aKiCadField->SetVisible( true );
2312
2313 ALIGNMENT alignment = aCadstarAttrLoc.Alignment;
2314 EDA_ANGLE textAngle = getAngle( aCadstarAttrLoc.OrientAngle );
2315
2316 if( aIsMirrored )
2317 {
2318 // We need to change the aligment when the symbol is mirrored based on the text orientation
2319 // To ensure the anchor point is the same in KiCad.
2320
2321 int textIsVertical = KiROUND( textAngle.AsDegrees() / 90.0 ) % 2;
2322
2323 if( textIsVertical )
2324 alignment = rotate180( alignment );
2325
2326 alignment = mirrorX( alignment );
2327 }
2328
2329 applyTextSettings( aKiCadField, aCadstarAttrLoc.TextCodeID, alignment,
2330 aCadstarAttrLoc.Justification,
2331 getCadstarAngle( textAngle - aComponentOrientation ),
2332 aCadstarAttrLoc.Mirror );
2333}
2334
2335
2337 EDA_ANGLE& aReturnedOrientation )
2338{
2339 int compOrientation = SYMBOL_ORIENTATION_T::SYM_ORIENT_0;
2340
2341 EDA_ANGLE oDeg = aOrientAngle;
2342 oDeg.Normalize180();
2343
2344 if( oDeg >= -ANGLE_45 && oDeg <= ANGLE_45 )
2345 {
2346 compOrientation = SYMBOL_ORIENTATION_T::SYM_ORIENT_0;
2347 aReturnedOrientation = ANGLE_0;
2348 }
2349 else if( oDeg >= ANGLE_45 && oDeg <= ANGLE_135 )
2350 {
2351 compOrientation = SYMBOL_ORIENTATION_T::SYM_ORIENT_90;
2352 aReturnedOrientation = ANGLE_90;
2353 }
2354 else if( oDeg >= ANGLE_135 || oDeg <= -ANGLE_135 )
2355 {
2356 compOrientation = SYMBOL_ORIENTATION_T::SYM_ORIENT_180;
2357 aReturnedOrientation = ANGLE_180;
2358 }
2359 else
2360 {
2361 compOrientation = SYMBOL_ORIENTATION_T::SYM_ORIENT_270;
2362 aReturnedOrientation = ANGLE_270;
2363 }
2364
2365 return compOrientation;
2366}
2367
2368
2371{
2372 auto logUnknownNetElementError =
2373 [&]()
2374 {
2375 m_reporter->Report( wxString::Format( _( "Net %s references unknown net element %s. The net was "
2376 "not properly loaded and may require manual fixing." ),
2377 getNetName( aNet ),
2378 aNetElementID ),
2380
2381 return POINT();
2382 };
2383
2384 if( aNetElementID.Contains( "J" ) ) // Junction
2385 {
2386 if( aNet.Junctions.find( aNetElementID ) == aNet.Junctions.end() )
2387 return logUnknownNetElementError();
2388
2389 return aNet.Junctions.at( aNetElementID ).Location;
2390 }
2391 else if( aNetElementID.Contains( "P" ) ) // Terminal/Pin of a symbol
2392 {
2393 if( aNet.Terminals.find( aNetElementID ) == aNet.Terminals.end() )
2394 return logUnknownNetElementError();
2395
2396 SYMBOL_ID symid = aNet.Terminals.at( aNetElementID ).SymbolID;
2397 TERMINAL_ID termid = aNet.Terminals.at( aNetElementID ).TerminalID;
2398
2399 if( Schematic.Symbols.find( symid ) == Schematic.Symbols.end() )
2400 return logUnknownNetElementError();
2401
2402 SYMBOL sym = Schematic.Symbols.at( symid );
2403 SYMDEF_ID symdefid = sym.SymdefID;
2404 VECTOR2I symbolOrigin( sym.Origin.x, sym.Origin.y );
2405
2406 if( Library.SymbolDefinitions.find( symdefid ) == Library.SymbolDefinitions.end() )
2407 return logUnknownNetElementError();
2408
2409 const SYMDEF_SCM symdef = Library.SymbolDefinitions.at( symdefid );
2410 VECTOR2I libOrigin( symdef.Origin.x, symdef.Origin.y );
2411
2412 if( symdef.Terminals.find( termid ) == symdef.Terminals.end() )
2413 {
2414 m_reporter->Report( wxString::Format( _( "Net %s references unknown terminal %s on symbol %s. "
2415 "The net was not properly loaded and may require manual "
2416 "fixing." ),
2417 getNetName( aNet ),
2418 termid,
2419 symdefid ),
2421
2422 return POINT();
2423 }
2424
2425 TERMINAL term = symdef.Terminals.at( termid );
2426 VECTOR2I libpinPosition( term.Position.x, term.Position.y );
2427
2428 VECTOR2I pinOffset = libpinPosition - libOrigin;
2429 pinOffset.x = ( pinOffset.x * sym.ScaleRatioNumerator ) / sym.ScaleRatioDenominator;
2430 pinOffset.y = ( pinOffset.y * sym.ScaleRatioNumerator ) / sym.ScaleRatioDenominator;
2431
2432 VECTOR2I pinPosition = symbolOrigin + pinOffset;
2433 EDA_ANGLE compAngle = getAngle( sym.OrientAngle );
2434
2435 if( sym.Mirror )
2436 pinPosition.x = ( 2 * symbolOrigin.x ) - pinPosition.x;
2437
2438 EDA_ANGLE adjustedOrientation;
2439 getComponentOrientation( compAngle, adjustedOrientation );
2440
2441 RotatePoint( pinPosition, symbolOrigin, -adjustedOrientation );
2442
2443 POINT retval;
2444 retval.x = pinPosition.x;
2445 retval.y = pinPosition.y;
2446
2447 return retval;
2448 }
2449 else if( aNetElementID.Contains( "BT" ) ) // Bus Terminal
2450 {
2451 if( aNet.BusTerminals.find( aNetElementID ) == aNet.BusTerminals.end() )
2452 return logUnknownNetElementError();
2453
2454 return aNet.BusTerminals.at( aNetElementID ).SecondPoint;
2455 }
2456 else if( aNetElementID.Contains( "BLKT" ) ) // Block Terminal (sheet hierarchy connection)
2457 {
2458 if( aNet.BlockTerminals.find( aNetElementID ) == aNet.BlockTerminals.end() )
2459 return logUnknownNetElementError();
2460
2461 BLOCK_ID blockid = aNet.BlockTerminals.at( aNetElementID ).BlockID;
2462 TERMINAL_ID termid = aNet.BlockTerminals.at( aNetElementID ).TerminalID;
2463
2464 if( Schematic.Blocks.find( blockid ) == Schematic.Blocks.end() )
2465 return logUnknownNetElementError();
2466
2467 BLOCK block = Schematic.Blocks.at( blockid );
2468
2469 if( block.Terminals.find( termid ) == block.Terminals.end() )
2470 {
2471 m_reporter->Report( wxString::Format( _( "Net %s references unknown terminal %s on block %s. The net "
2472 "was not properly loaded and may require manual fixing." ),
2473 getNetName( aNet ),
2474 termid,
2475 blockid ),
2477
2478 return POINT();
2479 }
2480
2481 return block.Terminals.at( termid ).Position;
2482 }
2483 else if( aNetElementID.Contains( "D" ) ) // Dangler
2484 {
2485 if( aNet.Danglers.find( aNetElementID ) == aNet.Danglers.end() )
2486 return logUnknownNetElementError();
2487
2488 return aNet.Danglers.at( aNetElementID ).Position;
2489 }
2490 else
2491 {
2492 return logUnknownNetElementError();
2493 }
2494}
2495
2496
2498{
2499 wxString netname = aNet.Name;
2500
2501 if( netname.IsEmpty() )
2502 netname = wxString::Format( "$%ld", aNet.SignalNum );
2503
2504 return netname;
2505}
2506
2507
2508void CADSTAR_SCH_ARCHIVE_LOADER::loadShapeVertices( const std::vector<VERTEX>& aCadstarVertices,
2509 LINECODE_ID aCadstarLineCodeID,
2510 LAYER_ID aCadstarSheetID,
2511 SCH_LAYER_ID aKiCadSchLayerID,
2512 const VECTOR2I& aMoveVector,
2513 const EDA_ANGLE& aRotation,
2514 const double& aScalingFactor,
2515 const VECTOR2I& aTransformCentre,
2516 const bool& aMirrorInvert )
2517{
2518 int lineWidth = KiROUND( getLineThickness( aCadstarLineCodeID ) * aScalingFactor );
2519 LINE_STYLE lineStyle = getLineStyle( aCadstarLineCodeID );
2520
2521 const VERTEX* prev = aCadstarVertices.empty() ? nullptr : &aCadstarVertices.at( 0 );
2522 const VERTEX* cur;
2523
2524 wxASSERT_MSG( prev && prev->Type == VERTEX_TYPE::VT_POINT, "First vertex should always be a point vertex" );
2525
2526 auto pointTransform =
2527 [&]( const VECTOR2I& aV )
2528 {
2529 return applyTransform( getKiCadPoint( aV ), aMoveVector, aRotation,
2530 aScalingFactor, aTransformCentre, aMirrorInvert );
2531 };
2532
2533 for( size_t ii = 1; ii < aCadstarVertices.size(); ii++ )
2534 {
2535 cur = &aCadstarVertices.at( ii );
2536
2537 VECTOR2I transformedStartPoint = pointTransform( prev->End );
2538 VECTOR2I transformedEndPoint = pointTransform( cur->End );
2539
2540 switch( cur->Type )
2541 {
2546 {
2547 SHAPE_ARC tempArc = cur->BuildArc( transformedStartPoint, pointTransform );
2548
2549 SCH_SHAPE* arcShape = new SCH_SHAPE( SHAPE_T::ARC, LAYER_NOTES, lineWidth );
2550 arcShape->SetArcGeometry( tempArc.GetP0(), tempArc.GetArcMid(), tempArc.GetP1() );
2551 arcShape->SetLineStyle( lineStyle );
2552
2553 loadItemOntoKiCadSheet( aCadstarSheetID, arcShape );
2554 break;
2555 }
2556
2558 {
2559 SCH_LINE* segment = new SCH_LINE();
2560
2561 segment->SetLayer( aKiCadSchLayerID );
2562 segment->SetLineWidth( lineWidth );
2563 segment->SetLineStyle( lineStyle );
2564
2565 segment->SetStartPoint( transformedStartPoint );
2566 segment->SetEndPoint( transformedEndPoint );
2567
2568 loadItemOntoKiCadSheet( aCadstarSheetID, segment );
2569 break;
2570 }
2571
2572 default:
2573 wxFAIL_MSG( "Unknown CADSTAR Vertex type" );
2574 }
2575
2576 prev = cur;
2577 }
2578}
2579
2580
2582 const LAYER_ID& aCadstarSheetIDOverride,
2583 SCH_LAYER_ID aKiCadSchLayerID,
2584 const VECTOR2I& aMoveVector,
2585 const EDA_ANGLE& aRotation,
2586 const double& aScalingFactor,
2587 const VECTOR2I& aTransformCentre,
2588 const bool& aMirrorInvert )
2589{
2590 loadShapeVertices( aCadstarFigure.Shape.Vertices, aCadstarFigure.LineCodeID,
2591 aCadstarSheetIDOverride, aKiCadSchLayerID, aMoveVector, aRotation,
2592 aScalingFactor, aTransformCentre, aMirrorInvert );
2593
2594 for( const CUTOUT& cutout : aCadstarFigure.Shape.Cutouts )
2595 {
2596 loadShapeVertices( cutout.Vertices, aCadstarFigure.LineCodeID, aCadstarSheetIDOverride,
2597 aKiCadSchLayerID, aMoveVector, aRotation, aScalingFactor,
2598 aTransformCentre, aMirrorInvert );
2599 }
2600}
2601
2602
2604 const VECTOR2I& aPosition,
2605 const VECTOR2I& aSheetSize,
2606 const SCH_SHEET_PATH& aParentSheet )
2607{
2608 wxCHECK_MSG( m_sheetMap.find( aCadstarSheetID ) == m_sheetMap.end(), ,
2609 "Sheet already loaded!" );
2610
2611 SCH_SHEET* sheet = new SCH_SHEET(
2612 /* aParent */ aParentSheet.Last(),
2613 /* aPosition */ aPosition,
2614 /* aSize */ VECTOR2I( aSheetSize ) );
2615 SCH_SCREEN* screen = new SCH_SCREEN( m_schematic );
2616 SCH_SHEET_PATH instance( aParentSheet );
2617
2618 sheet->SetScreen( screen );
2619
2620 wxString name = Sheets.SheetNames.at( aCadstarSheetID );
2621
2623
2624 int sheetNum = getSheetNumber( aCadstarSheetID );
2625 wxString loadedFilename = wxFileName( Filename ).GetName();
2626 std::string filename = wxString::Format( "%s_%02d", loadedFilename, sheetNum ).ToStdString();
2627
2628 ReplaceIllegalFileNameChars( filename );
2629 filename += wxT( "." ) + wxString( FILEEXT::KiCadSchematicFileExtension );
2630
2631 sheet->GetField( FIELD_T::SHEET_FILENAME )->SetText( filename );
2632
2633 wxFileName fn( m_schematic->Project().GetProjectPath() + filename );
2634 sheet->GetScreen()->SetFileName( fn.GetFullPath() );
2635 aParentSheet.Last()->GetScreen()->Append( sheet );
2636 instance.push_back( sheet );
2637
2638 wxString pageNumStr = wxString::Format( "%d", getSheetNumber( aCadstarSheetID ) );
2639 instance.SetPageNumber( pageNumStr );
2640
2641 sheet->AutoplaceFields( nullptr, AUTOPLACE_AUTO );
2642
2643 m_sheetMap.insert( { aCadstarSheetID, sheet } );
2644
2645 loadChildSheets( aCadstarSheetID, instance );
2646}
2647
2648
2650 const SCH_SHEET_PATH& aSheet )
2651{
2652 wxCHECK_MSG( m_sheetMap.find( aCadstarSheetID ) != m_sheetMap.end(), ,
2653 "FIXME! Parent sheet should be loaded before attempting to load subsheets" );
2654
2655 for( std::pair<BLOCK_ID, BLOCK> blockPair : Schematic.Blocks )
2656 {
2657 BLOCK& block = blockPair.second;
2658
2659 if( block.LayerID == aCadstarSheetID && block.Type == BLOCK::TYPE::CHILD )
2660 {
2661 if( block.AssocLayerID == wxT( "NO_LINK" ) )
2662 {
2663 if( block.Figures.size() > 0 )
2664 {
2665 m_reporter->Report( wxString::Format( _( "The block ID %s (Block name: '%s') is drawn on sheet "
2666 "'%s' but is not linked to another sheet in the design. "
2667 "KiCad requires all sheet symbols to be associated to a "
2668 "sheet, so the block was not loaded." ),
2669 block.ID, block.Name,
2670 Sheets.SheetNames.at( aCadstarSheetID ) ),
2672 }
2673
2674 continue;
2675 }
2676
2677 // In KiCad you can only draw rectangular shapes whereas in Cadstar arbitrary shapes
2678 // are allowed. We will calculate the extents of the Cadstar shape and draw a rectangle
2679
2680 std::pair<VECTOR2I, VECTOR2I> blockExtents;
2681
2682 if( block.Figures.size() > 0 )
2683 {
2684 blockExtents = getFigureExtentsKiCad( block.Figures.begin()->second );
2685 }
2686 else
2687 {
2688 THROW_IO_ERROR( wxString::Format( _( "The CADSTAR schematic might be corrupt: Block %s references "
2689 "a child sheet but has no Figure defined." ),
2690 block.ID ) );
2691 }
2692
2693 loadSheetAndChildSheets( block.AssocLayerID, blockExtents.first, blockExtents.second,
2694 aSheet );
2695
2696 // Hide all KiCad sheet properties (sheet name/filename is not applicable in CADSTAR)
2697 SCH_SHEET* loadedSheet = m_sheetMap.at( block.AssocLayerID );
2698 std::vector<SCH_FIELD> fields = loadedSheet->GetFields();
2699
2700 for( SCH_FIELD& field : fields )
2701 {
2702 field.SetVisible( false );
2703 }
2704
2705 if( block.HasBlockLabel )
2706 {
2707 //@todo use below code when KiCad supports multi-line fields
2708 /*
2709 // Add the block label as a separate field
2710 SCH_FIELD blockNameField( getKiCadPoint( block.BlockLabel.Position ), 2,
2711 loadedSheet, wxString( "Block name" ) );
2712 blockNameField.SetText( block.Name );
2713 blockNameField.SetVisible( true );
2714
2715 applyTextSettings( &blockNameField,
2716 block.BlockLabel.TextCodeID,
2717 block.BlockLabel.Alignment,
2718 block.BlockLabel.Justification,
2719 block.BlockLabel.OrientAngle,
2720 block.BlockLabel.Mirror );
2721
2722 fields.push_back( blockNameField );*/
2723
2724 // For now as as a text item (supports multi-line properly)
2725 SCH_TEXT* kiTxt = new SCH_TEXT();
2726
2727 kiTxt->SetParent( m_schematic );
2728 kiTxt->SetPosition( getKiCadPoint( block.BlockLabel.Position ) );
2729 kiTxt->SetText( block.Name );
2730
2733 block.BlockLabel.Mirror );
2734
2735 loadItemOntoKiCadSheet( aCadstarSheetID, kiTxt );
2736 }
2737
2738 loadedSheet->SetFields( fields );
2739 }
2740 }
2741}
2742
2743
2744std::vector<CADSTAR_SCH_ARCHIVE_LOADER::LAYER_ID> CADSTAR_SCH_ARCHIVE_LOADER::findOrphanSheets()
2745{
2746 std::vector<LAYER_ID> childSheets, orphanSheets;
2747
2748 //Find all sheets that are child of another
2749 for( std::pair<BLOCK_ID, BLOCK> blockPair : Schematic.Blocks )
2750 {
2751 BLOCK& block = blockPair.second;
2752 LAYER_ID& assocSheetID = block.AssocLayerID;
2753
2754 if( block.Type == BLOCK::TYPE::CHILD )
2755 childSheets.push_back( assocSheetID );
2756 }
2757
2758 //Add sheets that do not have a parent
2759 for( const LAYER_ID& sheetID : Sheets.SheetOrder )
2760 {
2761 if( std::find( childSheets.begin(), childSheets.end(), sheetID ) == childSheets.end() )
2762 orphanSheets.push_back( sheetID );
2763 }
2764
2765 return orphanSheets;
2766}
2767
2768
2770{
2771 int i = 1;
2772
2773 for( const LAYER_ID& sheetID : Sheets.SheetOrder )
2774 {
2775 if( sheetID == aCadstarSheetID )
2776 return i;
2777
2778 ++i;
2779 }
2780
2781 return -1;
2782}
2783
2784
2786 SCH_ITEM* aItem )
2787{
2788 wxCHECK_MSG( aItem, /*void*/, wxT( "aItem is null" ) );
2789
2790 if( aCadstarSheetID == "ALL_SHEETS" )
2791 {
2792 for( std::pair<LAYER_ID, SHEET_NAME> sheetPair : Sheets.SheetNames )
2793 {
2794 LAYER_ID sheetID = sheetPair.first;
2795 m_sheetMap.at( sheetID )->GetScreen()->Append( aItem->Duplicate( IGNORE_PARENT_GROUP ) );
2796 }
2797
2798 delete aItem;
2799 }
2800 else if( aCadstarSheetID == "NO_SHEET" )
2801 {
2802 wxFAIL_MSG( wxT( "Trying to add an item to NO_SHEET? This might be a documentation symbol." ) );
2803 }
2804 else
2805 {
2806 if( m_sheetMap.find( aCadstarSheetID ) != m_sheetMap.end() )
2807 {
2808 m_sheetMap.at( aCadstarSheetID )->GetScreen()->Append( aItem );
2809 }
2810 else
2811 {
2812 delete aItem;
2813 wxFAIL_MSG( wxT( "Unknown Sheet ID." ) );
2814 }
2815 }
2816}
2817
2818
2821 const wxString& aSymDefAlternate )
2822{
2823 if( m_SymDefNamesCache.size() != Library.SymbolDefinitions.size() )
2824 {
2825 // Re-initialise
2826 m_SymDefNamesCache.clear();
2828
2829 // Create a lower case cache to avoid searching each time
2830 for( auto& [id, symdef] : Library.SymbolDefinitions )
2831 {
2832 wxString refKey = symdef.ReferenceName.Lower();
2833 wxString altKey = symdef.Alternate.Lower();
2834
2835 m_SymDefNamesCache[{ refKey, altKey }] = id;
2836
2837 // Secondary cache to find symbols just by the Name (e.g. if the alternate
2838 // does not exist, we still want to return a symbo - the same behaviour
2839 // as CADSTAR
2840
2841 if( !m_DefaultSymDefNamesCache.count( refKey ) )
2842 {
2843 m_DefaultSymDefNamesCache.insert( { refKey, id } );
2844 }
2845 else if( altKey.IsEmpty() )
2846 {
2847 // Always use the empty alternate if it exists
2848 m_DefaultSymDefNamesCache[refKey] = id;
2849 }
2850 }
2851 }
2852
2853 wxString refKeyToFind = aSymdefName.Lower();
2854 wxString altKeyToFind = aSymDefAlternate.Lower();
2855
2856 if( m_SymDefNamesCache.count( { refKeyToFind, altKeyToFind } ) )
2857 {
2858 return m_SymDefNamesCache[{ refKeyToFind, altKeyToFind }];
2859 }
2860 else if( m_DefaultSymDefNamesCache.count( refKeyToFind ) )
2861 {
2862 return m_DefaultSymDefNamesCache[refKeyToFind];
2863 }
2864
2865 return SYMDEF_ID();
2866}
2867
2868
2870{
2871 // Use CADSTAR visibility settings to determine if an attribute is visible
2872 if( AttrColors.AttributeColors.find( aCadstarAttributeID ) != AttrColors.AttributeColors.end() )
2873 return AttrColors.AttributeColors.at( aCadstarAttributeID ).IsVisible;
2874
2875 return false; // If there is no visibility setting, assume not displayed
2876}
2877
2878
2880{
2881 wxCHECK( Assignments.Codedefs.LineCodes.find( aCadstarLineCodeID ) != Assignments.Codedefs.LineCodes.end(),
2882 schIUScale.MilsToIU( DEFAULT_WIRE_WIDTH_MILS ) );
2883
2884 return getKiCadLength( Assignments.Codedefs.LineCodes.at( aCadstarLineCodeID ).Width, 6.0 );
2885}
2886
2887
2889{
2890 wxCHECK( Assignments.Codedefs.LineCodes.find( aCadstarLineCodeID ) != Assignments.Codedefs.LineCodes.end(),
2892
2893 switch( Assignments.Codedefs.LineCodes.at( aCadstarLineCodeID ).Style )
2894 {
2895 case LINESTYLE::DASH: return LINE_STYLE::DASH;
2898 case LINESTYLE::DOT: return LINE_STYLE::DOT;
2900 default: return LINE_STYLE::DEFAULT;
2901 }
2902}
2903
2904
2907{
2908 wxCHECK( Assignments.Codedefs.TextCodes.find( aCadstarTextCodeID ) != Assignments.Codedefs.TextCodes.end(),
2909 TEXTCODE() );
2910
2911 return Assignments.Codedefs.TextCodes.at( aCadstarTextCodeID );
2912}
2913
2914
2916{
2917 TEXTCODE txtCode = getTextCode( aCadstarTextCodeID );
2918
2919 return KiROUND( (double) getKiCadLength( txtCode.Height, 50.0 ) * TXT_HEIGHT_RATIO );
2920}
2921
2922
2924{
2925 wxCHECK( Assignments.Codedefs.AttributeNames.find( aCadstarAttributeID )
2926 != Assignments.Codedefs.AttributeNames.end(),
2927 aCadstarAttributeID );
2928
2929 return Assignments.Codedefs.AttributeNames.at( aCadstarAttributeID ).Name;
2930}
2931
2932
2935{
2936 wxCHECK( Parts.PartDefinitions.find( aCadstarPartID ) != Parts.PartDefinitions.end(), PART() );
2937
2938 return Parts.PartDefinitions.at( aCadstarPartID );
2939}
2940
2941
2944{
2945 wxCHECK( Assignments.Codedefs.RouteCodes.find( aCadstarRouteCodeID ) != Assignments.Codedefs.RouteCodes.end(),
2946 ROUTECODE() );
2947
2948 return Assignments.Codedefs.RouteCodes.at( aCadstarRouteCodeID );
2949}
2950
2951
2952CADSTAR_SCH_ARCHIVE_LOADER::PART::DEFINITION::PIN
2954 const TERMINAL_ID& aTerminalID )
2955{
2956 for( std::pair<PART_DEFINITION_PIN_ID, PART::DEFINITION::PIN> pinPair :
2957 aCadstarPart.Definition.Pins )
2958 {
2959 PART::DEFINITION::PIN partPin = pinPair.second;
2960
2961 if( partPin.TerminalGate == aGateID && partPin.TerminalPin == aTerminalID )
2962 return partPin;
2963 }
2964
2965 return PART::DEFINITION::PIN();
2966}
2967
2968
2987
2989{
2990 if( aCadstarGateID.IsEmpty() )
2991 return 1;
2992
2993 return (int) aCadstarGateID.Upper().GetChar( 0 ) - (int) wxUniChar( 'A' ) + 1;
2994}
2995
2996
2997SPIN_STYLE CADSTAR_SCH_ARCHIVE_LOADER::getSpinStyle( const long long& aCadstarOrientation, bool aMirror )
2998{
2999 EDA_ANGLE orientation = getAngle( aCadstarOrientation );
3000 SPIN_STYLE spinStyle = getSpinStyle( orientation );
3001
3002 if( aMirror )
3003 {
3004 spinStyle = spinStyle.RotateCCW();
3005 spinStyle = spinStyle.RotateCCW();
3006 }
3007
3008 return spinStyle;
3009}
3010
3011
3013{
3014 SPIN_STYLE spinStyle = SPIN_STYLE::LEFT;
3015
3016 EDA_ANGLE oDeg = aOrientation;
3017 oDeg.Normalize180();
3018
3019 if( oDeg >= -ANGLE_45 && oDeg <= ANGLE_45 )
3020 spinStyle = SPIN_STYLE::RIGHT; // 0deg
3021 else if( oDeg >= ANGLE_45 && oDeg <= ANGLE_135 )
3022 spinStyle = SPIN_STYLE::UP; // 90deg
3023 else if( oDeg >= ANGLE_135 || oDeg <= -ANGLE_135 )
3024 spinStyle = SPIN_STYLE::LEFT; // 180deg
3025 else
3026 spinStyle = SPIN_STYLE::BOTTOM; // 270deg
3027
3028 return spinStyle;
3029}
3030
3031
3034{
3035 switch( aCadstarAlignment )
3036 {
3037 // Change left to right:
3042
3043 //Change right to left:
3047
3048 // Center alignment does not mirror:
3051 case ALIGNMENT::TOPCENTER: return aCadstarAlignment;
3052
3053 // Shouldn't be here
3054 default: wxFAIL_MSG( "Unknown Cadstar Alignment" ); return aCadstarAlignment;
3055 }
3056}
3057
3058
3061{
3062 switch( aCadstarAlignment )
3063 {
3074
3075 // Shouldn't be here
3076 default: wxFAIL_MSG( "Unknown Cadstar Alignment" ); return aCadstarAlignment;
3077 }
3078}
3079
3080
3082 const TEXTCODE_ID& aCadstarTextCodeID )
3083{
3084 // Ensure we have no Cadstar overbar characters
3085 wxString escapedText = HandleTextOverbar( aKiCadTextItem->GetText() );
3086 aKiCadTextItem->SetText( escapedText );
3087
3088 if( !Assignments.Codedefs.TextCodes.count( aCadstarTextCodeID ) )
3089 return;
3090
3091 TEXTCODE textCode = getTextCode( aCadstarTextCodeID );
3092 int textHeight = KiROUND( (double) getKiCadLength( textCode.Height, 50.0 ) * TXT_HEIGHT_RATIO );
3093 int textWidth = getKiCadLength( textCode.Width, 50.0 );
3094
3095 // The width is zero for all non-cadstar fonts. Using a width equal to 2/3 the height seems
3096 // to work well for most fonts.
3097 if( textWidth == 0 )
3098 textWidth = getKiCadLength( 2LL * textCode.Height / 3LL, 50.0 );
3099
3100 aKiCadTextItem->SetTextWidth( textWidth );
3101 aKiCadTextItem->SetTextHeight( textHeight );
3102
3103#if 0
3104 // EEschema currently supports only normal vs bold for text thickness.
3105 aKiCadTextItem->SetTextThickness( getKiCadLength( textCode.LineWidth, 6.0 ) );
3106#endif
3107
3108 // Must come after SetTextSize()
3109 aKiCadTextItem->SetBold( textCode.Font.Modifier1 == FONT_BOLD );
3110 aKiCadTextItem->SetItalic( textCode.Font.Italic );
3111}
3112
3113
3115 const TEXTCODE_ID& aCadstarTextCodeID,
3116 const ALIGNMENT& aCadstarAlignment,
3117 const JUSTIFICATION& aCadstarJustification,
3118 const long long aCadstarOrientAngle,
3119 bool aMirrored )
3120{
3121 applyTextCodeIfExists( aKiCadTextItem, aCadstarTextCodeID );
3122 aKiCadTextItem->SetTextAngle( getAngle( aCadstarOrientAngle ) );
3123
3124 // Justification ignored for now as not supported in Eeschema, but leaving this code in
3125 // place for future upgrades.
3126 // TODO update this when Eeschema supports justification independent of anchor position.
3127 ALIGNMENT textAlignment = aCadstarAlignment;
3128
3129 // KiCad mirrors the justification and alignment when the symbol is mirrored but CADSTAR
3130 // specifies it post-mirroring. In contrast, if the text item itself is mirrored (not
3131 // supported in KiCad), CADSTAR specifies the alignment and justification pre-mirroring
3132 if( aMirrored )
3133 textAlignment = mirrorX( aCadstarAlignment );
3134
3135 auto setAlignment =
3136 [&]( EDA_TEXT* aText, ALIGNMENT aAlignment )
3137 {
3138 switch( aAlignment )
3139 {
3140 case ALIGNMENT::NO_ALIGNMENT: // Bottom left of the first line
3141 //No exact KiCad equivalent, so lets move the position of the text
3147 break;
3148
3152 break;
3153
3157 break;
3158
3162 break;
3163
3167 break;
3168
3172 break;
3173
3174 case ALIGNMENT::TOPLEFT:
3177 break;
3178
3182 break;
3183
3187 break;
3188 }
3189 };
3190
3191 SPIN_STYLE spin = getSpinStyle( aCadstarOrientAngle, aMirrored );
3192 EDA_ITEM* textEdaItem = dynamic_cast<EDA_ITEM*>( aKiCadTextItem );
3193 wxCHECK( textEdaItem, /* void */ ); // ensure this is a EDA_ITEM
3194
3195 if( textEdaItem->Type() == SCH_FIELD_T )
3196 {
3197 // Spin style not used. All text justifications are permitted. However, only orientations
3198 // of 0 deg or 90 deg are supported
3199 EDA_ANGLE angle = aKiCadTextItem->GetTextAngle();
3200 angle.Normalize();
3201
3202 int quadrant = KiROUND( angle.AsDegrees() / 90.0 );
3203 quadrant %= 4;
3204
3205 switch( quadrant )
3206 {
3207 case 0:
3208 angle = ANGLE_HORIZONTAL;
3209 break;
3210 case 1:
3211 angle = ANGLE_VERTICAL;
3212 break;
3213 case 2:
3214 angle = ANGLE_HORIZONTAL;
3215 textAlignment = rotate180( textAlignment );
3216 break;
3217 case 3:
3218 angle = ANGLE_VERTICAL;
3219 textAlignment = rotate180( textAlignment );
3220 break;
3221 default:
3222 wxFAIL_MSG( "Unknown Quadrant" );
3223 }
3224
3225 aKiCadTextItem->SetTextAngle( angle );
3226 setAlignment( aKiCadTextItem, textAlignment );
3227 }
3228 else if( textEdaItem->Type() == SCH_TEXT_T )
3229 {
3230 // Note spin style in a SCH_TEXT results in a vertical alignment GR_TEXT_V_ALIGN_BOTTOM
3231 // so need to adjust the location of the text element based on Cadstar's original text
3232 // alignment (anchor position).
3233 setAlignment( aKiCadTextItem, textAlignment );
3234 BOX2I bb = textEdaItem->GetBoundingBox();
3235 int off = static_cast<SCH_TEXT*>( aKiCadTextItem )->GetTextOffset();
3236 VECTOR2I pos;
3237
3238 // Change the anchor point of the text item to make it match the same bounding box
3239 // And correct the error introduced by the text offsetting in KiCad
3240 switch( spin )
3241 {
3242 case SPIN_STYLE::BOTTOM: pos = { bb.GetRight() - off, bb.GetTop() }; break;
3243 case SPIN_STYLE::UP: pos = { bb.GetRight() - off, bb.GetBottom() }; break;
3244 case SPIN_STYLE::LEFT: pos = { bb.GetRight() , bb.GetBottom() + off }; break;
3245 case SPIN_STYLE::RIGHT: pos = { bb.GetLeft() , bb.GetBottom() + off }; break;
3246 default: wxFAIL_MSG( "Unexpected Spin Style" ); break;
3247 }
3248
3249 aKiCadTextItem->SetTextPos( pos );
3250
3251 switch( spin )
3252 {
3253 case SPIN_STYLE::RIGHT: // Horiz Normal Orientation
3254 aKiCadTextItem->SetTextAngle( ANGLE_HORIZONTAL );
3255 aKiCadTextItem->SetHorizJustify( GR_TEXT_H_ALIGN_LEFT );
3256 break;
3257
3258 case SPIN_STYLE::UP: // Vert Orientation UP
3259 aKiCadTextItem->SetTextAngle( ANGLE_VERTICAL );
3260 aKiCadTextItem->SetHorizJustify( GR_TEXT_H_ALIGN_LEFT );
3261 break;
3262
3263 case SPIN_STYLE::LEFT: // Horiz Orientation - Right justified
3264 aKiCadTextItem->SetTextAngle( ANGLE_HORIZONTAL );
3265 aKiCadTextItem->SetHorizJustify( GR_TEXT_H_ALIGN_RIGHT );
3266 break;
3267
3268 case SPIN_STYLE::BOTTOM: // Vert Orientation BOTTOM
3269 aKiCadTextItem->SetTextAngle( ANGLE_VERTICAL );
3270 aKiCadTextItem->SetHorizJustify( GR_TEXT_H_ALIGN_RIGHT );
3271 break;
3272
3273 default:
3274 wxFAIL_MSG( "Unexpected Spin Style" );
3275 break;
3276 }
3277
3278 aKiCadTextItem->SetVertJustify( GR_TEXT_V_ALIGN_BOTTOM );
3279 }
3280 else if( SCH_LABEL_BASE* label = dynamic_cast<SCH_LABEL_BASE*>( aKiCadTextItem ) )
3281 {
3282 // We don't want to change position of net labels as that would break connectivity
3283 label->SetSpinStyle( spin );
3284 }
3285 else
3286 {
3287 wxFAIL_MSG( "Unexpected item type" );
3288 }
3289}
3290
3291
3293{
3294 SCH_TEXT* kiTxt = new SCH_TEXT();
3295
3296 kiTxt->SetParent( m_schematic ); // set to the schematic for now to avoid asserts
3297 kiTxt->SetPosition( getKiCadPoint( aCadstarTextElement.Position ) );
3298 kiTxt->SetText( aCadstarTextElement.Text );
3299
3300 applyTextSettings( kiTxt, aCadstarTextElement.TextCodeID, aCadstarTextElement.Alignment,
3301 aCadstarTextElement.Justification, aCadstarTextElement.OrientAngle,
3302 aCadstarTextElement.Mirror );
3303
3304 return kiTxt;
3305}
3306
3307
3309 long long aScalingFactorNumerator,
3310 long long aScalingFactorDenominator )
3311{
3312 LIB_SYMBOL* retval = new LIB_SYMBOL( *aSymbol );
3313
3314 if( aScalingFactorNumerator == aScalingFactorDenominator )
3315 return retval; // 1:1 scale, nothing to do
3316
3317 auto scaleLen =
3318 [&]( int aLength ) -> int
3319 {
3320 return( aLength * aScalingFactorNumerator ) / aScalingFactorDenominator;
3321 };
3322
3323 auto scalePt =
3324 [&]( VECTOR2I aCoord ) -> VECTOR2I
3325 {
3326 return VECTOR2I( scaleLen( aCoord.x ), scaleLen( aCoord.y ) );
3327 };
3328
3329 auto scaleSize =
3330 [&]( VECTOR2I aSize ) -> VECTOR2I
3331 {
3332 return VECTOR2I( scaleLen( aSize.x ), scaleLen( aSize.y ) );
3333 };
3334
3335 LIB_ITEMS_CONTAINER& items = retval->GetDrawItems();
3336
3337 for( SCH_ITEM& item : items )
3338 {
3339 switch( item.Type() )
3340 {
3342 {
3343 SCH_SHAPE& shape = static_cast<SCH_SHAPE&>( item );
3344
3345 if( shape.GetShape() == SHAPE_T::ARC )
3346 {
3347 shape.SetPosition( scalePt( shape.GetPosition() ) );
3348 shape.SetStart( scalePt( shape.GetStart() ) );
3349 shape.SetEnd( scalePt( shape.GetEnd() ) );
3350 }
3351 else if( shape.GetShape() == SHAPE_T::POLY && !shape.GetPolyShape().IsEmpty() )
3352 {
3353 SHAPE_LINE_CHAIN& poly = shape.GetPolyShape().Outline( 0 );
3354
3355 for( int ii = 0; ii < (int) poly.GetPointCount(); ++ii )
3356 poly.SetPoint( ii, scalePt( poly.CPoint( ii ) ) );
3357 }
3358
3359 break;
3360 }
3361
3362 case KICAD_T::SCH_PIN_T:
3363 {
3364 SCH_PIN& pin = static_cast<SCH_PIN&>( item );
3365
3366 pin.SetPosition( scalePt( pin.GetPosition() ) );
3367 pin.SetLength( scaleLen( pin.GetLength() ) );
3368 break;
3369 }
3370
3372 {
3373 SCH_TEXT& txt = static_cast<SCH_TEXT&>( item );
3374
3375 txt.SetPosition( scalePt( txt.GetPosition() ) );
3376 txt.SetTextSize( scaleSize( txt.GetTextSize() ) );
3377 break;
3378 }
3379
3380 default:
3381 break;
3382 }
3383 }
3384
3385 return retval;
3386}
3387
3388
3389void CADSTAR_SCH_ARCHIVE_LOADER::fixUpLibraryPins( LIB_SYMBOL* aSymbolToFix, int aGateNumber )
3390{
3391 auto compLambda =
3392 []( const VECTOR2I& aA, const VECTOR2I& aB )
3393 {
3394 return LexicographicalCompare( aA, aB ) < 0;
3395 };
3396
3397 // Store a list of vertical or horizontal segments in the symbol
3398 // Note: Need the custom comparison function to ensure the map is sorted correctly
3399 std::map<VECTOR2I, SHAPE_LINE_CHAIN, decltype( compLambda )> uniqueSegments( compLambda );
3400
3401 LIB_ITEMS_CONTAINER::ITERATOR shapeIt = aSymbolToFix->GetDrawItems().begin( SCH_SHAPE_T );
3402
3403 for( ; shapeIt != aSymbolToFix->GetDrawItems().end( SCH_SHAPE_T ); ++shapeIt )
3404 {
3405 SCH_SHAPE& shape = static_cast<SCH_SHAPE&>( *shapeIt );
3406
3407 if( aGateNumber > 0 && shape.GetUnit() != aGateNumber )
3408 continue;
3409
3410 if( shape.GetShape() != SHAPE_T::POLY )
3411 continue;
3412
3413 SHAPE_LINE_CHAIN poly = shape.GetPolyShape().Outline( 0 );
3414
3415 if( poly.GetPointCount() == 2 )
3416 {
3417 VECTOR2I pt0 = poly.CPoint( 0 );
3418 VECTOR2I pt1 = poly.CPoint( 1 );
3419
3420 if( pt0 != pt1 && uniqueSegments.count( pt0 ) == 0 && uniqueSegments.count( pt1 ) == 0 )
3421 {
3422 // we are only interested in vertical or horizontal segments
3423 if( pt0.x == pt1.x || pt0.y == pt1.y )
3424 {
3425 uniqueSegments.insert( { pt0, poly } );
3426 uniqueSegments.insert( { pt1, poly } );
3427 }
3428 }
3429 }
3430 }
3431
3432 for( SCH_PIN* pin : aSymbolToFix->GetGraphicalPins( aGateNumber, 0 ) )
3433 {
3434 auto setPinOrientation =
3435 [&]( const EDA_ANGLE& aAngle )
3436 {
3437 EDA_ANGLE angle( aAngle );
3438 angle.Normalize180();
3439
3440 if( angle >= -ANGLE_45 && angle <= ANGLE_45 )
3441 pin->SetOrientation( PIN_ORIENTATION::PIN_RIGHT ); // 0 degrees
3442 else if( angle >= ANGLE_45 && angle <= ANGLE_135 )
3443 pin->SetOrientation( PIN_ORIENTATION::PIN_UP ); // 90 degrees
3444 else if( angle >= ANGLE_135 || angle <= -ANGLE_135 )
3445 pin->SetOrientation( PIN_ORIENTATION::PIN_LEFT ); // 180 degrees
3446 else
3447 pin->SetOrientation( PIN_ORIENTATION::PIN_DOWN ); // -90 degrees
3448 };
3449
3450 if( uniqueSegments.count( pin->GetPosition() ) )
3451 {
3452 SHAPE_LINE_CHAIN& poly = uniqueSegments.at( pin->GetPosition() );
3453
3454 VECTOR2I otherPt = poly.CPoint( 0 );
3455
3456 if( otherPt == pin->GetPosition() )
3457 otherPt = poly.CPoint( 1 );
3458
3459 VECTOR2I vec( otherPt - pin->GetPosition() );
3460
3461 pin->SetLength( vec.EuclideanNorm() );
3462 setPinOrientation( EDA_ANGLE( vec ) );
3463 }
3464 }
3465}
3466
3467
3468std::pair<VECTOR2I, VECTOR2I>
3470{
3471 VECTOR2I upperLeft( Assignments.Settings.DesignLimit.x, 0 );
3472 VECTOR2I lowerRight( 0, Assignments.Settings.DesignLimit.y );
3473
3474 for( const VERTEX& v : aCadstarFigure.Shape.Vertices )
3475 {
3476 if( upperLeft.x > v.End.x )
3477 upperLeft.x = v.End.x;
3478
3479 if( upperLeft.y < v.End.y )
3480 upperLeft.y = v.End.y;
3481
3482 if( lowerRight.x < v.End.x )
3483 lowerRight.x = v.End.x;
3484
3485 if( lowerRight.y > v.End.y )
3486 lowerRight.y = v.End.y;
3487 }
3488
3489 for( CUTOUT cutout : aCadstarFigure.Shape.Cutouts )
3490 {
3491 for( const VERTEX& v : aCadstarFigure.Shape.Vertices )
3492 {
3493 if( upperLeft.x > v.End.x )
3494 upperLeft.x = v.End.x;
3495
3496 if( upperLeft.y < v.End.y )
3497 upperLeft.y = v.End.y;
3498
3499 if( lowerRight.x < v.End.x )
3500 lowerRight.x = v.End.x;
3501
3502 if( lowerRight.y > v.End.y )
3503 lowerRight.y = v.End.y;
3504 }
3505 }
3506
3507 VECTOR2I upperLeftKiCad = getKiCadPoint( upperLeft );
3508 VECTOR2I lowerRightKiCad = getKiCadPoint( lowerRight );
3509
3510 VECTOR2I size = lowerRightKiCad - upperLeftKiCad;
3511
3512 return { upperLeftKiCad, VECTOR2I( abs( size.x ), abs( size.y ) ) };
3513}
3514
3515
3517{
3518 VECTOR2I retval;
3519
3520 retval.x = getKiCadOffset( aCadstarPoint.x - m_designCenter.x );
3521 retval.y = -getKiCadOffset( aCadstarPoint.y - m_designCenter.y );
3522
3523 return retval;
3524}
3525
3526
3528 const VECTOR2I& aCadstarCentre )
3529{
3530 VECTOR2I retval;
3531
3532 retval.x = getKiCadOffset( aCadstarPoint.x - aCadstarCentre.x );
3533 retval.y = -getKiCadOffset( aCadstarPoint.y - aCadstarCentre.y );
3534
3535 return retval;
3536}
3537
3538
3540 const VECTOR2I& aMoveVector,
3541 const EDA_ANGLE& aRotation,
3542 const double& aScalingFactor,
3543 const VECTOR2I& aTransformCentre,
3544 const bool& aMirrorInvert )
3545{
3546 VECTOR2I retVal = aPoint;
3547
3548 if( aScalingFactor != 1.0 )
3549 {
3550 //scale point
3551 retVal -= aTransformCentre;
3552 retVal.x = KiROUND( retVal.x * aScalingFactor );
3553 retVal.y = KiROUND( retVal.y * aScalingFactor );
3554 retVal += aTransformCentre;
3555 }
3556
3557 if( aMirrorInvert )
3558 MIRROR( retVal.x, aTransformCentre.x );
3559
3560 if( !aRotation.IsZero() )
3561 RotatePoint( retVal, aTransformCentre, aRotation );
3562
3563 if( aMoveVector != VECTOR2I{ 0, 0 } )
3564 retVal += aMoveVector;
3565
3566 return retVal;
3567}
3568
3569
3571{
3572 return sqrt( ( (double) aPoint.x * (double) aPoint.x )
3573 + ( (double) aPoint.y * (double) aPoint.y ) );
3574}
const char * name
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
constexpr double SCH_IU_PER_MM
Schematic internal units 1=100nm.
Definition base_units.h:70
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
@ OUTPUT_NOT_OR
Output pin not OR tieable.
@ TRISTATE_DRIVER
Tristate output pin.
@ OUTPUT_OR
Output pin OR tieable.
@ UNCOMMITTED
Uncommitted pin (default)
@ TRISTATE_INPUT
Tristate input pin.
@ TRISTATE_BIDIR
Tristate bi-directional driver pin.
@ OUTPUT_NOT_NORM_OR
Output pin not normally OR tieable.
#define SYMBOL_NAME_ATTRID
Symbol Name attribute ID - used for placement of designators on the schematic.
#define SIGNALNAME_ORIGIN_ATTRID
#define LINK_ORIGIN_ATTRID
#define PART_NAME_ATTRID
const wxString PartAcceptanceFieldName
const wxString PartNumberFieldName
const wxString PartNameFieldName
const wxString PartVersionFieldName
Loads a csa file into a KiCad SCHEMATIC object.
constexpr Vec Centre() const
Definition box2.h:100
constexpr BOX2< Vec > & Merge(const BOX2< Vec > &aRect)
Modify the position and size of the rectangle in order to contain aRect.
Definition box2.h:597
constexpr coord_type GetLeft() const
Definition box2.h:231
constexpr coord_type GetRight() const
Definition box2.h:220
constexpr const SizeVec & GetSize() const
Definition box2.h:209
constexpr coord_type GetTop() const
Definition box2.h:232
constexpr coord_type GetBottom() const
Definition box2.h:225
static wxString EscapeFieldText(const wxString &aFieldText)
@ FRACTIONALGRID
Param1 = Units, Param2 = Divisor.
static const std::map< TEXT_FIELD_NAME, wxString > CADSTAR_TO_KICAD_FIELDS
Map between CADSTAR fields and KiCad text variables.
long TERMINAL_ID
Terminal is the pin identifier in the schematic.
TEXT_FIELD_NAME
These are special fields in text objects enclosed between the tokens '<@' and '>' such as <@[FIELD_NA...
ALIGNMENT
From CADSTAR Help: "Text Alignment enables you to define the position of an alignment origin for all ...
@ NO_ALIGNMENT
NO_ALIGNMENT has different meaning depending on the object type.
static wxString generateLibName(const wxString &aRefName, const wxString &aAlternateName)
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.
static wxString HandleTextOverbar(wxString aCadstarString)
Convert a string with CADSTAR overbar characters to equivalent in KiCad.
JUSTIFICATION
From CADSTAR Help: "Multi Line Text can also be justified as Left, Centre or Right.
PROGRESS_REPORTER * m_progressReporter
bool CheckFileHeader(const std::filesystem::path &aPath) const
CADSTAR_PARTS_LIB_MODEL ReadFile(const std::filesystem::path &aPath) const
void loadItemOntoKiCadSheet(const LAYER_ID &aCadstarSheetID, SCH_ITEM *aItem)
void Load(SCHEMATIC *aSchematic, SCH_SHEET *aRootSheet)
Loads a CADSTAR Schematic Archive file into the KiCad SCHEMATIC object given.
ROUTECODE getRouteCode(const ROUTECODE_ID &aCadstarRouteCodeID)
static wxString CreateLibName(const wxFileName &aFileName, const SCH_SHEET *aRootSheet)
std::map< BLOCK_PIN_ID, SCH_HIERLABEL * > m_sheetPinMap
Cadstar->KiCad Sheet Pins.
VECTOR2I applyTransform(const VECTOR2I &aPoint, const VECTOR2I &aMoveVector={ 0, 0 }, const EDA_ANGLE &aRotation=ANGLE_0, const double &aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, const bool &aMirrorInvert=false)
std::map< SYMBOL_ID, SCH_GLOBALLABEL * > m_globalLabelsMap
Cadstar->KiCad Global Labels.
SCH_SYMBOL * loadSchematicSymbol(const SYMBOL &aCadstarSymbol, const LIB_SYMBOL &aKiCadPart, EDA_ANGLE &aComponentOrientation)
void applyTextSettings(EDA_TEXT *aKiCadTextItem, const TEXTCODE_ID &aCadstarTextCodeID, const ALIGNMENT &aCadstarAlignment, const JUSTIFICATION &aCadstarJustification, const long long aCadstarOrientAngle=0, bool aMirrored=false)
void loadSheetAndChildSheets(const LAYER_ID &aCadstarSheetID, const VECTOR2I &aPosition, const VECTOR2I &aSheetSize, const SCH_SHEET_PATH &aParentSheet)
wxString getAttributeName(const ATTRIBUTE_ID &aCadstarAttributeID)
std::vector< LIB_SYMBOL * > m_loadedSymbols
Loaded symbols so far.
static SCH_FIELD * addNewFieldToSymbol(const wxString &aFieldName, LIB_SYMBOL *aKiCadSymbol)
PART getPart(const PART_ID &aCadstarPartID)
std::vector< LAYER_ID > findOrphanSheets()
void setFootprintOnSymbol(LIB_SYMBOL *aKiCadSymbol, const wxString &aFootprintName, const wxString &aFootprintAlternate)
std::map< BUS_ID, std::shared_ptr< BUS_ALIAS > > m_busesMap
Cadstar->KiCad Buses.
SCH_TEXT * getKiCadSchText(const TEXT &aCadstarTextElement)
std::map< TERMINAL_ID, wxString > TERMINAL_TO_PINNUM_MAP
Map between a terminal ID in a symbol definition to the pin number that should be imported into KiCad...
wxString getNetName(const NET_SCH &aNet)
std::pair< BLOCK_ID, TERMINAL_ID > BLOCK_PIN_ID
std::map< SYMBOL_ID, SCH_SYMBOL * > m_powerSymMap
Cadstar->KiCad Power Symbols.
std::pair< PART_ID, GATE_ID > PART_GATE_ID
VECTOR2I getKiCadLibraryPoint(const VECTOR2I &aCadstarPoint, const VECTOR2I &aCadstarCentre)
std::vector< std::unique_ptr< LIB_SYMBOL > > m_ownedSymbols
Owns every LIB_SYMBOL the loader allocates while loading a design.
int getKiCadLength(long long aCadstarLength, double aDefaultInMils)
PART::DEFINITION::PIN getPartDefinitionPin(const PART &aCadstarPart, const GATE_ID &aGateID, const TERMINAL_ID &aTerminalID)
std::map< wxString, TERMINAL_ID > PINNUM_TO_TERMINAL_MAP
std::map< SYMDEF_ID, PINNUM_TO_TERMINAL_MAP > m_symDefTerminalsMap
int getTextHeightFromTextCode(const TEXTCODE_ID &aCadstarTextCodeID)
void loadChildSheets(const LAYER_ID &aCadstarSheetID, const SCH_SHEET_PATH &aSheet)
void applyToLibraryFieldAttribute(const ATTRIBUTE_LOCATION &aCadstarAttrLoc, const VECTOR2I &aSymbolOrigin, SCH_FIELD *aKiCadField)
double getPolarRadius(const VECTOR2I &aPoint)
void applyTextCodeIfExists(EDA_TEXT *aKiCadTextItem, const TEXTCODE_ID &aCadstarTextCodeID)
int getSheetNumber(const LAYER_ID &aCadstarSheetID)
int getLineThickness(const LINECODE_ID &aCadstarLineCodeID)
TEXTCODE getTextCode(const TEXTCODE_ID &aCadstarTextCodeID)
SPIN_STYLE getSpinStyle(const long long &aCadstarOrientation, bool aMirror)
std::map< wxString, LIB_SYMBOL * > m_powerSymLibMap
NetName->KiCad Power Lib Symbol.
std::map< std::pair< wxString, wxString >, SYMDEF_ID > m_SymDefNamesCache
Cache storing symbol names and alternates to symdef IDs.
std::map< PART_ID, TERMINAL_TO_PINNUM_MAP > m_pinNumsMap
Cadstar Part->KiCad Pin number map.
std::vector< LIB_SYMBOL * > LoadPartsLib(const wxString &aFilename)
ELECTRICAL_PINTYPE getKiCadPinType(const CADSTAR_PIN_TYPE &aPinType)
wxString m_footprintLibName
Name of the footprint library to prepend all footprints with.
std::map< PART_ID, LIB_SYMBOL * > m_partMap
Cadstar->KiCad Parts.
bool isAttributeVisible(const ATTRIBUTE_ID &aCadstarAttributeID)
VECTOR2I getKiCadPoint(const VECTOR2I &aCadstarPoint)
EDA_ANGLE getAngle(const long long &aCadstarAngle)
std::map< wxString, SYMDEF_ID > m_DefaultSymDefNamesCache
Cache storing symbol names (default alternate) to symdef IDs.
void loadSymbolGateAndPartFields(const SYMDEF_ID &aSymdefID, const PART &aCadstarPart, const GATE_ID &aGateID, LIB_SYMBOL *aSymbol)
void loadFigure(const FIGURE &aCadstarFigure, const LAYER_ID &aCadstarSheetIDOverride, SCH_LAYER_ID aKiCadSchLayerID, const VECTOR2I &aMoveVector={ 0, 0 }, const EDA_ANGLE &aRotation=ANGLE_0, const double &aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, const bool &aMirrorInvert=false)
std::map< PART_GATE_ID, SYMDEF_ID > m_partSymbolsMap
Map holding the symbols loaded so far for a particular PART_ID and GATE_ID.
LIB_SYMBOL * getScaledLibPart(const LIB_SYMBOL *aSymbol, long long aScalingFactorNumerator, long long aScalingFactorDenominator)
SYMDEF_ID getSymDefFromName(const wxString &aSymdefName, const wxString &aSymDefAlternate)
std::pair< VECTOR2I, VECTOR2I > getFigureExtentsKiCad(const FIGURE &aCadstarFigure)
std::map< LAYER_ID, SCH_SHEET * > m_sheetMap
Cadstar->KiCad Sheets.
void copySymbolItems(LIB_SYMBOL *aSourceSym, LIB_SYMBOL *aDestSym, int aDestUnit, bool aOverrideFields=true)
POINT getLocationOfNetElement(const NET_SCH &aNet, const NETELEMENT_ID &aNetElementID)
void fixUpLibraryPins(LIB_SYMBOL *aSymbolToFix, int aGateNumber)
std::map< SYMDEF_ID, std::unique_ptr< const LIB_SYMBOL > > m_symDefMap
Cadstar->KiCad Lib Symbols loaded so far.
std::unique_ptr< LIB_SYMBOL > loadLibPart(const CADSTAR_PART_ENTRY &aPart)
ALIGNMENT rotate180(const ALIGNMENT &aCadstarAlignment)
long long getCadstarAngle(const EDA_ANGLE &aAngle)
LINE_STYLE getLineStyle(const LINECODE_ID &aCadstarLineCodeID)
VECTOR2I m_designCenter
Required for calculating the offset to apply to the Cadstar design so that it fits in the KiCad canva...
ALIGNMENT mirrorX(const ALIGNMENT &aCadstarAlignment)
void loadLibrarySymbolShapeVertices(const std::vector< VERTEX > &aCadstarVertices, const VECTOR2I &aSymbolOrigin, LIB_SYMBOL *aSymbol, int aGateNumber, int aLineThickness, LINE_STYLE aLineStyle)
int getKiCadOffset(long long aCadstarOffset)
int getComponentOrientation(const EDA_ANGLE &aOrientAngle, EDA_ANGLE &aReturnedOrientation)
void loadShapeVertices(const std::vector< VERTEX > &aCadstarVertices, LINECODE_ID aCadstarLineCodeID, LAYER_ID aCadstarSheetID, SCH_LAYER_ID aKiCadSchLayerID, const VECTOR2I &aMoveVector={ 0, 0 }, const EDA_ANGLE &aRotation=ANGLE_0, const double &aScalingFactor=1.0, const VECTOR2I &aTransformCentre={ 0, 0 }, const bool &aMirrorInvert=false)
const LIB_SYMBOL * loadSymdef(const SYMDEF_ID &aSymdefID)
int getKiCadUnitNumberFromGate(const GATE_ID &aCadstarGateID)
void loadSymbolFieldAttribute(const ATTRIBUTE_LOCATION &aCadstarAttrLoc, const EDA_ANGLE &aComponentOrientation, bool aIsMirrored, SCH_FIELD *aKiCadField)
int KiCadUnitDivider
Use this value to convert units in this CSA file to KiCad units.
EDA_ANGLE Normalize()
Definition eda_angle.h:228
double AsDegrees() const
Definition eda_angle.h:115
bool IsZero() const
Definition eda_angle.h:135
EDA_ANGLE Normalize180()
Definition eda_angle.h:273
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
virtual const BOX2I GetBoundingBox() const
Return the orthogonal bounding box of this object for display purposes.
Definition eda_item.cpp:280
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
EDA_ITEM * GetParent() const
Definition eda_item.h:112
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
virtual void SetEnd(const VECTOR2I &aEnd)
Definition eda_shape.h:338
void SetLineStyle(const LINE_STYLE aStyle)
SHAPE_POLY_SET & GetPolyShape()
SHAPE_T GetShape() const
Definition eda_shape.h:178
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:334
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:284
virtual void SetArcGeometry(const VECTOR2I &aStart, const VECTOR2I &aMid, const VECTOR2I &aEnd)
Set the three controlling points for an arc.
void SetFillMode(FILL_T aFill)
virtual void SetPolyShape(const SHAPE_POLY_SET &aShape)
Definition eda_shape.h:529
virtual void SetStart(const VECTOR2I &aStart)
Definition eda_shape.h:288
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
virtual VECTOR2I GetTextSize() const
Definition eda_text.h:301
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
virtual int GetTextHeight() const
Definition eda_text.h:307
void SetVertJustify(GR_TEXT_V_ALIGN_T aType)
Definition eda_text.cpp:379
virtual int GetTextWidth() const
Definition eda_text.h:304
virtual void SetTextWidth(int aWidth)
Definition eda_text.cpp:535
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
virtual void SetTextThickness(int aWidth)
The TextThickness is that set by the user.
Definition eda_text.cpp:251
virtual void SetTextHeight(int aHeight)
Definition eda_text.cpp:546
virtual EDA_ANGLE GetTextAngle() const
Definition eda_text.h:178
void SetBold(bool aBold)
Set the text to be bold - this will also update the font if needed.
Definition eda_text.cpp:311
virtual int GetTextThickness() const
Definition eda_text.h:159
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
virtual void SetTextAngle(const EDA_ANGLE &aAngle)
Definition eda_text.cpp:269
void SetItalic(bool aItalic)
Set the text to be italic - this will also update the font if needed.
Definition eda_text.cpp:291
void SetMultilineAllowed(bool aAllow)
Definition eda_text.cpp:363
void SetHorizJustify(GR_TEXT_H_ALIGN_T aType)
Definition eda_text.cpp:371
ee_rtree::Iterator begin() const
Return a read/write iterator that points to the first.
Definition sch_rtree.h:288
ee_rtree::Iterator end() const
Return a read/write iterator that points to one past the last element in the EE_RTREE.
Definition sch_rtree.h:296
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int SetLibItemName(const UTF8 &aLibItemName)
Override the library item name portion of the LIB_ID to aLibItemName.
Definition lib_id.cpp:124
int SetLibNickname(const UTF8 &aLibNickname)
Override the logical library name portion of the LIB_ID to aLibNickname.
Definition lib_id.cpp:113
UTF8 Format() const
Definition lib_id.cpp:132
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:205
Define a library symbol object.
Definition lib_symbol.h:114
void SetGlobalPower()
void GetFields(std::vector< SCH_FIELD * > &aList, bool aVisibleOnly=false) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
std::vector< struct LIB_SYMBOL_UNIT > GetUnitDrawItems()
Return a list of SCH_ITEM objects separated by unit and convert number.
SCH_FIELD * GetField(const wxString &aFieldName)
Find a field within this symbol matching aFieldName; return nullptr if not found.
SCH_FIELD & GetFootprintField()
Definition lib_symbol.h:457
LIB_ITEMS_CONTAINER & GetDrawItems()
Return a reference to the draw item list.
Definition lib_symbol.h:845
wxString GetName() const override
Definition lib_symbol.h:183
void SetDescription(const wxString &aDescription)
Set the Description field text value.
SCH_FIELD & GetValueField()
Definition lib_symbol.h:449
void RemoveDrawItem(SCH_ITEM *aItem)
Remove draw aItem from list.
void SetFPFilters(const wxArrayString &aFilters)
Definition lib_symbol.h:250
std::vector< SCH_PIN * > GetPinsByNumber(const wxString &aNumber, int aUnit=0, int aBodyStyle=0)
Return all pin objects with the requested pin aNumber.
void AddField(SCH_FIELD *aField)
Add a field.
std::vector< SCH_PIN * > GetGraphicalPins(int aUnit=0, int aBodyStyle=0) const override
Graphical pins: Return schematic pin objects as drawn (unexpanded), filtered by unit/body.
void AddDrawItem(SCH_ITEM *aItem, bool aSort=true)
Add a new draw aItem to the draw object list and sort according to aSort.
virtual void SetName(const wxString &aName)
SCH_FIELD & GetReferenceField()
Definition lib_symbol.h:453
ITERATOR_BASE< SCH_ITEM, MULTIVECTOR< SCH_ITEM, FIRST_TYPE_VAL, LAST_TYPE_VAL >, typename ITEM_PTR_VECTOR::iterator > ITERATOR
ITERATOR begin(int aType=UNDEFINED_TYPE)
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
void SetHeightMils(double aHeightInMils)
const VECTOR2D GetSizeIU(double aIUScale) const
Gets the page size in internal units.
Definition page_info.h:172
void SetWidthMils(double aWidthInMils)
Container for project specific data.
Definition project.h:63
virtual std::map< wxString, wxString > & GetTextVars() const
Definition project.cpp:223
Holds all the data relating to one schematic.
Definition schematic.h:155
void SetSize(const VECTOR2I &aSize)
Class for a wire to bus entry.
virtual const wxString & GetText() const override
Return the string associated with the text object.
Definition sch_field.h:139
wxString GetName(bool aUseDefaultName=true) const
Return the field name (not translated).
void SetPosition(const VECTOR2I &aPosition) override
void SetText(const wxString &aText) override
void SetSpinStyle(SPIN_STYLE aSpinStyle) override
void SetSpinStyle(SPIN_STYLE aSpinStyle) override
Keeps wires of one net from touching pins, junctions and wire ends of other nets on import.
RESULT Route(const SEG &aWire, int aNet)
Detour a wire around foreign items lying on it and register the result as the wire's geometry.
bool TouchesOtherNet(const VECTOR2I &aPos, int aNet) const
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
SCH_ITEM * Duplicate(bool addToParentGroup, SCH_COMMIT *aCommit=nullptr, bool aDoClone=false) const
Routine to create a new copy of given item.
Definition sch_item.cpp:191
int GetUnit() const
Definition sch_item.h:243
void SetLayer(SCH_LAYER_ID aLayer)
Definition sch_item.h:354
virtual void SetUnit(int aUnit)
Definition sch_item.h:242
VECTOR2I GetPosition() const override
void SetPosition(const VECTOR2I &aPosition) override
void SetShape(LABEL_FLAG_SHAPE aShape)
Definition sch_label.h:179
void SetPosition(const VECTOR2I &aPosition) override
void AutoplaceFields(SCH_SCREEN *aScreen, AUTOPLACE_ALGO aAlgo) override
virtual void SetSpinStyle(SPIN_STYLE aSpinStyle)
Segment description base class to describe items which have 2 end points (track, wire,...
Definition sch_line.h:39
void SetStartPoint(const VECTOR2I &aPosition)
Definition sch_line.h:137
void SetLineWidth(const int aSize)
Definition sch_line.cpp:440
VECTOR2I GetEndPoint() const
Definition sch_line.h:145
VECTOR2I GetStartPoint() const
Definition sch_line.h:136
void SetLineStyle(const LINE_STYLE aStyle)
Definition sch_line.cpp:411
void SetEndPoint(const VECTOR2I &aPosition)
Definition sch_line.h:146
const PAGE_INFO & GetPageSettings() const
Definition sch_screen.h:144
void Append(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
void AddBusAlias(std::shared_ptr< BUS_ALIAS > aAlias)
Add a bus alias definition.
void SetPageSettings(const PAGE_INFO &aPageSettings)
Definition sch_screen.h:145
EE_RTREE & Items()
Get the full RTree, usually for iterating.
Definition sch_screen.h:122
void SetFileName(const wxString &aFileName)
Set the file name for this screen to aFileName.
void Update(SCH_ITEM *aItem, bool aUpdateLibSymbol=true)
Refresh a changed item in the tree and invalidate connectivity.
void SetPosition(const VECTOR2I &aPos) override
Definition sch_shape.h:89
void SetStroke(const STROKE_PARAMS &aStroke) override
void AddPoint(const VECTOR2I &aPosition)
VECTOR2I GetPosition() const override
Definition sch_shape.h:88
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
void SetPageNumber(const wxString &aPageNumber)
Set the sheet instance user definable page number.
SCH_SHEET * Last() const
Return a pointer to the last SCH_SHEET of the list.
void push_back(SCH_SHEET *aSheet)
Forwarded method from std::vector.
Define a sheet pin (label) used in sheets to create hierarchical schematics.
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
wxString GetFileName() const
Return the filename corresponding to this sheet.
Definition sch_sheet.h:428
void AddPin(SCH_SHEET_PIN *aSheetPin)
Add aSheetPin to the sheet.
std::vector< SCH_FIELD > & GetFields()
Return a reference to the vector holding the sheet's fields.
Definition sch_sheet.h:93
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this sheet.
VECTOR2I GetSize() const
Definition sch_sheet.h:189
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
VECTOR2I GetPosition() const override
Definition sch_sheet.h:548
void SetFields(const std::vector< SCH_FIELD > &aFields)
Set multiple schematic fields.
void SetScreen(SCH_SCREEN *aScreen)
Set the SCH_SCREEN associated with this sheet to aScreen.
static bool ClassOf(const EDA_ITEM *aItem)
Definition sch_sheet.h:69
void AutoplaceFields(SCH_SCREEN *aScreen, AUTOPLACE_ALGO aAlgo) override
Schematic symbol object.
Definition sch_symbol.h:76
void SetPosition(const VECTOR2I &aPosition) override
Definition sch_symbol.h:959
void UpdatePins()
Updates the cache of SCH_PIN objects for each pin.
void SetRef(const SCH_SHEET_PATH *aSheet, const wxString &aReference)
Set the base reference for the given sheet path for this symbol.
void SetOrientation(int aOrientation)
Compute the new transform matrix based on aOrientation for the symbol which is applied to the current...
std::vector< SCH_PIN * > GetLibPins() const
Populate a vector with all the pins from the library object that match the current unit and bodyStyle...
SCH_FIELD * AddField(const SCH_FIELD &aField)
Add a field to the symbol.
std::unique_ptr< LIB_SYMBOL > & GetLibSymbolRef()
Definition sch_symbol.h:185
VECTOR2I GetPinPhysicalPosition(const SCH_PIN *Pin) const
SCH_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this symbol.
VECTOR2I GetPosition() const override
Definition sch_text.h:143
void SetPosition(const VECTOR2I &aPosition) override
Definition sch_text.h:144
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
Definition sch_text.cpp:343
Definition seg.h:38
VECTOR2I B
Definition seg.h:46
const VECTOR2I & GetArcMid() const
Definition shape_arc.h:116
const VECTOR2I & GetP1() const
Definition shape_arc.h:115
const VECTOR2I & GetP0() const
Definition shape_arc.h:114
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
int Intersect(const SEG &aSeg, std::vector< INTERSECTION > &aIp) const
Find all intersection points between our line chain and the segment aSeg.
const SHAPE_LINE_CHAIN Reverse() const
Reverse point order in the line chain.
void SetPoint(int aIndex, const VECTOR2I &aPos)
Move a point to a specific location.
int FindSegment(const VECTOR2I &aP, int aThreshold=1) const
Search for segment containing point aP.
int PointCount() const
Return the number of points (vertices) in this line chain.
void Replace(int aStartIndex, int aEndIndex, const VECTOR2I &aP)
Replace points with indices in range [start_index, end_index] with a single point aP.
virtual size_t GetPointCount() const override
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
const VECTOR2I NearestPoint(const VECTOR2I &aP, bool aAllowInternalShapePoints=true) const
Find a point on the line chain that is closest to point aP.
const std::vector< VECTOR2I > & CPoints() const
bool IsEmpty() const
Return true if the set is empty (no polygons at all)
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
Spin style for labels of all kinds on schematics.
Definition sch_label.h:38
SPIN_STYLE MirrorX()
Mirror the label spin style across the X axis or simply swaps up and bottom.
SPIN_STYLE MirrorY()
Mirror the label spin style across the Y axis or simply swaps left and right.
SPIN_STYLE RotateCCW()
Simple container to manage line stroke parameters.
virtual void SetShowPinNumbers(bool aShow)
Set or clear the pin number visibility flag.
Definition symbol.h:174
virtual void SetShowPinNames(bool aShow)
Set or clear the pin name visibility flag.
Definition symbol.h:168
wxString wx_str() const
Definition utf8.cpp:41
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition vector2d.h:281
#define DEFAULT_WIRE_WIDTH_MILS
The default wire width in mils. (can be changed in preference menu)
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
static constexpr EDA_ANGLE ANGLE_VERTICAL
Definition eda_angle.h:469
static constexpr EDA_ANGLE ANGLE_HORIZONTAL
Definition eda_angle.h:468
static constexpr EDA_ANGLE ANGLE_45
Definition eda_angle.h:473
static constexpr EDA_ANGLE ANGLE_270
Definition eda_angle.h:477
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:476
static constexpr EDA_ANGLE ANGLE_135
Definition eda_angle.h:475
@ NO_FILL
Definition eda_fill.h:30
@ FILLED_WITH_BG_BODYCOLOR
Definition eda_fill.h:32
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
#define IGNORE_PARENT_GROUP
Definition eda_item.h:55
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
static const std::string KiCadSchematicFileExtension
SCH_LAYER_ID
Eeschema drawing layers.
Definition layer_ids.h:480
@ LAYER_DEVICE
Definition layer_ids.h:497
@ LAYER_WIRE
Definition layer_ids.h:483
@ LAYER_NOTES
Definition layer_ids.h:498
@ LAYER_BUS
Definition layer_ids.h:484
MULTIVECTOR< SCH_ITEM, SCH_SHAPE_T, SCH_PIN_T > LIB_ITEMS_CONTAINER
Definition lib_symbol.h:59
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
constexpr void MIRROR(T &aPoint, const T &aMirrorRef)
Updates aPoint with the mirror of aPoint relative to the aMirrorRef.
Definition mirror.h:44
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
ELECTRICAL_PINTYPE
The symbol library pin object electrical types used in ERC tests.
Definition pin_type.h:32
@ PT_INPUT
usual pin input: must be connected
Definition pin_type.h:33
@ PT_OUTPUT
usual output
Definition pin_type.h:34
@ PT_BIDI
input or output (like port for a microprocessor)
Definition pin_type.h:35
@ PT_OPENCOLLECTOR
pin type open collector
Definition pin_type.h:44
@ PT_POWER_IN
power input (GND, VCC for ICs). Must be connected to a power output.
Definition pin_type.h:42
@ PT_UNSPECIFIED
unknown electrical properties: creates always a warning when connected
Definition pin_type.h:41
@ PT_PASSIVE
pin for passive symbols: must be connected, and can be connected to any pin.
Definition pin_type.h:39
@ PIN_UP
The pin extends upwards from the connection point: Probably on the bottom side of the symbol.
Definition pin_type.h:123
@ PIN_RIGHT
The pin extends rightwards from the connection point.
Definition pin_type.h:107
@ PIN_LEFT
The pin extends leftwards from the connection point: Probably on the right side of the symbol.
Definition pin_type.h:114
@ PIN_DOWN
The pin extends downwards from the connection: Probably on the top side of the symbol.
Definition pin_type.h:131
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ AUTOPLACE_AUTO
Definition sch_item.h:75
@ L_BIDI
Definition sch_label.h:100
@ L_UNSPECIFIED
Definition sch_label.h:102
@ L_OUTPUT
Definition sch_label.h:99
@ L_INPUT
Definition sch_label.h:98
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
#define SIM_DEVICE_FIELD
Definition sim_model.h:49
#define SIM_PARAMS_FIELD
Definition sim_model.h:53
void wxStringSplit(const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
Split aString to a string list separated at aSplitter.
bool ReplaceIllegalFileNameChars(std::string &aName, int aReplaceChar)
Checks aName for illegal file name characters.
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
@ CTX_LIBID
LINE_STYLE
Dashed line types.
JUSTIFICATION Justification
Note: Justification has no effect on single lines of text.
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...
long Modifier1
It seems this is related to weight. 400=Normal, 700=Bold.
wxString Name
This is undefined (wxEmptyString) if the net is unnamed.
long SignalNum
This is undefined if the net has been given a name.
bool HidePinNames
Specifies whether to display the pin names/identifier in the schematic symbol or not.
std::map< ATTRIBUTE_ID, ATTRIBUTE_VALUE > AttributeValues
Some attributes are defined within the part definition, whilst others are defined in the part.
std::map< PART_DEFINITION_PIN_ID, PIN > Pins
std::map< ATTRIBUTE_ID, ATTRIBUTE_VALUE > AttributeValues
Some attributes are defined within the part definition, whilst others are defined in the part itself.
Represent a point in x,y coordinates.
SHAPE_POLY_SET ConvertToPolySet(const std::function< VECTOR2I(const VECTOR2I &)> aCadstarToKicadPointCallback, int aAccuracy) const
std::vector< CUTOUT > Cutouts
Not Applicable to OPENSHAPE Type.
std::map< FIGURE_ID, FIGURE > Figures
std::map< ATTRIBUTE_ID, TEXT_LOCATION > TextLocations
This contains location of any attributes, including designator position.
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.
std::map< ATTRIBUTE_ID, ATTRIBUTE_VALUE > AttributeValues
These attributes might also have a location.
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...
JUSTIFICATION Justification
Note: has no effect on single lines of text.
< Nodename = "VARIANT" or "VMASTER" (master variant
Represents a vertex in a shape.
SHAPE_ARC BuildArc(const VECTOR2I &aPrevPoint, const std::function< VECTOR2I(const VECTOR2I &)> aCadstarToKicadPointCallback) const
void AppendToChain(SHAPE_LINE_CHAIN *aChainToAppendTo, const std::function< VECTOR2I(const VECTOR2I &)> aCadstarToKicadPointCallback, int aAccuracy) const
CADSTAR Parts Library (*.lib) model - a data structure describing the contents of the file format.
std::vector< CADSTAR_PART_ENTRY > m_PartEntries
std::string m_ComponentStem
std::map< std::string, std::vector< CADSTAR_PART_PIN > > m_HiddenPins
Pins with an implied electrical connection to a net, not part of any symbol (Note: we probably will n...
std::map< std::string, CADSTAR_ATTRIBUTE_VALUE > m_SchAttributes
Dollar sign ($) line $[!]<SCM Attribute name>(<Attribute value>) Attributes related to the schematic ...
std::map< std::string, CADSTAR_ATTRIBUTE_VALUE > m_SchAndPcbAttributes
At symbol (@) line [@[!]<SCM/PCB Attribute name>(<Attribute value>)] Attributes related to the PCB co...
std::vector< CADSTAR_PART_SYMBOL_ENTRY > m_Symbols
Symbols that form this part.
std::map< std::string, std::string > m_UserAttributes
Star (*) line *<User-defined name> <Value> This line is ignored by CADSTAR.
std::map< long, std::string > m_PinNamesMap
Map of pin identifiers to alphanumeric pin names.
std::optional< std::string > m_AcceptancePartName
bool m_PinsVisible
std::optional< std::string > m_Pcb_alternate
std::optional< std::string > m_Version
std::string m_Name
std::optional< std::string > m_Description
std::optional< std::string > m_Number
std::string m_Pcb_component
std::optional< std::string > m_SpiceModel
std::map< std::string, CADSTAR_ATTRIBUTE_VALUE > m_PcbAttributes
Percentage sign (%) line %[!]<PCB Attribute name>(<Attribute value>) Attributes related to the PCB co...
std::optional< std::string > m_Value
std::map< std::string, CADSTAR_ATTRIBUTE_VALUE > m_PartAttributes
Tilde (~) line ~[!]<Parts Library Attribute Name>(<Attribute Value>) Attributes related to the Part i...
std::map< long, std::string > m_PinLabelsMap
Map of pin identifiers to alphanumeric pin labels.
std::string m_SymbolName
std::vector< CADSTAR_PART_PIN > m_Pins
std::optional< std::string > m_SymbolAlternateName
TYPE Type
Determines what the associated layer is, whether parent, child or clone.
LAYER_ID LayerID
The sheet block is on (TODO: verify this is true)
LAYER_ID AssocLayerID
Parent or Child linked sheet.
std::map< TERMINAL_ID, TERMINAL > Terminals
LAYER_ID LayerID
Sheet on which bus is located.
std::map< NETELEMENT_ID, DANGLER > Danglers
std::map< NETELEMENT_ID, SYM_TERM > Terminals
std::map< NETELEMENT_ID, BUS_TERM > BusTerminals
std::map< NETELEMENT_ID, BLOCK_TERM > BlockTerminals
std::map< NETELEMENT_ID, JUNCTION_SCH > Junctions
LAYER_ID LayerID
Sheet on which symbol is located.
std::map< ATTRIBUTE_ID, ATTRIBUTE_VALUE > AttributeValues
GATE_ID GateID
The gate this symbol represents within the associated Part.
long ScaleRatioNumerator
Symbols can be arbitrarily scaled in CADSTAR.
std::map< TERMINAL_ID, SYMPINNAME_LABEL > PinNames
Identifier of the pin in the PCB Equivalent to KiCad's Pin Number.
std::map< TERMINAL_ID, PIN_NUM > PinNumbers
This seems to only appear in older designs and is similar to PinNames but only allowing numerical val...
std::map< TERMINAL_ID, PIN_NUM_LABEL_LOC > PinLabelLocations
std::map< TERMINAL_ID, PIN_NUM_LABEL_LOC > PinNumberLocations
std::map< TERMINAL_ID, TERMINAL > Terminals
POINT Position
Pad position within the component's coordinate frame.
#define ALL_BODY_STYLES
Definition symbol.h:151
@ SYM_ORIENT_270
Definition symbol.h:39
@ SYM_MIRROR_Y
Definition symbol.h:41
@ SYM_ORIENT_180
Definition symbol.h:38
@ SYM_ORIENT_90
Definition symbol.h:37
@ SYM_ORIENT_0
Definition symbol.h:36
@ USER
The field ID hasn't been set yet; field is invalid.
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
static EDA_ORIENTATION orientation(double d)
KIBIS_COMPONENT * comp
KIBIS_PIN * pin
bool cw
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.
int delta
@ 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
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_FIELD_T
Definition typeinfo.h:146
@ SCH_SHAPE_T
Definition typeinfo.h:145
@ SCH_SHEET_PIN_T
Definition typeinfo.h:170
@ SCH_TEXT_T
Definition typeinfo.h:147
@ SCH_PIN_T
Definition typeinfo.h:149
constexpr int sign(T val)
Definition util.h:167
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
constexpr int LexicographicalCompare(const VECTOR2< T > &aA, const VECTOR2< T > &aB)
Definition vector2d.h:657
Definition of file extensions used in Kicad.