35#include <unordered_map>
36#include <unordered_set>
39#include <wx/strconv.h>
46 static constexpr std::array<uint16_t, 16> JUSTIFICATION_BY_NIBBLE_0 = { 0, 4, 1, 5, 8, 12, 9, 13,
47 2, 6, 3, 7, 10, 14, 11, 15 };
48 static constexpr std::array<uint16_t, 16> JUSTIFICATION_BY_NIBBLE_90 = { 0, 4, 2, 6, 8, 12, 10, 14,
49 1, 5, 3, 7, 9, 13, 11, 15 };
52 uint16_t terminalJustification( uint16_t aNibble,
bool aRotated )
54 return aRotated ? JUSTIFICATION_BY_NIBBLE_90[aNibble] : JUSTIFICATION_BY_NIBBLE_0[aNibble];
58 constexpr size_t OUTER_DIRECTORY_OFFSET = 0x20;
59 constexpr size_t OUTER_DESCRIPTOR_BYTES = 28;
60 constexpr size_t OUTER_USED_BYTES_OFFSET = 12;
61 constexpr size_t SHEET_HEADER_BYTES = 20;
62 constexpr size_t SHEET_DESCRIPTOR_COUNT = 24;
63 constexpr size_t SHEET_DESCRIPTOR_BYTES = 28;
64 constexpr size_t SHEET_COUNT_OFFSET = 12;
65 constexpr size_t SHEET_USED_BYTES_OFFSET = 16;
66 constexpr size_t SHEET_RECORD_BYTES = 48;
67 constexpr size_t TEXT_RECORD_BYTES = 32;
68 constexpr size_t SYMBOL_RECORD_BYTES = 80;
69 constexpr size_t SYMBOL_PIECE_BYTES = 6;
70 constexpr size_t SYMBOL_VERTEX_BYTES = 6;
71 constexpr size_t SYMBOL_ARC_BYTES = 14;
72 constexpr size_t USED_DECAL_BYTES = 108;
73 constexpr size_t TERMINAL_BYTES = 26;
74 constexpr size_t PART_TYPE_BYTES = 76;
75 constexpr size_t GATE_BYTES = 12;
76 constexpr size_t PIN_BYTES = 24;
77 constexpr size_t SIGNAL_PIN_BYTES = 64;
78 constexpr size_t NET_MEMBERSHIP_BYTES = 2;
79 constexpr size_t NET_RECORD_BYTES = 88;
80 constexpr size_t BUS_RECORD_BYTES = 44;
81 constexpr size_t JUNCTION_RECORD_BYTES = 12;
82 constexpr size_t OFFPAGE_RECORD_BYTES = 32;
83 constexpr size_t CONNECTION_RECORD_BYTES = 40;
84 constexpr size_t CONNECTION_VERTEX_BYTES = 8;
85 constexpr size_t NET_NAME_RECORD_BYTES = 48;
86 constexpr size_t PLACEMENT_GROUP_BYTES = 24;
87 constexpr size_t ATTRIBUTE_OFFSET_BYTES = 4;
88 constexpr size_t FONT_RECORD_BYTES = 36;
89 constexpr uint32_t DEFAULT_CODE_PAGE = 1252;
91 struct GLOBAL_NET_RECORD
93 SOURCE_PROVENANCE source;
95 uint32_t preservedIdentity = 0;
96 uint32_t preservedRelationship = 0xFFFFFFFF;
97 uint32_t membershipStart = 0;
98 uint16_t membershipCount = 0;
99 uint32_t aliasStringOffset = 0xFFFFFFFF;
100 uint16_t aliasCount = 0;
101 uint16_t kindFlags = 0;
102 bool tombstone =
false;
103 std::vector<SOURCE_STRING> aliasMembers;
107 struct CONNECTIVITY_GLOBALS
109 size_t membershipBase = 0;
110 uint32_t membershipCount = 0;
112 uint32_t fontCount = 0;
113 std::vector<uint16_t> membershipSheets;
114 std::vector<GLOBAL_NET_RECORD> nets;
117 struct PLACEMENT_LAYOUT
121 size_t placementBytes;
122 size_t placedPinBytes;
125 size_t componentIdentity;
126 size_t componentGroup;
137 size_t referenceFont;
139 size_t referenceField;
140 size_t referenceFieldAngle;
141 size_t partTypeField;
142 size_t partTypeFieldAngle;
143 size_t referenceHeight;
144 size_t partTypeHeight;
145 size_t referenceWidth;
146 size_t partTypeWidth;
147 size_t itemVisibility;
148 size_t placedPinOrdinal;
152 size_t customJustification;
153 size_t customAttributeIndex;
156 size_t customDisplayFlags;
160 constexpr PLACEMENT_LAYOUT PLACEMENT_LAYOUTS[] = { []
162 PLACEMENT_LAYOUT layout{};
163 layout.version = 0x000C;
168 .placementBytes = 136,
169 .placedPinBytes = 12,
172 .componentIdentity = 0x18,
173 .componentGroup = 0x1C,
186 .referenceField = 0x28,
187 .referenceFieldAngle = 0x2C,
188 .partTypeField = 0x30,
189 .partTypeFieldAngle = 0x34,
190 .referenceHeight = 0x50,
191 .partTypeHeight = 0x52,
192 .referenceWidth = 0x58,
193 .partTypeWidth = 0x59,
194 .itemVisibility = 0x87,
195 .placedPinOrdinal = 4,
199 .customJustification = 14,
200 .customAttributeIndex = 16,
203 .customDisplayFlags = 21,
204 .customTail = 22 } };
206 const PLACEMENT_LAYOUT& placementLayout( uint16_t aVersion )
208 auto layout = std::ranges::find_if( PLACEMENT_LAYOUTS,
209 [&](
const PLACEMENT_LAYOUT& aLayout )
211 return aLayout.version == aVersion;
214 if( layout == std::end( PLACEMENT_LAYOUTS ) )
215 THROW_IO_ERROR( wxString::Format( wxS(
"unsupported PADS placement layout v0x%04X" ), aVersion ) );
221 size_t outerControllerOffset(
const PADS_SCH_SDB& aSdb,
size_t aController )
225 for(
size_t controller = 1; controller < aController; ++controller )
226 offset += aSdb.
Pools()[controller].usedBytes;
232 SOURCE_PROVENANCE sourceAt(
const wxString& aFile, uint16_t aVersion,
const wxString& aObjectClass,
int aController,
233 size_t aRecord,
size_t aOffset,
size_t aLength,
int aSheet )
235 return { aFile, aVersion, aObjectClass, aController, aRecord, aOffset, aLength, aSheet };
239 [[noreturn]]
void throwDecodeError(
const SOURCE_PROVENANCE& aSource,
const wxString& aMessage )
245 int64_t decodeHalfMils( uint16_t aRaw )
247 return (int64_t) aRaw * 2;
250 int64_t decodeCoordinate( uint16_t aRaw )
252 return static_cast<int64_t
>( aRaw ) * 4 - 198144;
256 int64_t decodeDatabaseCoordinate( int32_t aRaw,
const SOURCE_PROVENANCE& aSource )
258 if( aRaw < std::numeric_limits<int16_t>::min() || aRaw > std::numeric_limits<int16_t>::max() )
259 throwDecodeError( aSource, wxS(
"embedded OLE database coordinate is not sign-extended 16-bit" ) );
261 return decodeCoordinate(
static_cast<uint16_t
>(
static_cast<int16_t
>( aRaw ) ) );
265 int64_t decodeLocalCoordinate( uint16_t aRaw )
267 return static_cast<int64_t
>(
static_cast<int16_t
>( aRaw ) ) * 4;
271 int64_t decodeTerminalCoordinate( uint16_t aRaw )
273 return static_cast<int64_t
>(
static_cast<int16_t
>( aRaw ) ) * 4;
277 SOURCE_STRING decodeFixedString(
const std::vector<uint8_t>& aBytes,
size_t aOffset,
size_t aBytesAvailable,
280 size_t end = aOffset;
282 while(
end < aOffset + aBytesAvailable && aBytes[
end] != 0 )
285 if(
end == aOffset + aBytesAvailable )
286 throwDecodeError( aSource, wxS(
"unterminated fixed string" ) );
289 DEFAULT_CODE_PAGE, aSource, aDiagnostics );
297 property.name.source = aSource;
298 property.value.text = aValue;
299 property.value.source = aSource;
301 property.source = aSource;
308 return aLeft.x == aRight.x && aLeft.y == aRight.y;
314 return aLeft.height == aRight.height && aLeft.width == aRight.width && aLeft.font.text == aRight.font.text
315 && aLeft.horizontalJustification == aRight.horizontalJustification
316 && aLeft.verticalJustification == aRight.verticalJustification && aLeft.bold == aRight.bold
317 && aLeft.italic == aRight.italic && aLeft.underline == aRight.underline
318 && aLeft.visible == aRight.visible;
324 return aLeft.kind == aRight.kind && aLeft.text.text == aRight.text.text && aLeft.lineStyle == aRight.lineStyle
325 && aLeft.strokeWidth == aRight.strokeWidth && aLeft.fill == aRight.fill
326 && samePresentationValue( aLeft.presentation, aRight.presentation ) && aLeft.angle == aRight.angle
327 && aLeft.arcSweepAngle == aRight.arcSweepAngle && aLeft.arcClockwise == aRight.arcClockwise
328 && samePointValue( aLeft.arcCenter, aRight.arcCenter )
329 && samePointValue( aLeft.arcBoundsStart, aRight.arcBoundsStart )
330 && samePointValue( aLeft.arcBoundsEnd, aRight.arcBoundsEnd )
331 && std::ranges::equal( aLeft.points, aRight.points, samePointValue );
337 std::vector<const MODEL_GRAPHIC*> leftDrawing;
338 std::vector<const MODEL_GRAPHIC*> rightDrawing;
339 std::vector<const MODEL_GRAPHIC*> leftText;
340 std::vector<const MODEL_GRAPHIC*> rightText;
350 return sameGraphicValue( *aLeftGraphic, *aRightGraphic );
353 return std::ranges::equal( leftDrawing, rightDrawing, equalPointers )
354 && std::ranges::is_permutation( leftText, rightText, equalPointers );
358 bool isProvenGraphicStrokeWidth( uint8_t aWidth )
360 constexpr std::array<uint16_t, 13> widths{ 1, 2, 5, 7, 8, 10, 11, 15, 20, 25, 30, 31, 40 };
361 return std::ranges::binary_search( widths, aWidth );
365 void decodeGraphicStrokeWidth( uint8_t aRawWidth, uint8_t aPackedPresentation,
367 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
371 packedSource.length = 1;
372 SOURCE_PROPERTY packed = sourceProperty( wxS(
"preserved_graphic_presentation" ),
373 wxString::Format( wxS(
"%u" ), aPackedPresentation ), packedSource );
375 aGraphic.properties.push_back( std::move( packed ) );
377 if( isProvenGraphicStrokeWidth( aRawWidth ) )
379 aGraphic.strokeWidth =
static_cast<int64_t
>( aRawWidth ) * 2;
385 strokeSource.length = 1;
386 SOURCE_PROPERTY stroke = sourceProperty( wxS(
"unsupported_graphic_stroke_width" ),
387 wxString::Format( wxS(
"%u" ), aRawWidth ), strokeSource );
390 RPT_SEVERITY_WARNING, stroke, wxS(
"unproved graphic stroke width preserved; using hairline" ) ) );
391 aGraphic.properties.push_back( std::move( stroke ) );
400 if( aHandle == -1 || aHandle == -4 )
402 font.text = wxS(
"Default Font" );
404 font.codePage = DEFAULT_CODE_PAGE;
405 font.codePageName = wxS(
"windows-1252" );
413 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
436 if( aPage ==
"A5" )
return { 16535, 11654, aSource };
437 else if( aPage ==
"A4" )
return { 23386, 16535, aSource };
438 else if( aPage ==
"A3" )
return { 33071, 23386, aSource };
439 else if( aPage ==
"A2" )
return { 46772, 33071, aSource };
440 else if( aPage ==
"A1" )
return { 66220, 46772, aSource };
441 else if( aPage ==
"A0" )
return { 93622, 66220, aSource };
442 else if( aPage ==
"A" )
return { 22000, 17000, aSource };
443 else if( aPage ==
"B" )
return { 34000, 22000, aSource };
444 else if( aPage ==
"C" )
return { 44000, 34000, aSource };
445 else if( aPage ==
"D" )
return { 68000, 44000, aSource };
446 else if( aPage ==
"E" )
return { 88000, 68000, aSource };
448 throwDecodeError( aSource, wxS(
"invalid design page-size token" ) );
455 if( aValue & 0x0004 )
458 if( aValue & 0x0001 )
468 if( aValue & 0x0008 )
471 if( aValue & 0x0002 )
478 uint16_t rotatedFieldJustification( uint16_t aValue,
int aAngle )
484 if( ( quarterTurns & 1 ) == 0 )
487 const uint16_t bit0 = aValue & 0x0001;
488 const uint16_t bit1 = aValue & 0x0002;
490 aValue &=
static_cast<uint16_t
>( ~0x0003 );
502 constexpr uint32_t CP1252_HIGH[] = { 0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
503 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0x017D, 0xFFFD,
504 0xFFFD, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
505 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0x017E, 0x0178 };
508 wxString decodeWindows1252(
const std::vector<uint8_t>& aBytes )
512 for( uint8_t
byte : aBytes )
514 uint32_t codePoint = byte;
516 if(
byte >= 0x80 &&
byte <= 0x9F )
517 codePoint = CP1252_HIGH[
byte - 0x80];
519 result += wxUniChar( codePoint );
526 wxString decodeUnknownCodePage(
const std::vector<uint8_t>& aBytes )
530 for( uint8_t
byte : aBytes )
531 result += wxUniChar(
byte < 0x80 ?
byte : 0xFFFD );
537 wxString decodeUtf8(
const std::vector<uint8_t>& aBytes,
bool& aHadInvalidBytes )
540 aHadInvalidBytes =
false;
542 for(
size_t i = 0; i < aBytes.size(); )
544 uint8_t lead = aBytes[i];
545 uint32_t codePoint = 0;
546 size_t continuationCount = 0;
547 uint32_t minimum = 0;
551 result += wxUniChar( lead );
555 else if( lead >= 0xC2 && lead <= 0xDF )
557 codePoint = lead & 0x1F;
558 continuationCount = 1;
561 else if( lead >= 0xE0 && lead <= 0xEF )
563 codePoint = lead & 0x0F;
564 continuationCount = 2;
567 else if( lead >= 0xF0 && lead <= 0xF4 )
569 codePoint = lead & 0x07;
570 continuationCount = 3;
575 result += wxUniChar( 0xFFFD );
576 aHadInvalidBytes =
true;
581 bool valid = i + continuationCount < aBytes.size();
583 for(
size_t j = 1; valid && j <= continuationCount; ++j )
585 uint8_t continuation = aBytes[i + j];
586 valid = ( continuation & 0xC0 ) == 0x80;
589 codePoint = ( codePoint << 6 ) | ( continuation & 0x3F );
592 valid = valid && codePoint >= minimum && codePoint <= 0x10FFFF
593 && !( codePoint >= 0xD800 && codePoint <= 0xDFFF );
597 result += wxUniChar( 0xFFFD );
598 aHadInvalidBytes =
true;
603 result += wxUniChar( codePoint );
604 i += continuationCount + 1;
610 [[noreturn]]
void throwValidationError(
const SOURCE_PROVENANCE& aSource,
const wxString& aMessage );
613 template <
typename Item,
typename IdAccessor,
typename SourceAccessor>
614 void validateUniqueIds(
const std::vector<Item>& aItems,
const wxString& aObjectClass, IdAccessor aId,
615 SourceAccessor aSource )
617 std::map<uint32_t, SOURCE_PROVENANCE> declarations;
619 for(
const Item& item : aItems )
621 const auto&
id = aId( item );
624 throwValidationError( aSource( item ), wxString::Format( wxS(
"invalid %s ID" ), aObjectClass ) );
626 auto [first, inserted] = declarations.emplace(
id.Value(), aSource( item ) );
631 wxString detail = wxString::Format(
632 wxS(
"duplicate %s ID %u; first at v0x%04X %s controller %d record %llu sheet %d "
634 aObjectClass,
id.Value(), firstSource.version, firstSource.objectClass, firstSource.controller,
635 static_cast<unsigned long long>( firstSource.recordIndex ), firstSource.sheet,
636 static_cast<unsigned long long>( firstSource.absoluteOffset ) );
637 throwValidationError( aSource( item ), detail );
643 [[noreturn]]
void throwValidationError(
const SOURCE_PROVENANCE& aSource,
const wxString& aMessage )
649 constexpr auto itemId = [](
const auto& aItem ) ->
const auto&
655 constexpr auto itemProvenance = [](
const auto& aItem ) ->
const SOURCE_PROVENANCE&
661 template <
typename Item,
typename Declarations>
662 void validateNestedId(
const Item& aItem,
const wxString& aObjectClass, Declarations& aDeclarations )
664 if( !aItem.id.IsValid() )
665 throwValidationError( aItem.source, wxString::Format( wxS(
"invalid %s ID" ), aObjectClass ) );
667 auto [first, inserted] = aDeclarations.emplace( aItem.id.Value(), aItem.source );
671 throwValidationError(
673 wxString::Format( wxS(
"duplicate %s ID %llu; first at v0x%04X %s controller %d record %llu "
674 "sheet %d offset 0x%llX" ),
675 aObjectClass,
static_cast<unsigned long long>( aItem.id.Value() ),
676 first->second.version, first->second.objectClass, first->second.controller,
677 static_cast<unsigned long long>( first->second.recordIndex ), first->second.sheet,
678 static_cast<unsigned long long>( first->second.absoluteOffset ) ) );
683 struct MODEL_REFERENCE_INDEX
685 std::unordered_map<uint32_t, const MODEL_SHEET*> sheets;
686 std::unordered_map<uint32_t, const MODEL_SYMBOL_DEFINITION*> definitions;
687 std::unordered_map<uint32_t, const MODEL_PART_TYPE*> partTypes;
688 std::unordered_map<uint32_t, const MODEL_GATE*> gates;
689 std::unordered_map<uint32_t, const MODEL_PART_TYPE*> gateOwners;
690 std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*> pins;
691 std::unordered_map<uint32_t, const MODEL_SYMBOL_DEFINITION*> pinOwners;
692 std::unordered_map<uint32_t, const MODEL_PLACEMENT*> placements;
693 std::unordered_map<uint32_t, const MODEL_NET*> nets;
695 explicit MODEL_REFERENCE_INDEX(
const PADS_SCH_MODEL& aModel )
697 for(
const MODEL_SHEET& sheet : aModel.sheets )
698 sheets.emplace( sheet.id.Value(), &sheet );
700 for(
const MODEL_SYMBOL_DEFINITION& definition : aModel.definitions )
702 definitions.emplace( definition.id.Value(), &definition );
704 for(
const MODEL_PIN_DEFINITION&
pin : definition.pins )
706 pins.emplace(
pin.id.Value(), &
pin );
707 pinOwners.emplace(
pin.id.Value(), &definition );
711 for(
const MODEL_PART_TYPE& partType : aModel.partTypes )
713 partTypes.emplace( partType.id.Value(), &partType );
715 for(
const MODEL_GATE& gate : partType.gates )
717 gates.emplace( gate.id.Value(), &gate );
718 gateOwners.emplace( gate.id.Value(), &partType );
722 for(
const MODEL_PLACEMENT& placement : aModel.placements )
723 placements.emplace( placement.id.Value(), &placement );
725 for(
const MODEL_NET& net : aModel.nets )
726 nets.emplace( net.id.Value(), &net );
734 return !aEndpoint.placement && !aEndpoint.pin;
739 auto placement = aIndex.placements.find( aEndpoint.placement->id.Value() );
741 if( placement == aIndex.placements.end() )
744 return aIndex.pins.contains( aEndpoint.pin->id.Value() )
745 && std::ranges::any_of( placement->second->pins,
748 return aPin.id == aEndpoint.pin->id;
753 struct SHEET_CONTROLLERS
755 std::array<SCH_SDB_POOL, 23> pools;
756 std::array<size_t, 23> offsets;
760 struct PLACEMENT_GLOBALS
762 size_t attributeHeapBase = 0;
763 uint32_t attributeHeapBytes = 0;
764 size_t groupBase = 0;
765 uint32_t groupCount = 0;
766 size_t attributeOffsetBase = 0;
767 uint32_t attributeOffsetCount = 0;
769 uint32_t fontCount = 0;
771 SOURCE_STRING defaultSystemFont;
775 PLACEMENT_GLOBALS placementGlobals(
const PADS_SCH_SDB& aSdb,
const wxString& aSourceName,
780 auto requireOuterStride = [&](
size_t aController,
size_t aStride )
784 if( pool.usedBytes != pool.count * aStride )
787 aSourceName, aSdb.
Version(), wxS(
"outer controller directory" ), aController, 0,
788 OUTER_DIRECTORY_OFFSET + aController * OUTER_DESCRIPTOR_BYTES + OUTER_USED_BYTES_OFFSET, 4,
791 wxString::Format( wxS(
"controller byte count does not match %llu-byte records" ),
792 static_cast<unsigned long long>( aStride ) ) );
796 requireOuterStride( 6, PLACEMENT_GROUP_BYTES );
797 requireOuterStride( 7, ATTRIBUTE_OFFSET_BYTES );
798 requireOuterStride( 19, FONT_RECORD_BYTES );
799 result.attributeHeapBase = outerControllerOffset( aSdb, 2 );
800 result.attributeHeapBytes = aSdb.
Pools()[2].usedBytes;
801 result.groupBase = outerControllerOffset( aSdb, 6 );
803 result.attributeOffsetBase = outerControllerOffset( aSdb, 7 );
804 result.attributeOffsetCount = aSdb.
Pools()[7].count;
805 result.fontBase = outerControllerOffset( aSdb, 19 );
807 result.fontMode = aSettings.fontMode;
808 result.defaultSystemFont = aSettings.defaultSystemFont;
813 void decodeGlobalFont(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
814 const PLACEMENT_GLOBALS& aGlobals,
const wxString& aSourceName, uint16_t aVersion,
817 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
819 if( aHandle == -1 || aHandle == -4 )
822 aPresentation.font = aGlobals.defaultSystemFont;
824 aPresentation.font = decodedDefinitionFont( aHandle, aHandleSource );
829 if( aHandle < 0 ||
static_cast<uint32_t
>( aHandle ) >= aGlobals.fontCount )
832 throwDecodeError( aHandleSource, wxS(
"placement font handle leaves outer controller 19" ) );
835 wxS(
"inline_font_payload" ), wxString::Format( wxS(
"%u" ), uint16_t( aHandle ) ), aHandleSource );
838 RPT_SEVERITY_WARNING, property, wxS(
"unsupported inline placement font payload preserved" ) ) );
839 aPresentation.properties.push_back( std::move( property ) );
843 const size_t fontOffset = aGlobals.fontBase +
static_cast<size_t>( aHandle ) * FONT_RECORD_BYTES;
844 SOURCE_PROVENANCE fontSource = sourceAt( aSourceName, aVersion, wxS(
"placement font" ), 19, aHandle,
845 fontOffset, FONT_RECORD_BYTES, -1 );
846 const uint32_t style = aCursor.
U32At( fontOffset );
850 nameSource.length = 32;
851 SOURCE_STRING name = decodeFixedString( aBytes, fontOffset + 4, 32, nameSource, aDiagnostics );
852 aPresentation.bold = ( style & 2 ) != 0;
853 aPresentation.italic = ( style & 1 ) != 0;
854 aPresentation.underline = ( style & 4 ) != 0;
855 aPresentation.font =
name;
857 if( aPresentation.bold )
858 aPresentation.font.text.Prepend( wxS(
"Bold " ) );
860 if( aPresentation.italic )
861 aPresentation.font.text.Prepend( wxS(
"Italic " ) );
863 aPresentation.properties.push_back(
864 sourceProperty( wxS(
"font_handle" ), wxString::Format( wxS(
"%d" ), aHandle ), fontSource ) );
866 if( ( style & ~uint32_t{ 7 } ) != 0 )
868 SOURCE_PROPERTY property = sourceProperty( wxS(
"unsupported_font_style_flags" ),
869 wxString::Format( wxS(
"%u" ), style & ~7U ), fontSource );
873 aPresentation.properties.push_back( std::move( property ) );
878 CONNECTIVITY_GLOBALS connectivityGlobals(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
882 CONNECTIVITY_GLOBALS
result;
887 if( membershipPool.usedBytes != membershipPool.count * NET_MEMBERSHIP_BYTES )
890 outerControllerOffset( aSdb, 4 ), membershipPool.usedBytes, -1 );
891 throwDecodeError(
source, wxS(
"controller byte count does not match 2-byte records" ) );
894 if( netPool.usedBytes != netPool.count * NET_RECORD_BYTES )
897 outerControllerOffset( aSdb, 8 ), netPool.usedBytes, -1 );
898 throwDecodeError(
source, wxS(
"controller byte count does not match 88-byte records" ) );
901 if( fontPool.usedBytes != fontPool.count * FONT_RECORD_BYTES )
904 outerControllerOffset( aSdb, 19 ), fontPool.usedBytes, -1 );
905 throwDecodeError(
source, wxS(
"controller byte count does not match 36-byte records" ) );
908 result.membershipBase = outerControllerOffset( aSdb, 4 );
909 result.membershipCount = membershipPool.count;
910 result.fontBase = outerControllerOffset( aSdb, 19 );
911 result.fontCount = fontPool.count;
912 result.membershipSheets.reserve( membershipPool.count );
914 for(
size_t record = 0; record < membershipPool.count; ++record )
915 result.membershipSheets.push_back( aCursor.
U16At(
result.membershipBase + record * 2 ) );
917 const size_t netBase = outerControllerOffset( aSdb, 8 );
918 const size_t aliasHeapBase = outerControllerOffset( aSdb, 1 );
919 const uint32_t aliasHeapBytes = aSdb.
Pools()[1].usedBytes;
920 std::vector<bool> claimedMemberships( membershipPool.count,
false );
922 result.nets.reserve( netPool.count );
924 for(
size_t record = 0; record < netPool.count; ++record )
926 const size_t offset = netBase + record * NET_RECORD_BYTES;
928 NET_RECORD_BYTES, -1 );
929 GLOBAL_NET_RECORD net;
931 net.preservedIdentity = aCursor.
U32At( offset );
932 net.preservedRelationship = aCursor.
U32At( offset + 84 );
933 net.membershipStart = aCursor.
U32At( offset + 4 );
934 net.aliasStringOffset = aCursor.
U32At( offset + 8 );
935 net.membershipCount = aCursor.
U16At( offset + 16 );
936 net.aliasCount = aCursor.
U16At( offset + 18 );
937 net.kindFlags = aCursor.
U16At( offset + 22 );
938 net.tombstone = net.membershipCount == 0xFFFF;
940 nameSource.absoluteOffset += 24;
941 nameSource.length = 56;
942 net.name = decodeFixedString( aBytes, offset + 24, 56, nameSource, aModel.diagnostics );
944 if( aCursor.
U16At( offset + 20 ) != 0 || aCursor.
U32At( offset + 80 ) != 0xFFFFFFFF )
946 throwDecodeError(
source, wxS(
"global net record has nonzero padding or a live reserved link" ) );
950 && ( net.membershipStart > membershipPool.count
951 || net.membershipCount > membershipPool.count - net.membershipStart ) )
953 throwDecodeError(
source, wxS(
"net sheet-membership slice leaves outer controller 4" ) );
956 for( uint32_t membership = net.membershipStart;
957 !net.tombstone && membership < net.membershipStart + net.membershipCount; ++membership )
959 if( claimedMemberships[membership] )
960 throwDecodeError(
source, wxS(
"duplicate net sheet-membership ownership" ) );
962 if(
result.membershipSheets[membership] >= aModel.sheets.size() )
963 throwDecodeError(
source, wxS(
"net membership references the wrong sheet object class" ) );
965 claimedMemberships[membership] =
true;
968 if( net.aliasCount == 0 )
970 if( net.aliasStringOffset != 0xFFFFFFFF )
971 throwDecodeError(
source, wxS(
"non-alias net has an alias-string handle" ) );
975 if( net.aliasStringOffset >= aliasHeapBytes )
976 throwDecodeError(
source, wxS(
"bus-alias string handle leaves outer controller 1" ) );
978 size_t stringOffset = net.aliasStringOffset;
980 for(
size_t alias = 0; alias < net.aliasCount; ++alias )
983 sourceAt( aSourceName, aModel.version, wxS(
"bus alias member" ), 1, alias,
984 aliasHeapBase + stringOffset, aliasHeapBytes - stringOffset, -1 );
986 decodeFixedString( aBytes, aliasHeapBase + stringOffset, aliasHeapBytes - stringOffset,
987 aliasSource, aModel.diagnostics );
988 aliasSource.length = member.raw.size();
989 member.source.length = member.raw.size();
990 stringOffset += member.raw.size() + 1;
991 net.aliasMembers.push_back( std::move( member ) );
995 result.nets.push_back( std::move( net ) );
1002 SHEET_CONTROLLERS sheetControllers(
const PADS_IO::BINARY_CURSOR& aCursor,
const SCH_SDB_BLOCK& aBlock )
1004 SHEET_CONTROLLERS
result;
1005 size_t descriptor = aBlock.offset + SHEET_HEADER_BYTES;
1006 size_t payload = descriptor + 24 * SHEET_DESCRIPTOR_BYTES;
1008 for(
size_t i = 0; i <
result.pools.size(); ++i )
1010 result.pools[i].count = aCursor.
U32At( descriptor + i * SHEET_DESCRIPTOR_BYTES + 12 );
1011 result.pools[i].usedBytes = aCursor.
U32At( descriptor + i * SHEET_DESCRIPTOR_BYTES + 16 );
1012 result.offsets[i] = payload;
1013 payload +=
result.pools[i].usedBytes;
1020 void requireFixedController(
const SHEET_CONTROLLERS& aControllers,
size_t aController,
size_t aStride,
1021 const wxString& aFile, uint16_t aVersion,
int aSheet )
1023 const SCH_SDB_POOL& pool = aControllers.pools[aController - 1];
1025 if( pool.usedBytes != pool.count * aStride )
1028 sourceAt( aFile, aVersion, wxS(
"controller directory" ),
static_cast<int>( aController ), 0,
1029 aControllers.offsets[aController - 1], pool.usedBytes, aSheet );
1030 throwDecodeError(
source, wxString::Format( wxS(
"controller byte count does not match %llu-byte records" ),
1031 static_cast<unsigned long long>( aStride ) ) );
1036 enum class TEXT_ROLE
1039 EMBEDDED_SYMBOL_TEXT,
1044 struct DEFINITION_TEXT_HEAP
1046 size_t recordBase = 0;
1047 uint32_t recordCount = 0;
1048 size_t stringBase = 0;
1049 uint32_t stringBytes = 0;
1055 int16_t& aRelationship )
1058 presentation.
source = aSource;
1059 presentation.height = decodeHalfMils( aCursor.
U16At( aOffset + 22 ) );
1060 presentation.width = decodeHalfMils( aCursor.
U8At( aOffset + 30 ) );
1061 presentation.properties.push_back( sourceProperty(
1062 wxS(
"display_flags" ), wxString::Format( wxS(
"%u" ), aCursor.
U8At( aOffset + 31 ) ), aSource ) );
1063 presentation.horizontalJustification = horizontalJustification( aCursor.
U16At( aOffset + 18 ) );
1064 presentation.verticalJustification = verticalJustification( aCursor.
U16At( aOffset + 18 ) );
1068 fontSource.length = 2;
1069 aRelationship =
static_cast<int16_t
>( aCursor.
U16At( aOffset + 28 ) );
1072 const bool pageText = aRole == TEXT_ROLE::PAGE_TEXT;
1074 presentation.font = decodedDefinitionFont( pageText ? int16_t( -1 ) : aRelationship, fontSource );
1075 presentation.properties.push_back( sourceProperty( pageText ? wxS(
"successor_ordinal" ) : wxS(
"font_handle" ),
1076 wxString::Format( wxS(
"%d" ), aRelationship ),
1078 return presentation;
1082 void decodeDefinitionTextRecord(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
1083 const wxString& aSourceName,
size_t aSheetIndex,
const DEFINITION_TEXT_HEAP& aHeap,
1087 if( aRecord >= aHeap.recordCount )
1088 throwDecodeError( aDefinition.source, wxS(
"definition field handle leaves controller 1" ) );
1090 const bool isField = aRole == TEXT_ROLE::DEFINITION_FIELD;
1091 const size_t offset = aHeap.recordBase + aRecord * TEXT_RECORD_BYTES;
1093 isField ? wxS(
"definition field" ) : wxS(
"embedded symbol text" ), 1,
1094 aRecord, offset, TEXT_RECORD_BYTES,
static_cast<int>( aSheetIndex ) );
1095 const uint32_t stringOffset = aCursor.
U32At( offset + 8 );
1096 const uint16_t stringBytes = aCursor.
U16At( offset + 20 );
1098 if( stringBytes == 0 || stringOffset > aHeap.stringBytes || stringBytes > aHeap.stringBytes - stringOffset
1099 || aBytes[aHeap.stringBase + stringOffset + stringBytes - 1] != 0 )
1101 throwDecodeError(
source, wxS(
"definition field string leaves controller 2" ) );
1105 sourceAt( aSourceName, aModel.version,
source.objectClass + wxS(
" string" ), 2, aRecord,
1106 aHeap.stringBase + stringOffset, stringBytes - 1,
static_cast<int>( aSheetIndex ) );
1108 { aBytes.begin() + stringSource.absoluteOffset,
1109 aBytes.begin() + stringSource.absoluteOffset + stringSource.length },
1110 DEFAULT_CODE_PAGE, stringSource, aModel.diagnostics );
1112 int16_t relationship = 0;
1114 const SOURCE_POINT position{ decodeLocalCoordinate( aCursor.
U16At( offset + 12 ) ),
1115 decodeLocalCoordinate( aCursor.
U16At( offset + 14 ) ),
source };
1122 field.name = std::move(
string );
1123 field.position = position;
1124 field.angle = angle;
1125 field.presentation = std::move( presentation );
1126 aDefinition.fields.push_back( std::move( field ) );
1133 graphic.text = std::move(
string );
1134 graphic.points.push_back( position );
1135 graphic.presentation = std::move( presentation );
1136 graphic.angle = angle;
1137 aDefinition.graphics.push_back( std::move( graphic ) );
1141 struct DEFINITION_LAYOUT
1143 size_t symbolBase = 0;
1144 size_t pieceBase = 0;
1145 size_t vertexBase = 0;
1147 size_t usedDecalBase = 0;
1148 size_t terminalBase = 0;
1149 size_t partBase = 0;
1150 size_t gateBase = 0;
1152 size_t signalPinBase = 0;
1153 size_t pinNameBase = 0;
1154 uint32_t pinNameBytes = 0;
1155 uint32_t definitionIdBase = 0;
1156 uint32_t pinIdBase = 0;
1157 uint32_t partIdBase = 0;
1158 uint32_t gateIdBase = 0;
1160 DEFINITION_TEXT_HEAP textHeap;
1161 std::vector<uint32_t> definitionPieceStart;
1162 std::vector<uint32_t> pieceVertexStart;
1163 std::vector<std::vector<size_t>> pieceArcRecords;
1170 uint32_t definitionRecord = 0;
1171 uint16_t terminalStart = 0;
1172 uint8_t terminalCount = 0;
1173 uint32_t fieldStart = 0;
1174 MODEL_SYMBOL_DEFINITION* definition =
nullptr;
1178 void preserveRawDefinitionControllers(
const std::vector<uint8_t>& aBytes,
const SHEET_CONTROLLERS& aControllers,
1179 size_t aSheetIndex,
const wxString& aSourceName,
PADS_SCH_MODEL& aModel )
1181 for(
size_t controller = 3; controller <= 23; ++controller )
1183 const SCH_SDB_POOL& pool = aControllers.pools[controller - 1];
1185 if( pool.usedBytes == 0 )
1189 sourceAt( aSourceName, aModel.version, wxS(
"definition controller" ), controller, 0,
1190 aControllers.offsets[controller - 1], pool.usedBytes,
static_cast<int>( aSheetIndex ) );
1191 aModel.preservedControllerPayloads.push_back(
1194 { aBytes.begin() +
source.absoluteOffset,
1195 aBytes.begin() +
source.absoluteOffset +
source.length } } );
1200 DEFINITION_LAYOUT definitionLayout(
const PADS_IO::BINARY_CURSOR& aCursor,
const SHEET_CONTROLLERS& aControllers,
1201 size_t aSheetIndex,
const wxString& aSourceName, uint16_t aVersion )
1203 requireFixedController( aControllers, 3, SYMBOL_RECORD_BYTES, aSourceName, aVersion, aSheetIndex );
1204 requireFixedController( aControllers, 4, SYMBOL_PIECE_BYTES, aSourceName, aVersion, aSheetIndex );
1205 requireFixedController( aControllers, 5, SYMBOL_VERTEX_BYTES, aSourceName, aVersion, aSheetIndex );
1206 requireFixedController( aControllers, 6, SYMBOL_ARC_BYTES, aSourceName, aVersion, aSheetIndex );
1207 requireFixedController( aControllers, 7, USED_DECAL_BYTES, aSourceName, aVersion, aSheetIndex );
1208 requireFixedController( aControllers, 8, TERMINAL_BYTES, aSourceName, aVersion, aSheetIndex );
1209 requireFixedController( aControllers, 9, PART_TYPE_BYTES, aSourceName, aVersion, aSheetIndex );
1210 requireFixedController( aControllers, 10, GATE_BYTES, aSourceName, aVersion, aSheetIndex );
1211 requireFixedController( aControllers, 11, PIN_BYTES, aSourceName, aVersion, aSheetIndex );
1212 requireFixedController( aControllers, 12, SIGNAL_PIN_BYTES, aSourceName, aVersion, aSheetIndex );
1214 DEFINITION_LAYOUT layout;
1215 layout.symbolBase = aControllers.offsets[2];
1216 layout.pieceBase = aControllers.offsets[3];
1217 layout.vertexBase = aControllers.offsets[4];
1218 layout.arcBase = aControllers.offsets[5];
1219 layout.usedDecalBase = aControllers.offsets[6];
1220 layout.terminalBase = aControllers.offsets[7];
1221 layout.partBase = aControllers.offsets[8];
1222 layout.gateBase = aControllers.offsets[9];
1223 layout.pinBase = aControllers.offsets[10];
1224 layout.signalPinBase = aControllers.offsets[11];
1225 layout.pinNameBase = aControllers.offsets[13];
1226 layout.pinNameBytes = aControllers.pools[13].usedBytes;
1227 layout.definitionIdBase =
static_cast<uint32_t
>( aSheetIndex * 0x100000 + 1 );
1228 layout.pinIdBase =
static_cast<uint32_t
>( aSheetIndex * 0x100000 + 0x10000 );
1229 layout.partIdBase =
static_cast<uint32_t
>( aSheetIndex * 0x100000 + 0x20000 );
1230 layout.gateIdBase =
static_cast<uint32_t
>( aSheetIndex * 0x100000 + 0x30000 );
1231 layout.textHeap = { aControllers.offsets[0], aControllers.pools[0].count, aControllers.offsets[1],
1232 aControllers.pools[1].usedBytes };
1237 uint64_t vertexCursor = 0;
1238 uint64_t pieceCursor = 0;
1240 for(
size_t definition = 0; definition < aControllers.pools[2].count; ++definition )
1242 layout.definitionPieceStart.push_back(
static_cast<uint32_t
>( pieceCursor ) );
1243 pieceCursor += aCursor.
U16At( layout.symbolBase + definition * SYMBOL_RECORD_BYTES + 0x2A );
1246 if( pieceCursor != aControllers.pools[3].count )
1249 sourceAt( aSourceName, aVersion, wxS(
"symbol definition" ), 3, 0, layout.symbolBase,
1250 aControllers.pools[2].usedBytes,
static_cast<int>( aSheetIndex ) );
1251 throwDecodeError(
source, wxS(
"symbol graphic-piece counts leave controller 4" ) );
1254 for(
size_t piece = 0; piece < aControllers.pools[3].count; ++piece )
1256 layout.pieceVertexStart.push_back(
static_cast<uint32_t
>( vertexCursor ) );
1257 vertexCursor += aCursor.
U16At( layout.pieceBase + piece * SYMBOL_PIECE_BYTES + 2 );
1260 if( vertexCursor != aControllers.pools[4].count )
1263 aControllers.pools[3].usedBytes,
static_cast<int>( aSheetIndex ) );
1264 throwDecodeError(
source, wxS(
"symbol piece vertex counts do not consume controller 5" ) );
1267 for(
size_t definition = 0; definition < aControllers.pools[2].count; ++definition )
1269 const size_t definitionOffset = layout.symbolBase + definition * SYMBOL_RECORD_BYTES;
1270 const uint32_t firstPiece = layout.definitionPieceStart[definition];
1271 const uint32_t pieceEnd = definition + 1 < layout.definitionPieceStart.size()
1272 ? layout.definitionPieceStart[definition + 1]
1273 : aControllers.pools[3].count;
1274 const uint32_t firstVertex = aCursor.
U32At( definitionOffset + 0x34 );
1275 const uint32_t vertexEnd = definition + 1 < aControllers.pools[2].count
1276 ? aCursor.
U32At( definitionOffset + SYMBOL_RECORD_BYTES + 0x34 )
1277 : aControllers.pools[4].count;
1278 const bool emptyMatches = firstPiece == pieceEnd && firstVertex == vertexEnd;
1279 const bool ownedMatches =
1280 firstPiece < pieceEnd && layout.pieceVertexStart[firstPiece] == firstVertex
1281 && layout.pieceVertexStart[pieceEnd - 1]
1282 + aCursor.
U16At( layout.pieceBase + ( pieceEnd - 1 ) * SYMBOL_PIECE_BYTES + 2 )
1285 if( !emptyMatches && !ownedMatches )
1288 sourceAt( aSourceName, aVersion, wxS(
"symbol definition" ), 3, definition, definitionOffset,
1289 SYMBOL_RECORD_BYTES,
static_cast<int>( aSheetIndex ) );
1290 throwDecodeError(
source, wxS(
"symbol piece/vertex ownership mismatch" ) );
1294 layout.pieceArcRecords.resize( aControllers.pools[3].count );
1295 size_t discoveredArcCount = 0;
1297 for(
size_t piece = 0; piece < aControllers.pools[3].count; ++piece )
1299 const size_t pieceOffset = layout.pieceBase + piece * SYMBOL_PIECE_BYTES;
1300 const uint16_t pointCount = aCursor.
U16At( pieceOffset + 2 );
1302 for(
size_t point = 0; point < pointCount; ++point )
1304 const size_t vertexOffset =
1305 layout.vertexBase + ( layout.pieceVertexStart[piece] + point ) * SYMBOL_VERTEX_BYTES;
1307 if(
static_cast<int16_t
>( aCursor.
U16At( vertexOffset + 4 ) ) >= 0 )
1308 layout.pieceArcRecords[piece].push_back( discoveredArcCount++ );
1312 if( discoveredArcCount != aControllers.pools[5].count )
1315 sourceAt( aSourceName, aVersion, wxS(
"symbol arc" ), 6, discoveredArcCount, layout.arcBase,
1316 aControllers.pools[5].usedBytes,
static_cast<int>( aSheetIndex ) );
1317 throwDecodeError(
source, wxS(
"arc markers do not consume controller 6" ) );
1324 void decodeSymbolDefinitions(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
1325 const SHEET_CONTROLLERS& aControllers,
const DEFINITION_LAYOUT& aLayout,
1326 size_t aSheetIndex,
const wxString& aSourceName,
1327 std::vector<MODEL_SYMBOL_DEFINITION*>& aDefinitionsByRecord,
1328 std::vector<size_t>& aPageGraphicRecords,
PADS_SCH_MODEL& aModel )
1331 aModel.definitions.reserve( aModel.definitions.size() + aControllers.pools[2].count );
1333 for(
size_t record = 0; record < aControllers.pools[2].count; ++record )
1335 const size_t offset = aLayout.symbolBase + record * SYMBOL_RECORD_BYTES;
1337 offset, SYMBOL_RECORD_BYTES,
static_cast<int>( aSheetIndex ) );
1339 nameSource.length = 38;
1340 SOURCE_STRING name = decodeFixedString( aBytes, offset, 38, nameSource, aModel.diagnostics );
1341 const uint8_t objectClass = aCursor.
U8At( offset + 0x29 );
1342 const uint32_t vertexStart = aCursor.
U32At( offset + 0x34 );
1343 const uint32_t vertexEnd = record + 1 < aControllers.pools[2].count
1344 ? aCursor.
U32At( offset + SYMBOL_RECORD_BYTES + 0x34 )
1345 : aControllers.pools[4].count;
1347 if( vertexStart > vertexEnd || vertexEnd > aControllers.pools[4].count )
1348 throwDecodeError(
source, wxS(
"symbol definition vertex slice leaves controller 5" ) );
1350 if( objectClass == 0 )
1352 const uint32_t firstPiece = aLayout.definitionPieceStart[record];
1353 const uint32_t pieceEnd = record + 1 < aLayout.definitionPieceStart.size()
1354 ? aLayout.definitionPieceStart[record + 1]
1355 : aControllers.pools[3].count;
1356 const uint16_t groupTextCount = aCursor.
U16At( offset + 64 );
1357 const uint16_t groupLastText = aCursor.
U16At( offset + 66 );
1358 const bool worksheetCandidate = pieceEnd - firstPiece == 69 && groupTextCount == 58;
1359 const bool hasCircularTextOwnership = groupTextCount == 0
1360 || ( groupTextCount <= aLayout.textHeap.recordCount
1361 && groupLastText < aLayout.textHeap.recordCount );
1363 originSource.objectClass = wxS(
"page graphic group origin" );
1364 originSource.absoluteOffset += 60;
1365 originSource.length = 4;
1366 const SOURCE_POINT groupOrigin{ decodeCoordinate( aCursor.
U16At( offset + 60 ) ),
1367 decodeCoordinate( aCursor.
U16At( offset + 62 ) ), originSource };
1369 if( aCursor.
U16At( offset + 42 ) != pieceEnd - firstPiece )
1370 throwDecodeError(
source, wxS(
"page-graphic piece count does not match controller 4 slice" ) );
1372 for(
size_t piece = firstPiece; piece < pieceEnd; ++piece )
1374 const size_t pieceOffset = aLayout.pieceBase + piece * SYMBOL_PIECE_BYTES;
1375 const uint8_t pieceKind = aCursor.
U8At( pieceOffset );
1376 const uint8_t lineStyle = aCursor.
U8At( pieceOffset + 1 );
1377 const uint16_t pointCount = aCursor.
U16At( pieceOffset + 2 );
1378 const uint32_t firstVertex = aLayout.pieceVertexStart[piece];
1380 sourceAt( aSourceName, aModel.version, wxS(
"page graphic" ), 4, piece, pieceOffset,
1381 SYMBOL_PIECE_BYTES,
static_cast<int>( aSheetIndex ) );
1383 if( firstVertex + pointCount > vertexEnd )
1384 throwDecodeError( graphicSource, wxS(
"page graphic crosses its controller-5 slice" ) );
1387 graphic.
source = graphicSource;
1388 decodeGraphicStrokeWidth( aCursor.
U8At( pieceOffset + 4 ), aCursor.
U8At( pieceOffset + 5 ),
1389 graphicSource, graphic, aModel.diagnostics );
1398 graphicSource, aModel.diagnostics );
1416 aModel.diagnostics );
1421 for(
size_t point = 0; point < pointCount; ++point )
1423 const size_t pointOffset = aLayout.vertexBase + ( firstVertex + point ) * SYMBOL_VERTEX_BYTES;
1425 aSourceName, aModel.version, wxS(
"page graphic vertex" ), 5, firstVertex + point,
1426 pointOffset, SYMBOL_VERTEX_BYTES,
static_cast<int>( aSheetIndex ) );
1427 graphic.points.push_back( { decodeLocalCoordinate( aCursor.
U16At( pointOffset ) ),
1428 decodeLocalCoordinate( aCursor.
U16At( pointOffset + 2 ) ),
1432 const int16_t arcMarker =
static_cast<int16_t
>(
1433 aCursor.
U16At( aLayout.vertexBase + firstVertex * SYMBOL_VERTEX_BYTES + 4 ) );
1435 if( pieceKind == 0 && arcMarker >= 0 )
1437 if( aLayout.pieceArcRecords[piece].empty() )
1438 throwDecodeError( graphicSource, wxS(
"page arc has no controller-6 record" ) );
1440 const size_t arcRecord = aLayout.pieceArcRecords[piece].front();
1441 const size_t arcOffset = aLayout.arcBase + arcRecord * SYMBOL_ARC_BYTES;
1443 sourceAt( aSourceName, aModel.version, wxS(
"page arc" ), 6, arcRecord, arcOffset,
1444 SYMBOL_ARC_BYTES,
static_cast<int>( aSheetIndex ) );
1446 graphic.arcSweepAngle = aCursor.
U16At( arcOffset );
1447 graphic.arcClockwise =
static_cast<int16_t
>( aCursor.
U16At( arcOffset + 2 ) ) < 0;
1448 graphic.arcBoundsStart = { decodeLocalCoordinate( aCursor.
U16At( arcOffset + 6 ) ),
1449 decodeLocalCoordinate( aCursor.
U16At( arcOffset + 8 ) ), arcSource };
1450 graphic.arcBoundsEnd = { decodeLocalCoordinate( aCursor.
U16At( arcOffset + 10 ) ),
1451 decodeLocalCoordinate( aCursor.
U16At( arcOffset + 12 ) ), arcSource };
1452 graphic.arcCenter = { ( graphic.arcBoundsStart.x + graphic.arcBoundsEnd.x ) / 2,
1453 ( graphic.arcBoundsStart.y + graphic.arcBoundsEnd.y ) / 2, arcSource };
1458 point.x += groupOrigin.x;
1459 point.y += groupOrigin.y;
1464 graphic.arcBoundsStart.x += groupOrigin.x;
1465 graphic.arcBoundsStart.y += groupOrigin.y;
1466 graphic.arcBoundsEnd.x += groupOrigin.x;
1467 graphic.arcBoundsEnd.y += groupOrigin.y;
1468 graphic.arcCenter.x += groupOrigin.x;
1469 graphic.arcCenter.y += groupOrigin.y;
1472 graphic.properties.push_back( sourceProperty( wxS(
"page_graphic_group" ),
name.text,
source ) );
1474 if( worksheetCandidate )
1475 graphic.properties.push_back( sourceProperty( wxS(
"worksheet_group" ),
name.text,
source ) );
1477 if( !hasCircularTextOwnership )
1480 relationshipSource.absoluteOffset += 64;
1481 relationshipSource.length = 4;
1483 wxS(
"preserved_drawing_text_relationship" ),
1484 wxString::Format( wxS(
"%u,%u" ), groupTextCount, groupLastText ), relationshipSource );
1488 wxS(
"unsupported class-zero drawing text relationship preserved" ) ) );
1489 graphic.properties.push_back( std::move( relationship ) );
1491 aModel.graphics.push_back(
1492 { graphicSource, { aModel.sheets[aSheetIndex].id, graphicSource }, std::move( graphic ) } );
1495 if( hasCircularTextOwnership )
1496 aPageGraphicRecords.push_back( record );
1500 if( objectClass != 0x06 )
1505 definition.source =
source;
1506 definition.name = std::move(
name );
1507 const uint32_t firstPiece = aLayout.definitionPieceStart[record];
1508 const uint32_t pieceEnd = record + 1 < aLayout.definitionPieceStart.size()
1509 ? aLayout.definitionPieceStart[record + 1]
1510 : aControllers.pools[3].count;
1512 for(
size_t piece = firstPiece; piece < pieceEnd; ++piece )
1514 const size_t pieceOffset = aLayout.pieceBase + piece * SYMBOL_PIECE_BYTES;
1515 const uint8_t pieceKind = aCursor.
U8At( pieceOffset );
1516 const uint16_t pointCount = aCursor.
U16At( pieceOffset + 2 );
1517 const uint32_t firstVertex = aLayout.pieceVertexStart[piece];
1519 if( firstVertex + pointCount > vertexEnd )
1520 throwDecodeError(
source, wxS(
"symbol piece crosses its definition vertex slice" ) );
1523 sourceAt( aSourceName, aModel.version, wxS(
"symbol graphic" ), 4, piece, pieceOffset,
1524 SYMBOL_PIECE_BYTES,
static_cast<int>( aSheetIndex ) );
1526 graphic.
source = graphicSource;
1527 decodeGraphicStrokeWidth( aCursor.
U8At( pieceOffset + 4 ), aCursor.
U8At( pieceOffset + 5 ),
1528 graphicSource, graphic, aModel.diagnostics );
1542 aModel.diagnostics );
1547 for(
size_t point = 0; point < pointCount; ++point )
1549 const size_t pointOffset = aLayout.vertexBase + ( firstVertex + point ) * SYMBOL_VERTEX_BYTES;
1551 sourceAt( aSourceName, aModel.version, wxS(
"symbol vertex" ), 5, firstVertex + point,
1552 pointOffset, SYMBOL_VERTEX_BYTES,
static_cast<int>( aSheetIndex ) );
1553 graphic.points.push_back( { decodeLocalCoordinate( aCursor.
U16At( pointOffset ) ),
1554 decodeLocalCoordinate( aCursor.
U16At( pointOffset + 2 ) ),
1558 if( pieceKind == 1 && graphic.points.size() == 5 && graphic.points.front().x == graphic.points.back().x
1559 && graphic.points.front().y == graphic.points.back().y )
1561 const auto [minX, maxX] = std::ranges::minmax( graphic.points, {}, &
SOURCE_POINT::x );
1562 const auto [minY, maxY] = std::ranges::minmax( graphic.points, {}, &
SOURCE_POINT::y );
1563 const bool cornersOnly =
1564 std::ranges::all_of( graphic.points,
1567 return ( aPoint.x == minX.x || aPoint.x == maxX.x )
1568 && ( aPoint.y == minY.y || aPoint.y == maxY.y );
1574 graphic.points = { { minX.x, minY.y, graphicSource }, { maxX.x, maxY.y, graphicSource } };
1578 const int16_t arcMarker =
static_cast<int16_t
>(
1579 aCursor.
U16At( aLayout.vertexBase + firstVertex * SYMBOL_VERTEX_BYTES + 4 ) );
1581 if( pieceKind == 0 && arcMarker >= 0 )
1583 if( aLayout.pieceArcRecords[piece].empty() )
1584 throwDecodeError( graphicSource, wxS(
"symbol arc has no controller-6 record" ) );
1586 const size_t arcRecord = aLayout.pieceArcRecords[piece].front();
1587 const size_t arcOffset = aLayout.arcBase + arcRecord * SYMBOL_ARC_BYTES;
1590 sourceAt( aSourceName, aModel.version, wxS(
"symbol arc" ), 6, arcRecord, arcOffset,
1591 SYMBOL_ARC_BYTES,
static_cast<int>( aSheetIndex ) );
1592 graphic.arcSweepAngle = aCursor.
U16At( arcOffset );
1593 graphic.arcClockwise =
static_cast<int16_t
>( aCursor.
U16At( arcOffset + 2 ) ) < 0;
1594 graphic.arcBoundsStart = { decodeLocalCoordinate( aCursor.
U16At( arcOffset + 6 ) ),
1595 decodeLocalCoordinate( aCursor.
U16At( arcOffset + 8 ) ), arcSource };
1596 graphic.arcBoundsEnd = { decodeLocalCoordinate( aCursor.
U16At( arcOffset + 10 ) ),
1597 decodeLocalCoordinate( aCursor.
U16At( arcOffset + 12 ) ), arcSource };
1598 graphic.arcCenter = { ( graphic.arcBoundsStart.x + graphic.arcBoundsEnd.x ) / 2,
1599 ( graphic.arcBoundsStart.y + graphic.arcBoundsEnd.y ) / 2, arcSource };
1600 graphic.properties.push_back( sourceProperty(
1601 wxS(
"arc_direction" ),
1602 graphic.arcClockwise ? wxS(
"clockwise" ) : wxS(
"counterclockwise" ), arcSource ) );
1603 graphic.properties.push_back( sourceProperty(
1604 wxS(
"arc_marker" ),
1605 wxString::Format( wxS(
"%d" ),
static_cast<int16_t
>( aCursor.
U16At( arcOffset + 4 ) ) ),
1609 definition.graphics.push_back( std::move( graphic ) );
1612 aModel.definitions.push_back( std::move( definition ) );
1613 aDefinitionsByRecord[record] = &aModel.definitions.back();
1618 void decodeUsedDecals(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
1619 const SHEET_CONTROLLERS& aControllers,
const DEFINITION_LAYOUT& aLayout,
size_t aSheetIndex,
1620 const wxString& aSourceName,
1621 const std::vector<MODEL_SYMBOL_DEFINITION*>& aDefinitionsByRecord,
1622 std::vector<USED_DECAL>& aUsedDecals, std::vector<USED_DECAL*>& aSemanticDecals,
1625 for(
size_t record = 0; record < aUsedDecals.size(); ++record )
1627 const size_t offset = aLayout.usedDecalBase + record * USED_DECAL_BYTES;
1629 USED_DECAL_BYTES,
static_cast<int>( aSheetIndex ) );
1631 nameSource.length = 40;
1632 SOURCE_STRING name = decodeFixedString( aBytes, offset, 40, nameSource, aModel.diagnostics );
1633 USED_DECAL& decal = aUsedDecals[record];
1634 decal.record = record;
1635 decal.terminalCount = aCursor.
U8At( offset + 42 );
1636 decal.terminalStart = aCursor.
U16At( offset + 44 );
1637 decal.definitionRecord = aCursor.
U32At( offset + 48 );
1638 decal.fieldStart = aCursor.
U32At( offset + 52 );
1640 if(
name.text.empty() || decal.definitionRecord == 0xFFFFFFFF )
1643 if( decal.definitionRecord >= aDefinitionsByRecord.size() )
1644 throwDecodeError(
source, wxS(
"unresolved symbol definition reference" ) );
1646 const size_t definitionOffset = aLayout.symbolBase + decal.definitionRecord * SYMBOL_RECORD_BYTES;
1648 sourceAt( aSourceName, aModel.version, wxS(
"symbol definition" ), 3, decal.definitionRecord,
1649 definitionOffset, 38,
static_cast<int>( aSheetIndex ) );
1651 decodeFixedString( aBytes, definitionOffset, 38, targetNameSource, aModel.diagnostics );
1653 if( targetName.text !=
name.text )
1655 const uint8_t targetClass = aCursor.
U8At( definitionOffset + 0x29 );
1656 throwDecodeError(
source, targetClass == 0x06 ? wxS(
"used-decal handle name mismatch" )
1657 : wxS(
"used-decal handle targets wrong object class" ) );
1660 decal.definition = aDefinitionsByRecord[decal.definitionRecord];
1662 if( !decal.definition )
1665 const uint16_t embeddedTextCount =
1666 aCursor.
U16At( aLayout.symbolBase + decal.definitionRecord * SYMBOL_RECORD_BYTES + 0x40 );
1668 if( embeddedTextCount != 0 && decal.fieldStart > aLayout.textHeap.recordCount
1669 && decal.fieldStart < 0x80000000 )
1670 throwDecodeError(
source, wxS(
"embedded definition text handle leaves controller 1" ) );
1672 if(
static_cast<uint32_t
>( decal.terminalStart ) + decal.terminalCount > aControllers.pools[7].count )
1673 throwDecodeError(
source, wxS(
"used-decal terminal slice leaves controller 8" ) );
1675 aSemanticDecals.push_back( &decal );
1677 for(
size_t pin = 0;
pin < decal.terminalCount; ++
pin )
1679 const size_t terminalRecord = decal.terminalStart +
pin;
1680 const size_t terminalOffset = aLayout.terminalBase + terminalRecord * TERMINAL_BYTES;
1682 sourceAt( aSourceName, aModel.version, wxS(
"symbol pin" ), 8, terminalRecord, terminalOffset,
1683 TERMINAL_BYTES,
static_cast<int>( aSheetIndex ) );
1684 const uint16_t pinDecalHandle = aCursor.
U16At( terminalOffset );
1686 definitionPin.
id =
PIN_ID( aLayout.pinIdBase + terminalRecord );
1687 definitionPin.source = pinSource;
1688 definitionPin.position = { decodeTerminalCoordinate( aCursor.
U16At( terminalOffset + 2 ) ),
1689 decodeTerminalCoordinate( aCursor.
U16At( terminalOffset + 4 ) ), pinSource };
1691 definitionPin.presentation.source = pinSource;
1692 definitionPin.presentation.visible =
true;
1694 numberPresentationSource.absoluteOffset = offset + 92;
1695 numberPresentationSource.length = 2;
1697 namePresentationSource.absoluteOffset = offset + 94;
1698 namePresentationSource.length = 2;
1700 definitionPin.numberPresentation.source = numberPresentationSource;
1701 definitionPin.numberPresentation.height =
static_cast<int64_t
>( aCursor.
U16At( offset + 92 ) ) * 2;
1702 definitionPin.numberPresentation.width =
static_cast<int64_t
>( aCursor.
U8At( offset + 98 ) ) * 2;
1703 definitionPin.namePresentation.source = namePresentationSource;
1704 definitionPin.namePresentation.height =
static_cast<int64_t
>( aCursor.
U16At( offset + 94 ) ) * 2;
1705 definitionPin.namePresentation.width =
static_cast<int64_t
>( aCursor.
U8At( offset + 99 ) ) * 2;
1708 numberFontSource.absoluteOffset = offset + 104;
1709 numberFontSource.length = 2;
1711 nameFontSource.absoluteOffset = offset + 106;
1712 nameFontSource.length = 2;
1713 int16_t numberFontHandle =
static_cast<int16_t
>( aCursor.
U16At( numberFontSource.absoluteOffset ) );
1714 int16_t nameFontHandle =
static_cast<int16_t
>( aCursor.
U16At( nameFontSource.absoluteOffset ) );
1715 definitionPin.numberPresentation.font = decodedDefinitionFont( numberFontHandle, numberFontSource );
1716 definitionPin.namePresentation.font = decodedDefinitionFont( nameFontHandle, nameFontSource );
1719 && !aModel.settings.defaultSystemFont.text.IsEmpty() )
1721 if( numberFontHandle == -1 || numberFontHandle == -4 )
1722 definitionPin.numberPresentation.font = aModel.settings.defaultSystemFont;
1724 if( nameFontHandle == -1 || nameFontHandle == -4 )
1725 definitionPin.namePresentation.font = aModel.settings.defaultSystemFont;
1728 definitionPin.numberPresentation.visible = definitionPin.numberPresentation.height != 0;
1729 definitionPin.namePresentation.visible = definitionPin.namePresentation.height != 0
1730 && ( aCursor.
U16At( terminalOffset + 24 ) & 0x8000 ) == 0;
1733 definitionPin.numberOffset = { decodeLocalCoordinate( aCursor.
U16At( terminalOffset + 6 ) ),
1734 decodeLocalCoordinate( aCursor.
U16At( terminalOffset + 8 ) ),
1736 definitionPin.nameOffset = { decodeLocalCoordinate( aCursor.
U16At( terminalOffset + 10 ) ),
1737 decodeLocalCoordinate( aCursor.
U16At( terminalOffset + 12 ) ), pinSource };
1738 const uint16_t presentationFlags = aCursor.
U16At( terminalOffset + 22 );
1739 const uint16_t visibilityFlags = aCursor.
U16At( terminalOffset + 24 );
1740 definitionPin.presentationFlags = presentationFlags;
1741 definitionPin.visibilityAndNumberPresentationFlags = visibilityFlags;
1745 definitionPin.side = ( presentationFlags & 0x0006 ) >> 1;
1747 definitionPin.angle = ( presentationFlags & 0x0001 ) != 0 ? 900 : 0;
1748 definitionPin.numberAngle = ( presentationFlags & 0x0100 ) != 0 ? 900 : 0;
1749 definitionPin.nameAngle = ( visibilityFlags & 0x0001 ) != 0 ? 900 : 0;
1751 definitionPin.numberJustification =
1752 terminalJustification( ( presentationFlags >> 12 ) & 0x0F, definitionPin.numberAngle != 0 );
1754 if( ( presentationFlags & 0x00F8 ) != 0 )
1756 aModel.diagnostics );
1758 definitionPin.nameJustification =
1759 terminalJustification( ( visibilityFlags >> 4 ) & 0x0F, definitionPin.nameAngle != 0 );
1760 const uint16_t nameOffsetFlags = visibilityFlags & 0x0F00;
1761 definitionPin.nameOffsetAngle = ( nameOffsetFlags & 0x0100 ) != 0 ? 900 : 0;
1762 definitionPin.numberOffsetAngle = ( nameOffsetFlags & 0x0200 ) != 0 ? 900 : 0;
1764 switch( visibilityFlags & 0x0F00 )
1767 case 0x0800: definitionPin.nameOffsetJustification = 0;
break;
1769 case 0x0C00: definitionPin.nameOffsetJustification = 1;
break;
1772 case 0x0F00: definitionPin.nameOffsetJustification = 2;
break;
1775 visibilityFlags & 0x0F00, pinSource,
1776 aModel.diagnostics );
1780 switch( visibilityFlags & 0x0F00 )
1782 case 0x0000: definitionPin.numberOffsetJustification = 0;
break;
1784 case 0x0C00: definitionPin.numberOffsetJustification = 1;
break;
1785 case 0x0D00: definitionPin.numberOffsetJustification = 8;
break;
1786 case 0x0F00: definitionPin.numberOffsetJustification = 2;
break;
1789 visibilityFlags & 0x0F00, pinSource,
1790 aModel.diagnostics );
1794 definitionPin.visibilityFlags = ( visibilityFlags >> 8 ) & 0x00C0;
1796 if( pinDecalHandle == 0xFFFF )
1798 definitionPin.length = 0;
1800 else if( pinDecalHandle >= aUsedDecals.size() )
1801 throwDecodeError( pinSource, wxS(
"unresolved pin-decal handle" ) );
1803 if( pinDecalHandle != 0xFFFF )
1809 const size_t handleOffset = aLayout.usedDecalBase + pinDecalHandle * USED_DECAL_BYTES;
1810 const uint32_t definitionRecord = aCursor.
U32At( handleOffset + 48 );
1812 if( definitionRecord >= aDefinitionsByRecord.size() || !aDefinitionsByRecord[definitionRecord] )
1813 throwDecodeError( pinSource, wxS(
"unresolved pin-decal handle" ) );
1815 pinDecal = aDefinitionsByRecord[definitionRecord];
1818 const wxString pinDecalName = pinDecal->name.text;
1819 definitionPin.decalName = pinDecal->name;
1821 int64_t provenLength = 0;
1825 const bool containsOrigin = std::ranges::any_of( pinGraphic.points,
1828 return aPoint.x == 0 && aPoint.y == 0;
1831 if( !containsOrigin )
1836 std::max( provenLength, std::max(
std::abs( point.x ),
std::abs( point.y ) ) );
1839 if( provenLength != 0 )
1840 definitionPin.length = provenLength;
1844 sourceProperty( wxS(
"pin_length" ), wxS(
"unknown" ), pinSource );
1846 definitionPin.properties.push_back( std::move( lengthProperty ) );
1849 const bool inverted = pinDecalName == wxS(
"PINB" ) || pinDecalName == wxS(
"PINORB" )
1850 || pinDecalName == wxS(
"PCLKB" ) || pinDecalName == wxS(
"PINIEB" );
1851 const bool clock = pinDecalName == wxS(
"PCLK" ) || pinDecalName == wxS(
"PCLKB" );
1852 definitionPin.graphicStyle = ( inverted ? 1U : 0U ) | ( clock ? 2U : 0U );
1855 definitionPin.properties.push_back( sourceProperty(
1856 wxS(
"pin_name_height_half_mils" ),
1857 wxString::Format( wxS(
"%lld" ), definitionPin.namePresentation.height ), pinSource ) );
1858 definitionPin.properties.push_back( sourceProperty(
1859 wxS(
"pin_number_height_half_mils" ),
1860 wxString::Format( wxS(
"%lld" ), definitionPin.numberPresentation.height ), pinSource ) );
1861 definitionPin.properties.push_back( sourceProperty(
1862 wxS(
"pin_name_width_half_mils" ),
1863 wxString::Format( wxS(
"%lld" ), definitionPin.namePresentation.width ), pinSource ) );
1864 definitionPin.properties.push_back( sourceProperty(
1865 wxS(
"pin_number_width_half_mils" ),
1866 wxString::Format( wxS(
"%lld" ), definitionPin.numberPresentation.width ), pinSource ) );
1867 definitionPin.properties.push_back(
1868 sourceProperty( wxS(
"terminal_side" ),
1869 wxString::Format( wxS(
"%u" ), definitionPin.side ), pinSource ) );
1872 for(
int pair = 0; pair < 2; ++pair )
1874 const size_t pairOffset = terminalOffset + 14 + pair * 4;
1875 definitionPin.properties.push_back( sourceProperty(
1876 wxString::Format( wxS(
"terminal_p_line_position_%d" ), pair + 1 ),
1877 wxString::Format( wxS(
"%lld,%lld" ), decodeLocalCoordinate( aCursor.
U16At( pairOffset ) ),
1878 decodeLocalCoordinate( aCursor.
U16At( pairOffset + 2 ) ) ),
1882 decal.definition->pins.push_back( std::move( definitionPin ) );
1888 std::vector<USED_DECAL*> buildFieldDecals(
const std::vector<USED_DECAL*>& aSemanticDecals,
1889 const DEFINITION_LAYOUT& aLayout,
size_t aSheetIndex,
1890 const wxString& aSourceName, uint16_t aVersion )
1892 std::vector<USED_DECAL*> fieldDecals;
1894 std::ranges::copy_if( aSemanticDecals, std::back_inserter( fieldDecals ),
1895 [&](
const USED_DECAL* aDecal )
1897 return aDecal->fieldStart < aLayout.textHeap.recordCount;
1899 std::ranges::sort( fieldDecals,
1900 [](
const USED_DECAL* aLeft,
const USED_DECAL* aRight )
1902 return aLeft->fieldStart < aRight->fieldStart;
1905 for(
size_t i = 1; i < fieldDecals.size(); ++i )
1907 if( fieldDecals[i - 1]->fieldStart != fieldDecals[i]->fieldStart )
1911 sourceAt( aSourceName, aVersion, wxS(
"used decal" ), 7, fieldDecals[i - 1]->record,
1912 aLayout.usedDecalBase + fieldDecals[i - 1]->record * USED_DECAL_BYTES, USED_DECAL_BYTES,
1913 static_cast<int>( aSheetIndex ) );
1915 sourceAt( aSourceName, aVersion, wxS(
"used decal" ), 7, fieldDecals[i]->record,
1916 aLayout.usedDecalBase + fieldDecals[i]->record * USED_DECAL_BYTES, USED_DECAL_BYTES,
1917 static_cast<int>( aSheetIndex ) );
1920 wxString::Format( wxS(
"duplicate field ID; first at v0x%04X %s controller %d record %llu "
1921 "sheet %d offset 0x%llX" ),
1922 first.version, first.objectClass, first.controller,
1923 static_cast<unsigned long long>( first.recordIndex ), first.sheet,
1924 static_cast<unsigned long long>( first.absoluteOffset ) ) );
1931 void decodePageGraphics(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
1932 const DEFINITION_LAYOUT& aLayout,
size_t aSheetIndex,
const wxString& aSourceName,
1933 const std::vector<size_t>& aPageGraphicRecords,
PADS_SCH_MODEL& aModel )
1935 for(
size_t record : aPageGraphicRecords )
1937 const size_t offset = aLayout.symbolBase + record * SYMBOL_RECORD_BYTES;
1939 offset, SYMBOL_RECORD_BYTES,
static_cast<int>( aSheetIndex ) );
1941 nameSource.length = 38;
1942 SOURCE_STRING groupName = decodeFixedString( aBytes, offset, 38, nameSource, aModel.diagnostics );
1943 const uint16_t textCountForGroup = aCursor.
U16At( offset + 64 );
1944 const uint16_t lastTextRecord = aCursor.
U16At( offset + 66 );
1945 const bool worksheetCandidate = aCursor.
U16At( offset + 42 ) == 69 && textCountForGroup == 58;
1947 if( textCountForGroup > aLayout.textHeap.recordCount
1948 || ( textCountForGroup != 0 && lastTextRecord >= aLayout.textHeap.recordCount ) )
1949 throwDecodeError(
source, wxS(
"page-text ownership leaves controller 1" ) );
1954 if( textCountForGroup != 0 )
1956 std::vector<size_t> textRecords( textCountForGroup );
1957 std::vector<bool> visitedTextRecords( aLayout.textHeap.recordCount,
false );
1958 size_t textRecord = lastTextRecord;
1960 for(
size_t reverseIndex = textCountForGroup; reverseIndex != 0; --reverseIndex )
1962 if( textRecord >= aLayout.textHeap.recordCount )
1963 throwDecodeError(
source, wxS(
"page-text predecessor leaves controller 1" ) );
1965 if( visitedTextRecords[textRecord] )
1966 throwDecodeError(
source, wxS(
"page-text predecessor repeats controller 1 record" ) );
1968 visitedTextRecords[textRecord] =
true;
1970 textRecords[reverseIndex - 1] = textRecord;
1972 if( reverseIndex != 1 )
1974 const size_t predecessor =
1975 aCursor.
U16At( aLayout.textHeap.recordBase + textRecord * TEXT_RECORD_BYTES + 24 );
1977 if( predecessor >= aLayout.textHeap.recordCount )
1978 throwDecodeError(
source, wxS(
"page-text predecessor leaves controller 1" ) );
1980 textRecord = predecessor;
1984 for(
size_t textRecordIndex : textRecords )
1985 decodeDefinitionTextRecord( aBytes, aCursor, aSourceName, aSheetIndex, aLayout.textHeap,
1986 textRecordIndex, TEXT_ROLE::PAGE_TEXT, textOwner, aModel );
1989 if( textOwner.graphics.size() != textCountForGroup )
1990 throwDecodeError(
source, wxS(
"page-text records do not exactly match declared count" ) );
1994 graphic.source.objectClass = wxS(
"page text" );
1995 const SOURCE_POINT groupOrigin{ decodeCoordinate( aCursor.
U16At( offset + 60 ) ),
1996 decodeCoordinate( aCursor.
U16At( offset + 62 ) ),
source };
2000 point.x += groupOrigin.x;
2001 point.y += groupOrigin.y;
2004 graphic.properties.push_back( sourceProperty( wxS(
"page_graphic_group" ), groupName.text,
source ) );
2006 if( worksheetCandidate )
2007 graphic.properties.push_back( sourceProperty( wxS(
"worksheet_group" ), groupName.text,
source ) );
2009 aModel.graphics.push_back(
2010 { graphic.source, { aModel.sheets[aSheetIndex].id, graphic.source }, std::move( graphic ) } );
2015 if( aGraphic.sheet.id != aModel.sheets[aSheetIndex].id )
2018 return std::ranges::any_of( aGraphic.graphic.properties,
2021 return aProperty.name.text == wxS(
"page_graphic_group" )
2022 && aProperty.value.text == groupName.text;
2026 size_t numericEdgeMarkers = 0;
2027 size_t alphabeticEdgeMarkers = 0;
2028 size_t textGraphics = 0;
2029 size_t drawingGraphics = 0;
2030 bool hasTitleAnchor =
false;
2031 bool hasSheetAnchor =
false;
2032 bool hasRevisionAnchor =
false;
2036 if( !belongsToGroup( pageGraphic ) )
2046 wxString
text = pageGraphic.graphic.text.text.Upper();
2048 if(
text.length() == 1 &&
text[0] >=
'0' &&
text[0] <=
'9' )
2049 ++numericEdgeMarkers;
2051 if(
text.length() == 1 &&
text[0] >=
'A' &&
text[0] <=
'Z' )
2052 ++alphabeticEdgeMarkers;
2054 hasTitleAnchor |=
text == wxS(
"TITLE" ) ||
text.StartsWith( wxS(
"TITLE:" ) );
2055 hasSheetAnchor |=
text == wxS(
"SHEET NUMBER" ) ||
text == wxS(
"NUMBER OF SHEETS" )
2056 ||
text.StartsWith( wxS(
"SHEET:" ) );
2057 hasRevisionAnchor |=
text == wxS(
"REVISION" ) ||
text.StartsWith( wxS(
"REV:" ) )
2058 ||
text.StartsWith( wxS(
"REVISION " ) );
2061 const bool worksheet = drawingGraphics >= 30 && textGraphics >= 30 && numericEdgeMarkers >= 4
2062 && alphabeticEdgeMarkers >= 4 && hasTitleAnchor && hasSheetAnchor
2063 && hasRevisionAnchor;
2069 modelWorksheet.sheet = { aModel.sheets[aSheetIndex].id,
source };
2070 modelWorksheet.name = groupName;
2072 for(
auto graphic = aModel.graphics.begin(); graphic != aModel.graphics.end(); )
2074 if( belongsToGroup( *graphic ) )
2076 modelWorksheet.graphics.push_back( std::move( graphic->graphic ) );
2077 graphic = aModel.graphics.erase( graphic );
2085 auto existing = std::ranges::find_if( aModel.worksheets,
2088 return aWorksheet.sheet.id == modelWorksheet.sheet.id;
2091 if( existing == aModel.worksheets.end() )
2093 aModel.worksheets.push_back( std::move( modelWorksheet ) );
2095 else if( !sameWorksheetValue( *existing, modelWorksheet ) )
2098 sourceProperty( wxS(
"distinct_worksheet_layout" ), groupName.text,
source );
2102 wxS(
"distinct worksheet layout preserved as schematic page graphics" ) ) );
2106 graphic.properties.push_back( distinct );
2107 aModel.graphics.push_back( { graphic.source,
2108 { aModel.sheets[aSheetIndex].id, graphic.source },
2109 std::move( graphic ) } );
2115 auto canonicalWorksheet = std::ranges::find_if( aModel.worksheets,
2118 return aWorksheet.name.text == wxS(
"DRW5982" );
2121 if( canonicalWorksheet != aModel.worksheets.end() )
2123 using GROUP_KEY = std::pair<uint32_t, wxString>;
2124 std::map<GROUP_KEY, std::vector<const MODEL_GRAPHIC*>>
candidates;
2125 std::vector<const MODEL_GRAPHIC*> canonicalGeometry;
2127 for(
const MODEL_GRAPHIC& graphic : canonicalWorksheet->graphics )
2130 canonicalGeometry.push_back( &graphic );
2135 auto groupProperty = std::ranges::find_if( pageGraphic.graphic.properties,
2138 return aProperty.name.text == wxS(
"worksheet_group" );
2141 if( groupProperty != pageGraphic.graphic.properties.end()
2144 candidates[{ pageGraphic.sheet.id.Value(), groupProperty->value.text }].push_back(
2145 &pageGraphic.graphic );
2149 std::set<GROUP_KEY> equivalentGroups;
2151 for(
const auto& [key, geometry] :
candidates )
2153 if( geometry.size() == canonicalGeometry.size()
2154 && std::ranges::equal( geometry, canonicalGeometry,
2157 return sameGraphicValue( *aLeft, *aRight );
2160 equivalentGroups.insert( key );
2164 std::erase_if( aModel.graphics,
2167 return std::ranges::any_of(
2168 aGraphic.graphic.properties,
2169 [&]( const SOURCE_PROPERTY& aProperty )
2171 return aProperty.name.text == wxS(
"worksheet_group" )
2172 && equivalentGroups.contains(
2173 { aGraphic.sheet.id.Value(), aProperty.value.text } );
2180 void decodeDefinitionFields(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
2181 const DEFINITION_LAYOUT& aLayout,
size_t aSheetIndex,
const wxString& aSourceName,
2182 const std::vector<USED_DECAL*>& aFieldDecals,
PADS_SCH_MODEL& aModel )
2184 for(
size_t i = 0; i < aFieldDecals.size(); ++i )
2186 USED_DECAL& decal = *aFieldDecals[i];
2187 const size_t definitionOffset = aLayout.symbolBase + decal.definitionRecord * SYMBOL_RECORD_BYTES;
2188 const uint16_t embeddedCount = aCursor.
U16At( definitionOffset + 0x40 );
2189 const uint32_t fieldEnd =
2190 i + 1 < aFieldDecals.size() ? aFieldDecals[i + 1]->fieldStart : aLayout.textHeap.recordCount;
2192 if( decal.fieldStart > fieldEnd )
2193 throwDecodeError( decal.definition->source, wxS(
"definition field slice is not monotone" ) );
2195 if( decal.definition->fields.empty() )
2197 for(
size_t standard = 0; standard < 2; ++standard )
2199 const size_t usedOffset = aLayout.usedDecalBase + decal.record * USED_DECAL_BYTES;
2201 sourceAt( aSourceName, aModel.version, wxS(
"standard definition field" ), 7, decal.record,
2202 usedOffset + 60 + standard * 8, 8,
static_cast<int>( aSheetIndex ) );
2204 field.
source = fieldSource;
2206 standard == 0 ? wxS(
"REF-DES" ) : wxS(
"PART-TYPE" ),
2209 field.position = { decodeLocalCoordinate( aCursor.
U16At( usedOffset + 60 + standard * 8 ) ),
2210 decodeLocalCoordinate( aCursor.
U16At( usedOffset + 62 + standard * 8 ) ),
2213 field.presentation.source = fieldSource;
2214 field.presentation.height = decodeHalfMils( aCursor.
U16At( usedOffset + 88 + standard * 2 ) );
2215 field.presentation.width = decodeHalfMils( aCursor.
U8At( usedOffset + 96 + standard ) );
2218 fontSource.length = 2;
2219 const int16_t fontHandle =
static_cast<int16_t
>( aCursor.
U16At( fontSource.absoluteOffset ) );
2220 field.presentation.font = decodedDefinitionFont( fontHandle, fontSource );
2221 field.presentation.properties.push_back( sourceProperty(
2222 wxS(
"font_handle" ), wxString::Format( wxS(
"%d" ), fontHandle ), fontSource ) );
2223 const uint16_t justification = aCursor.
U16At( usedOffset + 66 + standard * 8 );
2224 field.presentation.horizontalJustification = horizontalJustification( justification );
2225 field.presentation.verticalJustification = verticalJustification( justification );
2226 decal.definition->fields.push_back( std::move( field ) );
2230 if( embeddedCount != 0 )
2232 const uint16_t lastEmbeddedRecord = aCursor.
U16At( definitionOffset + 0x42 );
2234 if( embeddedCount > aLayout.textHeap.recordCount || lastEmbeddedRecord >= aLayout.textHeap.recordCount )
2235 throwDecodeError( decal.definition->source,
2236 wxS(
"embedded definition text ownership leaves controller 1" ) );
2238 const size_t firstEmbeddedRecord =
2239 (
static_cast<size_t>( lastEmbeddedRecord ) + aLayout.textHeap.recordCount + 1 - embeddedCount )
2240 % aLayout.textHeap.recordCount;
2242 for(
size_t textIndex = 0; textIndex < embeddedCount; ++textIndex )
2244 decodeDefinitionTextRecord( aBytes, aCursor, aSourceName, aSheetIndex, aLayout.textHeap,
2245 ( firstEmbeddedRecord + textIndex ) % aLayout.textHeap.recordCount,
2246 TEXT_ROLE::EMBEDDED_SYMBOL_TEXT, *decal.definition, aModel );
2250 for(
size_t record = decal.fieldStart; record < fieldEnd; ++record )
2251 decodeDefinitionTextRecord( aBytes, aCursor, aSourceName, aSheetIndex, aLayout.textHeap, record,
2252 TEXT_ROLE::DEFINITION_FIELD, *decal.definition, aModel );
2257 void decodePartTypes(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
2258 const SHEET_CONTROLLERS& aControllers,
const DEFINITION_LAYOUT& aLayout,
size_t aSheetIndex,
2259 const wxString& aSourceName,
const std::vector<USED_DECAL>& aUsedDecals,
2262 size_t signalPinCursor = 0;
2264 for(
size_t record = 0; record < aControllers.pools[8].count; ++record )
2266 const size_t offset = aLayout.partBase + record * PART_TYPE_BYTES;
2268 PART_TYPE_BYTES,
static_cast<int>( aSheetIndex ) );
2270 nameSource.length = 44;
2274 part.name = decodeFixedString( aBytes, offset, 44, nameSource, aModel.diagnostics );
2275 const uint32_t gateStart = aCursor.
U32At( offset + 44 );
2276 const uint32_t pinStart = aCursor.
U32At( offset + 48 );
2277 const uint32_t gateEnd = record + 1 < aControllers.pools[8].count
2278 ? aCursor.
U32At( offset + PART_TYPE_BYTES + 44 )
2279 : aControllers.pools[9].count;
2280 const uint32_t pinEnd = record + 1 < aControllers.pools[8].count
2281 ? aCursor.
U32At( offset + PART_TYPE_BYTES + 48 )
2282 : aControllers.pools[10].count;
2284 if( gateStart > gateEnd || gateEnd > aControllers.pools[9].count || pinStart > pinEnd
2285 || pinEnd > aControllers.pools[10].count )
2287 throwDecodeError(
source, wxS(
"part-type gate or pin slice leaves its controller" ) );
2290 if( aCursor.
U16At( offset + 68 ) != gateEnd - gateStart )
2291 throwDecodeError(
source, wxS(
"stored gate count does not match controller-10 slice" ) );
2293 size_t partPinCursor = pinStart;
2294 uint32_t unitCursor = 0;
2295 const uint32_t pinNameHeapBase = aCursor.
U32At( offset + 60 );
2297 if( pinNameHeapBase > aLayout.pinNameBytes )
2298 throwDecodeError(
source, wxS(
"part-type pin-name base leaves controller 14" ) );
2302 const size_t pinOffset = aLayout.pinBase + aPinRecord * PIN_BYTES;
2303 SOURCE_PROVENANCE pinSource = sourceAt( aSourceName, aModel.version, wxS(
"part pin" ), 11, aPinRecord,
2304 pinOffset, PIN_BYTES,
static_cast<int>( aSheetIndex ) );
2307 numberSource.length = 16;
2308 aDefinitionPin.number =
2309 decodeFixedString( aBytes, pinOffset + 4, 16, numberSource, aModel.diagnostics );
2310 const uint32_t nameOffset = aCursor.
U32At( pinOffset );
2312 if( nameOffset != 0xFFFFFFFF )
2314 if( nameOffset >= aLayout.pinNameBytes - pinNameHeapBase )
2315 throwDecodeError( pinSource, wxS(
"pin-name offset leaves controller 14" ) );
2318 aSourceName, aModel.version, wxS(
"pin name" ), 14, aPinRecord,
2319 aLayout.pinNameBase + pinNameHeapBase + nameOffset,
2320 aLayout.pinNameBytes - pinNameHeapBase - nameOffset,
static_cast<int>( aSheetIndex ) );
2321 aDefinitionPin.name = decodeFixedString( aBytes, aLayout.pinNameBase + pinNameHeapBase + nameOffset,
2322 aLayout.pinNameBytes - pinNameHeapBase - nameOffset,
2323 pinNameSource, aModel.diagnostics );
2326 aDefinitionPin.electricalType =
2329 logicalPin.
source = pinSource;
2330 logicalPin.definitionPin = { aDefinitionPin.id, pinSource };
2331 logicalPin.number = aDefinitionPin.number;
2332 logicalPin.name = aDefinitionPin.name;
2333 logicalPin.electricalType = aDefinitionPin.electricalType;
2334 logicalPin.swapGroup = aCursor.
U8At( pinOffset + 20 );
2335 logicalPin.flags = aCursor.
U16At( pinOffset + 22 );
2336 aDefinitionPin.properties.push_back(
2337 sourceProperty( wxS(
"swap_group" ),
2338 wxString::Format( wxS(
"%u" ), aCursor.
U8At( pinOffset + 20 ) ), pinSource ) );
2339 aGate.pins.push_back( { aDefinitionPin.id, pinSource } );
2340 aGate.logicalPins.push_back( std::move( logicalPin ) );
2343 auto decodeConnectorPin = [&](
size_t aPinRecord )
2345 const size_t pinOffset = aLayout.pinBase + aPinRecord * PIN_BYTES;
2347 sourceAt( aSourceName, aModel.version, wxS(
"connector logical pin" ), 11, aPinRecord,
2348 pinOffset, PIN_BYTES,
static_cast<int>( aSheetIndex ) );
2351 numberSource.length = 16;
2353 pin.source = pinSource;
2354 pin.number = decodeFixedString( aBytes, pinOffset + 4, 16, numberSource, aModel.diagnostics );
2355 const uint32_t nameOffset = aCursor.
U32At( pinOffset );
2357 if( nameOffset != 0xFFFFFFFF )
2359 if( nameOffset >= aLayout.pinNameBytes - pinNameHeapBase )
2360 throwDecodeError( pinSource, wxS(
"pin-name offset leaves controller 14" ) );
2363 aSourceName, aModel.version, wxS(
"connector pin name" ), 14, aPinRecord,
2364 aLayout.pinNameBase + pinNameHeapBase + nameOffset,
2365 aLayout.pinNameBytes - pinNameHeapBase - nameOffset,
static_cast<int>( aSheetIndex ) );
2366 pin.name = decodeFixedString( aBytes, aLayout.pinNameBase + pinNameHeapBase + nameOffset,
2367 aLayout.pinNameBytes - pinNameHeapBase - nameOffset, pinNameSource,
2368 aModel.diagnostics );
2371 pin.swapGroup = aCursor.
U8At( pinOffset + 20 );
2373 pin.flags = aCursor.
U16At( pinOffset + 22 );
2377 for(
size_t gateRecord = gateStart; gateRecord < gateEnd; ++gateRecord )
2379 const size_t gateOffset = aLayout.gateBase + gateRecord * GATE_BYTES;
2380 SOURCE_PROVENANCE gateSource = sourceAt( aSourceName, aModel.version, wxS(
"gate" ), 10, gateRecord,
2381 gateOffset, GATE_BYTES,
static_cast<int>( aSheetIndex ) );
2383 gate.
id =
GATE_ID( aLayout.gateIdBase + gateRecord );
2384 gate.source = gateSource;
2385 const uint16_t pinCount = aCursor.
U16At( gateOffset + 8 );
2386 const uint16_t swapGroup = aCursor.
U16At( gateOffset + 10 );
2387 const uint16_t primaryHandle = aCursor.
U16At( gateOffset );
2392 gate.unit = ++unitCursor;
2394 if( primaryHandle == 0xFFFF || primaryHandle >= aUsedDecals.size()
2395 || !aUsedDecals[primaryHandle].definition )
2397 bool pinDecalGroup = primaryHandle == 0xFFFF && gateRecord + 1 < gateEnd;
2399 for(
size_t member = gateRecord + 1; pinDecalGroup && member < gateEnd; ++member )
2401 const size_t memberOffset = aLayout.gateBase + member * GATE_BYTES;
2402 const uint16_t memberHandle = aCursor.
U16At( memberOffset );
2403 pinDecalGroup = aCursor.
U16At( memberOffset + 8 ) == 0 && memberHandle < aUsedDecals.size()
2404 && aUsedDecals[memberHandle].definition;
2407 if( !pinDecalGroup || partPinCursor + pinCount > pinEnd )
2408 throwDecodeError( gateSource, wxS(
"unresolved symbol definition reference" ) );
2410 part.properties.push_back( sourceProperty(
2411 wxString::Format( wxS(
"pin_decal_group_%llu" ),
2412 static_cast<unsigned long long>( gateRecord - gateStart + 1 ) ),
2413 wxString::Format( wxS(
"%u" ), pinCount ), gateSource ) );
2415 for(
size_t member = gateRecord + 1; member < gateEnd; ++member )
2417 const size_t memberOffset = aLayout.gateBase + member * GATE_BYTES;
2418 const uint16_t memberHandle = aCursor.
U16At( memberOffset );
2420 if( aCursor.
U16At( memberOffset + 8 ) != 0 )
2424 sourceAt( aSourceName, aModel.version, wxS(
"pin-decal group member" ), 10, member,
2425 memberOffset, GATE_BYTES,
static_cast<int>( aSheetIndex ) );
2427 if( memberHandle >= aUsedDecals.size() || !aUsedDecals[memberHandle].definition )
2428 throwDecodeError( memberSource, wxS(
"unresolved pin-decal group member" ) );
2430 gate.decalGroupMembers.push_back( { aUsedDecals[memberHandle].definition->id, memberSource } );
2433 for(
size_t pin = 0;
pin < pinCount; ++
pin, ++partPinCursor )
2434 gate.connectorPins.push_back( decodeConnectorPin( partPinCursor ) );
2436 part.gates.push_back( std::move( gate ) );
2441 gate.definition = { definition->id, gateSource };
2442 gate.properties.push_back(
2443 sourceProperty( wxS(
"swap_group" ), wxString::Format( wxS(
"%u" ), swapGroup ), gateSource ) );
2445 for(
size_t alternate = 1; alternate < 4; ++alternate )
2447 const uint16_t handle = aCursor.
U16At( gateOffset + alternate * 2 );
2449 if( handle == 0xFFFF )
2452 if( handle >= aUsedDecals.size() || !aUsedDecals[handle].definition )
2453 throwDecodeError( gateSource, wxS(
"unresolved alternate symbol definition reference" ) );
2455 gate.alternateDefinitions.push_back( { aUsedDecals[handle].definition->id, gateSource } );
2458 if( partPinCursor + pinCount > pinEnd || pinCount > definition->pins.size() )
2459 throwDecodeError( gateSource, wxS(
"gate pin slice leaves part type or symbol definition" ) );
2461 for(
size_t pin = 0;
pin < pinCount; ++
pin, ++partPinCursor )
2464 decodePartPin( definitionPin, partPinCursor, gate );
2467 part.gates.push_back( std::move( gate ) );
2470 if( partPinCursor != pinEnd )
2471 throwDecodeError(
source, wxS(
"part-type gates do not consume its pin slice" ) );
2473 if( !part.gates.empty() && part.gates.front().definition.id.IsValid() )
2475 auto defaultDefinition =
2476 std::ranges::find_if( aModel.definitions,
2479 return aDefinition.id == part.gates.front().definition.id;
2482 if( defaultDefinition == aModel.definitions.end() )
2483 throwDecodeError(
source, wxS(
"unresolved part-type default definition" ) );
2485 part.fields = defaultDefinition->fields;
2488 const uint16_t signalPinCount = aCursor.
U16At( offset + 70 );
2490 if( signalPinCursor + signalPinCount > aControllers.pools[11].count )
2491 throwDecodeError(
source, wxS(
"part-type signal-pin slice leaves controller 12" ) );
2493 for(
size_t signal = 0; signal < signalPinCount; ++signal, ++signalPinCursor )
2495 const size_t signalOffset = aLayout.signalPinBase + signalPinCursor * SIGNAL_PIN_BYTES;
2497 sourceAt( aSourceName, aModel.version, wxS(
"signal pin" ), 12, signalPinCursor, signalOffset,
2498 SIGNAL_PIN_BYTES,
static_cast<int>( aSheetIndex ) );
2500 numberSource.
length = 16;
2503 nameSource2.length = 48;
2504 SOURCE_STRING number = decodeFixedString( aBytes, signalOffset, 16, numberSource, aModel.diagnostics );
2506 decodeFixedString( aBytes, signalOffset + 16, 48, nameSource2, aModel.diagnostics );
2507 part.signalPins.push_back( { signalSource, number, signalName } );
2508 part.properties.push_back(
2509 sourceProperty( wxS(
"signal_pin_" ) + number.text, signalName.text, signalSource ) );
2512 aModel.partTypes.push_back( std::move( part ) );
2515 if( signalPinCursor != aControllers.pools[11].count )
2518 aLayout.signalPinBase, aControllers.pools[11].usedBytes,
2519 static_cast<int>( aSheetIndex ) );
2520 throwDecodeError(
source, wxS(
"unowned signal-pin record" ) );
2525 void decodeDefinitionsAndParts(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
2526 const SCH_SDB_BLOCK& aBlock,
size_t aSheetIndex,
const wxString& aSourceName,
2529 const SHEET_CONTROLLERS controllers = sheetControllers( aCursor, aBlock );
2531 if( aModel.version == 0x000C )
2533 preserveRawDefinitionControllers( aBytes, controllers, aSheetIndex, aSourceName, aModel );
2537 const DEFINITION_LAYOUT layout =
2538 definitionLayout( aCursor, controllers, aSheetIndex, aSourceName, aModel.version );
2540 std::vector<MODEL_SYMBOL_DEFINITION*> definitionsByRecord( controllers.pools[2].count );
2541 std::vector<size_t> pageGraphicRecords;
2542 std::vector<USED_DECAL> usedDecals( controllers.pools[6].count );
2543 std::vector<USED_DECAL*> semanticDecals;
2545 decodeSymbolDefinitions( aBytes, aCursor, controllers, layout, aSheetIndex, aSourceName, definitionsByRecord,
2546 pageGraphicRecords, aModel );
2547 decodeUsedDecals( aBytes, aCursor, controllers, layout, aSheetIndex, aSourceName, definitionsByRecord,
2548 usedDecals, semanticDecals, aModel );
2550 const std::vector<USED_DECAL*> fieldDecals =
2551 buildFieldDecals( semanticDecals, layout, aSheetIndex, aSourceName, aModel.version );
2553 decodePageGraphics( aBytes, aCursor, layout, aSheetIndex, aSourceName, pageGraphicRecords, aModel );
2554 decodeDefinitionFields( aBytes, aCursor, layout, aSheetIndex, aSourceName, fieldDecals, aModel );
2555 decodePartTypes( aBytes, aCursor, controllers, layout, aSheetIndex, aSourceName, usedDecals, aModel );
2559 struct PLACEMENT_DECODE
2561 const std::vector<uint8_t>& bytes;
2562 const PADS_IO::BINARY_CURSOR& cursor;
2563 const SHEET_CONTROLLERS& controllers;
2564 const PLACEMENT_LAYOUT& layout;
2565 const PLACEMENT_GLOBALS& globals;
2566 const wxString& sourceName;
2571 struct PLACEMENT_TARGET
2573 const MODEL_PART_TYPE* part =
nullptr;
2574 const MODEL_SYMBOL_DEFINITION* definition =
nullptr;
2575 const MODEL_GATE* gate =
nullptr;
2576 uint32_t componentIdentity = 0;
2577 uint32_t groupHandle = 0;
2578 uint32_t attributeStart = 0;
2579 uint16_t attributeCount = 0;
2580 uint16_t decalHandle = 0;
2581 uint16_t unitIndex = 0;
2585 struct INLINE_FIELD_LAYOUT
2595 std::pair<SOURCE_STRING, SOURCE_STRING> decodePlacementAttribute(
const PLACEMENT_DECODE& aDecode,
2596 uint32_t aOffsetIndex,
bool aRequireValue,
2599 if( aOffsetIndex >= aDecode.globals.attributeOffsetCount )
2602 sourceAt( aDecode.sourceName, aModel.version, wxS(
"attribute offset" ), 7, aOffsetIndex,
2603 aDecode.globals.attributeOffsetBase, ATTRIBUTE_OFFSET_BYTES, -1 );
2604 throwDecodeError(
source, wxS(
"attribute offset index leaves outer controller 7" ) );
2607 const size_t offsetRecord = aDecode.globals.attributeOffsetBase + aOffsetIndex * ATTRIBUTE_OFFSET_BYTES;
2608 const uint32_t heapOffset = aDecode.cursor.U32At( offsetRecord );
2610 aOffsetIndex, aDecode.globals.attributeHeapBase + heapOffset, 0, -1 );
2612 if( heapOffset >= aDecode.globals.attributeHeapBytes )
2613 throwDecodeError(
source, wxS(
"attribute string offset leaves outer controller 2" ) );
2616 const size_t heapEnd = aDecode.globals.attributeHeapBase + aDecode.globals.attributeHeapBytes;
2618 while(
end < heapEnd && aDecode.bytes[
end] != 0 )
2621 if(
end == heapEnd )
2622 throwDecodeError(
source, wxS(
"placement attribute is not NUL terminated" ) );
2625 size_t separator =
source.absoluteOffset;
2627 while( separator <
end && aDecode.bytes[separator] != 1 )
2630 if( aRequireValue && separator ==
end )
2631 throwDecodeError(
source, wxS(
"placement attribute lacks key/value separator" ) );
2634 { aDecode.bytes.begin() +
source.absoluteOffset, aDecode.bytes.begin() + separator }, DEFAULT_CODE_PAGE,
2635 source, aModel.diagnostics );
2638 if( separator !=
end )
2641 valueSource.absoluteOffset = separator + 1;
2642 valueSource.length =
end - separator - 1;
2644 { aDecode.bytes.begin() + valueSource.absoluteOffset, aDecode.bytes.begin() +
end },
2645 DEFAULT_CODE_PAGE, valueSource, aModel.diagnostics );
2648 return std::pair<SOURCE_STRING, SOURCE_STRING>{ std::move(
name ), std::move( value ) };
2652 PLACEMENT_TARGET resolvePlacementTarget(
const PLACEMENT_DECODE& aDecode,
size_t aOffset,
2655 PLACEMENT_TARGET target;
2656 target.componentIdentity = aDecode.cursor.U32At( aOffset + aDecode.layout.componentIdentity );
2658 const uint16_t partHandle = aDecode.cursor.U16At( aOffset + aDecode.layout.partType );
2659 auto part = std::ranges::find_if( aModel.partTypes,
2662 return aPart.source.sheet == static_cast<int>( aDecode.sheetIndex )
2663 && aPart.source.recordIndex == partHandle;
2666 if( part == aModel.partTypes.end() )
2668 const bool definitionClass =
2669 std::ranges::any_of( aModel.definitions,
2672 return aDefinition.source.sheet == static_cast<int>( aDecode.sheetIndex )
2673 && aDefinition.source.recordIndex == partHandle;
2675 throwDecodeError( aSource, definitionClass
2676 ? wxS(
"placement part-type handle targets definition object class" )
2677 : wxS(
"unresolved placement part-type reference" ) );
2680 const uint32_t groupHandle = aDecode.cursor.U32At( aOffset + aDecode.layout.componentGroup );
2682 if( groupHandle >= aDecode.globals.groupCount )
2683 throwDecodeError( aSource, wxS(
"placement component-group handle leaves outer controller 6" ) );
2685 const size_t groupOffset = aDecode.globals.groupBase + groupHandle * PLACEMENT_GROUP_BYTES;
2686 const uint32_t attributeStart = aDecode.cursor.U32At( groupOffset );
2687 const uint16_t attributeCount = aDecode.cursor.U16At( groupOffset + 20 );
2689 if( attributeCount < 2 || attributeStart > aDecode.globals.attributeOffsetCount
2690 || attributeCount > aDecode.globals.attributeOffsetCount - attributeStart )
2692 throwDecodeError( aSource, wxS(
"placement component-group attribute slice leaves controller 7" ) );
2695 auto [groupPartName, unusedGroupPartValue] =
2696 decodePlacementAttribute( aDecode, attributeStart + 1,
false, aModel );
2698 if( groupPartName.text != part->name.text )
2699 throwDecodeError( aSource, wxS(
"placement component-group targets wrong part-type object class" ) );
2701 const uint16_t decalHandle = aDecode.cursor.U16At( aOffset + aDecode.layout.decal );
2703 if( decalHandle >= aDecode.controllers.pools[6].count )
2704 throwDecodeError( aSource, wxS(
"unresolved placement decal reference" ) );
2706 const size_t decalOffset = aDecode.controllers.offsets[6] + decalHandle * USED_DECAL_BYTES;
2707 const uint32_t definitionHandle = aDecode.cursor.U32At( decalOffset + 48 );
2709 std::ranges::find_if( aModel.definitions,
2712 return aDefinition.source.sheet == static_cast<int>( aDecode.sheetIndex )
2713 && aDefinition.source.recordIndex == definitionHandle;
2716 if( definition == aModel.definitions.end() )
2717 throwDecodeError( aSource, wxS(
"placement decal targets wrong definition object class" ) );
2719 const uint16_t unitIndex = aDecode.cursor.U16At( aOffset + aDecode.layout.gate );
2723 if( unitIndex < part->gates.size() )
2724 gate = &part->gates[unitIndex];
2725 else if( part->gates.size() == 1 && !part->gates.front().decalGroupMembers.empty() )
2726 gate = &part->gates.front();
2727 else if( part->gates.empty() && unitIndex == 0 && definition->pins.empty() )
2731 const bool definitionClass =
2732 std::ranges::any_of( aModel.definitions,
2735 return aDefinition.source.sheet == static_cast<int>( aDecode.sheetIndex )
2736 && aDefinition.source.recordIndex == unitIndex;
2738 throwDecodeError( aSource, definitionClass ? wxS(
"placement gate handle targets definition object class" )
2739 : wxS(
"unresolved placement gate reference" ) );
2744 return aReference.id == definition->id;
2747 if( gate && !gateHasDefinition( gate->definition )
2748 && std::ranges::none_of( gate->alternateDefinitions, gateHasDefinition )
2749 && std::ranges::none_of( gate->decalGroupMembers, gateHasDefinition ) )
2751 throwDecodeError( aSource, wxS(
"placement decal and gate reference target different object classes" ) );
2754 target.part = &*part;
2755 target.definition = &*definition;
2757 target.groupHandle = groupHandle;
2758 target.attributeStart = attributeStart;
2759 target.attributeCount = attributeCount;
2760 target.decalHandle = decalHandle;
2761 target.unitIndex = unitIndex;
2766 void decodePlacedPins(
const PLACEMENT_DECODE& aDecode, uint32_t aPinStart, uint16_t aPinCount,
2770 const size_t placedPinBase = aDecode.controllers.offsets[15];
2772 for(
size_t pin = 0;
pin < aPinCount; ++
pin )
2774 const size_t pinOffset = placedPinBase + ( aPinStart +
pin ) * aDecode.layout.placedPinBytes;
2776 sourceAt( aDecode.sourceName, aModel.version, wxS(
"placed pin" ), 16, aPinStart +
pin, pinOffset,
2777 aDecode.layout.placedPinBytes,
static_cast<int>( aDecode.sheetIndex ) );
2778 const uint16_t pinOrdinal = aDecode.cursor.U16At( pinOffset + aDecode.layout.placedPinOrdinal );
2780 if( pinOrdinal >= aDefinition.pins.size() || pinOrdinal !=
pin )
2781 throwDecodeError( pinSource, wxS(
"placed-pin handle leaves placement definition" ) );
2785 static_cast<int64_t
>(
static_cast<int16_t
>( aDecode.cursor.U16At( pinOffset + 6 ) ) ) * 2,
2786 static_cast<int64_t
>(
static_cast<int16_t
>( aDecode.cursor.U16At( pinOffset + 8 ) ) ) * 2, pinSource
2788 pinReference.numberPresentationFlags = aDecode.cursor.U16At( pinOffset + 10 );
2789 pinReference.numberAngle = ( pinReference.numberPresentationFlags & 0x0001 ) != 0 ? 900 : 0;
2791 pinReference.numberJustification = terminalJustification(
2792 ( pinReference.numberPresentationFlags >> 4 ) & 0x0F, pinReference.numberAngle != 0 );
2794 pinReference.hasNumberPlacement =
true;
2795 aPlacement.pins.push_back( std::move( pinReference ) );
2800 void decodeInlineField(
const PLACEMENT_DECODE& aDecode,
size_t aOffset,
const SOURCE_PROVENANCE& aSource,
2801 const wxString& aName,
const SOURCE_STRING& aValue,
bool aVisible,
2806 fieldSource.
objectClass = wxS(
"placement field" );
2807 fieldSource.absoluteOffset += aFieldLayout.position;
2808 fieldSource.length = 8;
2810 field.
source = fieldSource;
2811 field.name.text = aName;
2812 field.name.source = fieldSource;
2813 field.value = aValue;
2814 field.position = { decodeLocalCoordinate( aDecode.cursor.U16At( aOffset + aFieldLayout.position ) ),
2815 decodeLocalCoordinate( aDecode.cursor.U16At( aOffset + aFieldLayout.position + 2 ) ),
2817 field.angle =
NormalizeAngle( aDecode.cursor.U16At( aOffset + aFieldLayout.angle ) );
2818 field.presentation.source = fieldSource;
2819 field.visible = aVisible;
2820 field.presentation.visible = aVisible;
2821 field.presentation.height = decodeHalfMils( aDecode.cursor.U16At( aOffset + aFieldLayout.height ) );
2822 field.presentation.width = decodeHalfMils( aDecode.cursor.U8At( aOffset + aFieldLayout.width ) );
2823 const uint16_t justification = aDecode.cursor.U16At( aOffset + aFieldLayout.angle + 2 );
2824 const uint16_t rotatedJustification = rotatedFieldJustification( justification, field.angle );
2825 field.presentation.horizontalJustification = horizontalJustification( rotatedJustification );
2826 field.presentation.verticalJustification = verticalJustification( rotatedJustification );
2829 fontSource.length = 2;
2830 decodeGlobalFont( aDecode.bytes, aDecode.cursor, aDecode.globals, aDecode.sourceName, aModel.version,
2831 static_cast<int16_t
>( aDecode.cursor.U16At( aOffset + aFieldLayout.font ) ), fontSource,
2832 field.presentation,
false, aModel.diagnostics );
2833 aPlacement.fields.push_back( std::move( field ) );
2837 void decodeCustomFields(
const PLACEMENT_DECODE& aDecode,
size_t aOffset,
const SOURCE_PROVENANCE& aSource,
2838 const PLACEMENT_TARGET& aTarget, uint32_t& aFieldCursor,
MODEL_PLACEMENT& aPlacement,
2841 const size_t fieldBase = aDecode.controllers.offsets[16];
2843 const uint16_t customFieldCount = aDecode.cursor.U16At( aOffset + aDecode.layout.fieldCount );
2845 if( aFieldCursor > aDecode.controllers.pools[16].count
2846 || customFieldCount > aDecode.controllers.pools[16].count - aFieldCursor )
2848 throwDecodeError( aSource, wxS(
"placement field ownership does not match controller 17" ) );
2851 for(
size_t fieldOrdinal = 0; fieldOrdinal < customFieldCount; ++fieldOrdinal )
2853 const size_t fieldOffset = fieldBase + aFieldCursor * aDecode.layout.fieldBytes;
2855 sourceAt( aDecode.sourceName, aModel.version, wxS(
"placement field" ), 17, aFieldCursor,
2856 fieldOffset, aDecode.layout.fieldBytes,
static_cast<int>( aDecode.sheetIndex ) );
2860 const uint8_t displayFlags = aDecode.cursor.U8At( fieldOffset + aDecode.layout.customDisplayFlags );
2861 const uint16_t attributeIndex = aDecode.cursor.U16At( fieldOffset + aDecode.layout.customAttributeIndex );
2863 if( attributeIndex == 0xFFFF )
2865 name.text = wxS(
"*" );
2866 name.source = fieldSource;
2867 value.source = fieldSource;
2871 if( attributeIndex >= aTarget.attributeCount )
2872 throwDecodeError( fieldSource, wxS(
"placement field attribute index leaves component group" ) );
2874 std::tie(
name, value ) =
2875 decodePlacementAttribute( aDecode, aTarget.attributeStart + attributeIndex,
true, aModel );
2878 field.
source = fieldSource;
2879 field.name = std::move(
name );
2880 field.value = std::move( value );
2882 decodeLocalCoordinate( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customX ) ),
2883 decodeLocalCoordinate( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customX + 2 ) ), fieldSource
2885 field.angle =
NormalizeAngle( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customAngle ) );
2887 if( field.angle % 900 != 0 )
2888 throwDecodeError( fieldSource, wxS(
"unsupported placement-field rotation" ) );
2890 const uint8_t justification = aDecode.cursor.U8At( fieldOffset + aDecode.layout.customJustification );
2891 const uint16_t rotatedJustification = rotatedFieldJustification( justification, field.angle );
2892 field.presentation.source = fieldSource;
2893 field.presentation.horizontalJustification = horizontalJustification( rotatedJustification );
2894 field.presentation.verticalJustification = verticalJustification( rotatedJustification );
2895 field.presentation.height = decodeHalfMils( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customHeight ) );
2896 field.presentation.width = decodeHalfMils( aDecode.cursor.U8At( fieldOffset + aDecode.layout.customWidth ) );
2897 field.presentation.visible = ( displayFlags & 8 ) == 0;
2898 field.visible = field.presentation.visible;
2902 decodeGlobalFont( aDecode.bytes, aDecode.cursor, aDecode.globals, aDecode.sourceName, aModel.version,
2903 static_cast<int16_t
>( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customFont ) ),
2904 fontSource, field.presentation,
true, aModel.diagnostics );
2905 field.properties.push_back( sourceProperty( wxS(
"display_flags" ),
2906 wxString::Format( wxS(
"%u" ), displayFlags ), fieldSource ) );
2908 attributeIndexSource.
absoluteOffset += aDecode.layout.customAttributeIndex;
2909 attributeIndexSource.length = 2;
2910 field.properties.push_back( sourceProperty(
2911 wxS(
"component_attribute_index" ),
2912 wxString::Format( wxS(
"%u" ),
2913 aDecode.cursor.U16At( fieldOffset + aDecode.layout.customAttributeIndex ) ),
2914 attributeIndexSource ) );
2916 wxS(
"preserved_field_tail" ),
2917 wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( fieldOffset + aDecode.layout.customTail ) ),
2920 field.properties.push_back( std::move( preservedTail ) );
2921 aPlacement.fields.push_back( std::move( field ) );
2927 void decodeGroupAttributeFields(
const PLACEMENT_DECODE& aDecode,
const PLACEMENT_TARGET& aTarget,
2930 for( uint16_t attributeIndex = 2; attributeIndex < aTarget.attributeCount; ++attributeIndex )
2932 auto [
name, value] =
2933 decodePlacementAttribute( aDecode, aTarget.attributeStart + attributeIndex,
true, aModel );
2935 if(
name.text.CmpNoCase( wxS(
"PCB DECAL" ) ) == 0
2936 || std::ranges::any_of( aPlacement.fields,
2939 return aField.name.text.CmpNoCase( name.text ) == 0;
2947 field.name = std::move(
name );
2948 field.value = std::move( value );
2949 field.visible =
false;
2950 field.presentation.source = field.source;
2951 field.presentation.visible =
false;
2952 aPlacement.fields.push_back( std::move( field ) );
2957 void recordPlacementProperties(
const PLACEMENT_DECODE& aDecode,
const SOURCE_PROVENANCE& aSource,
2958 const PLACEMENT_TARGET& aTarget, uint16_t aRawAngle,
MODEL_PLACEMENT& aPlacement )
2962 rawAngleSource.length = 2;
2963 aPlacement.properties.push_back(
2964 sourceProperty( wxS(
"raw_angle" ), wxString::Format( wxS(
"%u" ), aRawAngle ), rawAngleSource ) );
2965 aPlacement.properties.push_back( sourceProperty(
2966 wxS(
"component_identity" ), wxString::Format( wxS(
"%u" ), aTarget.componentIdentity ), aSource ) );
2967 aPlacement.properties.push_back( sourceProperty(
2968 wxS(
"component_group_handle" ), wxString::Format( wxS(
"%u" ), aTarget.groupHandle ), aSource ) );
2969 aPlacement.properties.push_back( sourceProperty(
2970 wxS(
"decal_handle" ), wxString::Format( wxS(
"%u" ), aTarget.decalHandle ), aSource ) );
2973 rawMirrorSource.length = 2;
2974 aPlacement.properties.push_back( sourceProperty(
2975 wxS(
"raw_mirror" ), wxString::Format( wxS(
"%u" ), aPlacement.mirrorFlags ), rawMirrorSource ) );
2977 visibilitySource.
absoluteOffset += aDecode.layout.itemVisibility;
2978 visibilitySource.length = 1;
2979 aPlacement.properties.push_back(
2980 sourceProperty( wxS(
"item_visibility_flags" ),
2981 wxString::Format( wxS(
"%u" ), aPlacement.itemVisibilityFlags ), visibilitySource ) );
2985 void decodePlacementRecord(
const PLACEMENT_DECODE& aDecode,
size_t aRecord, uint32_t& aExpectedPinStart,
2988 const PLACEMENT_LAYOUT& layout = aDecode.layout;
2989 const size_t offset = aDecode.controllers.offsets[14] + aRecord * layout.placementBytes;
2992 offset, layout.placementBytes,
static_cast<int>( aDecode.sheetIndex ) );
2994 const PLACEMENT_TARGET target = resolvePlacementTarget( aDecode, offset,
source, aModel );
2995 const uint32_t pinStart = aDecode.cursor.U32At( offset + layout.pinStart );
2996 const uint16_t pinCount = aDecode.cursor.U16At( offset + layout.pinCount );
2998 if( pinStart != aExpectedPinStart || pinStart > aDecode.controllers.pools[15].count
2999 || pinCount > aDecode.controllers.pools[15].count - pinStart || pinCount != target.definition->pins.size() )
3001 throwDecodeError(
source, wxS(
"placement pin ownership does not match controller 16" ) );
3006 if( aDecode.sheetIndex >= 0x0FFF || aRecord >= 0x100000 )
3007 throwDecodeError(
source, wxS(
"placement identity exceeds sheet/controller namespace" ) );
3009 placement.id =
PLACEMENT_ID(
static_cast<uint32_t
>( aDecode.sheetIndex * 0x100000 + aRecord + 1 ) );
3010 placement.source =
source;
3011 placement.sheet = { aModel.sheets[aDecode.sheetIndex].id,
source };
3012 placement.partType = { target.part->id,
source };
3017 placement.definition = { target.definition->id,
source };
3018 placement.unit = target.unitIndex + 1;
3019 placement.position = { decodeCoordinate( aDecode.cursor.U16At( offset + layout.x ) ),
3020 decodeCoordinate( aDecode.cursor.U16At( offset + layout.y ) ),
source };
3021 const uint16_t rawAngle = aDecode.cursor.U16At( offset + layout.angle );
3023 placement.mirrorFlags = aDecode.cursor.U16At( offset + layout.mirror );
3025 auto recordTransformEnum = [&](
size_t aFieldOffset )
3028 enumSource.absoluteOffset += aFieldOffset;
3029 enumSource.length = 2;
3030 aModel.diagnostics.push_back(
3034 const bool knownAngle = rawAngle == 0 || rawAngle == 900 || rawAngle == 1800 || rawAngle == 2700;
3037 recordTransformEnum( layout.angle );
3039 const bool knownMirror = placement.mirrorFlags <= 3;
3042 recordTransformEnum( layout.mirror );
3044 placement.mirrored = placement.mirrorFlags != 0;
3046 referenceSource.absoluteOffset += layout.reference;
3047 referenceSource.length = 40;
3048 placement.reference =
3049 decodeFixedString( aDecode.bytes, offset + layout.reference, 40, referenceSource, aModel.diagnostics );
3051 decodePlacedPins( aDecode, pinStart, pinCount, *target.definition, placement, aModel );
3052 aExpectedPinStart += pinCount;
3054 placement.itemVisibilityFlags = aDecode.cursor.U8At( offset + layout.itemVisibility );
3055 placement.referenceVisible = ( placement.itemVisibilityFlags & 0x01 ) == 0;
3056 placement.partTypeVisible = ( placement.itemVisibilityFlags & 0x02 ) == 0;
3057 placement.pinNamesVisible = ( placement.itemVisibilityFlags & 0x08 ) == 0;
3058 placement.pinNumbersVisible = ( placement.itemVisibilityFlags & 0x10 ) == 0;
3060 decodeInlineField( aDecode, offset,
source, wxS(
"REF-DES" ), placement.reference, placement.referenceVisible,
3061 { layout.referenceField, layout.referenceFieldAngle, layout.referenceFont,
3062 layout.referenceHeight, layout.referenceWidth },
3063 placement, aModel );
3064 decodeInlineField( aDecode, offset,
source, wxS(
"PART-TYPE" ), target.part->name, placement.partTypeVisible,
3065 { layout.partTypeField, layout.partTypeFieldAngle, layout.partTypeFont,
3066 layout.partTypeHeight, layout.partTypeWidth },
3067 placement, aModel );
3068 decodeCustomFields( aDecode, offset,
source, target, aFieldCursor, placement, aModel );
3069 decodeGroupAttributeFields( aDecode, target, placement, aModel );
3070 recordPlacementProperties( aDecode,
source, target, rawAngle, placement );
3071 aModel.placements.push_back( std::move( placement ) );
3075 void decodePlacements(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
3076 const SCH_SDB_BLOCK& aBlock,
size_t aSheetIndex,
const wxString& aSourceName,
3079 const PLACEMENT_LAYOUT& layout = placementLayout( aModel.version );
3081 if( !layout.decoded )
3082 throwDecodeError( aModel.source, wxS(
"placement decoder selected for raw-preserved version" ) );
3084 const SHEET_CONTROLLERS controllers = sheetControllers( aCursor, aBlock );
3085 requireFixedController( controllers, 15, layout.placementBytes, aSourceName, aModel.version, aSheetIndex );
3086 requireFixedController( controllers, 16, layout.placedPinBytes, aSourceName, aModel.version, aSheetIndex );
3087 requireFixedController( controllers, 17, layout.fieldBytes, aSourceName, aModel.version, aSheetIndex );
3089 const PLACEMENT_DECODE
decode{ aBytes, aCursor, controllers, layout, aGlobals, aSourceName, aSheetIndex };
3090 uint32_t expectedPinStart = 0;
3091 uint32_t fieldCursor = 0;
3093 for(
size_t record = 0; record < controllers.pools[14].count; ++record )
3094 decodePlacementRecord( decode, record, expectedPinStart, fieldCursor, aModel );
3096 if( expectedPinStart != controllers.pools[15].count )
3099 controllers.offsets[15], controllers.pools[15].usedBytes,
3100 static_cast<int>( aSheetIndex ) );
3101 throwDecodeError(
source, wxS(
"unowned placed-pin record" ) );
3104 if( fieldCursor != controllers.pools[16].count )
3107 controllers.offsets[16], controllers.pools[16].usedBytes,
3108 static_cast<int>( aSheetIndex ) );
3109 throwDecodeError(
source, wxS(
"unowned placement-field record" ) );
3114 struct CONNECTIVITY_DECODE
3116 const std::vector<uint8_t>& bytes;
3117 const PADS_IO::BINARY_CURSOR& cursor;
3118 const SHEET_CONTROLLERS& controllers;
3119 const CONNECTIVITY_GLOBALS& globals;
3120 const wxString& sourceName;
3123 size_t junctionBase;
3125 size_t connectionBase;
3131 struct VERTEX_TILING
3133 std::vector<uint32_t> starts;
3134 std::vector<uint32_t> ends;
3138 struct SHEET_CONNECTIVITY
3140 std::vector<MODEL_NET*> sheetNets;
3141 std::vector<MODEL_CONNECTION*> connections;
3142 std::vector<MODEL_NET*> connectionNets;
3143 std::vector<std::vector<size_t>> junctionBacklinks;
3144 std::vector<std::vector<size_t>> offpageBacklinks;
3148 std::pair<int64_t, int64_t> transformedPinPosition(
const MODEL_PLACEMENT& aPlacement,
3151 int64_t x = aPin.position.x;
3152 int64_t y = aPin.position.y;
3156 case 900: std::tie( x, y ) = std::pair{ -y, x };
break;
3157 case 1800: std::tie( x, y ) = std::pair{ -x, -y };
break;
3158 case 2700: std::tie( x, y ) = std::pair{ y, -x };
break;
3162 if( aPlacement.mirrorFlags & 1 )
3165 if( aPlacement.mirrorFlags & 2 )
3168 return std::pair{ aPlacement.position.x + x, aPlacement.position.y + y };
3172 SOURCE_POINT offpagePosition(
const CONNECTIVITY_DECODE& aDecode,
size_t aRecord, uint16_t aVersion )
3174 const size_t offset = aDecode.offpageBase + aRecord * OFFPAGE_RECORD_BYTES;
3176 offset, OFFPAGE_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3177 return SOURCE_POINT{ decodeCoordinate( aDecode.cursor.U16At( offset + 22 ) ),
3178 decodeCoordinate( aDecode.cursor.U16At( offset + 24 ) ),
source };
3182 SOURCE_POINT junctionPosition(
const CONNECTIVITY_DECODE& aDecode,
size_t aRecord, uint16_t aVersion )
3184 const size_t offset = aDecode.junctionBase + aRecord * JUNCTION_RECORD_BYTES;
3186 JUNCTION_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3187 return SOURCE_POINT{ decodeCoordinate( aDecode.cursor.U16At( offset + 4 ) ),
3188 decodeCoordinate( aDecode.cursor.U16At( offset + 6 ) ),
source };
3192 std::unordered_set<uint32_t> decodeBusGlobalRecords(
const CONNECTIVITY_DECODE& aDecode,
PADS_SCH_MODEL& aModel )
3194 std::unordered_set<uint32_t> busGlobalRecords;
3196 for(
size_t record = 0; record < aDecode.controllers.pools[17].count; ++record )
3198 const uint32_t globalRecord = aDecode.cursor.U32At( aDecode.busBase + record * BUS_RECORD_BYTES + 8 );
3199 const uint8_t netKind = globalRecord < aDecode.globals.nets.size()
3200 ? aDecode.globals.nets[globalRecord].kindFlags & 0xFF
3203 if( globalRecord >= aDecode.globals.nets.size() || aDecode.globals.nets[globalRecord].tombstone
3204 || ( netKind != 1 && netKind != 5 ) )
3207 aDecode.busBase + record * BUS_RECORD_BYTES, BUS_RECORD_BYTES,
3208 static_cast<int>( aDecode.sheetIndex ) );
3209 throwDecodeError(
source, wxS(
"bus global-net handle targets wrong or unresolved object class" ) );
3212 busGlobalRecords.insert( globalRecord );
3215 return busGlobalRecords;
3219 std::vector<MODEL_NET*> materializeSheetNets(
const CONNECTIVITY_DECODE& aDecode,
3220 const std::unordered_set<uint32_t>& aBusGlobalRecords,
3223 std::vector<MODEL_NET*> sheetNets( aDecode.globals.nets.size(),
nullptr );
3226 aModel.nets.reserve( aModel.nets.size() + aDecode.globals.membershipCount );
3228 for(
size_t globalRecord = 0; globalRecord < aDecode.globals.nets.size(); ++globalRecord )
3230 const GLOBAL_NET_RECORD& global = aDecode.globals.nets[globalRecord];
3232 if( global.tombstone )
3235 for( uint32_t membership = global.membershipStart;
3236 membership < global.membershipStart + global.membershipCount; ++membership )
3238 if( aDecode.globals.membershipSheets[membership] != aDecode.sheetIndex )
3241 if( global.aliasCount != 0 || aBusGlobalRecords.contains( globalRecord ) )
3245 net.id =
NET_ID( membership );
3246 net.source = global.source;
3247 net.source.sheet =
static_cast<int>( aDecode.sheetIndex );
3249 sourceAt( aDecode.sourceName, aModel.version, wxS(
"net sheet membership" ), 4, membership,
3250 aDecode.globals.membershipBase + membership * NET_MEMBERSHIP_BYTES,
3251 NET_MEMBERSHIP_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3252 net.sheet = { aModel.sheets[aDecode.sheetIndex].id, membershipSource };
3253 net.name = global.name;
3254 net.properties.push_back( sourceProperty(
3255 wxS(
"global_net_record" ), wxString::Format( wxS(
"%llu" ), globalRecord ), global.source ) );
3257 sourceProperty( wxS(
"preserved_net_identity" ),
3258 wxString::Format( wxS(
"%u" ), global.preservedIdentity ), global.source );
3260 net.properties.push_back( std::move( identity ) );
3262 relationshipSource.absoluteOffset += 84;
3263 relationshipSource.length = 4;
3265 wxS(
"preserved_net_relationship" ),
3266 wxString::Format( wxS(
"%u" ), global.preservedRelationship ), relationshipSource );
3268 net.properties.push_back( std::move( relationship ) );
3269 aModel.nets.push_back( std::move( net ) );
3270 sheetNets[globalRecord] = &aModel.nets.back();
3278 std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*> indexDefinitionPins(
const PADS_SCH_MODEL& aModel )
3280 std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*> definitionPins;
3285 definitionPins.emplace(
pin.id.Value(), &
pin );
3288 return definitionPins;
3292 std::vector<MODEL_PLACEMENT*> indexSheetPlacements(
const CONNECTIVITY_DECODE& aDecode,
PADS_SCH_MODEL& aModel )
3294 std::vector<MODEL_PLACEMENT*> placements( aDecode.controllers.pools[14].count,
nullptr );
3298 if( placement.source.sheet !=
static_cast<int>( aDecode.sheetIndex ) )
3301 if( placement.source.recordIndex >= placements.size() || placements[placement.source.recordIndex] )
3302 throwDecodeError( placement.source, wxS(
"placement endpoint identity leaves controller 15" ) );
3304 placements[placement.source.recordIndex] = &placement;
3311 void decodeJunctions(
const CONNECTIVITY_DECODE& aDecode,
PADS_SCH_MODEL& aModel )
3313 for(
size_t record = 0; record < aDecode.controllers.pools[18].count; ++record )
3315 const size_t offset = aDecode.junctionBase + record * JUNCTION_RECORD_BYTES;
3317 sourceAt( aDecode.sourceName, aModel.version, wxS(
"junction" ), 19, record, offset,
3318 JUNCTION_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3320 const uint16_t status = aDecode.cursor.U16At( offset + 10 );
3322 if( status != 0 && status != 0x00FC && status != 0x00FD )
3323 throwDecodeError(
source, wxS(
"invalid junction object-class marker" ) );
3327 junction.sheet = { aModel.sheets[aDecode.sheetIndex].id,
source };
3328 junction.position = junctionPosition( aDecode, record, aModel.version );
3330 connectionSource.absoluteOffset += 8;
3331 connectionSource.length = 2;
3332 junction.properties.push_back( sourceProperty(
3333 wxS(
"connection_record" ), wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( offset + 8 ) ),
3334 connectionSource ) );
3335 aModel.junctions.push_back( std::move( junction ) );
3340 VERTEX_TILING tileConnectivityVertices(
const CONNECTIVITY_DECODE& aDecode,
PADS_SCH_MODEL& aModel )
3342 VERTEX_TILING tiling;
3345 tiling.starts.reserve( aDecode.controllers.pools[17].count + aDecode.controllers.pools[20].count );
3347 for(
size_t record = 0; record < aDecode.controllers.pools[17].count; ++record )
3348 tiling.starts.push_back( aDecode.cursor.U32At( aDecode.busBase + record * BUS_RECORD_BYTES + 4 ) );
3350 for(
size_t record = 0; record < aDecode.controllers.pools[20].count; ++record )
3351 tiling.starts.push_back(
3352 aDecode.cursor.U32At( aDecode.connectionBase + record * CONNECTION_RECORD_BYTES + 4 ) );
3354 std::vector<size_t> objectOrder( tiling.starts.size() );
3356 for(
size_t object = 0;
object < objectOrder.size(); ++object )
3357 objectOrder[
object] =
object;
3359 std::ranges::sort( objectOrder,
3360 [&](
size_t aLeft,
size_t aRight )
3362 return tiling.starts[aLeft] < tiling.starts[aRight];
3364 tiling.ends.resize( tiling.starts.size() );
3366 for(
size_t ordinal = 0; ordinal < objectOrder.size(); ++ordinal )
3368 const size_t object = objectOrder[ordinal];
3369 const uint32_t
end = ordinal + 1 < objectOrder.size() ? tiling.starts[objectOrder[ordinal + 1]]
3370 : aDecode.controllers.pools[21].count;
3372 if( ( ordinal == 0 && tiling.starts[
object] != 0 ) || tiling.starts[
object] >=
end
3373 ||
end > aDecode.controllers.pools[21].count )
3376 sourceAt( aDecode.sourceName, aModel.version, wxS(
"connectivity vertex ownership" ),
3377 object < aDecode.controllers.pools[17].count ? 18 : 21,
object, aDecode.vertexBase,
3378 aDecode.controllers.pools[21].usedBytes,
static_cast<int>( aDecode.sheetIndex ) );
3379 throwDecodeError(
source, wxS(
"connectivity vertex slices do not exactly tile controller 22" ) );
3382 tiling.ends[object] =
end;
3385 if( tiling.starts.empty() && aDecode.controllers.pools[21].count != 0 )
3388 sourceAt( aDecode.sourceName, aModel.version, wxS(
"connection vertex" ), 22, 0, aDecode.vertexBase,
3389 aDecode.controllers.pools[21].usedBytes,
static_cast<int>( aDecode.sheetIndex ) );
3390 throwDecodeError(
source, wxS(
"unclaimed connection vertices" ) );
3397 void appendVertices(
const CONNECTIVITY_DECODE& aDecode,
const VERTEX_TILING& aTiling,
size_t aObject,
3398 uint16_t aVersion, std::vector<SOURCE_POINT>& aVertices )
3400 const uint32_t start = aTiling.starts[aObject];
3401 const uint32_t
end = aTiling.ends[aObject];
3403 for( uint32_t vertex = start; vertex <
end; ++vertex )
3405 const size_t offset = aDecode.vertexBase + vertex * CONNECTION_VERTEX_BYTES;
3407 sourceAt( aDecode.sourceName, aVersion, wxS(
"connection vertex" ), 22, vertex, offset,
3408 CONNECTION_VERTEX_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3410 if( aDecode.cursor.U32At( offset ) != 0 )
3411 throwDecodeError(
source, wxS(
"nonzero connection-vertex padding" ) );
3413 aVertices.push_back( { decodeCoordinate( aDecode.cursor.U16At( offset + 4 ) ),
3414 decodeCoordinate( aDecode.cursor.U16At( offset + 6 ) ),
source } );
3420 decodeConnectionEndpoint(
const CONNECTIVITY_DECODE& aDecode,
const SOURCE_PROVENANCE& aSource,
size_t aFieldOffset,
3421 size_t aRelationshipOffset,
const SOURCE_POINT& aWirePoint,
3422 const std::vector<MODEL_PLACEMENT*>& aPlacements,
3423 const std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*>& aDefinitionPins,
3427 endpointSource.
objectClass = wxS(
"connection endpoint" );
3428 endpointSource.absoluteOffset += aFieldOffset;
3429 endpointSource.length = 2;
3430 const uint16_t raw = aDecode.cursor.U16At( endpointSource.absoluteOffset );
3431 const uint16_t objectClass = raw >> 12;
3432 const uint16_t objectRecord = raw & 0x0FFF;
3434 relationshipSource.
objectClass = wxS(
"connection endpoint relationship" );
3435 relationshipSource.absoluteOffset += aRelationshipOffset;
3436 relationshipSource.length = 4;
3437 const uint32_t relationship = aDecode.cursor.U32At( relationshipSource.absoluteOffset );
3441 switch( objectClass )
3444 if( objectRecord >= aPlacements.size() || !aPlacements[objectRecord] )
3445 throwDecodeError( endpointSource, wxS(
"unresolved placement endpoint" ) );
3453 auto definitionPin = aDefinitionPins.find(
pin.id.Value() );
3455 if( definitionPin == aDefinitionPins.end() )
3456 throwDecodeError(
pin.source, wxS(
"placement pin definition is unresolved" ) );
3458 const auto position = transformedPinPosition( placement, *definitionPin->second );
3460 if( position.first != aWirePoint.x || position.second != aWirePoint.y )
3464 throwDecodeError( endpointSource,
3465 wxS(
"placement has duplicate pins at connection endpoint" ) );
3471 throwDecodeError( endpointSource,
3472 wxString::Format( wxS(
"placement has no pin at connection endpoint; "
3473 "angle %d mirror %u" ),
3474 placement.angle, placement.mirrorFlags ) );
3479 result.point = aWirePoint;
3484 if( objectRecord >= aDecode.controllers.pools[19].count )
3485 throwDecodeError( endpointSource, wxS(
"unresolved off-page endpoint" ) );
3488 result.point = offpagePosition( aDecode, objectRecord, aModel.version );
3492 if( objectRecord >= aDecode.controllers.pools[18].count )
3493 throwDecodeError( endpointSource, wxS(
"unresolved junction endpoint" ) );
3496 result.point = junctionPosition( aDecode, objectRecord, aModel.version );
3499 default: throwDecodeError( endpointSource, wxS(
"wrong endpoint object class" ) );
3502 result.properties.push_back(
3503 sourceProperty( wxS(
"raw_endpoint_handle" ), wxString::Format( wxS(
"%u" ), raw ), endpointSource ) );
3505 wxS(
"raw_endpoint_relationship" ), wxString::Format( wxS(
"%u" ), relationship ), relationshipSource );
3507 result.properties.push_back( std::move( relationshipProperty ) );
3512 void decodeConnections(
const CONNECTIVITY_DECODE& aDecode,
const VERTEX_TILING& aTiling,
3513 const std::vector<MODEL_PLACEMENT*>& aPlacements,
3514 const std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*>& aDefinitionPins,
3517 aConnectivity.connections.assign( aDecode.controllers.pools[20].count,
nullptr );
3518 aConnectivity.connectionNets.assign( aDecode.controllers.pools[20].count,
nullptr );
3519 aConnectivity.junctionBacklinks.assign( aDecode.controllers.pools[18].count, {} );
3520 aConnectivity.offpageBacklinks.assign( aDecode.controllers.pools[19].count, {} );
3521 std::vector<std::array<uint16_t, 2>> connectionEndpointHandles( aDecode.controllers.pools[20].count );
3522 std::vector<size_t> connectionCounts( aConnectivity.sheetNets.size(), 0 );
3524 for(
size_t record = 0; record < aDecode.controllers.pools[20].count; ++record )
3526 const uint32_t netHandle =
3527 aDecode.cursor.U32At( aDecode.connectionBase + record * CONNECTION_RECORD_BYTES + 8 );
3529 if( netHandle < connectionCounts.size() )
3530 ++connectionCounts[netHandle];
3533 for(
size_t net = 0; net < aConnectivity.sheetNets.size(); ++net )
3535 if( aConnectivity.sheetNets[net] )
3536 aConnectivity.sheetNets[net]->connections.reserve( connectionCounts[net] );
3539 for(
size_t record = 0; record < aDecode.controllers.pools[20].count; ++record )
3541 const size_t offset = aDecode.connectionBase + record * CONNECTION_RECORD_BYTES;
3543 sourceAt( aDecode.sourceName, aModel.version, wxS(
"connection" ), 21, record, offset,
3544 CONNECTION_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3545 const uint32_t netHandle = aDecode.cursor.U32At( offset + 8 );
3547 if( netHandle >= aConnectivity.sheetNets.size() || !aConnectivity.sheetNets[netHandle] )
3548 throwDecodeError(
source, wxS(
"connection net handle targets wrong or unresolved object class" ) );
3550 const uint16_t marker = aDecode.cursor.U16At( offset + 34 );
3552 const uint8_t markerStatus = marker & 0xFF;
3554 if( marker >> 8 < 2 || marker >> 8 > 6
3555 || ( markerStatus != 0 && markerStatus != 0xFC && markerStatus != 0xFD ) )
3556 throwDecodeError(
source, wxS(
"invalid connection object-class marker" ) );
3561 appendVertices( aDecode, aTiling, aDecode.controllers.pools[17].count + record, aModel.version,
3562 connection.vertices );
3564 if( connection.vertices.size() < 2 )
3565 throwDecodeError(
source, wxS(
"connection lacks explicit endpoint vertices" ) );
3567 connection.endpoints.push_back( decodeConnectionEndpoint(
3568 aDecode,
source, 12, 16, connection.vertices.front(), aPlacements, aDefinitionPins, aModel ) );
3569 connection.endpoints.push_back( decodeConnectionEndpoint(
3570 aDecode,
source, 14, 20, connection.vertices.back(), aPlacements, aDefinitionPins, aModel ) );
3572 for(
size_t endpointIndex = 0; endpointIndex < connection.endpoints.size(); ++endpointIndex )
3576 endpointIndex == 0 ? connection.vertices.front() : connection.vertices.back();
3579 && ( decodedEndpoint.point.x != wirePoint.x || decodedEndpoint.point.y != wirePoint.y ) )
3581 throwDecodeError( decodedEndpoint.source,
3582 wxS(
"typed endpoint position does not match wire endpoint vertex" ) );
3585 decodedEndpoint.point = { wirePoint.x, wirePoint.y, wirePoint.source };
3588 connectionEndpointHandles[record] = { aDecode.cursor.U16At( offset + 12 ),
3589 aDecode.cursor.U16At( offset + 14 ) };
3591 for(
size_t endpointIndex = 0; endpointIndex < connectionEndpointHandles[record].size(); ++endpointIndex )
3593 const uint16_t raw = connectionEndpointHandles[record][endpointIndex];
3594 const size_t objectClass = raw >> 12;
3595 const size_t objectRecord = raw & 0x0FFF;
3596 std::vector<size_t>* backlinks =
nullptr;
3598 if( objectClass == 2 )
3599 backlinks = &aConnectivity.offpageBacklinks[objectRecord];
3600 else if( objectClass == 3 )
3601 backlinks = &aConnectivity.junctionBacklinks[objectRecord];
3605 if( endpointIndex == 1 && connectionEndpointHandles[record][0] == raw )
3608 endpointSource.objectClass = wxS(
"connection endpoint" );
3609 endpointSource.absoluteOffset += endpointIndex == 0 ? 12 : 14;
3610 endpointSource.length = 2;
3611 throwDecodeError( endpointSource, wxS(
"duplicate typed endpoint backlink" ) );
3614 backlinks->push_back( record );
3618 connection.properties.push_back(
3619 sourceProperty( wxS(
"raw_connection_marker" ), wxString::Format( wxS(
"%u" ), marker ),
source ) );
3620 aConnectivity.sheetNets[netHandle]->connections.push_back( std::move( connection ) );
3621 aConnectivity.connections[record] = &aConnectivity.sheetNets[netHandle]->connections.back();
3622 aConnectivity.connectionNets[record] = aConnectivity.sheetNets[netHandle];
3627 void validateJunctionBacklinks(
const CONNECTIVITY_DECODE& aDecode,
const SHEET_CONNECTIVITY& aConnectivity,
3630 for(
size_t record = 0; record < aDecode.controllers.pools[18].count; ++record )
3632 const size_t offset = aDecode.junctionBase + record * JUNCTION_RECORD_BYTES;
3634 sourceAt( aDecode.sourceName, aModel.version, wxS(
"junction" ), 19, record, offset,
3635 JUNCTION_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3636 const uint16_t owner = aDecode.cursor.U16At( offset + 8 );
3638 ownerSource.absoluteOffset += 8;
3639 ownerSource.length = 2;
3641 if( owner >= aConnectivity.connections.size() || !aConnectivity.connections[owner] )
3642 throwDecodeError( ownerSource, wxS(
"junction connection handle leaves controller 21" ) );
3644 if( std::ranges::find( aConnectivity.junctionBacklinks[record], owner )
3645 == aConnectivity.junctionBacklinks[record].end() )
3646 throwDecodeError( ownerSource, wxS(
"junction connection handle does not point back" ) );
3648 for(
size_t connection : aConnectivity.junctionBacklinks[record] )
3650 if( aConnectivity.connectionNets[connection] != aConnectivity.connectionNets[owner] )
3652 throwDecodeError( ownerSource, wxS(
"junction is shared across different nets" ) );
3659 void validateOffpageBacklinks(
const CONNECTIVITY_DECODE& aDecode,
const SHEET_CONNECTIVITY& aConnectivity,
3662 for(
size_t record = 0; record < aDecode.controllers.pools[19].count; ++record )
3664 const size_t offset = aDecode.offpageBase + record * OFFPAGE_RECORD_BYTES;
3666 sourceAt( aDecode.sourceName, aModel.version, wxS(
"off-page reference" ), 20, record, offset,
3667 OFFPAGE_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3668 const uint16_t owner = aDecode.cursor.U16At( offset + 8 );
3670 ownerSource.absoluteOffset += 8;
3671 ownerSource.length = 2;
3673 if( owner >= aConnectivity.connections.size() || !aConnectivity.connections[owner] )
3674 throwDecodeError( ownerSource, wxS(
"off-page net handle leaves controller 21" ) );
3676 if( std::ranges::find( aConnectivity.offpageBacklinks[record], owner )
3677 == aConnectivity.offpageBacklinks[record].end() )
3678 throwDecodeError( ownerSource, wxS(
"off-page connection handle does not point back" ) );
3680 for(
size_t connection : aConnectivity.offpageBacklinks[record] )
3682 if( aConnectivity.connectionNets[connection] != aConnectivity.connectionNets[owner] )
3683 throwDecodeError( ownerSource, wxS(
"off-page reference is shared across different nets" ) );
3689 std::vector<bool> decodeBuses(
const CONNECTIVITY_DECODE& aDecode,
const VERTEX_TILING& aTiling,
3690 const std::unordered_set<uint32_t>& aBusGlobalRecords,
3691 const SHEET_CONNECTIVITY& aConnectivity,
PADS_SCH_MODEL& aModel )
3693 std::vector<bool> claimedBusEntries( aDecode.controllers.pools[19].count,
false );
3695 for(
size_t record = 0; record < aDecode.controllers.pools[17].count; ++record )
3697 const size_t offset = aDecode.busBase + record * BUS_RECORD_BYTES;
3699 BUS_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3700 const uint16_t marker = aDecode.cursor.U16At( offset + 38 );
3702 const uint8_t markerStatus = marker & 0xFF;
3704 if( marker >> 8 < 2 || marker >> 8 > 4 || ( markerStatus != 0 && markerStatus != 0xFD ) )
3705 throwDecodeError(
source, wxS(
"invalid bus object-class marker" ) );
3707 const size_t globalRecord = aDecode.cursor.U32At( offset + 8 );
3709 if( globalRecord >= aDecode.globals.nets.size() || aDecode.globals.nets[globalRecord].tombstone
3710 || !aBusGlobalRecords.contains( globalRecord ) )
3712 throwDecodeError(
source, wxS(
"bus global-net handle targets wrong or unresolved object class" ) );
3715 const GLOBAL_NET_RECORD& global = aDecode.globals.nets[globalRecord];
3716 uint32_t membership = global.membershipStart;
3718 while( membership < global.membershipStart + global.membershipCount
3719 && aDecode.globals.membershipSheets[membership] != aDecode.sheetIndex )
3724 if( membership == global.membershipStart + global.membershipCount )
3725 throwDecodeError(
source, wxS(
"bus global-net handle does not belong to this sheet" ) );
3728 bus.
id =
BUS_ID(
static_cast<uint32_t
>( aDecode.sheetIndex * 0x100000 + record + 1 ) );
3730 bus.sheet = { aModel.sheets[aDecode.sheetIndex].id,
source };
3731 bus.name = global.name;
3732 bus.aliases.push_back( global.name );
3733 bus.declaredMembers = global.aliasMembers;
3735 sourceProperty( wxS(
"preserved_net_identity" ),
3736 wxString::Format( wxS(
"%u" ), global.preservedIdentity ), global.source );
3738 bus.properties.push_back( std::move( identity ) );
3740 relationshipSource.absoluteOffset += 84;
3741 relationshipSource.length = 4;
3743 sourceProperty( wxS(
"preserved_net_relationship" ),
3744 wxString::Format( wxS(
"%u" ), global.preservedRelationship ), relationshipSource );
3746 bus.properties.push_back( std::move( relationship ) );
3747 appendVertices( aDecode, aTiling, record, aModel.version, bus.vertices );
3749 std::vector<size_t> entryRecords;
3750 uint16_t entryHandle = aDecode.cursor.U16At( offset + 24 );
3751 std::unordered_set<size_t>
chain;
3753 while( ( entryHandle >> 12 ) == 2 )
3755 const size_t entryRecord = entryHandle & 0x0FFF;
3757 if( entryRecord >= aDecode.controllers.pools[19].count )
3758 throwDecodeError(
source, wxS(
"unresolved bus-entry handle" ) );
3760 if( !
chain.insert( entryRecord ).second )
3761 throwDecodeError(
source, wxS(
"cyclic bus-entry handle chain" ) );
3763 entryRecords.push_back( entryRecord );
3764 entryHandle = aDecode.cursor.U16At( aDecode.offpageBase + entryRecord * OFFPAGE_RECORD_BYTES + 4 );
3767 if( record > 0x0FFF || entryHandle != 0xBFFF - record )
3768 throwDecodeError(
source, wxS(
"bus-entry chain terminates in wrong object class" ) );
3770 std::ranges::reverse( entryRecords );
3772 const bool exactAliasMapping = entryRecords.size() == global.aliasMembers.size();
3774 for(
size_t entry = 0; entry < entryRecords.size(); ++entry )
3776 const size_t entryRecord = entryRecords[entry];
3777 const size_t entryOffset = aDecode.offpageBase + entryRecord * OFFPAGE_RECORD_BYTES;
3779 sourceAt( aDecode.sourceName, aModel.version, wxS(
"bus entry" ), 20, entryRecord, entryOffset,
3780 OFFPAGE_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3782 if( aDecode.cursor.U8At( entryOffset + 30 ) != 0xFF )
3783 throwDecodeError( entrySource, wxS(
"bus-entry handle targets wrong off-page object class" ) );
3785 if( claimedBusEntries[entryRecord] )
3786 throwDecodeError( entrySource, wxS(
"duplicate bus-entry membership" ) );
3788 const uint16_t connectionHandle = aDecode.cursor.U16At( entryOffset + 8 );
3790 if( connectionHandle >= aConnectivity.connections.size()
3791 || !aConnectivity.connections[connectionHandle] )
3792 throwDecodeError( entrySource, wxS(
"unresolved bus-entry connection reference" ) );
3794 MODEL_CONNECTION* entryConnection = aConnectivity.connections[connectionHandle];
3795 MODEL_NET* memberNet = aConnectivity.connectionNets[connectionHandle];
3798 throwDecodeError( entrySource, wxS(
"bus-entry connection targets wrong member-net class" ) );
3800 if( exactAliasMapping && memberNet->name.text != global.aliasMembers[entry].text )
3801 throwDecodeError( entrySource, wxS(
"bus alias member does not match connected net" ) );
3803 const bool ownsConnection = std::ranges::any_of( memberNet->connections,
3806 return &aConnection == entryConnection;
3809 if( !ownsConnection )
3810 throwDecodeError( entrySource, wxS(
"bus-entry connection targets wrong member-net class" ) );
3812 claimedBusEntries[entryRecord] =
true;
3814 busEntry.
source = entrySource;
3815 busEntry.position = offpagePosition( aDecode, entryRecord, aModel.version );
3816 busEntry.memberNet = { memberNet->id, entrySource };
3817 bus.entries.push_back( std::move( busEntry ) );
3818 bus.memberNets.push_back( { memberNet->id, entrySource } );
3821 aModel.buses.push_back( std::move( bus ) );
3824 return claimedBusEntries;
3828 void decodeOffpageLabels(
const CONNECTIVITY_DECODE& aDecode,
const SHEET_CONNECTIVITY& aConnectivity,
3829 const std::vector<bool>& aClaimedBusEntries,
PADS_SCH_MODEL& aModel )
3831 for(
size_t record = 0; record < aDecode.controllers.pools[19].count; ++record )
3833 const size_t offset = aDecode.offpageBase + record * OFFPAGE_RECORD_BYTES;
3835 sourceAt( aDecode.sourceName, aModel.version, wxS(
"off-page reference" ), 20, record, offset,
3836 OFFPAGE_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
3837 const uint8_t rawKind = aDecode.cursor.U8At( offset + 30 );
3839 if( rawKind == 0xFF )
3841 if( !aClaimedBusEntries[record] )
3842 throwDecodeError(
source, wxS(
"unclaimed bus-entry record" ) );
3847 const uint16_t connectionHandle = aDecode.cursor.U16At( offset + 8 );
3849 if( connectionHandle >= aConnectivity.connections.size() || !aConnectivity.connections[connectionHandle] )
3850 throwDecodeError(
source, wxS(
"off-page net handle leaves controller 21" ) );
3852 MODEL_NET* ownerNet = aConnectivity.connectionNets[connectionHandle];
3855 throwDecodeError(
source, wxS(
"off-page record targets wrong net object class" ) );
3859 label.sheet = { aModel.sheets[aDecode.sheetIndex].id,
source };
3860 label.text = ownerNet->name;
3861 label.position = offpagePosition( aDecode, record, aModel.version );
3866 int32_t offpageAngle =
NormalizeAngle( aDecode.cursor.U16At( offset + 26 ) );
3867 const uint16_t offpageMirrorFlags = aDecode.cursor.U16At( offset + 28 );
3869 if( offpageMirrorFlags & 1 )
3872 if( offpageMirrorFlags & 2 )
3875 label.angle = offpageAngle;
3876 label.symbolVariant = rawKind;
3878 mirrorSource.absoluteOffset += 28;
3879 mirrorSource.length = 2;
3880 label.properties.push_back( sourceProperty( wxS(
"offpage_mirror_flags" ),
3881 wxString::Format( wxS(
"%u" ), offpageMirrorFlags ),
3885 if( offpageMirrorFlags & 0x00FC )
3890 wxS(
"unsupported PADS off-page mirror flag "
3891 "bits preserved" ) ) );
3894 if( rawKind == 0xFE )
3900 const uint16_t decalHandle = aDecode.cursor.U16At( offset + 4 );
3902 if( decalHandle == 0xFFFF )
3908 if( decalHandle >= aDecode.controllers.pools[6].count )
3909 throwDecodeError(
source, wxS(
"off-page decal handle leaves controller 7" ) );
3912 sourceAt( aDecode.sourceName, aModel.version, wxS(
"used decal" ), 7, decalHandle,
3913 aDecode.controllers.offsets[6] + decalHandle * USED_DECAL_BYTES, 40,
3914 static_cast<int>( aDecode.sheetIndex ) );
3915 SOURCE_STRING decalName = decodeFixedString( aDecode.bytes, decalSource.absoluteOffset,
3916 decalSource.length, decalSource, aModel.diagnostics );
3917 const uint32_t definitionRecord = aDecode.cursor.U32At( decalSource.absoluteOffset + 48 );
3919 if( definitionRecord >= aDecode.controllers.pools[2].count )
3920 throwDecodeError( decalSource, wxS(
"off-page decal definition leaves controller 3" ) );
3923 static_cast<uint32_t
>( aDecode.sheetIndex * 0x100000 + 1 + definitionRecord ) );
3924 auto specialPartOwnsDefinition = [&](
const wxString& aPartName )
3926 return std::ranges::any_of(
3930 if( aPart.name.text != aPartName )
3933 return std::ranges::any_of(
3935 [&]( const MODEL_GATE& aGate )
3937 return aGate.definition.id == definitionId
3938 || std::ranges::any_of( aGate.alternateDefinitions,
3939 [&]( const DEFINITION_REFERENCE& aRef )
3941 return aRef.id == definitionId;
3947 if( specialPartOwnsDefinition( wxS(
"$OSR_SYMS" ) ) )
3949 else if( specialPartOwnsDefinition( wxS(
"$GND_SYMS" ) ) )
3951 else if( specialPartOwnsDefinition( wxS(
"$PWR_SYMS" ) ) )
3957 sourceProperty( wxS(
"unsupported_offpage_decal" ), decalName.text, decalSource );
3959 aModel.diagnostics.push_back(
3961 wxS(
"unsupported off-page decal class preserved" ) ) );
3962 label.properties.push_back( std::move( unsupportedDecal ) );
3969 for( uint32_t membership =
3971 .nets[aDecode.cursor.U32At( aDecode.connectionBase
3972 + connectionHandle * CONNECTION_RECORD_BYTES + 8 )]
3975 < aDecode.globals.nets[aDecode.cursor.U32At( aDecode.connectionBase
3976 + connectionHandle * CONNECTION_RECORD_BYTES + 8 )]
3979 .nets[aDecode.cursor.U32At( aDecode.connectionBase
3980 + connectionHandle * CONNECTION_RECORD_BYTES + 8 )]
3984 const uint16_t peerSheet = aDecode.globals.membershipSheets[membership];
3986 if( peerSheet != aDecode.sheetIndex )
3987 label.linkedSheets.push_back( { aModel.sheets[peerSheet].id,
source } );
3992 label.presentation.visible =
false;
3994 label.properties.push_back(
3995 sourceProperty( wxS(
"offpage_variant" ), wxString::Format( wxS(
"%u" ), rawKind ),
source ) );
3996 aModel.labels.push_back( std::move( label ) );
4005 presentation.
source = aSource;
4006 presentation.height = decodeHalfMils( aDecode.cursor.U16At( aOffset + 2 ) );
4007 presentation.width = decodeHalfMils( aDecode.cursor.U16At( aOffset + 4 ) );
4008 presentation.horizontalJustification = horizontalJustification( aDecode.cursor.U16At( aOffset + 26 ) );
4009 presentation.verticalJustification = verticalJustification( aDecode.cursor.U16At( aOffset + 26 ) );
4010 const int16_t fontHandle =
static_cast<int16_t
>( aDecode.cursor.U16At( aOffset ) );
4014 if( fontHandle == -1 )
4016 presentation.font = decodedDefinitionFont( -1, fontSource );
4020 if( fontHandle < 0 ||
static_cast<uint32_t
>( fontHandle ) >= aDecode.globals.fontCount )
4021 throwDecodeError( fontSource, wxS(
"net-name font handle leaves outer controller 19" ) );
4023 const size_t fontOffset = aDecode.globals.fontBase +
static_cast<size_t>( fontHandle ) * FONT_RECORD_BYTES;
4024 SOURCE_PROVENANCE nameSource = sourceAt( aDecode.sourceName, aModel.version, wxS(
"net-name font" ), 19,
4025 fontHandle, fontOffset + 4, 32, -1 );
4026 presentation.font = decodeFixedString( aDecode.bytes, fontOffset + 4, 32, nameSource, aModel.diagnostics );
4027 const uint32_t style = aDecode.cursor.U32At( fontOffset );
4028 presentation.bold = style & 1;
4029 presentation.italic = style & 2;
4033 SOURCE_PROPERTY property = sourceProperty( wxS(
"unsupported_font_style_flags" ),
4034 wxString::Format( wxS(
"%u" ), style & ~3U ), fontSource );
4036 presentation.properties.push_back( property );
4042 presentation.properties.push_back(
4043 sourceProperty( wxS(
"font_handle" ), wxString::Format( wxS(
"%d" ), fontHandle ), fontSource ) );
4044 return presentation;
4048 void decodeNetNames(
const CONNECTIVITY_DECODE& aDecode,
const SHEET_CONNECTIVITY& aConnectivity,
4051 for(
size_t record = 0; record < aDecode.controllers.pools[22].count; ++record )
4053 const size_t offset = aDecode.netNameBase + record * NET_NAME_RECORD_BYTES;
4055 sourceAt( aDecode.sourceName, aModel.version, wxS(
"net-name presentation" ), 23, record, offset,
4056 NET_NAME_RECORD_BYTES,
static_cast<int>( aDecode.sheetIndex ) );
4057 const uint32_t globalRecord = aDecode.cursor.U32At( offset + 16 );
4058 const uint16_t ownerHandle = aDecode.cursor.U16At( offset + 38 );
4059 const uint16_t childHandle = aDecode.cursor.U16At( offset + 40 );
4060 std::vector<SOURCE_PROPERTY> preservedPresentation;
4061 auto preserve = [&](
const wxString& aName,
const wxString& aValue,
size_t aRelativeOffset,
size_t aLength )
4064 propertySource.absoluteOffset += aRelativeOffset;
4065 propertySource.length = aLength;
4066 SOURCE_PROPERTY property = sourceProperty( aName, aValue, propertySource );
4068 preservedPresentation.push_back( std::move( property ) );
4070 wxString presentation06;
4073 presentation06 += wxString::Format( wxS(
"%02x" ), aDecode.bytes[offset +
index] );
4075 preserve( wxS(
"preserved_net_name_presentation_06" ), presentation06, 6, 10 );
4076 preserve( wxS(
"preserved_net_name_secondary_offset" ),
4077 wxString::Format( wxS(
"%d,%d" ),
static_cast<int16_t
>( aDecode.cursor.U16At( offset + 28 ) ),
4078 static_cast<int16_t
>( aDecode.cursor.U16At( offset + 30 ) ) ),
4080 preserve( wxS(
"preserved_net_name_presentation_20" ),
4081 wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( offset + 32 ) ), 32, 2 );
4082 preserve( wxS(
"preserved_net_name_presentation_flags" ),
4083 wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( offset + 34 ) ), 34, 2 );
4084 preserve( wxS(
"preserved_net_name_predecessor_handle" ),
4085 wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( offset + 36 ) ), 36, 2 );
4086 preserve( wxS(
"preserved_net_name_predecessor_record" ),
4087 wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( offset + 42 ) ), 42, 2 );
4088 preserve( wxS(
"preserved_net_name_successor_record" ),
4089 wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( offset + 44 ) ), 44, 2 );
4090 preserve( wxS(
"preserved_net_name_tail" ),
4091 wxString::Format( wxS(
"%u" ), aDecode.cursor.U16At( offset + 46 ) ), 46, 2 );
4093 if( ( ownerHandle & 0xF000 ) == 0x4000 )
4095 if( globalRecord >= aDecode.globals.nets.size() || aDecode.globals.nets[globalRecord].tombstone )
4096 throwDecodeError(
source, wxS(
"bus net-name record targets wrong global-net object class" ) );
4098 const size_t busRecord = ownerHandle & 0x0FFF;
4099 auto bus = std::ranges::find_if( aModel.buses,
4102 return aBus.sheet.id == aModel.sheets[aDecode.sheetIndex].id
4103 && aBus.source.recordIndex == busRecord;
4106 if( bus == aModel.buses.end() || childHandle == 0 || childHandle > bus->memberNets.size()
4107 || bus->name.text != aDecode.globals.nets[globalRecord].name.text )
4109 throwDecodeError(
source, wxS(
"net-name bus owner targets wrong object class" ) );
4112 bus->properties.push_back( sourceProperty( wxS(
"net_name_presentation_record" ),
4113 wxString::Format( wxS(
"%llu" ), record ),
source ) );
4114 bus->properties.insert( bus->properties.end(), std::make_move_iterator( preservedPresentation.begin() ),
4115 std::make_move_iterator( preservedPresentation.end() ) );
4119 if( globalRecord >= aConnectivity.sheetNets.size() || !aConnectivity.sheetNets[globalRecord] )
4120 throwDecodeError(
source, wxS(
"net-name record targets wrong or unresolved net object class" ) );
4122 MODEL_NET& ownerNet = *aConnectivity.sheetNets[globalRecord];
4123 const SOURCE_POINT textOffset{ decodeTerminalCoordinate( aDecode.cursor.U16At( offset + 20 ) ),
4124 decodeTerminalCoordinate( aDecode.cursor.U16At( offset + 22 ) ),
source };
4126 presentation.properties.insert( presentation.properties.end(),
4127 std::make_move_iterator( preservedPresentation.begin() ),
4128 std::make_move_iterator( preservedPresentation.end() ) );
4130 if( ( ownerHandle & 0xF000 ) == 0x2000 )
4132 const size_t offpageRecord = ownerHandle & 0x0FFF;
4133 auto label = std::ranges::find_if( aModel.labels,
4136 return aLabel.sheet.id == aModel.sheets[aDecode.sheetIndex].id
4137 && aLabel.source.controller == 20
4138 && aLabel.source.recordIndex == offpageRecord;
4141 if( label == aModel.labels.end() )
4145 for(
const MODEL_BUS& bus : aModel.buses )
4147 if( bus.sheet.id != aModel.sheets[aDecode.sheetIndex].id )
4150 auto candidate = std::ranges::find_if( bus.entries,
4153 return aEntry.source.recordIndex == offpageRecord
4154 && aEntry.memberNet.id == ownerNet.id;
4157 if( candidate != bus.entries.end() )
4160 throwDecodeError(
source, wxS(
"net-name bus-entry owner is ambiguous" ) );
4162 busEntry = &*candidate;
4167 throwDecodeError(
source, wxS(
"net-name off-page owner targets wrong object class" ) );
4171 busText.sheet = { aModel.sheets[aDecode.sheetIndex].id,
source };
4172 busText.text = ownerNet.name;
4173 busText.position = { busEntry->position.x + textOffset.x, busEntry->position.y + textOffset.y,
4175 busText.angle =
NormalizeAngle( aDecode.cursor.U16At( offset + 24 ) );
4176 busText.presentation = std::move( presentation );
4177 busText.properties.push_back( sourceProperty(
4178 wxS(
"net_name_text_offset" ),
4179 wxString::Format( wxS(
"%lld,%lld" ), textOffset.x, textOffset.y ),
source ) );
4180 aModel.texts.push_back( std::move( busText ) );
4184 if( label->text.text != ownerNet.name.text )
4185 throwDecodeError(
source, wxS(
"net-name off-page owner targets wrong net object" ) );
4187 label->presentation = std::move( presentation );
4188 label->textOffset = textOffset;
4189 label->angle =
NormalizeAngle( aDecode.cursor.U16At( offset + 24 ) );
4190 label->properties.push_back(
4191 sourceProperty( wxS(
"net_name_text_offset" ),
4192 wxString::Format( wxS(
"%lld,%lld" ), textOffset.x, textOffset.y ),
source ) );
4197 std::ranges::find_if( aModel.placements,
4200 return aPlacement.sheet.id == aModel.sheets[aDecode.sheetIndex].id
4201 && aPlacement.source.recordIndex == ownerHandle;
4204 if( placement == aModel.placements.end() )
4205 throwDecodeError(
source, wxS(
"net-name placement owner targets wrong object class" ) );
4207 if( childHandle >= placement->pins.size() )
4208 throwDecodeError(
source, wxS(
"net-name placement pin ordinal leaves placement" ) );
4210 const PIN_ID ownerPin = placement->pins[childHandle].id;
4219 || candidate.placement->id != placement->id || candidate.pin->id != ownerPin )
4225 throwDecodeError(
source, wxS(
"net-name placement pin owner is ambiguous" ) );
4227 endpoint = &candidate;
4232 throwDecodeError(
source, wxS(
"net-name placement pin owner is unresolved" ) );
4236 text.sheet = { aModel.sheets[aDecode.sheetIndex].id,
source };
4237 text.text = ownerNet.name;
4238 text.position = { endpoint->point.x + textOffset.x, endpoint->point.y + textOffset.y,
source };
4240 text.presentation = std::move( presentation );
4241 text.properties.push_back(
4242 sourceProperty( wxS(
"net_name_text_offset" ),
4243 wxString::Format( wxS(
"%lld,%lld" ), textOffset.x, textOffset.y ),
source ) );
4244 aModel.texts.push_back( std::move(
text ) );
4249 void decodeConnectivity(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
4250 const SCH_SDB_BLOCK& aBlock,
size_t aSheetIndex,
const wxString& aSourceName,
4253 if( aModel.version != 0x000D )
4254 throwDecodeError( aModel.source, wxS(
"connectivity decoder selected for raw-preserved version" ) );
4256 const SHEET_CONTROLLERS controllers = sheetControllers( aCursor, aBlock );
4257 requireFixedController( controllers, 18, BUS_RECORD_BYTES, aSourceName, aModel.version, aSheetIndex );
4258 requireFixedController( controllers, 19, JUNCTION_RECORD_BYTES, aSourceName, aModel.version, aSheetIndex );
4259 requireFixedController( controllers, 20, OFFPAGE_RECORD_BYTES, aSourceName, aModel.version, aSheetIndex );
4260 requireFixedController( controllers, 21, CONNECTION_RECORD_BYTES, aSourceName, aModel.version, aSheetIndex );
4261 requireFixedController( controllers, 22, CONNECTION_VERTEX_BYTES, aSourceName, aModel.version, aSheetIndex );
4262 requireFixedController( controllers, 23, NET_NAME_RECORD_BYTES, aSourceName, aModel.version, aSheetIndex );
4264 const CONNECTIVITY_DECODE
decode{ aBytes,
4270 controllers.offsets[17],
4271 controllers.offsets[18],
4272 controllers.offsets[19],
4273 controllers.offsets[20],
4274 controllers.offsets[21],
4275 controllers.offsets[22] };
4277 const std::unordered_set<uint32_t> busGlobalRecords = decodeBusGlobalRecords( decode, aModel );
4278 SHEET_CONNECTIVITY connectivity;
4279 connectivity.sheetNets = materializeSheetNets( decode, busGlobalRecords, aModel );
4281 const std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*> definitionPins = indexDefinitionPins( aModel );
4282 const std::vector<MODEL_PLACEMENT*> placements = indexSheetPlacements( decode, aModel );
4284 decodeJunctions( decode, aModel );
4286 const VERTEX_TILING tiling = tileConnectivityVertices( decode, aModel );
4288 decodeConnections( decode, tiling, placements, definitionPins, connectivity, aModel );
4289 validateJunctionBacklinks( decode, connectivity, aModel );
4290 validateOffpageBacklinks( decode, connectivity, aModel );
4292 const std::vector<bool> claimedBusEntries =
4293 decodeBuses( decode, tiling, busGlobalRecords, connectivity, aModel );
4295 decodeOffpageLabels( decode, connectivity, claimedBusEntries, aModel );
4296 decodeNetNames( decode, connectivity, aModel );
4305 if( aPresentation.font.text.IsEmpty() || aPresentation.font.text == wxS(
"Default Font" ) )
4306 aPresentation.font = aSettings.defaultSystemFont;
4314 const auto applyField =
4317 inheritDefaultSystemFont( aField.presentation, settings );
4320 const auto applyGraphic =
4324 inheritDefaultSystemFont( aGraphic.presentation, settings );
4329 std::ranges::for_each( sheet.border, applyGraphic );
4330 std::ranges::for_each( sheet.titleBlockFields, applyField );
4335 std::ranges::for_each( definition.graphics, applyGraphic );
4336 std::ranges::for_each( definition.fields, applyField );
4340 inheritDefaultSystemFont(
pin.presentation, settings );
4341 inheritDefaultSystemFont(
pin.namePresentation, settings );
4342 inheritDefaultSystemFont(
pin.numberPresentation, settings );
4347 std::ranges::for_each( partType.fields, applyField );
4350 std::ranges::for_each( placement.fields, applyField );
4353 inheritDefaultSystemFont( label.presentation, settings );
4356 inheritDefaultSystemFont(
text.presentation, settings );
4359 applyGraphic( graphic.graphic );
4362 std::ranges::for_each( worksheet.graphics, applyGraphic );
4371 throwDecodeError( aField.source, wxS(
"field ordinal exceeds identity capacity" ) );
4373 aField.id =
MakeFieldId( aDomain, aOwner,
static_cast<uint32_t
>( aOrdinal ) );
4378 for(
size_t ordinal = 0; ordinal < sheet.titleBlockFields.size(); ++ordinal )
4380 MODEL_FIELD& field = sheet.titleBlockFields[ordinal];
4387 for(
size_t ordinal = 0; ordinal < definition.fields.size(); ++ordinal )
4396 for(
size_t ordinal = 0; ordinal < partType.fields.size(); ++ordinal )
4405 for(
size_t ordinal = 0; ordinal < placement.fields.size(); ++ordinal )
4414 template <
typename Item>
4415 void validateSheetRef(
const Item& aItem,
const MODEL_REFERENCE_INDEX& aIndex,
const wxString& aObjectClass )
4417 if( !aIndex.sheets.contains( aItem.sheet.id.Value() ) )
4419 throwValidationError( aItem.sheet.source,
4420 wxString::Format( wxS(
"unresolved %s sheet reference" ), aObjectClass ) );
4427 validateUniqueIds( aModel.sheets, wxS(
"sheet" ), itemId, itemProvenance );
4428 validateUniqueIds( aModel.definitions, wxS(
"definition" ), itemId, itemProvenance );
4429 validateUniqueIds( aModel.partTypes, wxS(
"part type" ), itemId, itemProvenance );
4430 validateUniqueIds( aModel.placements, wxS(
"placement" ), itemId, itemProvenance );
4431 validateUniqueIds( aModel.nets, wxS(
"net" ), itemId, itemProvenance );
4432 validateUniqueIds( aModel.buses, wxS(
"bus" ), itemId, itemProvenance );
4433 validateUniqueIds( aModel.images, wxS(
"embedded image" ), itemId, itemProvenance );
4435 std::vector<bool> sheetIndexes( aModel.sheets.size() );
4439 if( sheet.index >= sheetIndexes.size() )
4440 throwValidationError( sheet.source, wxS(
"sheet source index leaves the declared sheet range" ) );
4442 if( sheetIndexes[sheet.index] )
4443 throwValidationError( sheet.source, wxS(
"duplicate sheet source index" ) );
4445 sheetIndexes[sheet.index] =
true;
4448 std::unordered_map<uint32_t, SOURCE_PROVENANCE> gateDeclarations;
4449 std::unordered_map<uint32_t, SOURCE_PROVENANCE> pinDeclarations;
4450 std::unordered_map<uint64_t, SOURCE_PROVENANCE> fieldDeclarations;
4454 for(
const MODEL_GATE& gate : partType.gates )
4455 validateNestedId( gate, wxS(
"gate" ), gateDeclarations );
4461 validateNestedId(
pin, wxS(
"pin" ), pinDeclarations );
4463 for(
const MODEL_FIELD& field : definition.fields )
4464 validateNestedId( field, wxS(
"field" ), fieldDeclarations );
4469 for(
const MODEL_FIELD& field : sheet.titleBlockFields )
4470 validateNestedId( field, wxS(
"field" ), fieldDeclarations );
4476 validateNestedId( field, wxS(
"field" ), fieldDeclarations );
4481 for(
const MODEL_FIELD& field : placement.fields )
4482 validateNestedId( field, wxS(
"field" ), fieldDeclarations );
4487 void validateSymbolGraph(
const PADS_SCH_MODEL& aModel,
const MODEL_REFERENCE_INDEX& aIndex )
4491 if( sheet.parent && !aIndex.sheets.contains( sheet.parent->id.Value() ) )
4492 throwValidationError( sheet.parent->source, wxS(
"unresolved sheet reference" ) );
4497 for(
const MODEL_GATE& gate : partType.gates )
4499 auto definition = aIndex.definitions.find( gate.definition.id.Value() );
4501 if( definition == aIndex.definitions.end() && gate.decalGroupMembers.empty() )
4502 throwValidationError( gate.definition.source, wxS(
"unresolved symbol definition reference" ) );
4506 if( !aIndex.definitions.contains( alternate.id.Value() ) )
4507 throwValidationError( alternate.source, wxS(
"unresolved alternate definition reference" ) );
4512 if( !aIndex.definitions.contains( member.id.Value() ) )
4513 throwValidationError( member.source, wxS(
"unresolved pin-decal group member" ) );
4516 if( definition == aIndex.definitions.end() )
4519 if( !gate.logicalPins.empty() && gate.logicalPins.size() != gate.pins.size() )
4520 throwValidationError( gate.source, wxS(
"gate logical-pin count does not match definition pins" ) );
4522 for(
size_t pinOrdinal = 0; pinOrdinal < gate.pins.size(); ++pinOrdinal )
4525 auto pinOwner = aIndex.pinOwners.find(
pin.id.Value() );
4527 if( pinOwner == aIndex.pinOwners.end() || pinOwner->second != definition->second )
4528 throwValidationError(
pin.source, wxS(
"pin does not belong to gate definition" ) );
4530 if( !gate.logicalPins.empty() && gate.logicalPins[pinOrdinal].definitionPin.id !=
pin.id )
4531 throwValidationError( gate.logicalPins[pinOrdinal].definitionPin.source,
4532 wxS(
"logical pin does not belong to gate definition pin" ) );
4537 struct DEFINITION_EDGE
4540 SOURCE_PROVENANCE
source;
4543 std::unordered_map<uint32_t, std::vector<DEFINITION_EDGE>> definitionEdges;
4547 for(
const MODEL_GATE& gate : partType.gates )
4549 if( !gate.definition.id.IsValid() )
4553 definitionEdges[gate.definition.id.Value()].push_back( { alternate.id.Value(), alternate.source } );
4557 std::unordered_map<uint32_t, uint8_t> definitionColors;
4558 std::function<void( uint32_t )> visitDefinition =
4559 [&]( uint32_t aDefinition )
4561 definitionColors[aDefinition] = 1;
4563 auto edges = definitionEdges.find( aDefinition );
4565 if( edges == definitionEdges.end() )
4567 definitionColors[aDefinition] = 2;
4571 for(
const DEFINITION_EDGE& edge : edges->second )
4573 if( definitionColors[edge.target] == 1 )
4574 throwValidationError( edge.source, wxS(
"cyclic symbol definition reference" ) );
4576 if( definitionColors[edge.target] == 0 )
4577 visitDefinition( edge.target );
4580 definitionColors[aDefinition] = 2;
4583 for(
const auto& [definition, edges] : definitionEdges )
4585 if( definitionColors[definition] == 0 )
4586 visitDefinition( definition );
4591 void validatePlacements(
const PADS_SCH_MODEL& aModel,
const MODEL_REFERENCE_INDEX& aIndex )
4595 if( !aIndex.sheets.contains( placement.sheet.id.Value() ) )
4596 throwValidationError( placement.sheet.source, wxS(
"unresolved placement sheet reference" ) );
4598 auto partType = aIndex.partTypes.find( placement.partType.id.Value() );
4600 if( partType == aIndex.partTypes.end() )
4601 throwValidationError( placement.partType.source, wxS(
"unresolved placement part-type reference" ) );
4603 auto placementDefinition = aIndex.definitions.find( placement.definition.id.Value() );
4605 if( placementDefinition == aIndex.definitions.end() )
4606 throwValidationError( placement.definition.source, wxS(
"unresolved placement definition" ) );
4610 auto owner = aIndex.pinOwners.find(
pin.id.Value() );
4612 if( owner == aIndex.pinOwners.end() || owner->second != placementDefinition->second )
4613 throwValidationError(
pin.source, wxS(
"placement pin does not belong to selected definition" ) );
4616 if( !placement.gate )
4619 auto gate = aIndex.gates.find( placement.gate->id.Value() );
4620 auto gateOwner = aIndex.gateOwners.find( placement.gate->id.Value() );
4622 if( gate == aIndex.gates.end() || gateOwner == aIndex.gateOwners.end()
4623 || gateOwner->second != partType->second
4624 || ( gate->second->unit != placement.unit && gate->second->decalGroupMembers.empty() ) )
4625 throwValidationError( placement.gate->source, wxS(
"placement gate or unit mismatch" ) );
4627 const MODEL_GATE& selectedGate = *gate->second;
4628 const bool definitionMatches = selectedGate.
definition.
id == placement.definition.id
4629 || std::ranges::any_of( selectedGate.alternateDefinitions,
4632 return aDefinition.id == placement.definition.id;
4634 || std::ranges::any_of( selectedGate.decalGroupMembers,
4637 return aDefinition.id == placement.definition.id;
4640 if( !definitionMatches )
4641 throwValidationError( placement.definition.source,
4642 wxS(
"placement definition does not belong to selected gate" ) );
4644 auto definition = aIndex.definitions.find( placement.definition.id.Value() );
4646 if( definition == aIndex.definitions.end() )
4647 throwValidationError( placement.definition.source, wxS(
"unresolved placement definition" ) );
4651 auto owner = aIndex.pinOwners.find(
pin.id.Value() );
4653 if( owner == aIndex.pinOwners.end() || owner->second != definition->second )
4654 throwValidationError(
pin.source, wxS(
"placement pin does not belong to selected definition" ) );
4660 void validateSheetBoundContent(
const PADS_SCH_MODEL& aModel,
const MODEL_REFERENCE_INDEX& aIndex )
4662 for(
const MODEL_NET& net : aModel.nets )
4664 validateSheetRef( net, aIndex, wxS(
"net" ) );
4668 if( connection.endpoints.empty() )
4669 throwValidationError( connection.source, wxS(
"connection has no endpoints" ) );
4673 if( !endpointIsValid( aIndex, endpoint ) )
4675 throwValidationError( endpoint.source,
4676 wxS(
"empty, mixed, or unresolved connection endpoint" ) );
4679 if( !endpoint.placement )
4682 auto placement = aIndex.placements.find( endpoint.placement->id.Value() );
4684 if( placement != aIndex.placements.end() && placement->second->sheet.id != net.sheet.id )
4686 throwValidationError( endpoint.source,
4687 wxS(
"connection endpoint placement sheet does not match net sheet" ) );
4693 for(
const MODEL_BUS& bus : aModel.buses )
4695 validateSheetRef( bus, aIndex, wxS(
"bus" ) );
4699 auto net = aIndex.nets.find( member.id.Value() );
4701 if( net == aIndex.nets.end() )
4702 throwValidationError( member.source, wxS(
"unresolved bus member-net reference" ) );
4704 if( net->second->sheet.id != bus.sheet.id )
4705 throwValidationError( member.source, wxS(
"bus member-net sheet does not match bus sheet" ) );
4710 auto net = aIndex.nets.find( entry.memberNet.id.Value() );
4712 if( net == aIndex.nets.end() )
4713 throwValidationError( entry.memberNet.source, wxS(
"unresolved bus-entry net reference" ) );
4715 if( net->second->sheet.id != bus.sheet.id )
4716 throwValidationError( entry.memberNet.source,
4717 wxS(
"bus-entry net sheet does not match bus sheet" ) );
4719 if( std::ranges::none_of( bus.memberNets,
4722 return aMember.id == entry.memberNet.id;
4725 throwValidationError( entry.source, wxS(
"bus-entry net is absent from bus member nets" ) );
4732 validateSheetRef( label, aIndex, wxS(
"label" ) );
4736 if( !aIndex.sheets.contains( linkedSheet.id.Value() ) )
4737 throwValidationError( linkedSheet.source, wxS(
"unresolved cross-sheet label reference" ) );
4742 validateSheetRef( junction, aIndex, wxS(
"junction" ) );
4745 validateSheetRef(
text, aIndex, wxS(
"text" ) );
4748 validateSheetRef( graphic, aIndex, wxS(
"page-graphic" ) );
4750 std::set<uint32_t> worksheetSheets;
4754 validateSheetRef( worksheet, aIndex, wxS(
"worksheet" ) );
4756 if( !worksheetSheets.insert( worksheet.sheet.id.Value() ).second )
4757 throwValidationError( worksheet.source, wxS(
"duplicate worksheet for sheet" ) );
4759 if( worksheet.graphics.empty() )
4760 throwValidationError( worksheet.source, wxS(
"worksheet has no graphics" ) );
4765 validateSheetRef(
image, aIndex, wxS(
"embedded-image" ) );
4768 throwValidationError(
image.source, wxS(
"embedded image has no decoded payload" ) );
4773 void validateSheetHierarchy(
const PADS_SCH_MODEL& aModel,
const MODEL_REFERENCE_INDEX& aIndex )
4775 enum class VISIT_STATE : uint8_t
4780 std::unordered_map<uint32_t, VISIT_STATE> visitStates;
4785 std::vector<const MODEL_SHEET*>
path;
4787 while( current && !visitStates.contains( current->id.Value() ) )
4789 visitStates.emplace( current->id.Value(), VISIT_STATE::VISITING );
4790 path.push_back( current );
4792 if( !current->parent )
4798 auto parent = aIndex.sheets.find( current->parent->id.Value() );
4800 if( parent == aIndex.sheets.end() )
4803 current = parent->second;
4806 if( current && visitStates.at( current->id.Value() ) == VISIT_STATE::VISITING )
4807 throwValidationError( current->source, wxS(
"cyclic sheet hierarchy" ) );
4810 visitStates[visited->id.Value()] = VISIT_STATE::COMPLETE;
4815 std::vector<MODEL_FIELD> decodeDesignSettings(
const std::vector<uint8_t>& aBytes,
4816 const PADS_IO::BINARY_CURSOR& aCursor,
const PADS_SCH_SDB& aSdb,
4821 if( sheetPool.usedBytes != sheetPool.count * SHEET_RECORD_BYTES )
4824 sourceAt( aSourceName, aModel.version, wxS(
"sheet index" ), 3, 0,
4825 OUTER_DIRECTORY_OFFSET + 3 * OUTER_DESCRIPTOR_BYTES + OUTER_USED_BYTES_OFFSET, 4, -1 );
4826 throwDecodeError(
source, wxS(
"sheet-index byte count does not match 48-byte record count" ) );
4831 if( settingsPool.count != 100 || settingsPool.usedBytes != 400 )
4834 sourceAt( aSourceName, aModel.version, wxS(
"design settings" ), 5, 0,
4835 OUTER_DIRECTORY_OFFSET + 5 * OUTER_DESCRIPTOR_BYTES + OUTER_USED_BYTES_OFFSET, 4, -1 );
4836 throwDecodeError(
source, wxS(
"design-settings controller is not the required 400-byte record" ) );
4839 const size_t settingsOffset = outerControllerOffset( aSdb, 5 );
4840 SOURCE_PROVENANCE settingsSource = sourceAt( aSourceName, aModel.version, wxS(
"design settings" ), 5, 0,
4841 settingsOffset, settingsPool.usedBytes, -1 );
4842 aModel.settings.source = settingsSource;
4844 constexpr size_t PAGE_FIELD_OFFSET = 264;
4845 constexpr size_t PAGE_FIELD_MAX_BYTES = 11;
4846 const size_t pageFieldOffset = settingsOffset + PAGE_FIELD_OFFSET;
4847 size_t pageFieldEnd = pageFieldOffset;
4849 while( pageFieldEnd < pageFieldOffset + PAGE_FIELD_MAX_BYTES && aBytes[pageFieldEnd] != 0 )
4854 pageSource.length = pageFieldEnd - PAGE_FIELD_OFFSET;
4856 std::string pageField( aBytes.begin() + pageFieldOffset, aBytes.begin() + pageFieldEnd );
4857 std::string pageDesignator;
4859 if( pageField.starts_with(
"SIZE" ) && pageField.size() > 4 )
4860 pageDesignator = pageField.substr( 4 );
4861 else if( pageField.starts_with(
"WDITBSIZE" ) && pageField.size() > 9 )
4862 pageDesignator = pageField.substr( 9 );
4864 throwDecodeError( pageSource, wxS(
"invalid design page-size field" ) );
4866 aModel.settings.pageSize = pageExtent( pageDesignator, pageSource );
4867 aModel.settings.defaultLineWidth =
static_cast<int64_t
>( aCursor.
U32At( settingsOffset + 12 ) ) * 2;
4868 aModel.settings.defaultBusWidth =
static_cast<int64_t
>( aCursor.
U32At( settingsOffset + 16 ) ) * 2;
4872 fontModeSource.length = 4;
4873 const uint32_t fontModeRaw = aCursor.
U32At( settingsOffset + 252 );
4874 aModel.settings.properties.push_back( sourceProperty( wxS(
"font_mode_raw" ),
4875 wxString::Format( wxS(
"%u" ), fontModeRaw ),
4878 if( fontModeRaw == 0 )
4882 else if( fontModeRaw == 1 )
4892 wxS(
"unknown PADS schematic font mode preserved; "
4893 "using KiCad stroke font" ) ) );
4898 if( fontPool.usedBytes != fontPool.count * FONT_RECORD_BYTES )
4901 outerControllerOffset( aSdb, 19 ), fontPool.usedBytes, -1 );
4902 throwDecodeError(
source, wxS(
"controller byte count does not match 36-byte records" ) );
4905 if( fontPool.count > 0 )
4907 const size_t defaultFontOffset = outerControllerOffset( aSdb, 19 );
4908 SOURCE_PROVENANCE defaultFontSource = sourceAt( aSourceName, aModel.version, wxS(
"default system font" ),
4909 19, 0, defaultFontOffset + 4, 32, -1 );
4910 aModel.settings.defaultSystemFont = decodeFixedString( aBytes, defaultFontOffset + 4, 32,
4911 defaultFontSource, aModel.diagnostics );
4915 SOURCE_PROPERTY property = sourceProperty( wxS(
"default_system_font" ), wxS(
"" ), fontModeSource );
4918 wxS(
"PADS system-font mode has no default font "
4919 "record; using KiCad stroke font" ) ) );
4920 aModel.settings.properties.push_back( std::move( property ) );
4923 std::vector<MODEL_FIELD> titleFields;
4925 size_t titleOffset = outerControllerOffset( aSdb, 1 );
4926 const size_t titleEnd = titleOffset + titleFieldPool.usedBytes;
4927 size_t titleRecord = 0;
4929 while( titleOffset + 6 <= titleEnd
4930 && std::equal( aBytes.begin() + titleOffset, aBytes.begin() + titleOffset + 6,
"Field\n" ) )
4932 size_t terminator = titleOffset;
4934 while( terminator < titleEnd && aBytes[terminator] != 0 )
4938 titleOffset, terminator - titleOffset + 1, -1 );
4940 size_t separator = titleOffset + 6;
4942 while( separator < terminator && aBytes[separator] != 1 )
4945 if( terminator == titleEnd || terminator - titleOffset < 7 || separator == terminator
4946 || !std::equal( aBytes.begin() + titleOffset, aBytes.begin() + titleOffset + 6,
"Field\n" ) )
4948 throwDecodeError(
source, wxS(
"invalid title-field name record" ) );
4951 std::vector<uint8_t> nameBytes( aBytes.begin() + titleOffset + 6, aBytes.begin() + separator );
4952 std::vector<uint8_t> valueBytes( aBytes.begin() + separator + 1, aBytes.begin() + terminator );
4954 nameSource.absoluteOffset += 6;
4955 nameSource.length = nameBytes.size();
4957 valueSource.absoluteOffset = separator + 1;
4958 valueSource.length = valueBytes.size();
4962 aModel.diagnostics );
4964 aModel.diagnostics );
4965 field.presentation.source =
source;
4966 titleFields.push_back( std::move( field ) );
4967 titleOffset = terminator + 1;
4971 if( titleFields.empty() )
4974 sourceAt( aSourceName, aModel.version, wxS(
"title field" ), 1, titleFields.size(),
4975 outerControllerOffset( aSdb, 1 ), titleFieldPool.usedBytes, -1 );
4976 throwDecodeError(
source, wxS(
"title-field controller is empty" ) );
4983 void decodeSheets(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
4985 const std::vector<MODEL_FIELD>& aTitleFields,
PADS_SCH_MODEL& aModel )
4987 const size_t sheetIndexOffset = outerControllerOffset( aSdb, 3 );
4988 auto sheetBlocks = aSdb.
Blocks()
4989 | std::views::filter(
4994 auto sheetBlock = sheetBlocks.begin();
4998 size_t recordOffset = sheetIndexOffset +
index * SHEET_RECORD_BYTES;
5000 recordOffset, SHEET_RECORD_BYTES,
static_cast<int>(
index ) );
5002 if( sheetBlock == sheetBlocks.end() || aCursor.
U32At( recordOffset ) != sheetBlock->offset
5003 || aCursor.
U32At( recordOffset + 4 ) != sheetBlock->bytes )
5005 throwDecodeError( provenance, wxS(
"sheet-index record references the wrong SDB object class" ) );
5008 constexpr size_t nameOffset = 14;
5010 if( aCursor.
U16At( recordOffset + 10 ) != 0xFFFF || aCursor.
U16At( recordOffset + 12 ) != 0xFFFF )
5011 throwDecodeError( provenance, wxS(
"invalid sheet-index class marker" ) );
5013 size_t nameEnd = recordOffset + nameOffset;
5015 while( nameEnd < recordOffset + SHEET_RECORD_BYTES && aBytes[nameEnd] != 0 )
5018 if( nameEnd == recordOffset + SHEET_RECORD_BYTES )
5019 throwDecodeError( provenance, wxS(
"unterminated sheet name" ) );
5021 std::vector<uint8_t> nameBytes( aBytes.begin() + recordOffset + nameOffset, aBytes.begin() + nameEnd );
5024 nameSource.length = nameBytes.size();
5028 sheet.index = sheet.id.IsValid() ? sheet.id.Value() - 1 : std::numeric_limits<size_t>::max();
5029 sheet.source = provenance;
5031 aModel.diagnostics );
5033 if( sheet.name.text.empty() )
5034 sheet.name.text = wxS(
"$$$NONE" );
5036 sheet.pageSize = aModel.settings.pageSize;
5037 sheet.defaultLineWidth = aModel.settings.defaultLineWidth;
5038 sheet.defaultBusWidth = aModel.settings.defaultBusWidth;
5039 sheet.titleBlockFields = aTitleFields;
5041 auto title = std::ranges::find_if( sheet.titleBlockFields,
5044 return aField.name.text == wxS(
"Title" );
5047 if( title != sheet.titleBlockFields.end() )
5048 sheet.title = title->value;
5050 aModel.sheets.push_back( std::move( sheet ) );
5055 void decodeFreeText(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
5056 const wxString& aSourceName,
size_t aSheetIndex,
size_t aTextBase, uint32_t aTextCount,
5057 size_t aHeapBase, uint32_t aHeapBytes,
const PLACEMENT_GLOBALS& aGlobals,
5060 for(
size_t record = 0; record < aTextCount; ++record )
5062 size_t recordOffset = aTextBase + record * TEXT_RECORD_BYTES;
5064 if( aCursor.
U16At( recordOffset + 24 ) != aCursor.
U16At( recordOffset + 26 ) )
5067 SOURCE_PROVENANCE textSource = sourceAt( aSourceName, aModel.version, wxS(
"free text" ), 1, record,
5068 recordOffset, TEXT_RECORD_BYTES,
static_cast<int>( aSheetIndex ) );
5069 uint32_t stringOffset = aCursor.
U32At( recordOffset + 8 );
5070 uint16_t stringBytes = aCursor.
U16At( recordOffset + 20 );
5072 if( stringOffset > aHeapBytes )
5076 offsetSource.length = 4;
5077 throwDecodeError( offsetSource, wxS(
"free-text string offset leaves controller 2" ) );
5080 if( stringBytes == 0 || stringBytes > aHeapBytes - stringOffset )
5084 lengthSource.length = 2;
5085 throwDecodeError( lengthSource, wxS(
"free-text string length leaves controller 2" ) );
5088 if( aBytes[aHeapBase + stringOffset + stringBytes - 1] != 0 )
5091 sourceAt( aSourceName, aModel.version, wxS(
"free text string terminator" ), 2, record,
5092 aHeapBase + stringOffset + stringBytes - 1, 1,
static_cast<int>( aSheetIndex ) );
5093 throwDecodeError( terminatorSource, wxS(
"free-text string is not NUL terminated" ) );
5097 sourceAt( aSourceName, aModel.version, wxS(
"free text string" ), 2, record,
5098 aHeapBase + stringOffset, stringBytes - 1,
static_cast<int>( aSheetIndex ) );
5099 std::vector<uint8_t> string( aBytes.begin() + stringSource.absoluteOffset,
5100 aBytes.begin() + stringSource.absoluteOffset + stringSource.length );
5101 uint16_t justification = aCursor.
U16At( recordOffset + 18 );
5105 text.
sheet = { aModel.sheets[aSheetIndex].id, textSource };
5108 text.position = { decodeCoordinate( aCursor.
U16At( recordOffset + 12 ) ),
5109 decodeCoordinate( aCursor.
U16At( recordOffset + 14 ) ), textSource };
5111 text.presentation.source = textSource;
5112 text.presentation.height = aCursor.
U16At( recordOffset + 22 );
5113 text.presentation.width = aCursor.
U8At( recordOffset + 30 );
5114 const uint8_t displayFlags = aCursor.
U8At( recordOffset + 31 );
5115 text.presentation.visible = ( displayFlags & 1 ) == 0;
5116 text.presentation.horizontalJustification = horizontalJustification( justification );
5117 text.presentation.verticalJustification = verticalJustification( justification );
5120 fontHandleSource.
length = 2;
5121 decodeGlobalFont( aBytes, aCursor, aGlobals, aSourceName, aModel.version,
5122 static_cast<int16_t
>( aCursor.
U16At( recordOffset ) ), fontHandleSource,
5123 text.presentation,
false, aModel.diagnostics );
5127 displaySource.length = 1;
5128 text.presentation.properties.push_back( sourceProperty(
5129 wxS(
"display_flags" ), wxString::Format( wxS(
"%u" ), displayFlags ), displaySource ) );
5132 relationshipSource.
objectClass = wxS(
"free text relationship" );
5133 relationshipSource.absoluteOffset += 28;
5134 relationshipSource.length = 2;
5135 uint16_t relationship = aCursor.
U16At( relationshipSource.absoluteOffset );
5137 relationshipProperty.
name.
text = wxS(
"controller_1_relationship_word_28" );
5138 relationshipProperty.name.source = relationshipSource;
5139 relationshipProperty.value.raw = {
static_cast<uint8_t
>( relationship ),
5140 static_cast<uint8_t
>( relationship >> 8 ) };
5141 relationshipProperty.value.text = wxString::Format( wxS(
"%u" ), relationship );
5143 relationshipProperty.value.source = relationshipSource;
5144 relationshipProperty.value.codePage = DEFAULT_CODE_PAGE;
5145 relationshipProperty.value.codePageName = wxS(
"windows-1252" );
5147 relationshipProperty.source = relationshipSource;
5148 text.properties.push_back( std::move( relationshipProperty ) );
5149 aModel.texts.push_back( std::move(
text ) );
5154 void decodeSheetBlocks(
const std::vector<uint8_t>& aBytes,
const PADS_IO::BINARY_CURSOR& aCursor,
5157 size_t sheetIndex = 0;
5158 std::optional<PLACEMENT_GLOBALS> placementData;
5159 std::optional<CONNECTIVITY_GLOBALS> connectivityData;
5160 const PLACEMENT_LAYOUT& placementSchema = placementLayout( aModel.version );
5162 if( placementSchema.decoded )
5164 placementData = placementGlobals( aSdb, aSourceName, aModel.settings );
5165 connectivityData = connectivityGlobals( aBytes, aCursor, aSdb, aSourceName, aModel );
5173 size_t descriptors = block.offset + SHEET_HEADER_BYTES;
5174 size_t payload = descriptors + SHEET_DESCRIPTOR_COUNT * SHEET_DESCRIPTOR_BYTES;
5175 uint32_t textCount = aCursor.
U32At( descriptors + SHEET_COUNT_OFFSET );
5176 uint32_t textBytes = aCursor.
U32At( descriptors + SHEET_USED_BYTES_OFFSET );
5177 uint32_t heapBytes = aCursor.
U32At( descriptors + SHEET_DESCRIPTOR_BYTES + SHEET_USED_BYTES_OFFSET );
5179 SOURCE_PROVENANCE controllerSource = sourceAt( aSourceName, aModel.version, wxS(
"text controller" ), 1, 0,
5180 payload, textBytes,
static_cast<int>( sheetIndex ) );
5182 if( textBytes != textCount * TEXT_RECORD_BYTES )
5183 throwDecodeError( controllerSource,
5184 wxS(
"text-controller byte count does not match 32-byte records" ) );
5186 size_t heapOffset = payload + textBytes;
5188 if( !placementSchema.decoded )
5190 SOURCE_PROVENANCE heapSource = sourceAt( aSourceName, aModel.version, wxS(
"text string controller" ),
5191 2, 0, heapOffset, heapBytes,
static_cast<int>( sheetIndex ) );
5192 aModel.preservedControllerPayloads.push_back(
5195 { aBytes.begin() + payload, aBytes.begin() + payload + textBytes } } );
5196 aModel.preservedControllerPayloads.push_back(
5199 { aBytes.begin() + heapOffset, aBytes.begin() + heapOffset + heapBytes } } );
5200 decodeDefinitionsAndParts( aBytes, aCursor, block, sheetIndex, aSourceName, aModel );
5205 decodeFreeText( aBytes, aCursor, aSourceName, sheetIndex, payload, textCount, heapOffset, heapBytes,
5206 *placementData, aModel );
5207 decodeDefinitionsAndParts( aBytes, aCursor, block, sheetIndex, aSourceName, aModel );
5208 decodePlacements( aBytes, aCursor, block, sheetIndex, aSourceName, *placementData, aModel );
5209 decodeConnectivity( aBytes, aCursor, block, sheetIndex, aSourceName, *connectivityData, aModel );
5215 void decodeOleImages(
const std::vector<uint8_t>& aBytes,
const PADS_SCH_SDB& aSdb,
const wxString& aSourceName,
5222 sourceAt( aSourceName, aModel.version, wxS(
"embedded OLE image" ), item.cfb.controller,
index,
5223 item.cfb.offset, item.cfb.bytes,
static_cast<int>( item.sheetPlane ) );
5224 OLE_IMAGE_PAYLOAD payload =
ExtractOleImage( aBytes.data() + item.cfb.offset, item.cfb.bytes );
5228 image.sheet = { aModel.sheets[item.sheetPlane].id,
source };
5230 image.extent = item.extent;
5231 image.databaseBox = { item.left, item.bottom, item.right, item.top };
5233 boxSource.objectClass = wxS(
"embedded OLE image database box" );
5234 boxSource.absoluteOffset = item.boxOffset;
5235 boxSource.length = 16;
5236 int64_t
left = decodeDatabaseCoordinate( item.left, boxSource );
5237 int64_t bottom = decodeDatabaseCoordinate( item.bottom, boxSource );
5238 int64_t
right = decodeDatabaseCoordinate( item.right, boxSource );
5239 int64_t
top = decodeDatabaseCoordinate( item.top, boxSource );
5244 image.mirrorVertical = bottom <
top;
5245 image.flags = item.flags;
5248 switch( payload.
type )
5255 aModel.diagnostics.emplace_back(
5257 wxS(
"embedded OLE object has no supported BMP, DIB, or WMF stream" ) );
5264 aModel.diagnostics.emplace_back(
5266 wxS(
"embedded OLE image has a zero-size database box and was skipped" ) );
5269 if( item.flags != 1 )
5272 flagsSource.objectClass = wxS(
"embedded OLE image flags" );
5273 flagsSource.absoluteOffset = item.boxOffset + 20;
5274 flagsSource.length = 4;
5276 aModel.diagnostics );
5279 aModel.images.push_back( std::move(
image ) );
5289 return wxString::Format(
5290 wxS(
"%s: PADS schematic v0x%04X %s (controller %d, record %llu, sheet %d) at offset 0x%llX: %s" ),
5293 static_cast<unsigned long long>( aSource.
absoluteOffset ), aMessage );
5310 return std::nullopt;
5317 const wxString& aMessage )
5332 validateIdentity( *
this );
5334 const MODEL_REFERENCE_INDEX
index( *
this );
5336 validateSymbolGraph( *
this,
index );
5337 validatePlacements( *
this,
index );
5338 validateSheetBoundContent( *
this,
index );
5339 validateSheetHierarchy( *
this,
index );
5352 model.source = { aSourceName,
model.version, wxS(
"model" ), -1, 0, 0, aBytes.size(), -1 };
5353 model.settings.codePage = DEFAULT_CODE_PAGE;
5355 const std::vector<MODEL_FIELD> titleFields = decodeDesignSettings( aBytes,
cursor, sdb, aSourceName,
model );
5357 decodeSheets( aBytes,
cursor, sdb, aSourceName, titleFields,
model );
5358 decodeSheetBlocks( aBytes,
cursor, sdb, aSourceName,
model );
5359 decodeOleImages( aBytes, sdb, aSourceName,
model );
5360 inheritDefaultSystemFonts(
model );
5361 assignFieldIds(
model );
5362 model.ValidateOrThrow();
5369 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics,
5370 const wxString& aRecordedCodePageName )
5373 result.codePage = aCodePage;
5374 const wxString defaultName = aCodePage == 65001 ? wxString( wxS(
"UTF-8" ) )
5375 : aCodePage == 1252 ? wxString( wxS(
"windows-1252" ) )
5376 : wxString::Format( wxS(
"unknown-%u" ), aCodePage );
5377 result.codePageName = aRecordedCodePageName.empty() ? defaultName : aRecordedCodePageName;
5379 if( aCodePage == 1252 )
5381 else if( aCodePage != 65001 )
5384 if( aCodePage != 65001 && aCodePage != 1252 )
5387 wxString::Format( wxS(
"unknown code page %u; bytes preserved and "
5388 "non-ASCII bytes decoded as U+FFFD" ),
5392 if( aBytes.empty() )
5395 if( aCodePage == 1252 )
5397 result.text = decodeWindows1252( aBytes );
5401 if( aCodePage != 65001 )
5403 result.text = decodeUnknownCodePage( aBytes );
5407 bool invalid =
false;
5408 result.text = decodeUtf8( aBytes, invalid );
5414 wxS(
"invalid UTF-8 bytes replaced with U+FFFD; original bytes preserved" ) } );
5423 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
5426 wxString::Format( wxS(
"unknown %s %u preserved" ), aEnumName, aValue ) } );
Bounds-checked little-endian read cursor over a PADS binary buffer.
uint8_t U8At(size_t aOffset) const
uint16_t U16At(size_t aOffset) const
uint32_t U32At(size_t aOffset) const
PADS_SCH_MODEL Parse(const std::vector< uint8_t > &aBytes, const wxString &aSourceName={}) const
static SOURCE_STRING DecodeString(const std::vector< uint8_t > &aBytes, uint32_t aCodePage, const SOURCE_PROVENANCE &aSource, std::vector< PARSER_DIAGNOSTIC > &aDiagnostics, const wxString &aRecordedCodePageName={})
static void RecordUnknownEnum(const wxString &aEnumName, uint32_t aValue, const SOURCE_PROVENANCE &aSource, std::vector< PARSER_DIAGNOSTIC > &aDiagnostics)
const PADS_IO::BINARY_CURSOR & Cursor() const
void Load(std::vector< uint8_t > aBytes)
const std::array< SCH_SDB_POOL, 20 > & Pools() const
size_t PayloadOffset() const
const std::vector< SCH_SDB_BLOCK > & Blocks() const
const std::vector< SCH_SDB_OLE_ITEM > & OleItems() const
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
CONTROLLER_REFERENCE< DEFINITION_ID > DEFINITION_REFERENCE
constexpr int NormalizeAngle(int aAngle)
CONTROLLER_ID< NET_ID_TAG > NET_ID
CONTROLLER_ID< IMAGE_ID_TAG > IMAGE_ID
CONTROLLER_ID< DEFINITION_ID_TAG > DEFINITION_ID
CONTROLLER_REFERENCE< PLACEMENT_ID > PLACEMENT_REFERENCE
CONTROLLER_REFERENCE< SHEET_ID > SHEET_REFERENCE
CONTROLLER_ID< SHEET_ID_TAG > SHEET_ID
constexpr uint32_t FIELD_ID_MAX_ORDINAL
CONTROLLER_ID< PIN_ID_TAG > PIN_ID
constexpr FIELD_ID MakeFieldId(FIELD_ID_DOMAIN aDomain, uint32_t aOwner, uint32_t aOrdinal)
CONTROLLER_ID< PART_TYPE_ID_TAG > PART_TYPE_ID
wxString FormatParserError(const SOURCE_PROVENANCE &aSource, const wxString &aMessage)
CONTROLLER_ID< PLACEMENT_ID_TAG > PLACEMENT_ID
CONTROLLER_ID< GATE_ID_TAG > GATE_ID
CONTROLLER_REFERENCE< NET_ID > NET_REFERENCE
CONTROLLER_REFERENCE< GATE_ID > GATE_REFERENCE
std::optional< DIAGNOSTIC_PROPERTY_KEY > DiagnosticPropertyKey(const PARSER_DIAGNOSTIC &aDiagnostic)
PARSER_DIAGNOSTIC MakePropertyDiagnostic(SEVERITY aSeverity, const SOURCE_PROPERTY &aProperty, const wxString &aMessage)
CONTROLLER_ID< BUS_ID_TAG > BUS_ID
bool IsValid(const std::string &aString, SIM_VALUE::TYPE aValueType=SIM_VALUE::TYPE_FLOAT, NOTATION aNotation=NOTATION::SI)
std::chrono::steady_clock clock
void decode(const std::vector< uint8_t > &aInput, std::vector< uint8_t > &aOutput)
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
OLE_IMAGE_PAYLOAD ExtractOleImage(const uint8_t *aCfb, size_t aSize)
Prefer CONTENTS, then OlePres000, then the native stream.
std::vector< uint8_t > data
PROPERTY_DISPOSITION disposition
DIAGNOSTIC_PROPERTY_IDENTITY property
bool operator<(const DIAGNOSTIC_PROPERTY_KEY &aOther) const
DEFINITION_REFERENCE definition
void ValidateOrThrow() const
std::optional< DIAGNOSTIC_PROPERTY_IDENTITY > property
SOURCE_POINT numberOffset
PROPERTY_DISPOSITION disposition
KIBIS top(path, &reporter)
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
const SHAPE_LINE_CHAIN chain
wxString result
Test unit parsing edge cases and error handling.