KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pads_sch_binary_parser.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
21
22#include "pads_sch_sdb.h"
23
24#include <sch_io/ole_image.h>
25
26#include <algorithm>
27#include <array>
28#include <cmath>
29#include <functional>
30#include <iterator>
31#include <map>
32#include <ranges>
33#include <set>
34#include <tuple>
35#include <unordered_map>
36#include <unordered_set>
37
38#include <ki_exception.h>
39#include <wx/strconv.h>
40
41namespace PADS_SCH_BINARY
42{
43
44namespace
45{
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 };
50
51
52 uint16_t terminalJustification( uint16_t aNibble, bool aRotated )
53 {
54 return aRotated ? JUSTIFICATION_BY_NIBBLE_90[aNibble] : JUSTIFICATION_BY_NIBBLE_0[aNibble];
55 }
56
57
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;
90
91 struct GLOBAL_NET_RECORD
92 {
93 SOURCE_PROVENANCE source;
94 SOURCE_STRING name;
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;
104 };
105
106
107 struct CONNECTIVITY_GLOBALS
108 {
109 size_t membershipBase = 0;
110 uint32_t membershipCount = 0;
111 size_t fontBase = 0;
112 uint32_t fontCount = 0;
113 std::vector<uint16_t> membershipSheets;
114 std::vector<GLOBAL_NET_RECORD> nets;
115 };
116
117 struct PLACEMENT_LAYOUT
118 {
119 uint16_t version;
120 bool decoded;
121 size_t placementBytes;
122 size_t placedPinBytes;
123 size_t fieldBytes;
124 size_t pinStart;
125 size_t componentIdentity;
126 size_t componentGroup;
127 size_t x;
128 size_t y;
129 size_t angle;
130 size_t mirror;
131 size_t partType;
132 size_t decal;
133 size_t gate;
134 size_t pinCount;
135 size_t fieldCount;
136 size_t reference;
137 size_t referenceFont;
138 size_t partTypeFont;
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;
149 size_t customFont;
150 size_t customX;
151 size_t customAngle;
152 size_t customJustification;
153 size_t customAttributeIndex;
154 size_t customHeight;
155 size_t customWidth;
156 size_t customDisplayFlags;
157 size_t customTail;
158 };
159
160 constexpr PLACEMENT_LAYOUT PLACEMENT_LAYOUTS[] = { []
161 {
162 PLACEMENT_LAYOUT layout{};
163 layout.version = 0x000C;
164 return layout;
165 }(),
166 { .version = 0x000D,
167 .decoded = true,
168 .placementBytes = 136,
169 .placedPinBytes = 12,
170 .fieldBytes = 24,
171 .pinStart = 0x14,
172 .componentIdentity = 0x18,
173 .componentGroup = 0x1C,
174 .x = 0x20,
175 .y = 0x22,
176 .angle = 0x24,
177 .mirror = 0x26,
178 .partType = 0x42,
179 .decal = 0x44,
180 .gate = 0x4A,
181 .pinCount = 0x4C,
182 .fieldCount = 0x4E,
183 .reference = 0x5E,
184 .referenceFont = 0,
185 .partTypeFont = 2,
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,
196 .customFont = 0,
197 .customX = 8,
198 .customAngle = 12,
199 .customJustification = 14,
200 .customAttributeIndex = 16,
201 .customHeight = 18,
202 .customWidth = 20,
203 .customDisplayFlags = 21,
204 .customTail = 22 } };
205
206 const PLACEMENT_LAYOUT& placementLayout( uint16_t aVersion )
207 {
208 auto layout = std::ranges::find_if( PLACEMENT_LAYOUTS,
209 [&]( const PLACEMENT_LAYOUT& aLayout )
210 {
211 return aLayout.version == aVersion;
212 } );
213
214 if( layout == std::end( PLACEMENT_LAYOUTS ) )
215 THROW_IO_ERROR( wxString::Format( wxS( "unsupported PADS placement layout v0x%04X" ), aVersion ) );
216
217 return *layout;
218 }
219
220
221 size_t outerControllerOffset( const PADS_SCH_SDB& aSdb, size_t aController )
222 {
223 size_t offset = aSdb.PayloadOffset() + 4;
224
225 for( size_t controller = 1; controller < aController; ++controller )
226 offset += aSdb.Pools()[controller].usedBytes;
227
228 return offset;
229 }
230
231
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 )
234 {
235 return { aFile, aVersion, aObjectClass, aController, aRecord, aOffset, aLength, aSheet };
236 }
237
238
239 [[noreturn]] void throwDecodeError( const SOURCE_PROVENANCE& aSource, const wxString& aMessage )
240 {
241 THROW_IO_ERROR( FormatParserError( aSource, aMessage ) );
242 }
243
244
245 int64_t decodeHalfMils( uint16_t aRaw )
246 {
247 return (int64_t) aRaw * 2;
248 }
249
250 int64_t decodeCoordinate( uint16_t aRaw )
251 {
252 return static_cast<int64_t>( aRaw ) * 4 - 198144;
253 }
254
255
256 int64_t decodeDatabaseCoordinate( int32_t aRaw, const SOURCE_PROVENANCE& aSource )
257 {
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" ) );
260
261 return decodeCoordinate( static_cast<uint16_t>( static_cast<int16_t>( aRaw ) ) );
262 }
263
264
265 int64_t decodeLocalCoordinate( uint16_t aRaw )
266 {
267 return static_cast<int64_t>( static_cast<int16_t>( aRaw ) ) * 4;
268 }
269
270
271 int64_t decodeTerminalCoordinate( uint16_t aRaw )
272 {
273 return static_cast<int64_t>( static_cast<int16_t>( aRaw ) ) * 4;
274 }
275
276
277 SOURCE_STRING decodeFixedString( const std::vector<uint8_t>& aBytes, size_t aOffset, size_t aBytesAvailable,
278 const SOURCE_PROVENANCE& aSource, std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
279 {
280 size_t end = aOffset;
281
282 while( end < aOffset + aBytesAvailable && aBytes[end] != 0 )
283 ++end;
284
285 if( end == aOffset + aBytesAvailable )
286 throwDecodeError( aSource, wxS( "unterminated fixed string" ) );
287
288 return PADS_SCH_BINARY_PARSER::DecodeString( { aBytes.begin() + aOffset, aBytes.begin() + end },
289 DEFAULT_CODE_PAGE, aSource, aDiagnostics );
290 }
291
292
293 SOURCE_PROPERTY sourceProperty( const wxString& aName, const wxString& aValue, const SOURCE_PROVENANCE& aSource )
294 {
295 SOURCE_PROPERTY property;
296 property.name.text = aName;
297 property.name.source = aSource;
298 property.value.text = aValue;
299 property.value.source = aSource;
300 property.disposition = PROPERTY_DISPOSITION::EXACT;
301 property.source = aSource;
302 return property;
303 }
304
305
306 bool samePointValue( const SOURCE_POINT& aLeft, const SOURCE_POINT& aRight )
307 {
308 return aLeft.x == aRight.x && aLeft.y == aRight.y;
309 }
310
311
312 bool samePresentationValue( const MODEL_TEXT_PRESENTATION& aLeft, const MODEL_TEXT_PRESENTATION& aRight )
313 {
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;
319 }
320
321
322 bool sameGraphicValue( const MODEL_GRAPHIC& aLeft, const MODEL_GRAPHIC& aRight )
323 {
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 );
332 }
333
334
335 bool sameWorksheetValue( const MODEL_WORKSHEET& aLeft, const MODEL_WORKSHEET& aRight )
336 {
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;
341
342 for( const MODEL_GRAPHIC& graphic : aLeft.graphics )
343 ( graphic.kind == MODEL_GRAPHIC_KIND::TEXT ? leftText : leftDrawing ).push_back( &graphic );
344
345 for( const MODEL_GRAPHIC& graphic : aRight.graphics )
346 ( graphic.kind == MODEL_GRAPHIC_KIND::TEXT ? rightText : rightDrawing ).push_back( &graphic );
347
348 const auto equalPointers = []( const MODEL_GRAPHIC* aLeftGraphic, const MODEL_GRAPHIC* aRightGraphic )
349 {
350 return sameGraphicValue( *aLeftGraphic, *aRightGraphic );
351 };
352
353 return std::ranges::equal( leftDrawing, rightDrawing, equalPointers )
354 && std::ranges::is_permutation( leftText, rightText, equalPointers );
355 }
356
357
358 bool isProvenGraphicStrokeWidth( uint8_t aWidth )
359 {
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 );
362 }
363
364
365 void decodeGraphicStrokeWidth( uint8_t aRawWidth, uint8_t aPackedPresentation,
366 const SOURCE_PROVENANCE& aGraphicSource, MODEL_GRAPHIC& aGraphic,
367 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
368 {
369 SOURCE_PROVENANCE packedSource = aGraphicSource;
370 packedSource.absoluteOffset += 5;
371 packedSource.length = 1;
372 SOURCE_PROPERTY packed = sourceProperty( wxS( "preserved_graphic_presentation" ),
373 wxString::Format( wxS( "%u" ), aPackedPresentation ), packedSource );
374 packed.disposition = PROPERTY_DISPOSITION::PRESERVED;
375 aGraphic.properties.push_back( std::move( packed ) );
376
377 if( isProvenGraphicStrokeWidth( aRawWidth ) )
378 {
379 aGraphic.strokeWidth = static_cast<int64_t>( aRawWidth ) * 2;
380 return;
381 }
382
383 SOURCE_PROVENANCE strokeSource = aGraphicSource;
384 strokeSource.absoluteOffset += 4;
385 strokeSource.length = 1;
386 SOURCE_PROPERTY stroke = sourceProperty( wxS( "unsupported_graphic_stroke_width" ),
387 wxString::Format( wxS( "%u" ), aRawWidth ), strokeSource );
388 stroke.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
389 aDiagnostics.push_back( MakePropertyDiagnostic(
390 RPT_SEVERITY_WARNING, stroke, wxS( "unproved graphic stroke width preserved; using hairline" ) ) );
391 aGraphic.properties.push_back( std::move( stroke ) );
392 }
393
394
395 SOURCE_STRING decodedDefinitionFont( int16_t aHandle, const SOURCE_PROVENANCE& aSource )
396 {
397 SOURCE_STRING font;
398 font.source = aSource;
399
400 if( aHandle == -1 || aHandle == -4 )
401 {
402 font.text = wxS( "Default Font" );
403 font.encoding = STRING_ENCODING_STATUS::CODE_PAGE;
404 font.codePage = DEFAULT_CODE_PAGE;
405 font.codePageName = wxS( "windows-1252" );
406 }
407
408 return font;
409 }
410
411
412 uint32_t pinElectricalType( uint8_t aType, const SOURCE_PROVENANCE& aSource,
413 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
414 {
415 switch( aType )
416 {
417 case 'U': return 0;
418 case 'L': return 1;
419 case 'S': return 2;
420 case 'B': return 3;
421 case 'T': return 4;
422 case 'C': return 5;
423 case 'E': return 6;
424 case 'P':
425 case 'G': return 7;
426 case 'Z': return 8;
427 default:
428 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "pin electrical type" ), aType, aSource, aDiagnostics );
429 return 8;
430 }
431 }
432
433
434 SOURCE_POINT pageExtent( const std::string& aPage, const SOURCE_PROVENANCE& aSource )
435 {
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 };
447
448 throwDecodeError( aSource, wxS( "invalid design page-size token" ) );
449 }
450
451
452 // PADS justification is a bitfield where center wins: bit 2 centers and bit 0 right-aligns horizontally
453 MODEL_JUSTIFICATION horizontalJustification( uint16_t aValue )
454 {
455 if( aValue & 0x0004 )
457
458 if( aValue & 0x0001 )
460
462 }
463
464
465 // Bit 3 centers and bit 1 top-aligns vertically; LEFT and RIGHT stand for top and bottom
466 MODEL_JUSTIFICATION verticalJustification( uint16_t aValue )
467 {
468 if( aValue & 0x0008 )
470
471 if( aValue & 0x0002 )
473
475 }
476
477
478 uint16_t rotatedFieldJustification( uint16_t aValue, int aAngle )
479 {
480 // PADS swaps the side-selector bits for field text rotated by
481 // 90/270 degrees. This mirrors the ASCII importer behavior.
482 const int quarterTurns = NormalizeAngle( aAngle ) / 900;
483
484 if( ( quarterTurns & 1 ) == 0 )
485 return aValue;
486
487 const uint16_t bit0 = aValue & 0x0001;
488 const uint16_t bit1 = aValue & 0x0002;
489
490 aValue &= static_cast<uint16_t>( ~0x0003 );
491
492 if( bit0 )
493 aValue |= 0x0002;
494
495 if( bit1 )
496 aValue |= 0x0001;
497
498 return aValue;
499 }
500
501
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 };
506
507
508 wxString decodeWindows1252( const std::vector<uint8_t>& aBytes )
509 {
510 wxString result;
511
512 for( uint8_t byte : aBytes )
513 {
514 uint32_t codePoint = byte;
515
516 if( byte >= 0x80 && byte <= 0x9F )
517 codePoint = CP1252_HIGH[byte - 0x80];
518
519 result += wxUniChar( codePoint );
520 }
521
522 return result;
523 }
524
525
526 wxString decodeUnknownCodePage( const std::vector<uint8_t>& aBytes )
527 {
528 wxString result;
529
530 for( uint8_t byte : aBytes )
531 result += wxUniChar( byte < 0x80 ? byte : 0xFFFD );
532
533 return result;
534 }
535
536
537 wxString decodeUtf8( const std::vector<uint8_t>& aBytes, bool& aHadInvalidBytes )
538 {
539 wxString result;
540 aHadInvalidBytes = false;
541
542 for( size_t i = 0; i < aBytes.size(); )
543 {
544 uint8_t lead = aBytes[i];
545 uint32_t codePoint = 0;
546 size_t continuationCount = 0;
547 uint32_t minimum = 0;
548
549 if( lead < 0x80 )
550 {
551 result += wxUniChar( lead );
552 ++i;
553 continue;
554 }
555 else if( lead >= 0xC2 && lead <= 0xDF )
556 {
557 codePoint = lead & 0x1F;
558 continuationCount = 1;
559 minimum = 0x80;
560 }
561 else if( lead >= 0xE0 && lead <= 0xEF )
562 {
563 codePoint = lead & 0x0F;
564 continuationCount = 2;
565 minimum = 0x800;
566 }
567 else if( lead >= 0xF0 && lead <= 0xF4 )
568 {
569 codePoint = lead & 0x07;
570 continuationCount = 3;
571 minimum = 0x10000;
572 }
573 else
574 {
575 result += wxUniChar( 0xFFFD );
576 aHadInvalidBytes = true;
577 ++i;
578 continue;
579 }
580
581 bool valid = i + continuationCount < aBytes.size();
582
583 for( size_t j = 1; valid && j <= continuationCount; ++j )
584 {
585 uint8_t continuation = aBytes[i + j];
586 valid = ( continuation & 0xC0 ) == 0x80;
587
588 if( valid )
589 codePoint = ( codePoint << 6 ) | ( continuation & 0x3F );
590 }
591
592 valid = valid && codePoint >= minimum && codePoint <= 0x10FFFF
593 && !( codePoint >= 0xD800 && codePoint <= 0xDFFF );
594
595 if( !valid )
596 {
597 result += wxUniChar( 0xFFFD );
598 aHadInvalidBytes = true;
599 ++i;
600 continue;
601 }
602
603 result += wxUniChar( codePoint );
604 i += continuationCount + 1;
605 }
606
607 return result;
608 }
609
610 [[noreturn]] void throwValidationError( const SOURCE_PROVENANCE& aSource, const wxString& aMessage );
611
612
613 template <typename Item, typename IdAccessor, typename SourceAccessor>
614 void validateUniqueIds( const std::vector<Item>& aItems, const wxString& aObjectClass, IdAccessor aId,
615 SourceAccessor aSource )
616 {
617 std::map<uint32_t, SOURCE_PROVENANCE> declarations;
618
619 for( const Item& item : aItems )
620 {
621 const auto& id = aId( item );
622
623 if( !id.IsValid() )
624 throwValidationError( aSource( item ), wxString::Format( wxS( "invalid %s ID" ), aObjectClass ) );
625
626 auto [first, inserted] = declarations.emplace( id.Value(), aSource( item ) );
627
628 if( !inserted )
629 {
630 const SOURCE_PROVENANCE& firstSource = first->second;
631 wxString detail = wxString::Format(
632 wxS( "duplicate %s ID %u; first at v0x%04X %s controller %d record %llu sheet %d "
633 "offset 0x%llX" ),
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 );
638 }
639 }
640 }
641
642
643 [[noreturn]] void throwValidationError( const SOURCE_PROVENANCE& aSource, const wxString& aMessage )
644 {
645 THROW_IO_ERROR( FormatParserError( aSource, aMessage ) );
646 }
647
648
649 constexpr auto itemId = []( const auto& aItem ) -> const auto&
650 {
651 return aItem.id;
652 };
653
654
655 constexpr auto itemProvenance = []( const auto& aItem ) -> const SOURCE_PROVENANCE&
656 {
657 return aItem.source;
658 };
659
660
661 template <typename Item, typename Declarations>
662 void validateNestedId( const Item& aItem, const wxString& aObjectClass, Declarations& aDeclarations )
663 {
664 if( !aItem.id.IsValid() )
665 throwValidationError( aItem.source, wxString::Format( wxS( "invalid %s ID" ), aObjectClass ) );
666
667 auto [first, inserted] = aDeclarations.emplace( aItem.id.Value(), aItem.source );
668
669 if( !inserted )
670 {
671 throwValidationError(
672 aItem.source,
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 ) ) );
679 }
680 }
681
682
683 struct MODEL_REFERENCE_INDEX
684 {
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;
694
695 explicit MODEL_REFERENCE_INDEX( const PADS_SCH_MODEL& aModel )
696 {
697 for( const MODEL_SHEET& sheet : aModel.sheets )
698 sheets.emplace( sheet.id.Value(), &sheet );
699
700 for( const MODEL_SYMBOL_DEFINITION& definition : aModel.definitions )
701 {
702 definitions.emplace( definition.id.Value(), &definition );
703
704 for( const MODEL_PIN_DEFINITION& pin : definition.pins )
705 {
706 pins.emplace( pin.id.Value(), &pin );
707 pinOwners.emplace( pin.id.Value(), &definition );
708 }
709 }
710
711 for( const MODEL_PART_TYPE& partType : aModel.partTypes )
712 {
713 partTypes.emplace( partType.id.Value(), &partType );
714
715 for( const MODEL_GATE& gate : partType.gates )
716 {
717 gates.emplace( gate.id.Value(), &gate );
718 gateOwners.emplace( gate.id.Value(), &partType );
719 }
720 }
721
722 for( const MODEL_PLACEMENT& placement : aModel.placements )
723 placements.emplace( placement.id.Value(), &placement );
724
725 for( const MODEL_NET& net : aModel.nets )
726 nets.emplace( net.id.Value(), &net );
727 }
728 };
729
730
731 bool endpointIsValid( const MODEL_REFERENCE_INDEX& aIndex, const MODEL_CONNECTION_ENDPOINT& aEndpoint )
732 {
733 if( aEndpoint.kind == MODEL_ENDPOINT_KIND::POINT )
734 return !aEndpoint.placement && !aEndpoint.pin;
735
736 if( aEndpoint.kind != MODEL_ENDPOINT_KIND::PIN || !aEndpoint.placement || !aEndpoint.pin )
737 return false;
738
739 auto placement = aIndex.placements.find( aEndpoint.placement->id.Value() );
740
741 if( placement == aIndex.placements.end() )
742 return false;
743
744 return aIndex.pins.contains( aEndpoint.pin->id.Value() )
745 && std::ranges::any_of( placement->second->pins,
746 [&]( const PIN_REFERENCE& aPin )
747 {
748 return aPin.id == aEndpoint.pin->id;
749 } );
750 }
751
752
753 struct SHEET_CONTROLLERS
754 {
755 std::array<SCH_SDB_POOL, 23> pools;
756 std::array<size_t, 23> offsets;
757 };
758
759
760 struct PLACEMENT_GLOBALS
761 {
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;
768 size_t fontBase = 0;
769 uint32_t fontCount = 0;
771 SOURCE_STRING defaultSystemFont;
772 };
773
774
775 PLACEMENT_GLOBALS placementGlobals( const PADS_SCH_SDB& aSdb, const wxString& aSourceName,
776 const DESIGN_SETTINGS& aSettings )
777 {
778 PLACEMENT_GLOBALS result;
779
780 auto requireOuterStride = [&]( size_t aController, size_t aStride )
781 {
782 const SCH_SDB_POOL& pool = aSdb.Pools()[aController];
783
784 if( pool.usedBytes != pool.count * aStride )
785 {
786 SOURCE_PROVENANCE source = sourceAt(
787 aSourceName, aSdb.Version(), wxS( "outer controller directory" ), aController, 0,
788 OUTER_DIRECTORY_OFFSET + aController * OUTER_DESCRIPTOR_BYTES + OUTER_USED_BYTES_OFFSET, 4,
789 -1 );
790 throwDecodeError( source,
791 wxString::Format( wxS( "controller byte count does not match %llu-byte records" ),
792 static_cast<unsigned long long>( aStride ) ) );
793 }
794 };
795
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 );
802 result.groupCount = aSdb.Pools()[6].count;
803 result.attributeOffsetBase = outerControllerOffset( aSdb, 7 );
804 result.attributeOffsetCount = aSdb.Pools()[7].count;
805 result.fontBase = outerControllerOffset( aSdb, 19 );
806 result.fontCount = aSdb.Pools()[19].count;
807 result.fontMode = aSettings.fontMode;
808 result.defaultSystemFont = aSettings.defaultSystemFont;
809 return result;
810 }
811
812
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,
815 int16_t aHandle, const SOURCE_PROVENANCE& aHandleSource,
816 MODEL_TEXT_PRESENTATION& aPresentation, bool aStrictHandle,
817 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
818 {
819 if( aHandle == -1 || aHandle == -4 )
820 {
821 if( aGlobals.fontMode == MODEL_FONT_MODE::SYSTEM && !aGlobals.defaultSystemFont.text.IsEmpty() )
822 aPresentation.font = aGlobals.defaultSystemFont;
823 else
824 aPresentation.font = decodedDefinitionFont( aHandle, aHandleSource );
825
826 return;
827 }
828
829 if( aHandle < 0 || static_cast<uint32_t>( aHandle ) >= aGlobals.fontCount )
830 {
831 if( aStrictHandle )
832 throwDecodeError( aHandleSource, wxS( "placement font handle leaves outer controller 19" ) );
833
834 SOURCE_PROPERTY property = sourceProperty(
835 wxS( "inline_font_payload" ), wxString::Format( wxS( "%u" ), uint16_t( aHandle ) ), aHandleSource );
836 property.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
837 aDiagnostics.push_back( MakePropertyDiagnostic(
838 RPT_SEVERITY_WARNING, property, wxS( "unsupported inline placement font payload preserved" ) ) );
839 aPresentation.properties.push_back( std::move( property ) );
840 return;
841 }
842
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 );
847
848 SOURCE_PROVENANCE nameSource = fontSource;
849 nameSource.absoluteOffset += 4;
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;
856
857 if( aPresentation.bold )
858 aPresentation.font.text.Prepend( wxS( "Bold " ) );
859
860 if( aPresentation.italic )
861 aPresentation.font.text.Prepend( wxS( "Italic " ) );
862
863 aPresentation.properties.push_back(
864 sourceProperty( wxS( "font_handle" ), wxString::Format( wxS( "%d" ), aHandle ), fontSource ) );
865
866 if( ( style & ~uint32_t{ 7 } ) != 0 )
867 {
868 SOURCE_PROPERTY property = sourceProperty( wxS( "unsupported_font_style_flags" ),
869 wxString::Format( wxS( "%u" ), style & ~7U ), fontSource );
870 property.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
871 aDiagnostics.push_back( MakePropertyDiagnostic(
872 RPT_SEVERITY_WARNING, property, wxS( "unsupported placement font style flags preserved" ) ) );
873 aPresentation.properties.push_back( std::move( property ) );
874 }
875 }
876
877
878 CONNECTIVITY_GLOBALS connectivityGlobals( const std::vector<uint8_t>& aBytes, const PADS_IO::BINARY_CURSOR& aCursor,
879 const PADS_SCH_SDB& aSdb, const wxString& aSourceName,
880 PADS_SCH_MODEL& aModel )
881 {
882 CONNECTIVITY_GLOBALS result;
883 const SCH_SDB_POOL& membershipPool = aSdb.Pools()[4];
884 const SCH_SDB_POOL& netPool = aSdb.Pools()[8];
885 const SCH_SDB_POOL& fontPool = aSdb.Pools()[19];
886
887 if( membershipPool.usedBytes != membershipPool.count * NET_MEMBERSHIP_BYTES )
888 {
889 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "net membership directory" ), 4, 0,
890 outerControllerOffset( aSdb, 4 ), membershipPool.usedBytes, -1 );
891 throwDecodeError( source, wxS( "controller byte count does not match 2-byte records" ) );
892 }
893
894 if( netPool.usedBytes != netPool.count * NET_RECORD_BYTES )
895 {
896 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "net directory" ), 8, 0,
897 outerControllerOffset( aSdb, 8 ), netPool.usedBytes, -1 );
898 throwDecodeError( source, wxS( "controller byte count does not match 88-byte records" ) );
899 }
900
901 if( fontPool.usedBytes != fontPool.count * FONT_RECORD_BYTES )
902 {
903 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "font directory" ), 19, 0,
904 outerControllerOffset( aSdb, 19 ), fontPool.usedBytes, -1 );
905 throwDecodeError( source, wxS( "controller byte count does not match 36-byte records" ) );
906 }
907
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 );
913
914 for( size_t record = 0; record < membershipPool.count; ++record )
915 result.membershipSheets.push_back( aCursor.U16At( result.membershipBase + record * 2 ) );
916
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 );
921
922 result.nets.reserve( netPool.count );
923
924 for( size_t record = 0; record < netPool.count; ++record )
925 {
926 const size_t offset = netBase + record * NET_RECORD_BYTES;
927 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "global net" ), 8, record, offset,
928 NET_RECORD_BYTES, -1 );
929 GLOBAL_NET_RECORD net;
930 net.source = source;
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;
939 SOURCE_PROVENANCE nameSource = source;
940 nameSource.absoluteOffset += 24;
941 nameSource.length = 56;
942 net.name = decodeFixedString( aBytes, offset + 24, 56, nameSource, aModel.diagnostics );
943
944 if( aCursor.U16At( offset + 20 ) != 0 || aCursor.U32At( offset + 80 ) != 0xFFFFFFFF )
945 {
946 throwDecodeError( source, wxS( "global net record has nonzero padding or a live reserved link" ) );
947 }
948
949 if( !net.tombstone
950 && ( net.membershipStart > membershipPool.count
951 || net.membershipCount > membershipPool.count - net.membershipStart ) )
952 {
953 throwDecodeError( source, wxS( "net sheet-membership slice leaves outer controller 4" ) );
954 }
955
956 for( uint32_t membership = net.membershipStart;
957 !net.tombstone && membership < net.membershipStart + net.membershipCount; ++membership )
958 {
959 if( claimedMemberships[membership] )
960 throwDecodeError( source, wxS( "duplicate net sheet-membership ownership" ) );
961
962 if( result.membershipSheets[membership] >= aModel.sheets.size() )
963 throwDecodeError( source, wxS( "net membership references the wrong sheet object class" ) );
964
965 claimedMemberships[membership] = true;
966 }
967
968 if( net.aliasCount == 0 )
969 {
970 if( net.aliasStringOffset != 0xFFFFFFFF )
971 throwDecodeError( source, wxS( "non-alias net has an alias-string handle" ) );
972 }
973 else
974 {
975 if( net.aliasStringOffset >= aliasHeapBytes )
976 throwDecodeError( source, wxS( "bus-alias string handle leaves outer controller 1" ) );
977
978 size_t stringOffset = net.aliasStringOffset;
979
980 for( size_t alias = 0; alias < net.aliasCount; ++alias )
981 {
982 SOURCE_PROVENANCE aliasSource =
983 sourceAt( aSourceName, aModel.version, wxS( "bus alias member" ), 1, alias,
984 aliasHeapBase + stringOffset, aliasHeapBytes - stringOffset, -1 );
985 SOURCE_STRING member =
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 ) );
992 }
993 }
994
995 result.nets.push_back( std::move( net ) );
996 }
997
998 return result;
999 }
1000
1001
1002 SHEET_CONTROLLERS sheetControllers( const PADS_IO::BINARY_CURSOR& aCursor, const SCH_SDB_BLOCK& aBlock )
1003 {
1004 SHEET_CONTROLLERS result;
1005 size_t descriptor = aBlock.offset + SHEET_HEADER_BYTES;
1006 size_t payload = descriptor + 24 * SHEET_DESCRIPTOR_BYTES;
1007
1008 for( size_t i = 0; i < result.pools.size(); ++i )
1009 {
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;
1014 }
1015
1016 return result;
1017 }
1018
1019
1020 void requireFixedController( const SHEET_CONTROLLERS& aControllers, size_t aController, size_t aStride,
1021 const wxString& aFile, uint16_t aVersion, int aSheet )
1022 {
1023 const SCH_SDB_POOL& pool = aControllers.pools[aController - 1];
1024
1025 if( pool.usedBytes != pool.count * aStride )
1026 {
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 ) ) );
1032 }
1033 }
1034
1035
1036 enum class TEXT_ROLE
1037 {
1038 DEFINITION_FIELD,
1039 EMBEDDED_SYMBOL_TEXT,
1040 PAGE_TEXT
1041 };
1042
1043
1044 struct DEFINITION_TEXT_HEAP
1045 {
1046 size_t recordBase = 0;
1047 uint32_t recordCount = 0;
1048 size_t stringBase = 0;
1049 uint32_t stringBytes = 0;
1050 };
1051
1052
1053 MODEL_TEXT_PRESENTATION decodeTextPresentation( const PADS_IO::BINARY_CURSOR& aCursor, size_t aOffset,
1054 const SOURCE_PROVENANCE& aSource, TEXT_ROLE aRole,
1055 int16_t& aRelationship )
1056 {
1057 MODEL_TEXT_PRESENTATION presentation;
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 ) );
1065
1066 SOURCE_PROVENANCE fontSource = aSource;
1067 fontSource.absoluteOffset += 28;
1068 fontSource.length = 2;
1069 aRelationship = static_cast<int16_t>( aCursor.U16At( aOffset + 28 ) );
1070
1071 // Page text spends word 28 on the successor ordinal, so it always falls back to the default font.
1072 const bool pageText = aRole == TEXT_ROLE::PAGE_TEXT;
1073
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 ),
1077 fontSource ) );
1078 return presentation;
1079 }
1080
1081
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,
1084 size_t aRecord, TEXT_ROLE aRole, MODEL_SYMBOL_DEFINITION& aDefinition,
1085 PADS_SCH_MODEL& aModel )
1086 {
1087 if( aRecord >= aHeap.recordCount )
1088 throwDecodeError( aDefinition.source, wxS( "definition field handle leaves controller 1" ) );
1089
1090 const bool isField = aRole == TEXT_ROLE::DEFINITION_FIELD;
1091 const size_t offset = aHeap.recordBase + aRecord * TEXT_RECORD_BYTES;
1092 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version,
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 );
1097
1098 if( stringBytes == 0 || stringOffset > aHeap.stringBytes || stringBytes > aHeap.stringBytes - stringOffset
1099 || aBytes[aHeap.stringBase + stringOffset + stringBytes - 1] != 0 )
1100 {
1101 throwDecodeError( source, wxS( "definition field string leaves controller 2" ) );
1102 }
1103
1104 SOURCE_PROVENANCE stringSource =
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 );
1111
1112 int16_t relationship = 0;
1113 MODEL_TEXT_PRESENTATION presentation = decodeTextPresentation( aCursor, offset, source, aRole, relationship );
1114 const SOURCE_POINT position{ decodeLocalCoordinate( aCursor.U16At( offset + 12 ) ),
1115 decodeLocalCoordinate( aCursor.U16At( offset + 14 ) ), source };
1116 const int angle = NormalizeAngle( aCursor.U16At( offset + 16 ) );
1117
1118 if( isField )
1119 {
1120 MODEL_FIELD field;
1121 field.source = 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 ) );
1127 return;
1128 }
1129
1130 MODEL_GRAPHIC graphic;
1131 graphic.source = source;
1132 graphic.kind = MODEL_GRAPHIC_KIND::TEXT;
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 ) );
1138 }
1139
1140
1141 struct DEFINITION_LAYOUT
1142 {
1143 size_t symbolBase = 0;
1144 size_t pieceBase = 0;
1145 size_t vertexBase = 0;
1146 size_t arcBase = 0;
1147 size_t usedDecalBase = 0;
1148 size_t terminalBase = 0;
1149 size_t partBase = 0;
1150 size_t gateBase = 0;
1151 size_t pinBase = 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;
1159
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;
1164 };
1165
1166
1167 struct USED_DECAL
1168 {
1169 size_t record = 0;
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;
1175 };
1176
1177
1178 void preserveRawDefinitionControllers( const std::vector<uint8_t>& aBytes, const SHEET_CONTROLLERS& aControllers,
1179 size_t aSheetIndex, const wxString& aSourceName, PADS_SCH_MODEL& aModel )
1180 {
1181 for( size_t controller = 3; controller <= 23; ++controller )
1182 {
1183 const SCH_SDB_POOL& pool = aControllers.pools[controller - 1];
1184
1185 if( pool.usedBytes == 0 )
1186 continue;
1187
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(
1192 { source,
1194 { aBytes.begin() + source.absoluteOffset,
1195 aBytes.begin() + source.absoluteOffset + source.length } } );
1196 }
1197 }
1198
1199
1200 DEFINITION_LAYOUT definitionLayout( const PADS_IO::BINARY_CURSOR& aCursor, const SHEET_CONTROLLERS& aControllers,
1201 size_t aSheetIndex, const wxString& aSourceName, uint16_t aVersion )
1202 {
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 );
1213
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 };
1233
1234 // Prefix sums over file-supplied per-record counts. A 32-bit accumulator wraps on a
1235 // crafted file and the exact-total checks below then compare small against their pools
1236 // while the stored offsets are already nonsense, so accumulate in 64 bits
1237 uint64_t vertexCursor = 0;
1238 uint64_t pieceCursor = 0;
1239
1240 for( size_t definition = 0; definition < aControllers.pools[2].count; ++definition )
1241 {
1242 layout.definitionPieceStart.push_back( static_cast<uint32_t>( pieceCursor ) );
1243 pieceCursor += aCursor.U16At( layout.symbolBase + definition * SYMBOL_RECORD_BYTES + 0x2A );
1244 }
1245
1246 if( pieceCursor != aControllers.pools[3].count )
1247 {
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" ) );
1252 }
1253
1254 for( size_t piece = 0; piece < aControllers.pools[3].count; ++piece )
1255 {
1256 layout.pieceVertexStart.push_back( static_cast<uint32_t>( vertexCursor ) );
1257 vertexCursor += aCursor.U16At( layout.pieceBase + piece * SYMBOL_PIECE_BYTES + 2 );
1258 }
1259
1260 if( vertexCursor != aControllers.pools[4].count )
1261 {
1262 SOURCE_PROVENANCE source = sourceAt( aSourceName, aVersion, wxS( "symbol piece" ), 4, 0, layout.pieceBase,
1263 aControllers.pools[3].usedBytes, static_cast<int>( aSheetIndex ) );
1264 throwDecodeError( source, wxS( "symbol piece vertex counts do not consume controller 5" ) );
1265 }
1266
1267 for( size_t definition = 0; definition < aControllers.pools[2].count; ++definition )
1268 {
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 )
1283 == vertexEnd;
1284
1285 if( !emptyMatches && !ownedMatches )
1286 {
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" ) );
1291 }
1292 }
1293
1294 layout.pieceArcRecords.resize( aControllers.pools[3].count );
1295 size_t discoveredArcCount = 0;
1296
1297 for( size_t piece = 0; piece < aControllers.pools[3].count; ++piece )
1298 {
1299 const size_t pieceOffset = layout.pieceBase + piece * SYMBOL_PIECE_BYTES;
1300 const uint16_t pointCount = aCursor.U16At( pieceOffset + 2 );
1301
1302 for( size_t point = 0; point < pointCount; ++point )
1303 {
1304 const size_t vertexOffset =
1305 layout.vertexBase + ( layout.pieceVertexStart[piece] + point ) * SYMBOL_VERTEX_BYTES;
1306
1307 if( static_cast<int16_t>( aCursor.U16At( vertexOffset + 4 ) ) >= 0 )
1308 layout.pieceArcRecords[piece].push_back( discoveredArcCount++ );
1309 }
1310 }
1311
1312 if( discoveredArcCount != aControllers.pools[5].count )
1313 {
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" ) );
1318 }
1319
1320 return layout;
1321 }
1322
1323
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 )
1329 {
1330 // Definitions must not reallocate; aDefinitionsByRecord holds pointers into them
1331 aModel.definitions.reserve( aModel.definitions.size() + aControllers.pools[2].count );
1332
1333 for( size_t record = 0; record < aControllers.pools[2].count; ++record )
1334 {
1335 const size_t offset = aLayout.symbolBase + record * SYMBOL_RECORD_BYTES;
1336 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "symbol definition" ), 3, record,
1337 offset, SYMBOL_RECORD_BYTES, static_cast<int>( aSheetIndex ) );
1338 SOURCE_PROVENANCE nameSource = source;
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;
1346
1347 if( vertexStart > vertexEnd || vertexEnd > aControllers.pools[4].count )
1348 throwDecodeError( source, wxS( "symbol definition vertex slice leaves controller 5" ) );
1349
1350 if( objectClass == 0 )
1351 {
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 );
1362 SOURCE_PROVENANCE originSource = source;
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 };
1368
1369 if( aCursor.U16At( offset + 42 ) != pieceEnd - firstPiece )
1370 throwDecodeError( source, wxS( "page-graphic piece count does not match controller 4 slice" ) );
1371
1372 for( size_t piece = firstPiece; piece < pieceEnd; ++piece )
1373 {
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];
1379 SOURCE_PROVENANCE graphicSource =
1380 sourceAt( aSourceName, aModel.version, wxS( "page graphic" ), 4, piece, pieceOffset,
1381 SYMBOL_PIECE_BYTES, static_cast<int>( aSheetIndex ) );
1382
1383 if( firstVertex + pointCount > vertexEnd )
1384 throwDecodeError( graphicSource, wxS( "page graphic crosses its controller-5 slice" ) );
1385
1386 MODEL_GRAPHIC graphic;
1387 graphic.source = graphicSource;
1388 decodeGraphicStrokeWidth( aCursor.U8At( pieceOffset + 4 ), aCursor.U8At( pieceOffset + 5 ),
1389 graphicSource, graphic, aModel.diagnostics );
1390
1391 switch( lineStyle )
1392 {
1393 case 0xFF: graphic.lineStyle = MODEL_LINE_STYLE::SOLID; break;
1394 case 0: graphic.lineStyle = MODEL_LINE_STYLE::DASH; break;
1395 case 1: graphic.lineStyle = MODEL_LINE_STYLE::DOT; break;
1396 default:
1397 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "page graphic line style" ), lineStyle,
1398 graphicSource, aModel.diagnostics );
1399 graphic.lineStyle = MODEL_LINE_STYLE::DEFAULT;
1400 break;
1401 }
1402
1403 switch( pieceKind )
1404 {
1405 case 0:
1406 graphic.kind = pointCount == 2 ? MODEL_GRAPHIC_KIND::LINE : MODEL_GRAPHIC_KIND::POLYLINE;
1407 break;
1408 case 1: graphic.kind = MODEL_GRAPHIC_KIND::POLYLINE; break;
1409 case 2: graphic.kind = MODEL_GRAPHIC_KIND::CIRCLE; break;
1410 case 4:
1411 graphic.kind = MODEL_GRAPHIC_KIND::POLYLINE;
1412 graphic.fill = MODEL_FILL_STYLE::FILLED;
1413 break;
1414 default:
1415 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "page graphic kind" ), pieceKind, graphicSource,
1416 aModel.diagnostics );
1417 graphic.kind = MODEL_GRAPHIC_KIND::POLYLINE;
1418 break;
1419 }
1420
1421 for( size_t point = 0; point < pointCount; ++point )
1422 {
1423 const size_t pointOffset = aLayout.vertexBase + ( firstVertex + point ) * SYMBOL_VERTEX_BYTES;
1424 SOURCE_PROVENANCE pointSource = sourceAt(
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 ) ),
1429 pointSource } );
1430 }
1431
1432 const int16_t arcMarker = static_cast<int16_t>(
1433 aCursor.U16At( aLayout.vertexBase + firstVertex * SYMBOL_VERTEX_BYTES + 4 ) );
1434
1435 if( pieceKind == 0 && arcMarker >= 0 )
1436 {
1437 if( aLayout.pieceArcRecords[piece].empty() )
1438 throwDecodeError( graphicSource, wxS( "page arc has no controller-6 record" ) );
1439
1440 const size_t arcRecord = aLayout.pieceArcRecords[piece].front();
1441 const size_t arcOffset = aLayout.arcBase + arcRecord * SYMBOL_ARC_BYTES;
1442 SOURCE_PROVENANCE arcSource =
1443 sourceAt( aSourceName, aModel.version, wxS( "page arc" ), 6, arcRecord, arcOffset,
1444 SYMBOL_ARC_BYTES, static_cast<int>( aSheetIndex ) );
1445 graphic.kind = MODEL_GRAPHIC_KIND::ARC;
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 };
1454 }
1455
1456 for( SOURCE_POINT& point : graphic.points )
1457 {
1458 point.x += groupOrigin.x;
1459 point.y += groupOrigin.y;
1460 }
1461
1462 if( graphic.kind == MODEL_GRAPHIC_KIND::ARC )
1463 {
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;
1470 }
1471
1472 graphic.properties.push_back( sourceProperty( wxS( "page_graphic_group" ), name.text, source ) );
1473
1474 if( worksheetCandidate )
1475 graphic.properties.push_back( sourceProperty( wxS( "worksheet_group" ), name.text, source ) );
1476
1477 if( !hasCircularTextOwnership )
1478 {
1479 SOURCE_PROVENANCE relationshipSource = source;
1480 relationshipSource.absoluteOffset += 64;
1481 relationshipSource.length = 4;
1482 SOURCE_PROPERTY relationship = sourceProperty(
1483 wxS( "preserved_drawing_text_relationship" ),
1484 wxString::Format( wxS( "%u,%u" ), groupTextCount, groupLastText ), relationshipSource );
1485 relationship.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
1486 aModel.diagnostics.push_back( MakePropertyDiagnostic(
1487 RPT_SEVERITY_WARNING, relationship,
1488 wxS( "unsupported class-zero drawing text relationship preserved" ) ) );
1489 graphic.properties.push_back( std::move( relationship ) );
1490 }
1491 aModel.graphics.push_back(
1492 { graphicSource, { aModel.sheets[aSheetIndex].id, graphicSource }, std::move( graphic ) } );
1493 }
1494
1495 if( hasCircularTextOwnership )
1496 aPageGraphicRecords.push_back( record );
1497 continue;
1498 }
1499
1500 if( objectClass != 0x06 )
1501 continue;
1502
1503 MODEL_SYMBOL_DEFINITION definition;
1504 definition.id = DEFINITION_ID( aLayout.definitionIdBase + record );
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;
1511
1512 for( size_t piece = firstPiece; piece < pieceEnd; ++piece )
1513 {
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];
1518
1519 if( firstVertex + pointCount > vertexEnd )
1520 throwDecodeError( source, wxS( "symbol piece crosses its definition vertex slice" ) );
1521
1522 SOURCE_PROVENANCE graphicSource =
1523 sourceAt( aSourceName, aModel.version, wxS( "symbol graphic" ), 4, piece, pieceOffset,
1524 SYMBOL_PIECE_BYTES, static_cast<int>( aSheetIndex ) );
1525 MODEL_GRAPHIC graphic;
1526 graphic.source = graphicSource;
1527 decodeGraphicStrokeWidth( aCursor.U8At( pieceOffset + 4 ), aCursor.U8At( pieceOffset + 5 ),
1528 graphicSource, graphic, aModel.diagnostics );
1529 graphic.lineStyle = MODEL_LINE_STYLE::SOLID;
1530
1531 switch( pieceKind )
1532 {
1533 case 0: graphic.kind = pointCount == 2 ? MODEL_GRAPHIC_KIND::LINE : MODEL_GRAPHIC_KIND::POLYLINE; break;
1534 case 1: graphic.kind = MODEL_GRAPHIC_KIND::POLYLINE; break;
1535 case 2: graphic.kind = MODEL_GRAPHIC_KIND::CIRCLE; break;
1536 case 4:
1537 graphic.kind = MODEL_GRAPHIC_KIND::POLYLINE;
1538 graphic.fill = MODEL_FILL_STYLE::FILLED;
1539 break;
1540 default:
1541 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "symbol graphic kind" ), pieceKind, graphicSource,
1542 aModel.diagnostics );
1543 graphic.kind = MODEL_GRAPHIC_KIND::POLYLINE;
1544 break;
1545 }
1546
1547 for( size_t point = 0; point < pointCount; ++point )
1548 {
1549 const size_t pointOffset = aLayout.vertexBase + ( firstVertex + point ) * SYMBOL_VERTEX_BYTES;
1550 SOURCE_PROVENANCE pointSource =
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 ) ),
1555 pointSource } );
1556 }
1557
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 )
1560 {
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,
1565 [&]( const SOURCE_POINT& aPoint )
1566 {
1567 return ( aPoint.x == minX.x || aPoint.x == maxX.x )
1568 && ( aPoint.y == minY.y || aPoint.y == maxY.y );
1569 } );
1570
1571 if( cornersOnly )
1572 {
1573 graphic.kind = MODEL_GRAPHIC_KIND::RECTANGLE;
1574 graphic.points = { { minX.x, minY.y, graphicSource }, { maxX.x, maxY.y, graphicSource } };
1575 }
1576 }
1577
1578 const int16_t arcMarker = static_cast<int16_t>(
1579 aCursor.U16At( aLayout.vertexBase + firstVertex * SYMBOL_VERTEX_BYTES + 4 ) );
1580
1581 if( pieceKind == 0 && arcMarker >= 0 )
1582 {
1583 if( aLayout.pieceArcRecords[piece].empty() )
1584 throwDecodeError( graphicSource, wxS( "symbol arc has no controller-6 record" ) );
1585
1586 const size_t arcRecord = aLayout.pieceArcRecords[piece].front();
1587 const size_t arcOffset = aLayout.arcBase + arcRecord * SYMBOL_ARC_BYTES;
1588 graphic.kind = MODEL_GRAPHIC_KIND::ARC;
1589 SOURCE_PROVENANCE arcSource =
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 ) ) ),
1606 arcSource ) );
1607 }
1608
1609 definition.graphics.push_back( std::move( graphic ) );
1610 }
1611
1612 aModel.definitions.push_back( std::move( definition ) );
1613 aDefinitionsByRecord[record] = &aModel.definitions.back();
1614 }
1615 }
1616
1617
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,
1623 PADS_SCH_MODEL& aModel )
1624 {
1625 for( size_t record = 0; record < aUsedDecals.size(); ++record )
1626 {
1627 const size_t offset = aLayout.usedDecalBase + record * USED_DECAL_BYTES;
1628 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "used decal" ), 7, record, offset,
1629 USED_DECAL_BYTES, static_cast<int>( aSheetIndex ) );
1630 SOURCE_PROVENANCE nameSource = source;
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 );
1639
1640 if( name.text.empty() || decal.definitionRecord == 0xFFFFFFFF )
1641 continue;
1642
1643 if( decal.definitionRecord >= aDefinitionsByRecord.size() )
1644 throwDecodeError( source, wxS( "unresolved symbol definition reference" ) );
1645
1646 const size_t definitionOffset = aLayout.symbolBase + decal.definitionRecord * SYMBOL_RECORD_BYTES;
1647 SOURCE_PROVENANCE targetNameSource =
1648 sourceAt( aSourceName, aModel.version, wxS( "symbol definition" ), 3, decal.definitionRecord,
1649 definitionOffset, 38, static_cast<int>( aSheetIndex ) );
1650 SOURCE_STRING targetName =
1651 decodeFixedString( aBytes, definitionOffset, 38, targetNameSource, aModel.diagnostics );
1652
1653 if( targetName.text != name.text )
1654 {
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" ) );
1658 }
1659
1660 decal.definition = aDefinitionsByRecord[decal.definitionRecord];
1661
1662 if( !decal.definition )
1663 continue;
1664
1665 const uint16_t embeddedTextCount =
1666 aCursor.U16At( aLayout.symbolBase + decal.definitionRecord * SYMBOL_RECORD_BYTES + 0x40 );
1667
1668 if( embeddedTextCount != 0 && decal.fieldStart > aLayout.textHeap.recordCount
1669 && decal.fieldStart < 0x80000000 )
1670 throwDecodeError( source, wxS( "embedded definition text handle leaves controller 1" ) );
1671
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" ) );
1674
1675 aSemanticDecals.push_back( &decal );
1676
1677 for( size_t pin = 0; pin < decal.terminalCount; ++pin )
1678 {
1679 const size_t terminalRecord = decal.terminalStart + pin;
1680 const size_t terminalOffset = aLayout.terminalBase + terminalRecord * TERMINAL_BYTES;
1681 SOURCE_PROVENANCE pinSource =
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 );
1685 MODEL_PIN_DEFINITION definitionPin;
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 };
1690
1691 definitionPin.presentation.source = pinSource;
1692 definitionPin.presentation.visible = true;
1693 SOURCE_PROVENANCE numberPresentationSource = source;
1694 numberPresentationSource.absoluteOffset = offset + 92;
1695 numberPresentationSource.length = 2;
1696 SOURCE_PROVENANCE namePresentationSource = source;
1697 namePresentationSource.absoluteOffset = offset + 94;
1698 namePresentationSource.length = 2;
1699
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;
1706
1707 SOURCE_PROVENANCE numberFontSource = source;
1708 numberFontSource.absoluteOffset = offset + 104;
1709 numberFontSource.length = 2;
1710 SOURCE_PROVENANCE nameFontSource = source;
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 );
1717
1718 if( aModel.settings.fontMode == MODEL_FONT_MODE::SYSTEM
1719 && !aModel.settings.defaultSystemFont.text.IsEmpty() )
1720 {
1721 if( numberFontHandle == -1 || numberFontHandle == -4 )
1722 definitionPin.numberPresentation.font = aModel.settings.defaultSystemFont;
1723
1724 if( nameFontHandle == -1 || nameFontHandle == -4 )
1725 definitionPin.namePresentation.font = aModel.settings.defaultSystemFont;
1726 }
1727
1728 definitionPin.numberPresentation.visible = definitionPin.numberPresentation.height != 0;
1729 definitionPin.namePresentation.visible = definitionPin.namePresentation.height != 0
1730 && ( aCursor.U16At( terminalOffset + 24 ) & 0x8000 ) == 0;
1731
1732 // The first T-line pair locates the pin number; the second locates the pin name.
1733 definitionPin.numberOffset = { decodeLocalCoordinate( aCursor.U16At( terminalOffset + 6 ) ),
1734 decodeLocalCoordinate( aCursor.U16At( terminalOffset + 8 ) ),
1735 pinSource };
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;
1742
1743 // PADS binary stores the same terminal-local X/Y mirror state as the ASCII T-line side field,
1744 // shifted left by one because bit 0 carries the terminal quarter-turn flag.
1745 definitionPin.side = ( presentationFlags & 0x0006 ) >> 1;
1746
1747 definitionPin.angle = ( presentationFlags & 0x0001 ) != 0 ? 900 : 0;
1748 definitionPin.numberAngle = ( presentationFlags & 0x0100 ) != 0 ? 900 : 0;
1749 definitionPin.nameAngle = ( visibilityFlags & 0x0001 ) != 0 ? 900 : 0;
1750
1751 definitionPin.numberJustification =
1752 terminalJustification( ( presentationFlags >> 12 ) & 0x0F, definitionPin.numberAngle != 0 );
1753
1754 if( ( presentationFlags & 0x00F8 ) != 0 )
1755 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "terminal side" ), presentationFlags, pinSource,
1756 aModel.diagnostics );
1757
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;
1763
1764 switch( visibilityFlags & 0x0F00 )
1765 {
1766 case 0x0000:
1767 case 0x0800: definitionPin.nameOffsetJustification = 0; break;
1768 case 0x0400:
1769 case 0x0C00: definitionPin.nameOffsetJustification = 1; break;
1770 case 0x0500:
1771 case 0x0D00:
1772 case 0x0F00: definitionPin.nameOffsetJustification = 2; break;
1773 default:
1774 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "terminal name-offset presentation" ),
1775 visibilityFlags & 0x0F00, pinSource,
1776 aModel.diagnostics );
1777 break;
1778 }
1779
1780 switch( visibilityFlags & 0x0F00 )
1781 {
1782 case 0x0000: definitionPin.numberOffsetJustification = 0; break;
1783 case 0x0800:
1784 case 0x0C00: definitionPin.numberOffsetJustification = 1; break;
1785 case 0x0D00: definitionPin.numberOffsetJustification = 8; break;
1786 case 0x0F00: definitionPin.numberOffsetJustification = 2; break;
1787 default:
1788 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "terminal number-offset presentation" ),
1789 visibilityFlags & 0x0F00, pinSource,
1790 aModel.diagnostics );
1791 break;
1792 }
1793
1794 definitionPin.visibilityFlags = ( visibilityFlags >> 8 ) & 0x00C0;
1795
1796 if( pinDecalHandle == 0xFFFF )
1797 {
1798 definitionPin.length = 0;
1799 }
1800 else if( pinDecalHandle >= aUsedDecals.size() )
1801 throwDecodeError( pinSource, wxS( "unresolved pin-decal handle" ) );
1802
1803 if( pinDecalHandle != 0xFFFF )
1804 {
1805 MODEL_SYMBOL_DEFINITION* pinDecal = aUsedDecals[pinDecalHandle].definition;
1806
1807 if( !pinDecal )
1808 {
1809 const size_t handleOffset = aLayout.usedDecalBase + pinDecalHandle * USED_DECAL_BYTES;
1810 const uint32_t definitionRecord = aCursor.U32At( handleOffset + 48 );
1811
1812 if( definitionRecord >= aDefinitionsByRecord.size() || !aDefinitionsByRecord[definitionRecord] )
1813 throwDecodeError( pinSource, wxS( "unresolved pin-decal handle" ) );
1814
1815 pinDecal = aDefinitionsByRecord[definitionRecord];
1816 }
1817
1818 const wxString pinDecalName = pinDecal->name.text;
1819 definitionPin.decalName = pinDecal->name;
1820
1821 int64_t provenLength = 0;
1822
1823 for( const MODEL_GRAPHIC& pinGraphic : pinDecal->graphics )
1824 {
1825 const bool containsOrigin = std::ranges::any_of( pinGraphic.points,
1826 []( const SOURCE_POINT& aPoint )
1827 {
1828 return aPoint.x == 0 && aPoint.y == 0;
1829 } );
1830
1831 if( !containsOrigin )
1832 continue;
1833
1834 for( const SOURCE_POINT& point : pinGraphic.points )
1835 provenLength =
1836 std::max( provenLength, std::max( std::abs( point.x ), std::abs( point.y ) ) );
1837 }
1838
1839 if( provenLength != 0 )
1840 definitionPin.length = provenLength;
1841 else
1842 {
1843 SOURCE_PROPERTY lengthProperty =
1844 sourceProperty( wxS( "pin_length" ), wxS( "unknown" ), pinSource );
1845 lengthProperty.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
1846 definitionPin.properties.push_back( std::move( lengthProperty ) );
1847 }
1848
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 );
1853 }
1854
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 ) );
1870
1871 // Keep the ASCII P-line positions; PADS draws nothing at them so their meaning is unknown
1872 for( int pair = 0; pair < 2; ++pair )
1873 {
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 ) ) ),
1879 pinSource ) );
1880 }
1881
1882 decal.definition->pins.push_back( std::move( definitionPin ) );
1883 }
1884 }
1885 }
1886
1887
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 )
1891 {
1892 std::vector<USED_DECAL*> fieldDecals;
1893
1894 std::ranges::copy_if( aSemanticDecals, std::back_inserter( fieldDecals ),
1895 [&]( const USED_DECAL* aDecal )
1896 {
1897 return aDecal->fieldStart < aLayout.textHeap.recordCount;
1898 } );
1899 std::ranges::sort( fieldDecals,
1900 []( const USED_DECAL* aLeft, const USED_DECAL* aRight )
1901 {
1902 return aLeft->fieldStart < aRight->fieldStart;
1903 } );
1904
1905 for( size_t i = 1; i < fieldDecals.size(); ++i )
1906 {
1907 if( fieldDecals[i - 1]->fieldStart != fieldDecals[i]->fieldStart )
1908 continue;
1909
1910 SOURCE_PROVENANCE first =
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 ) );
1918 throwDecodeError(
1919 duplicate,
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 ) ) );
1925 }
1926
1927 return fieldDecals;
1928 }
1929
1930
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 )
1934 {
1935 for( size_t record : aPageGraphicRecords )
1936 {
1937 const size_t offset = aLayout.symbolBase + record * SYMBOL_RECORD_BYTES;
1938 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "page graphic group" ), 3, record,
1939 offset, SYMBOL_RECORD_BYTES, static_cast<int>( aSheetIndex ) );
1940 SOURCE_PROVENANCE nameSource = source;
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;
1946
1947 if( textCountForGroup > aLayout.textHeap.recordCount
1948 || ( textCountForGroup != 0 && lastTextRecord >= aLayout.textHeap.recordCount ) )
1949 throwDecodeError( source, wxS( "page-text ownership leaves controller 1" ) );
1950
1951 MODEL_SYMBOL_DEFINITION textOwner;
1952 textOwner.source = source;
1953
1954 if( textCountForGroup != 0 )
1955 {
1956 std::vector<size_t> textRecords( textCountForGroup );
1957 std::vector<bool> visitedTextRecords( aLayout.textHeap.recordCount, false );
1958 size_t textRecord = lastTextRecord;
1959
1960 for( size_t reverseIndex = textCountForGroup; reverseIndex != 0; --reverseIndex )
1961 {
1962 if( textRecord >= aLayout.textHeap.recordCount )
1963 throwDecodeError( source, wxS( "page-text predecessor leaves controller 1" ) );
1964
1965 if( visitedTextRecords[textRecord] )
1966 throwDecodeError( source, wxS( "page-text predecessor repeats controller 1 record" ) );
1967
1968 visitedTextRecords[textRecord] = true;
1969
1970 textRecords[reverseIndex - 1] = textRecord;
1971
1972 if( reverseIndex != 1 )
1973 {
1974 const size_t predecessor =
1975 aCursor.U16At( aLayout.textHeap.recordBase + textRecord * TEXT_RECORD_BYTES + 24 );
1976
1977 if( predecessor >= aLayout.textHeap.recordCount )
1978 throwDecodeError( source, wxS( "page-text predecessor leaves controller 1" ) );
1979
1980 textRecord = predecessor;
1981 }
1982 }
1983
1984 for( size_t textRecordIndex : textRecords )
1985 decodeDefinitionTextRecord( aBytes, aCursor, aSourceName, aSheetIndex, aLayout.textHeap,
1986 textRecordIndex, TEXT_ROLE::PAGE_TEXT, textOwner, aModel );
1987 }
1988
1989 if( textOwner.graphics.size() != textCountForGroup )
1990 throwDecodeError( source, wxS( "page-text records do not exactly match declared count" ) );
1991
1992 for( MODEL_GRAPHIC& graphic : textOwner.graphics )
1993 {
1994 graphic.source.objectClass = wxS( "page text" );
1995 const SOURCE_POINT groupOrigin{ decodeCoordinate( aCursor.U16At( offset + 60 ) ),
1996 decodeCoordinate( aCursor.U16At( offset + 62 ) ), source };
1997
1998 for( SOURCE_POINT& point : graphic.points )
1999 {
2000 point.x += groupOrigin.x;
2001 point.y += groupOrigin.y;
2002 }
2003
2004 graphic.properties.push_back( sourceProperty( wxS( "page_graphic_group" ), groupName.text, source ) );
2005
2006 if( worksheetCandidate )
2007 graphic.properties.push_back( sourceProperty( wxS( "worksheet_group" ), groupName.text, source ) );
2008
2009 aModel.graphics.push_back(
2010 { graphic.source, { aModel.sheets[aSheetIndex].id, graphic.source }, std::move( graphic ) } );
2011 }
2012
2013 auto belongsToGroup = [&]( const MODEL_PAGE_GRAPHIC& aGraphic )
2014 {
2015 if( aGraphic.sheet.id != aModel.sheets[aSheetIndex].id )
2016 return false;
2017
2018 return std::ranges::any_of( aGraphic.graphic.properties,
2019 [&]( const SOURCE_PROPERTY& aProperty )
2020 {
2021 return aProperty.name.text == wxS( "page_graphic_group" )
2022 && aProperty.value.text == groupName.text;
2023 } );
2024 };
2025
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;
2033
2034 for( const MODEL_PAGE_GRAPHIC& pageGraphic : aModel.graphics )
2035 {
2036 if( !belongsToGroup( pageGraphic ) )
2037 continue;
2038
2039 if( pageGraphic.graphic.kind != MODEL_GRAPHIC_KIND::TEXT )
2040 {
2041 ++drawingGraphics;
2042 continue;
2043 }
2044
2045 ++textGraphics;
2046 wxString text = pageGraphic.graphic.text.text.Upper();
2047
2048 if( text.length() == 1 && text[0] >= '0' && text[0] <= '9' )
2049 ++numericEdgeMarkers;
2050
2051 if( text.length() == 1 && text[0] >= 'A' && text[0] <= 'Z' )
2052 ++alphabeticEdgeMarkers;
2053
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 " ) );
2059 }
2060
2061 const bool worksheet = drawingGraphics >= 30 && textGraphics >= 30 && numericEdgeMarkers >= 4
2062 && alphabeticEdgeMarkers >= 4 && hasTitleAnchor && hasSheetAnchor
2063 && hasRevisionAnchor;
2064
2065 if( worksheet )
2066 {
2067 MODEL_WORKSHEET modelWorksheet;
2068 modelWorksheet.source = source;
2069 modelWorksheet.sheet = { aModel.sheets[aSheetIndex].id, source };
2070 modelWorksheet.name = groupName;
2071
2072 for( auto graphic = aModel.graphics.begin(); graphic != aModel.graphics.end(); )
2073 {
2074 if( belongsToGroup( *graphic ) )
2075 {
2076 modelWorksheet.graphics.push_back( std::move( graphic->graphic ) );
2077 graphic = aModel.graphics.erase( graphic );
2078 }
2079 else
2080 {
2081 ++graphic;
2082 }
2083 }
2084
2085 auto existing = std::ranges::find_if( aModel.worksheets,
2086 [&]( const MODEL_WORKSHEET& aWorksheet )
2087 {
2088 return aWorksheet.sheet.id == modelWorksheet.sheet.id;
2089 } );
2090
2091 if( existing == aModel.worksheets.end() )
2092 {
2093 aModel.worksheets.push_back( std::move( modelWorksheet ) );
2094 }
2095 else if( !sameWorksheetValue( *existing, modelWorksheet ) )
2096 {
2097 SOURCE_PROPERTY distinct =
2098 sourceProperty( wxS( "distinct_worksheet_layout" ), groupName.text, source );
2099 distinct.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
2100 aModel.diagnostics.push_back( MakePropertyDiagnostic(
2101 RPT_SEVERITY_WARNING, distinct,
2102 wxS( "distinct worksheet layout preserved as schematic page graphics" ) ) );
2103
2104 for( MODEL_GRAPHIC& graphic : modelWorksheet.graphics )
2105 {
2106 graphic.properties.push_back( distinct );
2107 aModel.graphics.push_back( { graphic.source,
2108 { aModel.sheets[aSheetIndex].id, graphic.source },
2109 std::move( graphic ) } );
2110 }
2111 }
2112 }
2113 }
2114
2115 auto canonicalWorksheet = std::ranges::find_if( aModel.worksheets,
2116 []( const MODEL_WORKSHEET& aWorksheet )
2117 {
2118 return aWorksheet.name.text == wxS( "DRW5982" );
2119 } );
2120
2121 if( canonicalWorksheet != aModel.worksheets.end() )
2122 {
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;
2126
2127 for( const MODEL_GRAPHIC& graphic : canonicalWorksheet->graphics )
2128 {
2129 if( graphic.kind != MODEL_GRAPHIC_KIND::TEXT )
2130 canonicalGeometry.push_back( &graphic );
2131 }
2132
2133 for( const MODEL_PAGE_GRAPHIC& pageGraphic : aModel.graphics )
2134 {
2135 auto groupProperty = std::ranges::find_if( pageGraphic.graphic.properties,
2136 []( const SOURCE_PROPERTY& aProperty )
2137 {
2138 return aProperty.name.text == wxS( "worksheet_group" );
2139 } );
2140
2141 if( groupProperty != pageGraphic.graphic.properties.end()
2142 && pageGraphic.graphic.kind != MODEL_GRAPHIC_KIND::TEXT )
2143 {
2144 candidates[{ pageGraphic.sheet.id.Value(), groupProperty->value.text }].push_back(
2145 &pageGraphic.graphic );
2146 }
2147 }
2148
2149 std::set<GROUP_KEY> equivalentGroups;
2150
2151 for( const auto& [key, geometry] : candidates )
2152 {
2153 if( geometry.size() == canonicalGeometry.size()
2154 && std::ranges::equal( geometry, canonicalGeometry,
2155 [&]( const MODEL_GRAPHIC* aLeft, const MODEL_GRAPHIC* aRight )
2156 {
2157 return sameGraphicValue( *aLeft, *aRight );
2158 } ) )
2159 {
2160 equivalentGroups.insert( key );
2161 }
2162 }
2163
2164 std::erase_if( aModel.graphics,
2165 [&]( const MODEL_PAGE_GRAPHIC& aGraphic )
2166 {
2167 return std::ranges::any_of(
2168 aGraphic.graphic.properties,
2169 [&]( const SOURCE_PROPERTY& aProperty )
2170 {
2171 return aProperty.name.text == wxS( "worksheet_group" )
2172 && equivalentGroups.contains(
2173 { aGraphic.sheet.id.Value(), aProperty.value.text } );
2174 } );
2175 } );
2176 }
2177 }
2178
2179
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 )
2183 {
2184 for( size_t i = 0; i < aFieldDecals.size(); ++i )
2185 {
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;
2191
2192 if( decal.fieldStart > fieldEnd )
2193 throwDecodeError( decal.definition->source, wxS( "definition field slice is not monotone" ) );
2194
2195 if( decal.definition->fields.empty() )
2196 {
2197 for( size_t standard = 0; standard < 2; ++standard )
2198 {
2199 const size_t usedOffset = aLayout.usedDecalBase + decal.record * USED_DECAL_BYTES;
2200 SOURCE_PROVENANCE fieldSource =
2201 sourceAt( aSourceName, aModel.version, wxS( "standard definition field" ), 7, decal.record,
2202 usedOffset + 60 + standard * 8, 8, static_cast<int>( aSheetIndex ) );
2203 MODEL_FIELD field;
2204 field.source = fieldSource;
2205 field.name = { {},
2206 standard == 0 ? wxS( "REF-DES" ) : wxS( "PART-TYPE" ),
2208 fieldSource };
2209 field.position = { decodeLocalCoordinate( aCursor.U16At( usedOffset + 60 + standard * 8 ) ),
2210 decodeLocalCoordinate( aCursor.U16At( usedOffset + 62 + standard * 8 ) ),
2211 fieldSource };
2212 field.angle = NormalizeAngle( aCursor.U16At( usedOffset + 64 + 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 ) );
2216 SOURCE_PROVENANCE fontSource = fieldSource;
2217 fontSource.absoluteOffset = usedOffset + 100 + standard * 2;
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 ) );
2227 }
2228 }
2229
2230 if( embeddedCount != 0 )
2231 {
2232 const uint16_t lastEmbeddedRecord = aCursor.U16At( definitionOffset + 0x42 );
2233
2234 if( embeddedCount > aLayout.textHeap.recordCount || lastEmbeddedRecord >= aLayout.textHeap.recordCount )
2235 throwDecodeError( decal.definition->source,
2236 wxS( "embedded definition text ownership leaves controller 1" ) );
2237
2238 const size_t firstEmbeddedRecord =
2239 ( static_cast<size_t>( lastEmbeddedRecord ) + aLayout.textHeap.recordCount + 1 - embeddedCount )
2240 % aLayout.textHeap.recordCount;
2241
2242 for( size_t textIndex = 0; textIndex < embeddedCount; ++textIndex )
2243 {
2244 decodeDefinitionTextRecord( aBytes, aCursor, aSourceName, aSheetIndex, aLayout.textHeap,
2245 ( firstEmbeddedRecord + textIndex ) % aLayout.textHeap.recordCount,
2246 TEXT_ROLE::EMBEDDED_SYMBOL_TEXT, *decal.definition, aModel );
2247 }
2248 }
2249
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 );
2253 }
2254 }
2255
2256
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,
2260 PADS_SCH_MODEL& aModel )
2261 {
2262 size_t signalPinCursor = 0;
2263
2264 for( size_t record = 0; record < aControllers.pools[8].count; ++record )
2265 {
2266 const size_t offset = aLayout.partBase + record * PART_TYPE_BYTES;
2267 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "part type" ), 9, record, offset,
2268 PART_TYPE_BYTES, static_cast<int>( aSheetIndex ) );
2269 SOURCE_PROVENANCE nameSource = source;
2270 nameSource.length = 44;
2271 MODEL_PART_TYPE part;
2272 part.id = PART_TYPE_ID( aLayout.partIdBase + record );
2273 part.source = source;
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;
2283
2284 if( gateStart > gateEnd || gateEnd > aControllers.pools[9].count || pinStart > pinEnd
2285 || pinEnd > aControllers.pools[10].count )
2286 {
2287 throwDecodeError( source, wxS( "part-type gate or pin slice leaves its controller" ) );
2288 }
2289
2290 if( aCursor.U16At( offset + 68 ) != gateEnd - gateStart )
2291 throwDecodeError( source, wxS( "stored gate count does not match controller-10 slice" ) );
2292
2293 size_t partPinCursor = pinStart;
2294 uint32_t unitCursor = 0;
2295 const uint32_t pinNameHeapBase = aCursor.U32At( offset + 60 );
2296
2297 if( pinNameHeapBase > aLayout.pinNameBytes )
2298 throwDecodeError( source, wxS( "part-type pin-name base leaves controller 14" ) );
2299
2300 auto decodePartPin = [&]( MODEL_PIN_DEFINITION& aDefinitionPin, size_t aPinRecord, MODEL_GATE& aGate )
2301 {
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 ) );
2305 SOURCE_PROVENANCE numberSource = pinSource;
2306 numberSource.absoluteOffset += 4;
2307 numberSource.length = 16;
2308 aDefinitionPin.number =
2309 decodeFixedString( aBytes, pinOffset + 4, 16, numberSource, aModel.diagnostics );
2310 const uint32_t nameOffset = aCursor.U32At( pinOffset );
2311
2312 if( nameOffset != 0xFFFFFFFF )
2313 {
2314 if( nameOffset >= aLayout.pinNameBytes - pinNameHeapBase )
2315 throwDecodeError( pinSource, wxS( "pin-name offset leaves controller 14" ) );
2316
2317 SOURCE_PROVENANCE pinNameSource = sourceAt(
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 );
2324 }
2325
2326 aDefinitionPin.electricalType =
2327 pinElectricalType( aCursor.U8At( pinOffset + 21 ), pinSource, aModel.diagnostics );
2328 MODEL_GATE_PIN logicalPin;
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 ) );
2341 };
2342
2343 auto decodeConnectorPin = [&]( size_t aPinRecord )
2344 {
2345 const size_t pinOffset = aLayout.pinBase + aPinRecord * PIN_BYTES;
2346 SOURCE_PROVENANCE pinSource =
2347 sourceAt( aSourceName, aModel.version, wxS( "connector logical pin" ), 11, aPinRecord,
2348 pinOffset, PIN_BYTES, static_cast<int>( aSheetIndex ) );
2349 SOURCE_PROVENANCE numberSource = pinSource;
2350 numberSource.absoluteOffset += 4;
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 );
2356
2357 if( nameOffset != 0xFFFFFFFF )
2358 {
2359 if( nameOffset >= aLayout.pinNameBytes - pinNameHeapBase )
2360 throwDecodeError( pinSource, wxS( "pin-name offset leaves controller 14" ) );
2361
2362 SOURCE_PROVENANCE pinNameSource = sourceAt(
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 );
2369 }
2370
2371 pin.swapGroup = aCursor.U8At( pinOffset + 20 );
2372 pin.electricalType = pinElectricalType( aCursor.U8At( pinOffset + 21 ), pinSource, aModel.diagnostics );
2373 pin.flags = aCursor.U16At( pinOffset + 22 );
2374 return pin;
2375 };
2376
2377 for( size_t gateRecord = gateStart; gateRecord < gateEnd; ++gateRecord )
2378 {
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 ) );
2382 MODEL_GATE gate;
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 );
2388
2389 if( pinCount == 0 )
2390 continue;
2391
2392 gate.unit = ++unitCursor;
2393
2394 if( primaryHandle == 0xFFFF || primaryHandle >= aUsedDecals.size()
2395 || !aUsedDecals[primaryHandle].definition )
2396 {
2397 bool pinDecalGroup = primaryHandle == 0xFFFF && gateRecord + 1 < gateEnd;
2398
2399 for( size_t member = gateRecord + 1; pinDecalGroup && member < gateEnd; ++member )
2400 {
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;
2405 }
2406
2407 if( !pinDecalGroup || partPinCursor + pinCount > pinEnd )
2408 throwDecodeError( gateSource, wxS( "unresolved symbol definition reference" ) );
2409
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 ) );
2414
2415 for( size_t member = gateRecord + 1; member < gateEnd; ++member )
2416 {
2417 const size_t memberOffset = aLayout.gateBase + member * GATE_BYTES;
2418 const uint16_t memberHandle = aCursor.U16At( memberOffset );
2419
2420 if( aCursor.U16At( memberOffset + 8 ) != 0 )
2421 break;
2422
2423 SOURCE_PROVENANCE memberSource =
2424 sourceAt( aSourceName, aModel.version, wxS( "pin-decal group member" ), 10, member,
2425 memberOffset, GATE_BYTES, static_cast<int>( aSheetIndex ) );
2426
2427 if( memberHandle >= aUsedDecals.size() || !aUsedDecals[memberHandle].definition )
2428 throwDecodeError( memberSource, wxS( "unresolved pin-decal group member" ) );
2429
2430 gate.decalGroupMembers.push_back( { aUsedDecals[memberHandle].definition->id, memberSource } );
2431 }
2432
2433 for( size_t pin = 0; pin < pinCount; ++pin, ++partPinCursor )
2434 gate.connectorPins.push_back( decodeConnectorPin( partPinCursor ) );
2435
2436 part.gates.push_back( std::move( gate ) );
2437 continue;
2438 }
2439
2440 MODEL_SYMBOL_DEFINITION* definition = aUsedDecals[primaryHandle].definition;
2441 gate.definition = { definition->id, gateSource };
2442 gate.properties.push_back(
2443 sourceProperty( wxS( "swap_group" ), wxString::Format( wxS( "%u" ), swapGroup ), gateSource ) );
2444
2445 for( size_t alternate = 1; alternate < 4; ++alternate )
2446 {
2447 const uint16_t handle = aCursor.U16At( gateOffset + alternate * 2 );
2448
2449 if( handle == 0xFFFF )
2450 continue;
2451
2452 if( handle >= aUsedDecals.size() || !aUsedDecals[handle].definition )
2453 throwDecodeError( gateSource, wxS( "unresolved alternate symbol definition reference" ) );
2454
2455 gate.alternateDefinitions.push_back( { aUsedDecals[handle].definition->id, gateSource } );
2456 }
2457
2458 if( partPinCursor + pinCount > pinEnd || pinCount > definition->pins.size() )
2459 throwDecodeError( gateSource, wxS( "gate pin slice leaves part type or symbol definition" ) );
2460
2461 for( size_t pin = 0; pin < pinCount; ++pin, ++partPinCursor )
2462 {
2463 MODEL_PIN_DEFINITION& definitionPin = definition->pins[pin];
2464 decodePartPin( definitionPin, partPinCursor, gate );
2465 }
2466
2467 part.gates.push_back( std::move( gate ) );
2468 }
2469
2470 if( partPinCursor != pinEnd )
2471 throwDecodeError( source, wxS( "part-type gates do not consume its pin slice" ) );
2472
2473 if( !part.gates.empty() && part.gates.front().definition.id.IsValid() )
2474 {
2475 auto defaultDefinition =
2476 std::ranges::find_if( aModel.definitions,
2477 [&]( const MODEL_SYMBOL_DEFINITION& aDefinition )
2478 {
2479 return aDefinition.id == part.gates.front().definition.id;
2480 } );
2481
2482 if( defaultDefinition == aModel.definitions.end() )
2483 throwDecodeError( source, wxS( "unresolved part-type default definition" ) );
2484
2485 part.fields = defaultDefinition->fields;
2486 }
2487
2488 const uint16_t signalPinCount = aCursor.U16At( offset + 70 );
2489
2490 if( signalPinCursor + signalPinCount > aControllers.pools[11].count )
2491 throwDecodeError( source, wxS( "part-type signal-pin slice leaves controller 12" ) );
2492
2493 for( size_t signal = 0; signal < signalPinCount; ++signal, ++signalPinCursor )
2494 {
2495 const size_t signalOffset = aLayout.signalPinBase + signalPinCursor * SIGNAL_PIN_BYTES;
2496 SOURCE_PROVENANCE signalSource =
2497 sourceAt( aSourceName, aModel.version, wxS( "signal pin" ), 12, signalPinCursor, signalOffset,
2498 SIGNAL_PIN_BYTES, static_cast<int>( aSheetIndex ) );
2499 SOURCE_PROVENANCE numberSource = signalSource;
2500 numberSource.length = 16;
2501 SOURCE_PROVENANCE nameSource2 = signalSource;
2502 nameSource2.absoluteOffset += 16;
2503 nameSource2.length = 48;
2504 SOURCE_STRING number = decodeFixedString( aBytes, signalOffset, 16, numberSource, aModel.diagnostics );
2505 SOURCE_STRING signalName =
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 ) );
2510 }
2511
2512 aModel.partTypes.push_back( std::move( part ) );
2513 }
2514
2515 if( signalPinCursor != aControllers.pools[11].count )
2516 {
2517 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "signal pin" ), 12, signalPinCursor,
2518 aLayout.signalPinBase, aControllers.pools[11].usedBytes,
2519 static_cast<int>( aSheetIndex ) );
2520 throwDecodeError( source, wxS( "unowned signal-pin record" ) );
2521 }
2522 }
2523
2524
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,
2527 PADS_SCH_MODEL& aModel )
2528 {
2529 const SHEET_CONTROLLERS controllers = sheetControllers( aCursor, aBlock );
2530
2531 if( aModel.version == 0x000C )
2532 {
2533 preserveRawDefinitionControllers( aBytes, controllers, aSheetIndex, aSourceName, aModel );
2534 return;
2535 }
2536
2537 const DEFINITION_LAYOUT layout =
2538 definitionLayout( aCursor, controllers, aSheetIndex, aSourceName, aModel.version );
2539
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;
2544
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 );
2549
2550 const std::vector<USED_DECAL*> fieldDecals =
2551 buildFieldDecals( semanticDecals, layout, aSheetIndex, aSourceName, aModel.version );
2552
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 );
2556 }
2557
2558
2559 struct PLACEMENT_DECODE
2560 {
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;
2567 size_t sheetIndex;
2568 };
2569
2570
2571 struct PLACEMENT_TARGET
2572 {
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;
2582 };
2583
2584
2585 struct INLINE_FIELD_LAYOUT
2586 {
2587 size_t position;
2588 size_t angle;
2589 size_t font;
2590 size_t height;
2591 size_t width;
2592 };
2593
2594
2595 std::pair<SOURCE_STRING, SOURCE_STRING> decodePlacementAttribute( const PLACEMENT_DECODE& aDecode,
2596 uint32_t aOffsetIndex, bool aRequireValue,
2597 PADS_SCH_MODEL& aModel )
2598 {
2599 if( aOffsetIndex >= aDecode.globals.attributeOffsetCount )
2600 {
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" ) );
2605 }
2606
2607 const size_t offsetRecord = aDecode.globals.attributeOffsetBase + aOffsetIndex * ATTRIBUTE_OFFSET_BYTES;
2608 const uint32_t heapOffset = aDecode.cursor.U32At( offsetRecord );
2609 SOURCE_PROVENANCE source = sourceAt( aDecode.sourceName, aModel.version, wxS( "placement attribute" ), 2,
2610 aOffsetIndex, aDecode.globals.attributeHeapBase + heapOffset, 0, -1 );
2611
2612 if( heapOffset >= aDecode.globals.attributeHeapBytes )
2613 throwDecodeError( source, wxS( "attribute string offset leaves outer controller 2" ) );
2614
2615 size_t end = source.absoluteOffset;
2616 const size_t heapEnd = aDecode.globals.attributeHeapBase + aDecode.globals.attributeHeapBytes;
2617
2618 while( end < heapEnd && aDecode.bytes[end] != 0 )
2619 ++end;
2620
2621 if( end == heapEnd )
2622 throwDecodeError( source, wxS( "placement attribute is not NUL terminated" ) );
2623
2624 source.length = end - source.absoluteOffset;
2625 size_t separator = source.absoluteOffset;
2626
2627 while( separator < end && aDecode.bytes[separator] != 1 )
2628 ++separator;
2629
2630 if( aRequireValue && separator == end )
2631 throwDecodeError( source, wxS( "placement attribute lacks key/value separator" ) );
2632
2634 { aDecode.bytes.begin() + source.absoluteOffset, aDecode.bytes.begin() + separator }, DEFAULT_CODE_PAGE,
2635 source, aModel.diagnostics );
2636 SOURCE_STRING value;
2637
2638 if( separator != end )
2639 {
2640 SOURCE_PROVENANCE valueSource = source;
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 );
2646 }
2647
2648 return std::pair<SOURCE_STRING, SOURCE_STRING>{ std::move( name ), std::move( value ) };
2649 }
2650
2651
2652 PLACEMENT_TARGET resolvePlacementTarget( const PLACEMENT_DECODE& aDecode, size_t aOffset,
2653 const SOURCE_PROVENANCE& aSource, PADS_SCH_MODEL& aModel )
2654 {
2655 PLACEMENT_TARGET target;
2656 target.componentIdentity = aDecode.cursor.U32At( aOffset + aDecode.layout.componentIdentity );
2657
2658 const uint16_t partHandle = aDecode.cursor.U16At( aOffset + aDecode.layout.partType );
2659 auto part = std::ranges::find_if( aModel.partTypes,
2660 [&]( const MODEL_PART_TYPE& aPart )
2661 {
2662 return aPart.source.sheet == static_cast<int>( aDecode.sheetIndex )
2663 && aPart.source.recordIndex == partHandle;
2664 } );
2665
2666 if( part == aModel.partTypes.end() )
2667 {
2668 const bool definitionClass =
2669 std::ranges::any_of( aModel.definitions,
2670 [&]( const MODEL_SYMBOL_DEFINITION& aDefinition )
2671 {
2672 return aDefinition.source.sheet == static_cast<int>( aDecode.sheetIndex )
2673 && aDefinition.source.recordIndex == partHandle;
2674 } );
2675 throwDecodeError( aSource, definitionClass
2676 ? wxS( "placement part-type handle targets definition object class" )
2677 : wxS( "unresolved placement part-type reference" ) );
2678 }
2679
2680 const uint32_t groupHandle = aDecode.cursor.U32At( aOffset + aDecode.layout.componentGroup );
2681
2682 if( groupHandle >= aDecode.globals.groupCount )
2683 throwDecodeError( aSource, wxS( "placement component-group handle leaves outer controller 6" ) );
2684
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 );
2688
2689 if( attributeCount < 2 || attributeStart > aDecode.globals.attributeOffsetCount
2690 || attributeCount > aDecode.globals.attributeOffsetCount - attributeStart )
2691 {
2692 throwDecodeError( aSource, wxS( "placement component-group attribute slice leaves controller 7" ) );
2693 }
2694
2695 auto [groupPartName, unusedGroupPartValue] =
2696 decodePlacementAttribute( aDecode, attributeStart + 1, false, aModel );
2697
2698 if( groupPartName.text != part->name.text )
2699 throwDecodeError( aSource, wxS( "placement component-group targets wrong part-type object class" ) );
2700
2701 const uint16_t decalHandle = aDecode.cursor.U16At( aOffset + aDecode.layout.decal );
2702
2703 if( decalHandle >= aDecode.controllers.pools[6].count )
2704 throwDecodeError( aSource, wxS( "unresolved placement decal reference" ) );
2705
2706 const size_t decalOffset = aDecode.controllers.offsets[6] + decalHandle * USED_DECAL_BYTES;
2707 const uint32_t definitionHandle = aDecode.cursor.U32At( decalOffset + 48 );
2708 auto definition =
2709 std::ranges::find_if( aModel.definitions,
2710 [&]( const MODEL_SYMBOL_DEFINITION& aDefinition )
2711 {
2712 return aDefinition.source.sheet == static_cast<int>( aDecode.sheetIndex )
2713 && aDefinition.source.recordIndex == definitionHandle;
2714 } );
2715
2716 if( definition == aModel.definitions.end() )
2717 throwDecodeError( aSource, wxS( "placement decal targets wrong definition object class" ) );
2718
2719 const uint16_t unitIndex = aDecode.cursor.U16At( aOffset + aDecode.layout.gate );
2720
2721 const MODEL_GATE* gate = nullptr;
2722
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() )
2728 gate = nullptr;
2729 else
2730 {
2731 const bool definitionClass =
2732 std::ranges::any_of( aModel.definitions,
2733 [&]( const MODEL_SYMBOL_DEFINITION& aDefinition )
2734 {
2735 return aDefinition.source.sheet == static_cast<int>( aDecode.sheetIndex )
2736 && aDefinition.source.recordIndex == unitIndex;
2737 } );
2738 throwDecodeError( aSource, definitionClass ? wxS( "placement gate handle targets definition object class" )
2739 : wxS( "unresolved placement gate reference" ) );
2740 }
2741
2742 auto gateHasDefinition = [&]( const DEFINITION_REFERENCE& aReference )
2743 {
2744 return aReference.id == definition->id;
2745 };
2746
2747 if( gate && !gateHasDefinition( gate->definition )
2748 && std::ranges::none_of( gate->alternateDefinitions, gateHasDefinition )
2749 && std::ranges::none_of( gate->decalGroupMembers, gateHasDefinition ) )
2750 {
2751 throwDecodeError( aSource, wxS( "placement decal and gate reference target different object classes" ) );
2752 }
2753
2754 target.part = &*part;
2755 target.definition = &*definition;
2756 target.gate = gate;
2757 target.groupHandle = groupHandle;
2758 target.attributeStart = attributeStart;
2759 target.attributeCount = attributeCount;
2760 target.decalHandle = decalHandle;
2761 target.unitIndex = unitIndex;
2762 return target;
2763 }
2764
2765
2766 void decodePlacedPins( const PLACEMENT_DECODE& aDecode, uint32_t aPinStart, uint16_t aPinCount,
2767 const MODEL_SYMBOL_DEFINITION& aDefinition, MODEL_PLACEMENT& aPlacement,
2768 PADS_SCH_MODEL& aModel )
2769 {
2770 const size_t placedPinBase = aDecode.controllers.offsets[15];
2771
2772 for( size_t pin = 0; pin < aPinCount; ++pin )
2773 {
2774 const size_t pinOffset = placedPinBase + ( aPinStart + pin ) * aDecode.layout.placedPinBytes;
2775 SOURCE_PROVENANCE pinSource =
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 );
2779
2780 if( pinOrdinal >= aDefinition.pins.size() || pinOrdinal != pin )
2781 throwDecodeError( pinSource, wxS( "placed-pin handle leaves placement definition" ) );
2782
2783 PLACED_PIN_REFERENCE pinReference{ aDefinition.pins[pinOrdinal].id, pinSource };
2784 pinReference.numberOffset = {
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
2787 };
2788 pinReference.numberPresentationFlags = aDecode.cursor.U16At( pinOffset + 10 );
2789 pinReference.numberAngle = ( pinReference.numberPresentationFlags & 0x0001 ) != 0 ? 900 : 0;
2790
2791 pinReference.numberJustification = terminalJustification(
2792 ( pinReference.numberPresentationFlags >> 4 ) & 0x0F, pinReference.numberAngle != 0 );
2793
2794 pinReference.hasNumberPlacement = true;
2795 aPlacement.pins.push_back( std::move( pinReference ) );
2796 }
2797 }
2798
2799
2800 void decodeInlineField( const PLACEMENT_DECODE& aDecode, size_t aOffset, const SOURCE_PROVENANCE& aSource,
2801 const wxString& aName, const SOURCE_STRING& aValue, bool aVisible,
2802 const INLINE_FIELD_LAYOUT& aFieldLayout, MODEL_PLACEMENT& aPlacement,
2803 PADS_SCH_MODEL& aModel )
2804 {
2805 SOURCE_PROVENANCE fieldSource = aSource;
2806 fieldSource.objectClass = wxS( "placement field" );
2807 fieldSource.absoluteOffset += aFieldLayout.position;
2808 fieldSource.length = 8;
2809 MODEL_FIELD field;
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 ) ),
2816 fieldSource };
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 );
2827 SOURCE_PROVENANCE fontSource = fieldSource;
2828 fontSource.absoluteOffset = aOffset + aFieldLayout.font;
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 ) );
2834 }
2835
2836
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,
2839 PADS_SCH_MODEL& aModel )
2840 {
2841 const size_t fieldBase = aDecode.controllers.offsets[16];
2842
2843 const uint16_t customFieldCount = aDecode.cursor.U16At( aOffset + aDecode.layout.fieldCount );
2844
2845 if( aFieldCursor > aDecode.controllers.pools[16].count
2846 || customFieldCount > aDecode.controllers.pools[16].count - aFieldCursor )
2847 {
2848 throwDecodeError( aSource, wxS( "placement field ownership does not match controller 17" ) );
2849 }
2850
2851 for( size_t fieldOrdinal = 0; fieldOrdinal < customFieldCount; ++fieldOrdinal )
2852 {
2853 const size_t fieldOffset = fieldBase + aFieldCursor * aDecode.layout.fieldBytes;
2854 SOURCE_PROVENANCE fieldSource =
2855 sourceAt( aDecode.sourceName, aModel.version, wxS( "placement field" ), 17, aFieldCursor,
2856 fieldOffset, aDecode.layout.fieldBytes, static_cast<int>( aDecode.sheetIndex ) );
2858 SOURCE_STRING value;
2859
2860 const uint8_t displayFlags = aDecode.cursor.U8At( fieldOffset + aDecode.layout.customDisplayFlags );
2861 const uint16_t attributeIndex = aDecode.cursor.U16At( fieldOffset + aDecode.layout.customAttributeIndex );
2862
2863 if( attributeIndex == 0xFFFF )
2864 {
2865 name.text = wxS( "*" );
2866 name.source = fieldSource;
2867 value.source = fieldSource;
2868 }
2869 else
2870 {
2871 if( attributeIndex >= aTarget.attributeCount )
2872 throwDecodeError( fieldSource, wxS( "placement field attribute index leaves component group" ) );
2873
2874 std::tie( name, value ) =
2875 decodePlacementAttribute( aDecode, aTarget.attributeStart + attributeIndex, true, aModel );
2876 }
2877 MODEL_FIELD field;
2878 field.source = fieldSource;
2879 field.name = std::move( name );
2880 field.value = std::move( value );
2881 field.position = {
2882 decodeLocalCoordinate( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customX ) ),
2883 decodeLocalCoordinate( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customX + 2 ) ), fieldSource
2884 };
2885 field.angle = NormalizeAngle( aDecode.cursor.U16At( fieldOffset + aDecode.layout.customAngle ) );
2886
2887 if( field.angle % 900 != 0 )
2888 throwDecodeError( fieldSource, wxS( "unsupported placement-field rotation" ) );
2889
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;
2899
2900 SOURCE_PROVENANCE fontSource = fieldSource;
2901 fontSource.length = 2;
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 ) );
2907 SOURCE_PROVENANCE attributeIndexSource = 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 ) );
2915 SOURCE_PROPERTY preservedTail = sourceProperty(
2916 wxS( "preserved_field_tail" ),
2917 wxString::Format( wxS( "%u" ), aDecode.cursor.U16At( fieldOffset + aDecode.layout.customTail ) ),
2918 fieldSource );
2919 preservedTail.disposition = PROPERTY_DISPOSITION::PRESERVED;
2920 field.properties.push_back( std::move( preservedTail ) );
2921 aPlacement.fields.push_back( std::move( field ) );
2922 ++aFieldCursor;
2923 }
2924 }
2925
2926
2927 void decodeGroupAttributeFields( const PLACEMENT_DECODE& aDecode, const PLACEMENT_TARGET& aTarget,
2928 MODEL_PLACEMENT& aPlacement, PADS_SCH_MODEL& aModel )
2929 {
2930 for( uint16_t attributeIndex = 2; attributeIndex < aTarget.attributeCount; ++attributeIndex )
2931 {
2932 auto [name, value] =
2933 decodePlacementAttribute( aDecode, aTarget.attributeStart + attributeIndex, true, aModel );
2934
2935 if( name.text.CmpNoCase( wxS( "PCB DECAL" ) ) == 0
2936 || std::ranges::any_of( aPlacement.fields,
2937 [&]( const MODEL_FIELD& aField )
2938 {
2939 return aField.name.text.CmpNoCase( name.text ) == 0;
2940 } ) )
2941 {
2942 continue;
2943 }
2944
2945 MODEL_FIELD field;
2946 field.source = name.source;
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 ) );
2953 }
2954 }
2955
2956
2957 void recordPlacementProperties( const PLACEMENT_DECODE& aDecode, const SOURCE_PROVENANCE& aSource,
2958 const PLACEMENT_TARGET& aTarget, uint16_t aRawAngle, MODEL_PLACEMENT& aPlacement )
2959 {
2960 SOURCE_PROVENANCE rawAngleSource = aSource;
2961 rawAngleSource.absoluteOffset += aDecode.layout.angle;
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 ) );
2971 SOURCE_PROVENANCE rawMirrorSource = aSource;
2972 rawMirrorSource.absoluteOffset += aDecode.layout.mirror;
2973 rawMirrorSource.length = 2;
2974 aPlacement.properties.push_back( sourceProperty(
2975 wxS( "raw_mirror" ), wxString::Format( wxS( "%u" ), aPlacement.mirrorFlags ), rawMirrorSource ) );
2976 SOURCE_PROVENANCE visibilitySource = aSource;
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 ) );
2982 }
2983
2984
2985 void decodePlacementRecord( const PLACEMENT_DECODE& aDecode, size_t aRecord, uint32_t& aExpectedPinStart,
2986 uint32_t& aFieldCursor, PADS_SCH_MODEL& aModel )
2987 {
2988 const PLACEMENT_LAYOUT& layout = aDecode.layout;
2989 const size_t offset = aDecode.controllers.offsets[14] + aRecord * layout.placementBytes;
2990
2991 SOURCE_PROVENANCE source = sourceAt( aDecode.sourceName, aModel.version, wxS( "placement" ), 15, aRecord,
2992 offset, layout.placementBytes, static_cast<int>( aDecode.sheetIndex ) );
2993
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 );
2997
2998 if( pinStart != aExpectedPinStart || pinStart > aDecode.controllers.pools[15].count
2999 || pinCount > aDecode.controllers.pools[15].count - pinStart || pinCount != target.definition->pins.size() )
3000 {
3001 throwDecodeError( source, wxS( "placement pin ownership does not match controller 16" ) );
3002 }
3003
3004 MODEL_PLACEMENT placement;
3005
3006 if( aDecode.sheetIndex >= 0x0FFF || aRecord >= 0x100000 )
3007 throwDecodeError( source, wxS( "placement identity exceeds sheet/controller namespace" ) );
3008
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 };
3013
3014 if( target.gate )
3015 placement.gate = GATE_REFERENCE{ target.gate->id, source };
3016
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 );
3022 placement.angle = NormalizeAngle( rawAngle );
3023 placement.mirrorFlags = aDecode.cursor.U16At( offset + layout.mirror );
3024
3025 auto recordTransformEnum = [&]( size_t aFieldOffset )
3026 {
3027 SOURCE_PROVENANCE enumSource = source;
3028 enumSource.absoluteOffset += aFieldOffset;
3029 enumSource.length = 2;
3030 aModel.diagnostics.push_back(
3031 { RPT_SEVERITY_WARNING, enumSource, wxS( "unknown placement transform enum preserved" ) } );
3032 };
3033
3034 const bool knownAngle = rawAngle == 0 || rawAngle == 900 || rawAngle == 1800 || rawAngle == 2700;
3035
3036 if( !knownAngle )
3037 recordTransformEnum( layout.angle );
3038
3039 const bool knownMirror = placement.mirrorFlags <= 3;
3040
3041 if( !knownMirror )
3042 recordTransformEnum( layout.mirror );
3043
3044 placement.mirrored = placement.mirrorFlags != 0;
3045 SOURCE_PROVENANCE referenceSource = source;
3046 referenceSource.absoluteOffset += layout.reference;
3047 referenceSource.length = 40;
3048 placement.reference =
3049 decodeFixedString( aDecode.bytes, offset + layout.reference, 40, referenceSource, aModel.diagnostics );
3050
3051 decodePlacedPins( aDecode, pinStart, pinCount, *target.definition, placement, aModel );
3052 aExpectedPinStart += pinCount;
3053
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;
3059
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 ) );
3072 }
3073
3074
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,
3077 const PLACEMENT_GLOBALS& aGlobals, PADS_SCH_MODEL& aModel )
3078 {
3079 const PLACEMENT_LAYOUT& layout = placementLayout( aModel.version );
3080
3081 if( !layout.decoded )
3082 throwDecodeError( aModel.source, wxS( "placement decoder selected for raw-preserved version" ) );
3083
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 );
3088
3089 const PLACEMENT_DECODE decode{ aBytes, aCursor, controllers, layout, aGlobals, aSourceName, aSheetIndex };
3090 uint32_t expectedPinStart = 0;
3091 uint32_t fieldCursor = 0;
3092
3093 for( size_t record = 0; record < controllers.pools[14].count; ++record )
3094 decodePlacementRecord( decode, record, expectedPinStart, fieldCursor, aModel );
3095
3096 if( expectedPinStart != controllers.pools[15].count )
3097 {
3098 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "placed pin" ), 16, expectedPinStart,
3099 controllers.offsets[15], controllers.pools[15].usedBytes,
3100 static_cast<int>( aSheetIndex ) );
3101 throwDecodeError( source, wxS( "unowned placed-pin record" ) );
3102 }
3103
3104 if( fieldCursor != controllers.pools[16].count )
3105 {
3106 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "placement field" ), 17, fieldCursor,
3107 controllers.offsets[16], controllers.pools[16].usedBytes,
3108 static_cast<int>( aSheetIndex ) );
3109 throwDecodeError( source, wxS( "unowned placement-field record" ) );
3110 }
3111 }
3112
3113
3114 struct CONNECTIVITY_DECODE
3115 {
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;
3121 size_t sheetIndex;
3122 size_t busBase;
3123 size_t junctionBase;
3124 size_t offpageBase;
3125 size_t connectionBase;
3126 size_t vertexBase;
3127 size_t netNameBase;
3128 };
3129
3130
3131 struct VERTEX_TILING
3132 {
3133 std::vector<uint32_t> starts;
3134 std::vector<uint32_t> ends;
3135 };
3136
3137
3138 struct SHEET_CONNECTIVITY
3139 {
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;
3145 };
3146
3147
3148 std::pair<int64_t, int64_t> transformedPinPosition( const MODEL_PLACEMENT& aPlacement,
3149 const MODEL_PIN_DEFINITION& aPin )
3150 {
3151 int64_t x = aPin.position.x;
3152 int64_t y = aPin.position.y;
3153
3154 switch( NormalizeAngle( aPlacement.angle ) )
3155 {
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;
3159 default: break;
3160 }
3161
3162 if( aPlacement.mirrorFlags & 1 )
3163 x = -x;
3164
3165 if( aPlacement.mirrorFlags & 2 )
3166 y = -y;
3167
3168 return std::pair{ aPlacement.position.x + x, aPlacement.position.y + y };
3169 }
3170
3171
3172 SOURCE_POINT offpagePosition( const CONNECTIVITY_DECODE& aDecode, size_t aRecord, uint16_t aVersion )
3173 {
3174 const size_t offset = aDecode.offpageBase + aRecord * OFFPAGE_RECORD_BYTES;
3175 SOURCE_PROVENANCE source = sourceAt( aDecode.sourceName, aVersion, wxS( "off-page reference" ), 20, aRecord,
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 };
3179 }
3180
3181
3182 SOURCE_POINT junctionPosition( const CONNECTIVITY_DECODE& aDecode, size_t aRecord, uint16_t aVersion )
3183 {
3184 const size_t offset = aDecode.junctionBase + aRecord * JUNCTION_RECORD_BYTES;
3185 SOURCE_PROVENANCE source = sourceAt( aDecode.sourceName, aVersion, wxS( "junction" ), 19, aRecord, offset,
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 };
3189 }
3190
3191
3192 std::unordered_set<uint32_t> decodeBusGlobalRecords( const CONNECTIVITY_DECODE& aDecode, PADS_SCH_MODEL& aModel )
3193 {
3194 std::unordered_set<uint32_t> busGlobalRecords;
3195
3196 for( size_t record = 0; record < aDecode.controllers.pools[17].count; ++record )
3197 {
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
3201 : 0;
3202
3203 if( globalRecord >= aDecode.globals.nets.size() || aDecode.globals.nets[globalRecord].tombstone
3204 || ( netKind != 1 && netKind != 5 ) )
3205 {
3206 SOURCE_PROVENANCE source = sourceAt( aDecode.sourceName, aModel.version, wxS( "bus" ), 18, record,
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" ) );
3210 }
3211
3212 busGlobalRecords.insert( globalRecord );
3213 }
3214
3215 return busGlobalRecords;
3216 }
3217
3218
3219 std::vector<MODEL_NET*> materializeSheetNets( const CONNECTIVITY_DECODE& aDecode,
3220 const std::unordered_set<uint32_t>& aBusGlobalRecords,
3221 PADS_SCH_MODEL& aModel )
3222 {
3223 std::vector<MODEL_NET*> sheetNets( aDecode.globals.nets.size(), nullptr );
3224 // sheetNets holds pointers into nets, and one global record can own several memberships on
3225 // this sheet, so bound the reserve by the disjoint membership slices
3226 aModel.nets.reserve( aModel.nets.size() + aDecode.globals.membershipCount );
3227
3228 for( size_t globalRecord = 0; globalRecord < aDecode.globals.nets.size(); ++globalRecord )
3229 {
3230 const GLOBAL_NET_RECORD& global = aDecode.globals.nets[globalRecord];
3231
3232 if( global.tombstone )
3233 continue;
3234
3235 for( uint32_t membership = global.membershipStart;
3236 membership < global.membershipStart + global.membershipCount; ++membership )
3237 {
3238 if( aDecode.globals.membershipSheets[membership] != aDecode.sheetIndex )
3239 continue;
3240
3241 if( global.aliasCount != 0 || aBusGlobalRecords.contains( globalRecord ) )
3242 continue;
3243
3244 MODEL_NET net;
3245 net.id = NET_ID( membership );
3246 net.source = global.source;
3247 net.source.sheet = static_cast<int>( aDecode.sheetIndex );
3248 SOURCE_PROVENANCE membershipSource =
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 ) );
3256 SOURCE_PROPERTY identity =
3257 sourceProperty( wxS( "preserved_net_identity" ),
3258 wxString::Format( wxS( "%u" ), global.preservedIdentity ), global.source );
3259 identity.disposition = PROPERTY_DISPOSITION::PRESERVED;
3260 net.properties.push_back( std::move( identity ) );
3261 SOURCE_PROVENANCE relationshipSource = global.source;
3262 relationshipSource.absoluteOffset += 84;
3263 relationshipSource.length = 4;
3264 SOURCE_PROPERTY relationship = sourceProperty(
3265 wxS( "preserved_net_relationship" ),
3266 wxString::Format( wxS( "%u" ), global.preservedRelationship ), relationshipSource );
3267 relationship.disposition = PROPERTY_DISPOSITION::PRESERVED;
3268 net.properties.push_back( std::move( relationship ) );
3269 aModel.nets.push_back( std::move( net ) );
3270 sheetNets[globalRecord] = &aModel.nets.back();
3271 }
3272 }
3273
3274 return sheetNets;
3275 }
3276
3277
3278 std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*> indexDefinitionPins( const PADS_SCH_MODEL& aModel )
3279 {
3280 std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*> definitionPins;
3281
3282 for( const MODEL_SYMBOL_DEFINITION& definition : aModel.definitions )
3283 {
3284 for( const MODEL_PIN_DEFINITION& pin : definition.pins )
3285 definitionPins.emplace( pin.id.Value(), &pin );
3286 }
3287
3288 return definitionPins;
3289 }
3290
3291
3292 std::vector<MODEL_PLACEMENT*> indexSheetPlacements( const CONNECTIVITY_DECODE& aDecode, PADS_SCH_MODEL& aModel )
3293 {
3294 std::vector<MODEL_PLACEMENT*> placements( aDecode.controllers.pools[14].count, nullptr );
3295
3296 for( MODEL_PLACEMENT& placement : aModel.placements )
3297 {
3298 if( placement.source.sheet != static_cast<int>( aDecode.sheetIndex ) )
3299 continue;
3300
3301 if( placement.source.recordIndex >= placements.size() || placements[placement.source.recordIndex] )
3302 throwDecodeError( placement.source, wxS( "placement endpoint identity leaves controller 15" ) );
3303
3304 placements[placement.source.recordIndex] = &placement;
3305 }
3306
3307 return placements;
3308 }
3309
3310
3311 void decodeJunctions( const CONNECTIVITY_DECODE& aDecode, PADS_SCH_MODEL& aModel )
3312 {
3313 for( size_t record = 0; record < aDecode.controllers.pools[18].count; ++record )
3314 {
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 ) );
3319
3320 const uint16_t status = aDecode.cursor.U16At( offset + 10 );
3321
3322 if( status != 0 && status != 0x00FC && status != 0x00FD )
3323 throwDecodeError( source, wxS( "invalid junction object-class marker" ) );
3324
3325 MODEL_JUNCTION junction;
3326 junction.source = source;
3327 junction.sheet = { aModel.sheets[aDecode.sheetIndex].id, source };
3328 junction.position = junctionPosition( aDecode, record, aModel.version );
3329 SOURCE_PROVENANCE connectionSource = source;
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 ) );
3336 }
3337 }
3338
3339
3340 VERTEX_TILING tileConnectivityVertices( const CONNECTIVITY_DECODE& aDecode, PADS_SCH_MODEL& aModel )
3341 {
3342 VERTEX_TILING tiling;
3343
3344
3345 tiling.starts.reserve( aDecode.controllers.pools[17].count + aDecode.controllers.pools[20].count );
3346
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 ) );
3349
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 ) );
3353
3354 std::vector<size_t> objectOrder( tiling.starts.size() );
3355
3356 for( size_t object = 0; object < objectOrder.size(); ++object )
3357 objectOrder[object] = object;
3358
3359 std::ranges::sort( objectOrder,
3360 [&]( size_t aLeft, size_t aRight )
3361 {
3362 return tiling.starts[aLeft] < tiling.starts[aRight];
3363 } );
3364 tiling.ends.resize( tiling.starts.size() );
3365
3366 for( size_t ordinal = 0; ordinal < objectOrder.size(); ++ordinal )
3367 {
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;
3371
3372 if( ( ordinal == 0 && tiling.starts[object] != 0 ) || tiling.starts[object] >= end
3373 || end > aDecode.controllers.pools[21].count )
3374 {
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" ) );
3380 }
3381
3382 tiling.ends[object] = end;
3383 }
3384
3385 if( tiling.starts.empty() && aDecode.controllers.pools[21].count != 0 )
3386 {
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" ) );
3391 }
3392
3393 return tiling;
3394 }
3395
3396
3397 void appendVertices( const CONNECTIVITY_DECODE& aDecode, const VERTEX_TILING& aTiling, size_t aObject,
3398 uint16_t aVersion, std::vector<SOURCE_POINT>& aVertices )
3399 {
3400 const uint32_t start = aTiling.starts[aObject];
3401 const uint32_t end = aTiling.ends[aObject];
3402
3403 for( uint32_t vertex = start; vertex < end; ++vertex )
3404 {
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 ) );
3409
3410 if( aDecode.cursor.U32At( offset ) != 0 )
3411 throwDecodeError( source, wxS( "nonzero connection-vertex padding" ) );
3412
3413 aVertices.push_back( { decodeCoordinate( aDecode.cursor.U16At( offset + 4 ) ),
3414 decodeCoordinate( aDecode.cursor.U16At( offset + 6 ) ), source } );
3415 }
3416 }
3417
3418
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,
3424 PADS_SCH_MODEL& aModel )
3425 {
3426 SOURCE_PROVENANCE endpointSource = aSource;
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;
3433 SOURCE_PROVENANCE relationshipSource = aSource;
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 );
3439 result.source = endpointSource;
3440
3441 switch( objectClass )
3442 {
3443 case 0:
3444 if( objectRecord >= aPlacements.size() || !aPlacements[objectRecord] )
3445 throwDecodeError( endpointSource, wxS( "unresolved placement endpoint" ) );
3446
3447 {
3448 MODEL_PLACEMENT& placement = *aPlacements[objectRecord];
3449 const PIN_REFERENCE* matchedPin = nullptr;
3450
3451 for( const PIN_REFERENCE& pin : placement.pins )
3452 {
3453 auto definitionPin = aDefinitionPins.find( pin.id.Value() );
3454
3455 if( definitionPin == aDefinitionPins.end() )
3456 throwDecodeError( pin.source, wxS( "placement pin definition is unresolved" ) );
3457
3458 const auto position = transformedPinPosition( placement, *definitionPin->second );
3459
3460 if( position.first != aWirePoint.x || position.second != aWirePoint.y )
3461 continue;
3462
3463 if( matchedPin )
3464 throwDecodeError( endpointSource,
3465 wxS( "placement has duplicate pins at connection endpoint" ) );
3466
3467 matchedPin = &pin;
3468 }
3469
3470 if( !matchedPin )
3471 throwDecodeError( endpointSource,
3472 wxString::Format( wxS( "placement has no pin at connection endpoint; "
3473 "angle %d mirror %u" ),
3474 placement.angle, placement.mirrorFlags ) );
3475
3477 result.placement = PLACEMENT_REFERENCE{ placement.id, endpointSource };
3478 result.pin = PIN_REFERENCE{ matchedPin->id, endpointSource };
3479 result.point = aWirePoint;
3480 }
3481 break;
3482
3483 case 2:
3484 if( objectRecord >= aDecode.controllers.pools[19].count )
3485 throwDecodeError( endpointSource, wxS( "unresolved off-page endpoint" ) );
3486
3488 result.point = offpagePosition( aDecode, objectRecord, aModel.version );
3489 break;
3490
3491 case 3:
3492 if( objectRecord >= aDecode.controllers.pools[18].count )
3493 throwDecodeError( endpointSource, wxS( "unresolved junction endpoint" ) );
3494
3496 result.point = junctionPosition( aDecode, objectRecord, aModel.version );
3497 break;
3498
3499 default: throwDecodeError( endpointSource, wxS( "wrong endpoint object class" ) );
3500 }
3501
3502 result.properties.push_back(
3503 sourceProperty( wxS( "raw_endpoint_handle" ), wxString::Format( wxS( "%u" ), raw ), endpointSource ) );
3504 SOURCE_PROPERTY relationshipProperty = sourceProperty(
3505 wxS( "raw_endpoint_relationship" ), wxString::Format( wxS( "%u" ), relationship ), relationshipSource );
3506 relationshipProperty.disposition = PROPERTY_DISPOSITION::PRESERVED;
3507 result.properties.push_back( std::move( relationshipProperty ) );
3508 return result;
3509 }
3510
3511
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,
3515 SHEET_CONNECTIVITY& aConnectivity, PADS_SCH_MODEL& aModel )
3516 {
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 );
3523
3524 for( size_t record = 0; record < aDecode.controllers.pools[20].count; ++record )
3525 {
3526 const uint32_t netHandle =
3527 aDecode.cursor.U32At( aDecode.connectionBase + record * CONNECTION_RECORD_BYTES + 8 );
3528
3529 if( netHandle < connectionCounts.size() )
3530 ++connectionCounts[netHandle];
3531 }
3532
3533 for( size_t net = 0; net < aConnectivity.sheetNets.size(); ++net )
3534 {
3535 if( aConnectivity.sheetNets[net] )
3536 aConnectivity.sheetNets[net]->connections.reserve( connectionCounts[net] );
3537 }
3538
3539 for( size_t record = 0; record < aDecode.controllers.pools[20].count; ++record )
3540 {
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 );
3546
3547 if( netHandle >= aConnectivity.sheetNets.size() || !aConnectivity.sheetNets[netHandle] )
3548 throwDecodeError( source, wxS( "connection net handle targets wrong or unresolved object class" ) );
3549
3550 const uint16_t marker = aDecode.cursor.U16At( offset + 34 );
3551
3552 const uint8_t markerStatus = marker & 0xFF;
3553
3554 if( marker >> 8 < 2 || marker >> 8 > 6
3555 || ( markerStatus != 0 && markerStatus != 0xFC && markerStatus != 0xFD ) )
3556 throwDecodeError( source, wxS( "invalid connection object-class marker" ) );
3557
3558 MODEL_CONNECTION connection;
3559 connection.source = source;
3560
3561 appendVertices( aDecode, aTiling, aDecode.controllers.pools[17].count + record, aModel.version,
3562 connection.vertices );
3563
3564 if( connection.vertices.size() < 2 )
3565 throwDecodeError( source, wxS( "connection lacks explicit endpoint vertices" ) );
3566
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 ) );
3571
3572 for( size_t endpointIndex = 0; endpointIndex < connection.endpoints.size(); ++endpointIndex )
3573 {
3574 MODEL_CONNECTION_ENDPOINT& decodedEndpoint = connection.endpoints[endpointIndex];
3575 const SOURCE_POINT& wirePoint =
3576 endpointIndex == 0 ? connection.vertices.front() : connection.vertices.back();
3577
3578 if( decodedEndpoint.kind == MODEL_ENDPOINT_KIND::POINT
3579 && ( decodedEndpoint.point.x != wirePoint.x || decodedEndpoint.point.y != wirePoint.y ) )
3580 {
3581 throwDecodeError( decodedEndpoint.source,
3582 wxS( "typed endpoint position does not match wire endpoint vertex" ) );
3583 }
3584
3585 decodedEndpoint.point = { wirePoint.x, wirePoint.y, wirePoint.source };
3586 }
3587
3588 connectionEndpointHandles[record] = { aDecode.cursor.U16At( offset + 12 ),
3589 aDecode.cursor.U16At( offset + 14 ) };
3590
3591 for( size_t endpointIndex = 0; endpointIndex < connectionEndpointHandles[record].size(); ++endpointIndex )
3592 {
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;
3597
3598 if( objectClass == 2 )
3599 backlinks = &aConnectivity.offpageBacklinks[objectRecord];
3600 else if( objectClass == 3 )
3601 backlinks = &aConnectivity.junctionBacklinks[objectRecord];
3602
3603 if( backlinks )
3604 {
3605 if( endpointIndex == 1 && connectionEndpointHandles[record][0] == raw )
3606 {
3607 SOURCE_PROVENANCE endpointSource = source;
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" ) );
3612 }
3613
3614 backlinks->push_back( record );
3615 }
3616 }
3617
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];
3623 }
3624 }
3625
3626
3627 void validateJunctionBacklinks( const CONNECTIVITY_DECODE& aDecode, const SHEET_CONNECTIVITY& aConnectivity,
3628 PADS_SCH_MODEL& aModel )
3629 {
3630 for( size_t record = 0; record < aDecode.controllers.pools[18].count; ++record )
3631 {
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 );
3637 SOURCE_PROVENANCE ownerSource = source;
3638 ownerSource.absoluteOffset += 8;
3639 ownerSource.length = 2;
3640
3641 if( owner >= aConnectivity.connections.size() || !aConnectivity.connections[owner] )
3642 throwDecodeError( ownerSource, wxS( "junction connection handle leaves controller 21" ) );
3643
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" ) );
3647
3648 for( size_t connection : aConnectivity.junctionBacklinks[record] )
3649 {
3650 if( aConnectivity.connectionNets[connection] != aConnectivity.connectionNets[owner] )
3651 {
3652 throwDecodeError( ownerSource, wxS( "junction is shared across different nets" ) );
3653 }
3654 }
3655 }
3656 }
3657
3658
3659 void validateOffpageBacklinks( const CONNECTIVITY_DECODE& aDecode, const SHEET_CONNECTIVITY& aConnectivity,
3660 PADS_SCH_MODEL& aModel )
3661 {
3662 for( size_t record = 0; record < aDecode.controllers.pools[19].count; ++record )
3663 {
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 );
3669 SOURCE_PROVENANCE ownerSource = source;
3670 ownerSource.absoluteOffset += 8;
3671 ownerSource.length = 2;
3672
3673 if( owner >= aConnectivity.connections.size() || !aConnectivity.connections[owner] )
3674 throwDecodeError( ownerSource, wxS( "off-page net handle leaves controller 21" ) );
3675
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" ) );
3679
3680 for( size_t connection : aConnectivity.offpageBacklinks[record] )
3681 {
3682 if( aConnectivity.connectionNets[connection] != aConnectivity.connectionNets[owner] )
3683 throwDecodeError( ownerSource, wxS( "off-page reference is shared across different nets" ) );
3684 }
3685 }
3686 }
3687
3688
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 )
3692 {
3693 std::vector<bool> claimedBusEntries( aDecode.controllers.pools[19].count, false );
3694
3695 for( size_t record = 0; record < aDecode.controllers.pools[17].count; ++record )
3696 {
3697 const size_t offset = aDecode.busBase + record * BUS_RECORD_BYTES;
3698 SOURCE_PROVENANCE source = sourceAt( aDecode.sourceName, aModel.version, wxS( "bus" ), 18, record, offset,
3699 BUS_RECORD_BYTES, static_cast<int>( aDecode.sheetIndex ) );
3700 const uint16_t marker = aDecode.cursor.U16At( offset + 38 );
3701
3702 const uint8_t markerStatus = marker & 0xFF;
3703
3704 if( marker >> 8 < 2 || marker >> 8 > 4 || ( markerStatus != 0 && markerStatus != 0xFD ) )
3705 throwDecodeError( source, wxS( "invalid bus object-class marker" ) );
3706
3707 const size_t globalRecord = aDecode.cursor.U32At( offset + 8 );
3708
3709 if( globalRecord >= aDecode.globals.nets.size() || aDecode.globals.nets[globalRecord].tombstone
3710 || !aBusGlobalRecords.contains( globalRecord ) )
3711 {
3712 throwDecodeError( source, wxS( "bus global-net handle targets wrong or unresolved object class" ) );
3713 }
3714
3715 const GLOBAL_NET_RECORD& global = aDecode.globals.nets[globalRecord];
3716 uint32_t membership = global.membershipStart;
3717
3718 while( membership < global.membershipStart + global.membershipCount
3719 && aDecode.globals.membershipSheets[membership] != aDecode.sheetIndex )
3720 {
3721 ++membership;
3722 }
3723
3724 if( membership == global.membershipStart + global.membershipCount )
3725 throwDecodeError( source, wxS( "bus global-net handle does not belong to this sheet" ) );
3726
3727 MODEL_BUS bus;
3728 bus.id = BUS_ID( static_cast<uint32_t>( aDecode.sheetIndex * 0x100000 + record + 1 ) );
3729 bus.source = source;
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;
3734 SOURCE_PROPERTY identity =
3735 sourceProperty( wxS( "preserved_net_identity" ),
3736 wxString::Format( wxS( "%u" ), global.preservedIdentity ), global.source );
3737 identity.disposition = PROPERTY_DISPOSITION::PRESERVED;
3738 bus.properties.push_back( std::move( identity ) );
3739 SOURCE_PROVENANCE relationshipSource = global.source;
3740 relationshipSource.absoluteOffset += 84;
3741 relationshipSource.length = 4;
3742 SOURCE_PROPERTY relationship =
3743 sourceProperty( wxS( "preserved_net_relationship" ),
3744 wxString::Format( wxS( "%u" ), global.preservedRelationship ), relationshipSource );
3745 relationship.disposition = PROPERTY_DISPOSITION::PRESERVED;
3746 bus.properties.push_back( std::move( relationship ) );
3747 appendVertices( aDecode, aTiling, record, aModel.version, bus.vertices );
3748
3749 std::vector<size_t> entryRecords;
3750 uint16_t entryHandle = aDecode.cursor.U16At( offset + 24 );
3751 std::unordered_set<size_t> chain;
3752
3753 while( ( entryHandle >> 12 ) == 2 )
3754 {
3755 const size_t entryRecord = entryHandle & 0x0FFF;
3756
3757 if( entryRecord >= aDecode.controllers.pools[19].count )
3758 throwDecodeError( source, wxS( "unresolved bus-entry handle" ) );
3759
3760 if( !chain.insert( entryRecord ).second )
3761 throwDecodeError( source, wxS( "cyclic bus-entry handle chain" ) );
3762
3763 entryRecords.push_back( entryRecord );
3764 entryHandle = aDecode.cursor.U16At( aDecode.offpageBase + entryRecord * OFFPAGE_RECORD_BYTES + 4 );
3765 }
3766
3767 if( record > 0x0FFF || entryHandle != 0xBFFF - record )
3768 throwDecodeError( source, wxS( "bus-entry chain terminates in wrong object class" ) );
3769
3770 std::ranges::reverse( entryRecords );
3771
3772 const bool exactAliasMapping = entryRecords.size() == global.aliasMembers.size();
3773
3774 for( size_t entry = 0; entry < entryRecords.size(); ++entry )
3775 {
3776 const size_t entryRecord = entryRecords[entry];
3777 const size_t entryOffset = aDecode.offpageBase + entryRecord * OFFPAGE_RECORD_BYTES;
3778 SOURCE_PROVENANCE entrySource =
3779 sourceAt( aDecode.sourceName, aModel.version, wxS( "bus entry" ), 20, entryRecord, entryOffset,
3780 OFFPAGE_RECORD_BYTES, static_cast<int>( aDecode.sheetIndex ) );
3781
3782 if( aDecode.cursor.U8At( entryOffset + 30 ) != 0xFF )
3783 throwDecodeError( entrySource, wxS( "bus-entry handle targets wrong off-page object class" ) );
3784
3785 if( claimedBusEntries[entryRecord] )
3786 throwDecodeError( entrySource, wxS( "duplicate bus-entry membership" ) );
3787
3788 const uint16_t connectionHandle = aDecode.cursor.U16At( entryOffset + 8 );
3789
3790 if( connectionHandle >= aConnectivity.connections.size()
3791 || !aConnectivity.connections[connectionHandle] )
3792 throwDecodeError( entrySource, wxS( "unresolved bus-entry connection reference" ) );
3793
3794 MODEL_CONNECTION* entryConnection = aConnectivity.connections[connectionHandle];
3795 MODEL_NET* memberNet = aConnectivity.connectionNets[connectionHandle];
3796
3797 if( !memberNet )
3798 throwDecodeError( entrySource, wxS( "bus-entry connection targets wrong member-net class" ) );
3799
3800 if( exactAliasMapping && memberNet->name.text != global.aliasMembers[entry].text )
3801 throwDecodeError( entrySource, wxS( "bus alias member does not match connected net" ) );
3802
3803 const bool ownsConnection = std::ranges::any_of( memberNet->connections,
3804 [&]( const MODEL_CONNECTION& aConnection )
3805 {
3806 return &aConnection == entryConnection;
3807 } );
3808
3809 if( !ownsConnection )
3810 throwDecodeError( entrySource, wxS( "bus-entry connection targets wrong member-net class" ) );
3811
3812 claimedBusEntries[entryRecord] = true;
3813 MODEL_BUS_ENTRY busEntry;
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 } );
3819 }
3820
3821 aModel.buses.push_back( std::move( bus ) );
3822 }
3823
3824 return claimedBusEntries;
3825 }
3826
3827
3828 void decodeOffpageLabels( const CONNECTIVITY_DECODE& aDecode, const SHEET_CONNECTIVITY& aConnectivity,
3829 const std::vector<bool>& aClaimedBusEntries, PADS_SCH_MODEL& aModel )
3830 {
3831 for( size_t record = 0; record < aDecode.controllers.pools[19].count; ++record )
3832 {
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 );
3838
3839 if( rawKind == 0xFF )
3840 {
3841 if( !aClaimedBusEntries[record] )
3842 throwDecodeError( source, wxS( "unclaimed bus-entry record" ) );
3843
3844 continue;
3845 }
3846
3847 const uint16_t connectionHandle = aDecode.cursor.U16At( offset + 8 );
3848
3849 if( connectionHandle >= aConnectivity.connections.size() || !aConnectivity.connections[connectionHandle] )
3850 throwDecodeError( source, wxS( "off-page net handle leaves controller 21" ) );
3851
3852 MODEL_NET* ownerNet = aConnectivity.connectionNets[connectionHandle];
3853
3854 if( !ownerNet )
3855 throwDecodeError( source, wxS( "off-page record targets wrong net object class" ) );
3856
3857 MODEL_LABEL label;
3858 label.source = source;
3859 label.sheet = { aModel.sheets[aDecode.sheetIndex].id, source };
3860 label.text = ownerNet->name;
3861 label.position = offpagePosition( aDecode, record, aModel.version );
3862
3863 // Apply the PADS off-page mirror flags to the label direction. The ASCII
3864 // rotation/mirror pair maps to binary words +26/+28; ignoring +28 reverses
3865 // horizontal $OSR_SYMS attached to left-facing pins.
3866 int32_t offpageAngle = NormalizeAngle( aDecode.cursor.U16At( offset + 26 ) );
3867 const uint16_t offpageMirrorFlags = aDecode.cursor.U16At( offset + 28 );
3868
3869 if( offpageMirrorFlags & 1 )
3870 offpageAngle = NormalizeAngle( 1800 - offpageAngle );
3871
3872 if( offpageMirrorFlags & 2 )
3873 offpageAngle = NormalizeAngle( -offpageAngle );
3874
3875 label.angle = offpageAngle;
3876 label.symbolVariant = rawKind;
3877 SOURCE_PROVENANCE mirrorSource = source;
3878 mirrorSource.absoluteOffset += 28;
3879 mirrorSource.length = 2;
3880 label.properties.push_back( sourceProperty( wxS( "offpage_mirror_flags" ),
3881 wxString::Format( wxS( "%u" ), offpageMirrorFlags ),
3882 mirrorSource ) );
3883
3884 // Real designs carry unrelated data in the high byte, so only unknown low bits warrant a warning
3885 if( offpageMirrorFlags & 0x00FC )
3886 {
3887 SOURCE_PROPERTY& property = label.properties.back();
3889 aModel.diagnostics.push_back( MakePropertyDiagnostic( RPT_SEVERITY_WARNING, property,
3890 wxS( "unsupported PADS off-page mirror flag "
3891 "bits preserved" ) ) );
3892 }
3893
3894 if( rawKind == 0xFE )
3895 {
3896 label.kind = MODEL_LABEL_KIND::LOCAL;
3897 }
3898 else
3899 {
3900 const uint16_t decalHandle = aDecode.cursor.U16At( offset + 4 );
3901
3902 if( decalHandle == 0xFFFF )
3903 {
3904 label.kind = MODEL_LABEL_KIND::GLOBAL;
3905 }
3906 else
3907 {
3908 if( decalHandle >= aDecode.controllers.pools[6].count )
3909 throwDecodeError( source, wxS( "off-page decal handle leaves controller 7" ) );
3910
3911 SOURCE_PROVENANCE decalSource =
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 );
3918
3919 if( definitionRecord >= aDecode.controllers.pools[2].count )
3920 throwDecodeError( decalSource, wxS( "off-page decal definition leaves controller 3" ) );
3921
3922 const DEFINITION_ID definitionId(
3923 static_cast<uint32_t>( aDecode.sheetIndex * 0x100000 + 1 + definitionRecord ) );
3924 auto specialPartOwnsDefinition = [&]( const wxString& aPartName )
3925 {
3926 return std::ranges::any_of(
3927 aModel.partTypes,
3928 [&]( const MODEL_PART_TYPE& aPart )
3929 {
3930 if( aPart.name.text != aPartName )
3931 return false;
3932
3933 return std::ranges::any_of(
3934 aPart.gates,
3935 [&]( const MODEL_GATE& aGate )
3936 {
3937 return aGate.definition.id == definitionId
3938 || std::ranges::any_of( aGate.alternateDefinitions,
3939 [&]( const DEFINITION_REFERENCE& aRef )
3940 {
3941 return aRef.id == definitionId;
3942 } );
3943 } );
3944 } );
3945 };
3946
3947 if( specialPartOwnsDefinition( wxS( "$OSR_SYMS" ) ) )
3948 label.kind = MODEL_LABEL_KIND::GLOBAL;
3949 else if( specialPartOwnsDefinition( wxS( "$GND_SYMS" ) ) )
3950 label.kind = MODEL_LABEL_KIND::GROUND;
3951 else if( specialPartOwnsDefinition( wxS( "$PWR_SYMS" ) ) )
3952 label.kind = MODEL_LABEL_KIND::POWER;
3953 else
3954 {
3955 label.kind = MODEL_LABEL_KIND::UNSUPPORTED;
3956 SOURCE_PROPERTY unsupportedDecal =
3957 sourceProperty( wxS( "unsupported_offpage_decal" ), decalName.text, decalSource );
3958 unsupportedDecal.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
3959 aModel.diagnostics.push_back(
3961 wxS( "unsupported off-page decal class preserved" ) ) );
3962 label.properties.push_back( std::move( unsupportedDecal ) );
3963 }
3964 }
3965 }
3966
3967 if( label.kind == MODEL_LABEL_KIND::GLOBAL )
3968 {
3969 for( uint32_t membership =
3970 aDecode.globals
3971 .nets[aDecode.cursor.U32At( aDecode.connectionBase
3972 + connectionHandle * CONNECTION_RECORD_BYTES + 8 )]
3973 .membershipStart;
3974 membership
3975 < aDecode.globals.nets[aDecode.cursor.U32At( aDecode.connectionBase
3976 + connectionHandle * CONNECTION_RECORD_BYTES + 8 )]
3977 .membershipStart
3978 + aDecode.globals
3979 .nets[aDecode.cursor.U32At( aDecode.connectionBase
3980 + connectionHandle * CONNECTION_RECORD_BYTES + 8 )]
3981 .membershipCount;
3982 ++membership )
3983 {
3984 const uint16_t peerSheet = aDecode.globals.membershipSheets[membership];
3985
3986 if( peerSheet != aDecode.sheetIndex )
3987 label.linkedSheets.push_back( { aModel.sheets[peerSheet].id, source } );
3988 }
3989 }
3990
3991 if( label.kind == MODEL_LABEL_KIND::GROUND || label.kind == MODEL_LABEL_KIND::POWER )
3992 label.presentation.visible = false;
3993
3994 label.properties.push_back(
3995 sourceProperty( wxS( "offpage_variant" ), wxString::Format( wxS( "%u" ), rawKind ), source ) );
3996 aModel.labels.push_back( std::move( label ) );
3997 }
3998 }
3999
4000
4001 MODEL_TEXT_PRESENTATION netNamePresentation( const CONNECTIVITY_DECODE& aDecode, size_t aOffset,
4002 const SOURCE_PROVENANCE& aSource, PADS_SCH_MODEL& aModel )
4003 {
4004 MODEL_TEXT_PRESENTATION presentation;
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 ) );
4011 SOURCE_PROVENANCE fontSource = aSource;
4012 fontSource.length = 2;
4013
4014 if( fontHandle == -1 )
4015 {
4016 presentation.font = decodedDefinitionFont( -1, fontSource );
4017 }
4018 else
4019 {
4020 if( fontHandle < 0 || static_cast<uint32_t>( fontHandle ) >= aDecode.globals.fontCount )
4021 throwDecodeError( fontSource, wxS( "net-name font handle leaves outer controller 19" ) );
4022
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;
4030
4031 if( style & ~3U )
4032 {
4033 SOURCE_PROPERTY property = sourceProperty( wxS( "unsupported_font_style_flags" ),
4034 wxString::Format( wxS( "%u" ), style & ~3U ), fontSource );
4035 property.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
4036 presentation.properties.push_back( property );
4037 aModel.diagnostics.push_back( MakePropertyDiagnostic(
4038 RPT_SEVERITY_WARNING, property, wxS( "unsupported net-name font style flags preserved" ) ) );
4039 }
4040 }
4041
4042 presentation.properties.push_back(
4043 sourceProperty( wxS( "font_handle" ), wxString::Format( wxS( "%d" ), fontHandle ), fontSource ) );
4044 return presentation;
4045 }
4046
4047
4048 void decodeNetNames( const CONNECTIVITY_DECODE& aDecode, const SHEET_CONNECTIVITY& aConnectivity,
4049 PADS_SCH_MODEL& aModel )
4050 {
4051 for( size_t record = 0; record < aDecode.controllers.pools[22].count; ++record )
4052 {
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 )
4062 {
4063 SOURCE_PROVENANCE propertySource = source;
4064 propertySource.absoluteOffset += aRelativeOffset;
4065 propertySource.length = aLength;
4066 SOURCE_PROPERTY property = sourceProperty( aName, aValue, propertySource );
4067 property.disposition = PROPERTY_DISPOSITION::PRESERVED;
4068 preservedPresentation.push_back( std::move( property ) );
4069 };
4070 wxString presentation06;
4071
4072 for( size_t index = 6; index < 16; ++index )
4073 presentation06 += wxString::Format( wxS( "%02x" ), aDecode.bytes[offset + index] );
4074
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 ) ) ),
4079 28, 4 );
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 );
4092
4093 if( ( ownerHandle & 0xF000 ) == 0x4000 )
4094 {
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" ) );
4097
4098 const size_t busRecord = ownerHandle & 0x0FFF;
4099 auto bus = std::ranges::find_if( aModel.buses,
4100 [&]( const MODEL_BUS& aBus )
4101 {
4102 return aBus.sheet.id == aModel.sheets[aDecode.sheetIndex].id
4103 && aBus.source.recordIndex == busRecord;
4104 } );
4105
4106 if( bus == aModel.buses.end() || childHandle == 0 || childHandle > bus->memberNets.size()
4107 || bus->name.text != aDecode.globals.nets[globalRecord].name.text )
4108 {
4109 throwDecodeError( source, wxS( "net-name bus owner targets wrong object class" ) );
4110 }
4111
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() ) );
4116 continue;
4117 }
4118
4119 if( globalRecord >= aConnectivity.sheetNets.size() || !aConnectivity.sheetNets[globalRecord] )
4120 throwDecodeError( source, wxS( "net-name record targets wrong or unresolved net object class" ) );
4121
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 };
4125 MODEL_TEXT_PRESENTATION presentation = netNamePresentation( aDecode, offset, source, aModel );
4126 presentation.properties.insert( presentation.properties.end(),
4127 std::make_move_iterator( preservedPresentation.begin() ),
4128 std::make_move_iterator( preservedPresentation.end() ) );
4129
4130 if( ( ownerHandle & 0xF000 ) == 0x2000 )
4131 {
4132 const size_t offpageRecord = ownerHandle & 0x0FFF;
4133 auto label = std::ranges::find_if( aModel.labels,
4134 [&]( const MODEL_LABEL& aLabel )
4135 {
4136 return aLabel.sheet.id == aModel.sheets[aDecode.sheetIndex].id
4137 && aLabel.source.controller == 20
4138 && aLabel.source.recordIndex == offpageRecord;
4139 } );
4140
4141 if( label == aModel.labels.end() )
4142 {
4143 const MODEL_BUS_ENTRY* busEntry = nullptr;
4144
4145 for( const MODEL_BUS& bus : aModel.buses )
4146 {
4147 if( bus.sheet.id != aModel.sheets[aDecode.sheetIndex].id )
4148 continue;
4149
4150 auto candidate = std::ranges::find_if( bus.entries,
4151 [&]( const MODEL_BUS_ENTRY& aEntry )
4152 {
4153 return aEntry.source.recordIndex == offpageRecord
4154 && aEntry.memberNet.id == ownerNet.id;
4155 } );
4156
4157 if( candidate != bus.entries.end() )
4158 {
4159 if( busEntry )
4160 throwDecodeError( source, wxS( "net-name bus-entry owner is ambiguous" ) );
4161
4162 busEntry = &*candidate;
4163 }
4164 }
4165
4166 if( !busEntry )
4167 throwDecodeError( source, wxS( "net-name off-page owner targets wrong object class" ) );
4168
4169 MODEL_TEXT busText;
4170 busText.source = source;
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,
4174 source };
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 ) );
4181 continue;
4182 }
4183
4184 if( label->text.text != ownerNet.name.text )
4185 throwDecodeError( source, wxS( "net-name off-page owner targets wrong net object" ) );
4186
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 ) );
4193 continue;
4194 }
4195
4196 auto placement =
4197 std::ranges::find_if( aModel.placements,
4198 [&]( const MODEL_PLACEMENT& aPlacement )
4199 {
4200 return aPlacement.sheet.id == aModel.sheets[aDecode.sheetIndex].id
4201 && aPlacement.source.recordIndex == ownerHandle;
4202 } );
4203
4204 if( placement == aModel.placements.end() )
4205 throwDecodeError( source, wxS( "net-name placement owner targets wrong object class" ) );
4206
4207 if( childHandle >= placement->pins.size() )
4208 throwDecodeError( source, wxS( "net-name placement pin ordinal leaves placement" ) );
4209
4210 const PIN_ID ownerPin = placement->pins[childHandle].id;
4211
4212 const MODEL_CONNECTION_ENDPOINT* endpoint = nullptr;
4213
4214 for( const MODEL_CONNECTION& connection : ownerNet.connections )
4215 {
4216 for( const MODEL_CONNECTION_ENDPOINT& candidate : connection.endpoints )
4217 {
4218 if( candidate.kind != MODEL_ENDPOINT_KIND::PIN || !candidate.placement || !candidate.pin
4219 || candidate.placement->id != placement->id || candidate.pin->id != ownerPin )
4220 {
4221 continue;
4222 }
4223
4224 if( endpoint )
4225 throwDecodeError( source, wxS( "net-name placement pin owner is ambiguous" ) );
4226
4227 endpoint = &candidate;
4228 }
4229 }
4230
4231 if( !endpoint )
4232 throwDecodeError( source, wxS( "net-name placement pin owner is unresolved" ) );
4233
4235 text.source = source;
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 };
4239 text.angle = NormalizeAngle( aDecode.cursor.U16At( offset + 24 ) );
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 ) );
4245 }
4246 }
4247
4248
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,
4251 const CONNECTIVITY_GLOBALS& aGlobals, PADS_SCH_MODEL& aModel )
4252 {
4253 if( aModel.version != 0x000D )
4254 throwDecodeError( aModel.source, wxS( "connectivity decoder selected for raw-preserved version" ) );
4255
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 );
4263
4264 const CONNECTIVITY_DECODE decode{ aBytes,
4265 aCursor,
4266 controllers,
4267 aGlobals,
4268 aSourceName,
4269 aSheetIndex,
4270 controllers.offsets[17],
4271 controllers.offsets[18],
4272 controllers.offsets[19],
4273 controllers.offsets[20],
4274 controllers.offsets[21],
4275 controllers.offsets[22] };
4276
4277 const std::unordered_set<uint32_t> busGlobalRecords = decodeBusGlobalRecords( decode, aModel );
4278 SHEET_CONNECTIVITY connectivity;
4279 connectivity.sheetNets = materializeSheetNets( decode, busGlobalRecords, aModel );
4280
4281 const std::unordered_map<uint32_t, const MODEL_PIN_DEFINITION*> definitionPins = indexDefinitionPins( aModel );
4282 const std::vector<MODEL_PLACEMENT*> placements = indexSheetPlacements( decode, aModel );
4283
4284 decodeJunctions( decode, aModel );
4285
4286 const VERTEX_TILING tiling = tileConnectivityVertices( decode, aModel );
4287
4288 decodeConnections( decode, tiling, placements, definitionPins, connectivity, aModel );
4289 validateJunctionBacklinks( decode, connectivity, aModel );
4290 validateOffpageBacklinks( decode, connectivity, aModel );
4291
4292 const std::vector<bool> claimedBusEntries =
4293 decodeBuses( decode, tiling, busGlobalRecords, connectivity, aModel );
4294
4295 decodeOffpageLabels( decode, connectivity, claimedBusEntries, aModel );
4296 decodeNetNames( decode, connectivity, aModel );
4297 }
4298
4299
4300 void inheritDefaultSystemFont( MODEL_TEXT_PRESENTATION& aPresentation, const DESIGN_SETTINGS& aSettings )
4301 {
4302 if( aSettings.fontMode != MODEL_FONT_MODE::SYSTEM || aSettings.defaultSystemFont.text.IsEmpty() )
4303 return;
4304
4305 if( aPresentation.font.text.IsEmpty() || aPresentation.font.text == wxS( "Default Font" ) )
4306 aPresentation.font = aSettings.defaultSystemFont;
4307 }
4308
4309
4310 void inheritDefaultSystemFonts( PADS_SCH_MODEL& aModel )
4311 {
4312 const DESIGN_SETTINGS& settings = aModel.settings;
4313
4314 const auto applyField =
4315 [&]( MODEL_FIELD& aField )
4316 {
4317 inheritDefaultSystemFont( aField.presentation, settings );
4318 };
4319
4320 const auto applyGraphic =
4321 [&]( MODEL_GRAPHIC& aGraphic )
4322 {
4323 if( aGraphic.kind == MODEL_GRAPHIC_KIND::TEXT )
4324 inheritDefaultSystemFont( aGraphic.presentation, settings );
4325 };
4326
4327 for( MODEL_SHEET& sheet : aModel.sheets )
4328 {
4329 std::ranges::for_each( sheet.border, applyGraphic );
4330 std::ranges::for_each( sheet.titleBlockFields, applyField );
4331 }
4332
4333 for( MODEL_SYMBOL_DEFINITION& definition : aModel.definitions )
4334 {
4335 std::ranges::for_each( definition.graphics, applyGraphic );
4336 std::ranges::for_each( definition.fields, applyField );
4337
4338 for( MODEL_PIN_DEFINITION& pin : definition.pins )
4339 {
4340 inheritDefaultSystemFont( pin.presentation, settings );
4341 inheritDefaultSystemFont( pin.namePresentation, settings );
4342 inheritDefaultSystemFont( pin.numberPresentation, settings );
4343 }
4344 }
4345
4346 for( MODEL_PART_TYPE& partType : aModel.partTypes )
4347 std::ranges::for_each( partType.fields, applyField );
4348
4349 for( MODEL_PLACEMENT& placement : aModel.placements )
4350 std::ranges::for_each( placement.fields, applyField );
4351
4352 for( MODEL_LABEL& label : aModel.labels )
4353 inheritDefaultSystemFont( label.presentation, settings );
4354
4355 for( MODEL_TEXT& text : aModel.texts )
4356 inheritDefaultSystemFont( text.presentation, settings );
4357
4358 for( MODEL_PAGE_GRAPHIC& graphic : aModel.graphics )
4359 applyGraphic( graphic.graphic );
4360
4361 for( MODEL_WORKSHEET& worksheet : aModel.worksheets )
4362 std::ranges::for_each( worksheet.graphics, applyGraphic );
4363 }
4364
4365
4366 void assignFieldIds( PADS_SCH_MODEL& aModel )
4367 {
4368 auto assign = []( MODEL_FIELD& aField, FIELD_ID_DOMAIN aDomain, uint32_t aOwner, size_t aOrdinal )
4369 {
4370 if( aOrdinal > FIELD_ID_MAX_ORDINAL )
4371 throwDecodeError( aField.source, wxS( "field ordinal exceeds identity capacity" ) );
4372
4373 aField.id = MakeFieldId( aDomain, aOwner, static_cast<uint32_t>( aOrdinal ) );
4374 };
4375
4376 for( MODEL_SHEET& sheet : aModel.sheets )
4377 {
4378 for( size_t ordinal = 0; ordinal < sheet.titleBlockFields.size(); ++ordinal )
4379 {
4380 MODEL_FIELD& field = sheet.titleBlockFields[ordinal];
4381 assign( field, FIELD_ID_DOMAIN::SHEET, sheet.id.Value(), ordinal );
4382 }
4383 }
4384
4385 for( MODEL_SYMBOL_DEFINITION& definition : aModel.definitions )
4386 {
4387 for( size_t ordinal = 0; ordinal < definition.fields.size(); ++ordinal )
4388 {
4389 MODEL_FIELD& field = definition.fields[ordinal];
4390 assign( field, FIELD_ID_DOMAIN::DEFINITION, definition.id.Value(), ordinal );
4391 }
4392 }
4393
4394 for( MODEL_PART_TYPE& partType : aModel.partTypes )
4395 {
4396 for( size_t ordinal = 0; ordinal < partType.fields.size(); ++ordinal )
4397 {
4398 MODEL_FIELD& field = partType.fields[ordinal];
4399 assign( field, FIELD_ID_DOMAIN::PART_TYPE, partType.id.Value(), ordinal );
4400 }
4401 }
4402
4403 for( MODEL_PLACEMENT& placement : aModel.placements )
4404 {
4405 for( size_t ordinal = 0; ordinal < placement.fields.size(); ++ordinal )
4406 {
4407 MODEL_FIELD& field = placement.fields[ordinal];
4408 assign( field, FIELD_ID_DOMAIN::PLACEMENT, placement.id.Value(), ordinal );
4409 }
4410 }
4411 }
4412
4413
4414 template <typename Item>
4415 void validateSheetRef( const Item& aItem, const MODEL_REFERENCE_INDEX& aIndex, const wxString& aObjectClass )
4416 {
4417 if( !aIndex.sheets.contains( aItem.sheet.id.Value() ) )
4418 {
4419 throwValidationError( aItem.sheet.source,
4420 wxString::Format( wxS( "unresolved %s sheet reference" ), aObjectClass ) );
4421 }
4422 }
4423
4424
4425 void validateIdentity( const PADS_SCH_MODEL& aModel )
4426 {
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 );
4434
4435 std::vector<bool> sheetIndexes( aModel.sheets.size() );
4436
4437 for( const MODEL_SHEET& sheet : aModel.sheets )
4438 {
4439 if( sheet.index >= sheetIndexes.size() )
4440 throwValidationError( sheet.source, wxS( "sheet source index leaves the declared sheet range" ) );
4441
4442 if( sheetIndexes[sheet.index] )
4443 throwValidationError( sheet.source, wxS( "duplicate sheet source index" ) );
4444
4445 sheetIndexes[sheet.index] = true;
4446 }
4447
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;
4451
4452 for( const MODEL_PART_TYPE& partType : aModel.partTypes )
4453 {
4454 for( const MODEL_GATE& gate : partType.gates )
4455 validateNestedId( gate, wxS( "gate" ), gateDeclarations );
4456 }
4457
4458 for( const MODEL_SYMBOL_DEFINITION& definition : aModel.definitions )
4459 {
4460 for( const MODEL_PIN_DEFINITION& pin : definition.pins )
4461 validateNestedId( pin, wxS( "pin" ), pinDeclarations );
4462
4463 for( const MODEL_FIELD& field : definition.fields )
4464 validateNestedId( field, wxS( "field" ), fieldDeclarations );
4465 }
4466
4467 for( const MODEL_SHEET& sheet : aModel.sheets )
4468 {
4469 for( const MODEL_FIELD& field : sheet.titleBlockFields )
4470 validateNestedId( field, wxS( "field" ), fieldDeclarations );
4471 }
4472
4473 for( const MODEL_PART_TYPE& partType : aModel.partTypes )
4474 {
4475 for( const MODEL_FIELD& field : partType.fields )
4476 validateNestedId( field, wxS( "field" ), fieldDeclarations );
4477 }
4478
4479 for( const MODEL_PLACEMENT& placement : aModel.placements )
4480 {
4481 for( const MODEL_FIELD& field : placement.fields )
4482 validateNestedId( field, wxS( "field" ), fieldDeclarations );
4483 }
4484 }
4485
4486
4487 void validateSymbolGraph( const PADS_SCH_MODEL& aModel, const MODEL_REFERENCE_INDEX& aIndex )
4488 {
4489 for( const MODEL_SHEET& sheet : aModel.sheets )
4490 {
4491 if( sheet.parent && !aIndex.sheets.contains( sheet.parent->id.Value() ) )
4492 throwValidationError( sheet.parent->source, wxS( "unresolved sheet reference" ) );
4493 }
4494
4495 for( const MODEL_PART_TYPE& partType : aModel.partTypes )
4496 {
4497 for( const MODEL_GATE& gate : partType.gates )
4498 {
4499 auto definition = aIndex.definitions.find( gate.definition.id.Value() );
4500
4501 if( definition == aIndex.definitions.end() && gate.decalGroupMembers.empty() )
4502 throwValidationError( gate.definition.source, wxS( "unresolved symbol definition reference" ) );
4503
4504 for( const DEFINITION_REFERENCE& alternate : gate.alternateDefinitions )
4505 {
4506 if( !aIndex.definitions.contains( alternate.id.Value() ) )
4507 throwValidationError( alternate.source, wxS( "unresolved alternate definition reference" ) );
4508 }
4509
4510 for( const DEFINITION_REFERENCE& member : gate.decalGroupMembers )
4511 {
4512 if( !aIndex.definitions.contains( member.id.Value() ) )
4513 throwValidationError( member.source, wxS( "unresolved pin-decal group member" ) );
4514 }
4515
4516 if( definition == aIndex.definitions.end() )
4517 continue;
4518
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" ) );
4521
4522 for( size_t pinOrdinal = 0; pinOrdinal < gate.pins.size(); ++pinOrdinal )
4523 {
4524 const PIN_REFERENCE& pin = gate.pins[pinOrdinal];
4525 auto pinOwner = aIndex.pinOwners.find( pin.id.Value() );
4526
4527 if( pinOwner == aIndex.pinOwners.end() || pinOwner->second != definition->second )
4528 throwValidationError( pin.source, wxS( "pin does not belong to gate definition" ) );
4529
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" ) );
4533 }
4534 }
4535 }
4536
4537 struct DEFINITION_EDGE
4538 {
4539 uint32_t target;
4540 SOURCE_PROVENANCE source;
4541 };
4542
4543 std::unordered_map<uint32_t, std::vector<DEFINITION_EDGE>> definitionEdges;
4544
4545 for( const MODEL_PART_TYPE& partType : aModel.partTypes )
4546 {
4547 for( const MODEL_GATE& gate : partType.gates )
4548 {
4549 if( !gate.definition.id.IsValid() )
4550 continue;
4551
4552 for( const DEFINITION_REFERENCE& alternate : gate.alternateDefinitions )
4553 definitionEdges[gate.definition.id.Value()].push_back( { alternate.id.Value(), alternate.source } );
4554 }
4555 }
4556
4557 std::unordered_map<uint32_t, uint8_t> definitionColors;
4558 std::function<void( uint32_t )> visitDefinition =
4559 [&]( uint32_t aDefinition )
4560 {
4561 definitionColors[aDefinition] = 1;
4562
4563 auto edges = definitionEdges.find( aDefinition );
4564
4565 if( edges == definitionEdges.end() )
4566 {
4567 definitionColors[aDefinition] = 2;
4568 return;
4569 }
4570
4571 for( const DEFINITION_EDGE& edge : edges->second )
4572 {
4573 if( definitionColors[edge.target] == 1 )
4574 throwValidationError( edge.source, wxS( "cyclic symbol definition reference" ) );
4575
4576 if( definitionColors[edge.target] == 0 )
4577 visitDefinition( edge.target );
4578 }
4579
4580 definitionColors[aDefinition] = 2;
4581 };
4582
4583 for( const auto& [definition, edges] : definitionEdges )
4584 {
4585 if( definitionColors[definition] == 0 )
4586 visitDefinition( definition );
4587 }
4588 }
4589
4590
4591 void validatePlacements( const PADS_SCH_MODEL& aModel, const MODEL_REFERENCE_INDEX& aIndex )
4592 {
4593 for( const MODEL_PLACEMENT& placement : aModel.placements )
4594 {
4595 if( !aIndex.sheets.contains( placement.sheet.id.Value() ) )
4596 throwValidationError( placement.sheet.source, wxS( "unresolved placement sheet reference" ) );
4597
4598 auto partType = aIndex.partTypes.find( placement.partType.id.Value() );
4599
4600 if( partType == aIndex.partTypes.end() )
4601 throwValidationError( placement.partType.source, wxS( "unresolved placement part-type reference" ) );
4602
4603 auto placementDefinition = aIndex.definitions.find( placement.definition.id.Value() );
4604
4605 if( placementDefinition == aIndex.definitions.end() )
4606 throwValidationError( placement.definition.source, wxS( "unresolved placement definition" ) );
4607
4608 for( const PIN_REFERENCE& pin : placement.pins )
4609 {
4610 auto owner = aIndex.pinOwners.find( pin.id.Value() );
4611
4612 if( owner == aIndex.pinOwners.end() || owner->second != placementDefinition->second )
4613 throwValidationError( pin.source, wxS( "placement pin does not belong to selected definition" ) );
4614 }
4615
4616 if( !placement.gate )
4617 continue;
4618
4619 auto gate = aIndex.gates.find( placement.gate->id.Value() );
4620 auto gateOwner = aIndex.gateOwners.find( placement.gate->id.Value() );
4621
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" ) );
4626
4627 const MODEL_GATE& selectedGate = *gate->second;
4628 const bool definitionMatches = selectedGate.definition.id == placement.definition.id
4629 || std::ranges::any_of( selectedGate.alternateDefinitions,
4630 [&]( const DEFINITION_REFERENCE& aDefinition )
4631 {
4632 return aDefinition.id == placement.definition.id;
4633 } )
4634 || std::ranges::any_of( selectedGate.decalGroupMembers,
4635 [&]( const DEFINITION_REFERENCE& aDefinition )
4636 {
4637 return aDefinition.id == placement.definition.id;
4638 } );
4639
4640 if( !definitionMatches )
4641 throwValidationError( placement.definition.source,
4642 wxS( "placement definition does not belong to selected gate" ) );
4643
4644 auto definition = aIndex.definitions.find( placement.definition.id.Value() );
4645
4646 if( definition == aIndex.definitions.end() )
4647 throwValidationError( placement.definition.source, wxS( "unresolved placement definition" ) );
4648
4649 for( const PIN_REFERENCE& pin : placement.pins )
4650 {
4651 auto owner = aIndex.pinOwners.find( pin.id.Value() );
4652
4653 if( owner == aIndex.pinOwners.end() || owner->second != definition->second )
4654 throwValidationError( pin.source, wxS( "placement pin does not belong to selected definition" ) );
4655 }
4656 }
4657 }
4658
4659
4660 void validateSheetBoundContent( const PADS_SCH_MODEL& aModel, const MODEL_REFERENCE_INDEX& aIndex )
4661 {
4662 for( const MODEL_NET& net : aModel.nets )
4663 {
4664 validateSheetRef( net, aIndex, wxS( "net" ) );
4665
4666 for( const MODEL_CONNECTION& connection : net.connections )
4667 {
4668 if( connection.endpoints.empty() )
4669 throwValidationError( connection.source, wxS( "connection has no endpoints" ) );
4670
4671 for( const MODEL_CONNECTION_ENDPOINT& endpoint : connection.endpoints )
4672 {
4673 if( !endpointIsValid( aIndex, endpoint ) )
4674 {
4675 throwValidationError( endpoint.source,
4676 wxS( "empty, mixed, or unresolved connection endpoint" ) );
4677 }
4678
4679 if( !endpoint.placement )
4680 continue;
4681
4682 auto placement = aIndex.placements.find( endpoint.placement->id.Value() );
4683
4684 if( placement != aIndex.placements.end() && placement->second->sheet.id != net.sheet.id )
4685 {
4686 throwValidationError( endpoint.source,
4687 wxS( "connection endpoint placement sheet does not match net sheet" ) );
4688 }
4689 }
4690 }
4691 }
4692
4693 for( const MODEL_BUS& bus : aModel.buses )
4694 {
4695 validateSheetRef( bus, aIndex, wxS( "bus" ) );
4696
4697 for( const NET_REFERENCE& member : bus.memberNets )
4698 {
4699 auto net = aIndex.nets.find( member.id.Value() );
4700
4701 if( net == aIndex.nets.end() )
4702 throwValidationError( member.source, wxS( "unresolved bus member-net reference" ) );
4703
4704 if( net->second->sheet.id != bus.sheet.id )
4705 throwValidationError( member.source, wxS( "bus member-net sheet does not match bus sheet" ) );
4706 }
4707
4708 for( const MODEL_BUS_ENTRY& entry : bus.entries )
4709 {
4710 auto net = aIndex.nets.find( entry.memberNet.id.Value() );
4711
4712 if( net == aIndex.nets.end() )
4713 throwValidationError( entry.memberNet.source, wxS( "unresolved bus-entry net reference" ) );
4714
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" ) );
4718
4719 if( std::ranges::none_of( bus.memberNets,
4720 [&]( const NET_REFERENCE& aMember )
4721 {
4722 return aMember.id == entry.memberNet.id;
4723 } ) )
4724 {
4725 throwValidationError( entry.source, wxS( "bus-entry net is absent from bus member nets" ) );
4726 }
4727 }
4728 }
4729
4730 for( const MODEL_LABEL& label : aModel.labels )
4731 {
4732 validateSheetRef( label, aIndex, wxS( "label" ) );
4733
4734 for( const SHEET_REFERENCE& linkedSheet : label.linkedSheets )
4735 {
4736 if( !aIndex.sheets.contains( linkedSheet.id.Value() ) )
4737 throwValidationError( linkedSheet.source, wxS( "unresolved cross-sheet label reference" ) );
4738 }
4739 }
4740
4741 for( const MODEL_JUNCTION& junction : aModel.junctions )
4742 validateSheetRef( junction, aIndex, wxS( "junction" ) );
4743
4744 for( const MODEL_TEXT& text : aModel.texts )
4745 validateSheetRef( text, aIndex, wxS( "text" ) );
4746
4747 for( const MODEL_PAGE_GRAPHIC& graphic : aModel.graphics )
4748 validateSheetRef( graphic, aIndex, wxS( "page-graphic" ) );
4749
4750 std::set<uint32_t> worksheetSheets;
4751
4752 for( const MODEL_WORKSHEET& worksheet : aModel.worksheets )
4753 {
4754 validateSheetRef( worksheet, aIndex, wxS( "worksheet" ) );
4755
4756 if( !worksheetSheets.insert( worksheet.sheet.id.Value() ).second )
4757 throwValidationError( worksheet.source, wxS( "duplicate worksheet for sheet" ) );
4758
4759 if( worksheet.graphics.empty() )
4760 throwValidationError( worksheet.source, wxS( "worksheet has no graphics" ) );
4761 }
4762
4763 for( const MODEL_EMBEDDED_IMAGE& image : aModel.images )
4764 {
4765 validateSheetRef( image, aIndex, wxS( "embedded-image" ) );
4766
4767 if( image.type != MODEL_EMBEDDED_IMAGE_TYPE::UNSUPPORTED && image.data.empty() )
4768 throwValidationError( image.source, wxS( "embedded image has no decoded payload" ) );
4769 }
4770 }
4771
4772
4773 void validateSheetHierarchy( const PADS_SCH_MODEL& aModel, const MODEL_REFERENCE_INDEX& aIndex )
4774 {
4775 enum class VISIT_STATE : uint8_t
4776 {
4777 VISITING,
4778 COMPLETE
4779 };
4780 std::unordered_map<uint32_t, VISIT_STATE> visitStates;
4781
4782 for( const MODEL_SHEET& sheet : aModel.sheets )
4783 {
4784 const MODEL_SHEET* current = &sheet;
4785 std::vector<const MODEL_SHEET*> path;
4786
4787 while( current && !visitStates.contains( current->id.Value() ) )
4788 {
4789 visitStates.emplace( current->id.Value(), VISIT_STATE::VISITING );
4790 path.push_back( current );
4791
4792 if( !current->parent )
4793 {
4794 current = nullptr;
4795 break;
4796 }
4797
4798 auto parent = aIndex.sheets.find( current->parent->id.Value() );
4799
4800 if( parent == aIndex.sheets.end() )
4801 break;
4802
4803 current = parent->second;
4804 }
4805
4806 if( current && visitStates.at( current->id.Value() ) == VISIT_STATE::VISITING )
4807 throwValidationError( current->source, wxS( "cyclic sheet hierarchy" ) );
4808
4809 for( const MODEL_SHEET* visited : path )
4810 visitStates[visited->id.Value()] = VISIT_STATE::COMPLETE;
4811 }
4812 }
4813
4814
4815 std::vector<MODEL_FIELD> decodeDesignSettings( const std::vector<uint8_t>& aBytes,
4816 const PADS_IO::BINARY_CURSOR& aCursor, const PADS_SCH_SDB& aSdb,
4817 const wxString& aSourceName, PADS_SCH_MODEL& aModel )
4818 {
4819 const SCH_SDB_POOL& sheetPool = aSdb.Pools()[3];
4820
4821 if( sheetPool.usedBytes != sheetPool.count * SHEET_RECORD_BYTES )
4822 {
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" ) );
4827 }
4828
4829 const SCH_SDB_POOL& settingsPool = aSdb.Pools()[5];
4830
4831 if( settingsPool.count != 100 || settingsPool.usedBytes != 400 )
4832 {
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" ) );
4837 }
4838
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;
4843
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;
4848
4849 while( pageFieldEnd < pageFieldOffset + PAGE_FIELD_MAX_BYTES && aBytes[pageFieldEnd] != 0 )
4850 ++pageFieldEnd;
4851
4852 SOURCE_PROVENANCE pageSource = settingsSource;
4853 pageSource.absoluteOffset += PAGE_FIELD_OFFSET;
4854 pageSource.length = pageFieldEnd - PAGE_FIELD_OFFSET;
4855
4856 std::string pageField( aBytes.begin() + pageFieldOffset, aBytes.begin() + pageFieldEnd );
4857 std::string pageDesignator;
4858
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 );
4863 else
4864 throwDecodeError( pageSource, wxS( "invalid design page-size field" ) );
4865
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;
4869
4870 SOURCE_PROVENANCE fontModeSource = settingsSource;
4871 fontModeSource.absoluteOffset += 252;
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 ),
4876 fontModeSource ) );
4877
4878 if( fontModeRaw == 0 )
4879 {
4880 aModel.settings.fontMode = MODEL_FONT_MODE::STROKE;
4881 }
4882 else if( fontModeRaw == 1 )
4883 {
4884 aModel.settings.fontMode = MODEL_FONT_MODE::SYSTEM;
4885 }
4886 else
4887 {
4888 aModel.settings.fontMode = MODEL_FONT_MODE::UNKNOWN;
4889 SOURCE_PROPERTY& property = aModel.settings.properties.back();
4891 aModel.diagnostics.push_back( MakePropertyDiagnostic( RPT_SEVERITY_WARNING, property,
4892 wxS( "unknown PADS schematic font mode preserved; "
4893 "using KiCad stroke font" ) ) );
4894 }
4895
4896 const SCH_SDB_POOL& fontPool = aSdb.Pools()[19];
4897
4898 if( fontPool.usedBytes != fontPool.count * FONT_RECORD_BYTES )
4899 {
4900 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "font directory" ), 19, 0,
4901 outerControllerOffset( aSdb, 19 ), fontPool.usedBytes, -1 );
4902 throwDecodeError( source, wxS( "controller byte count does not match 36-byte records" ) );
4903 }
4904
4905 if( fontPool.count > 0 )
4906 {
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 );
4912 }
4913 else if( aModel.settings.fontMode == MODEL_FONT_MODE::SYSTEM )
4914 {
4915 SOURCE_PROPERTY property = sourceProperty( wxS( "default_system_font" ), wxS( "" ), fontModeSource );
4916 property.disposition = PROPERTY_DISPOSITION::UNSUPPORTED;
4917 aModel.diagnostics.push_back( MakePropertyDiagnostic( RPT_SEVERITY_WARNING, property,
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 ) );
4921 }
4922
4923 std::vector<MODEL_FIELD> titleFields;
4924 const SCH_SDB_POOL& titleFieldPool = aSdb.Pools()[1];
4925 size_t titleOffset = outerControllerOffset( aSdb, 1 );
4926 const size_t titleEnd = titleOffset + titleFieldPool.usedBytes;
4927 size_t titleRecord = 0;
4928
4929 while( titleOffset + 6 <= titleEnd
4930 && std::equal( aBytes.begin() + titleOffset, aBytes.begin() + titleOffset + 6, "Field\n" ) )
4931 {
4932 size_t terminator = titleOffset;
4933
4934 while( terminator < titleEnd && aBytes[terminator] != 0 )
4935 ++terminator;
4936
4937 SOURCE_PROVENANCE source = sourceAt( aSourceName, aModel.version, wxS( "title field" ), 1, titleRecord,
4938 titleOffset, terminator - titleOffset + 1, -1 );
4939
4940 size_t separator = titleOffset + 6;
4941
4942 while( separator < terminator && aBytes[separator] != 1 )
4943 ++separator;
4944
4945 if( terminator == titleEnd || terminator - titleOffset < 7 || separator == terminator
4946 || !std::equal( aBytes.begin() + titleOffset, aBytes.begin() + titleOffset + 6, "Field\n" ) )
4947 {
4948 throwDecodeError( source, wxS( "invalid title-field name record" ) );
4949 }
4950
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 );
4953 SOURCE_PROVENANCE nameSource = source;
4954 nameSource.absoluteOffset += 6;
4955 nameSource.length = nameBytes.size();
4956 SOURCE_PROVENANCE valueSource = source;
4957 valueSource.absoluteOffset = separator + 1;
4958 valueSource.length = valueBytes.size();
4959 MODEL_FIELD field;
4960 field.source = source;
4961 field.name = PADS_SCH_BINARY_PARSER::DecodeString( nameBytes, DEFAULT_CODE_PAGE, nameSource,
4962 aModel.diagnostics );
4963 field.value = PADS_SCH_BINARY_PARSER::DecodeString( valueBytes, DEFAULT_CODE_PAGE, valueSource,
4964 aModel.diagnostics );
4965 field.presentation.source = source;
4966 titleFields.push_back( std::move( field ) );
4967 titleOffset = terminator + 1;
4968 ++titleRecord;
4969 }
4970
4971 if( titleFields.empty() )
4972 {
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" ) );
4977 }
4978
4979 return titleFields;
4980 }
4981
4982
4983 void decodeSheets( const std::vector<uint8_t>& aBytes, const PADS_IO::BINARY_CURSOR& aCursor,
4984 const PADS_SCH_SDB& aSdb, const wxString& aSourceName,
4985 const std::vector<MODEL_FIELD>& aTitleFields, PADS_SCH_MODEL& aModel )
4986 {
4987 const size_t sheetIndexOffset = outerControllerOffset( aSdb, 3 );
4988 auto sheetBlocks = aSdb.Blocks()
4989 | std::views::filter(
4990 []( const SCH_SDB_BLOCK& aBlock )
4991 {
4992 return aBlock.kind == SCH_SDB_BLOCK_KIND::SHEET;
4993 } );
4994 auto sheetBlock = sheetBlocks.begin();
4995
4996 for( size_t index = 0; index < aSdb.Pools()[3].count; ++index, ++sheetBlock )
4997 {
4998 size_t recordOffset = sheetIndexOffset + index * SHEET_RECORD_BYTES;
4999 SOURCE_PROVENANCE provenance = sourceAt( aSourceName, aModel.version, wxS( "sheet" ), 3, index,
5000 recordOffset, SHEET_RECORD_BYTES, static_cast<int>( index ) );
5001
5002 if( sheetBlock == sheetBlocks.end() || aCursor.U32At( recordOffset ) != sheetBlock->offset
5003 || aCursor.U32At( recordOffset + 4 ) != sheetBlock->bytes )
5004 {
5005 throwDecodeError( provenance, wxS( "sheet-index record references the wrong SDB object class" ) );
5006 }
5007
5008 constexpr size_t nameOffset = 14;
5009
5010 if( aCursor.U16At( recordOffset + 10 ) != 0xFFFF || aCursor.U16At( recordOffset + 12 ) != 0xFFFF )
5011 throwDecodeError( provenance, wxS( "invalid sheet-index class marker" ) );
5012
5013 size_t nameEnd = recordOffset + nameOffset;
5014
5015 while( nameEnd < recordOffset + SHEET_RECORD_BYTES && aBytes[nameEnd] != 0 )
5016 ++nameEnd;
5017
5018 if( nameEnd == recordOffset + SHEET_RECORD_BYTES )
5019 throwDecodeError( provenance, wxS( "unterminated sheet name" ) );
5020
5021 std::vector<uint8_t> nameBytes( aBytes.begin() + recordOffset + nameOffset, aBytes.begin() + nameEnd );
5022 SOURCE_PROVENANCE nameSource = provenance;
5023 nameSource.absoluteOffset += nameOffset;
5024 nameSource.length = nameBytes.size();
5025
5026 MODEL_SHEET sheet;
5027 sheet.id = SHEET_ID( aCursor.U16At( recordOffset + 8 ) );
5028 sheet.index = sheet.id.IsValid() ? sheet.id.Value() - 1 : std::numeric_limits<size_t>::max();
5029 sheet.source = provenance;
5030 sheet.name = PADS_SCH_BINARY_PARSER::DecodeString( nameBytes, DEFAULT_CODE_PAGE, nameSource,
5031 aModel.diagnostics );
5032
5033 if( sheet.name.text.empty() )
5034 sheet.name.text = wxS( "$$$NONE" );
5035
5036 sheet.pageSize = aModel.settings.pageSize;
5037 sheet.defaultLineWidth = aModel.settings.defaultLineWidth;
5038 sheet.defaultBusWidth = aModel.settings.defaultBusWidth;
5039 sheet.titleBlockFields = aTitleFields;
5040
5041 auto title = std::ranges::find_if( sheet.titleBlockFields,
5042 []( const MODEL_FIELD& aField )
5043 {
5044 return aField.name.text == wxS( "Title" );
5045 } );
5046
5047 if( title != sheet.titleBlockFields.end() )
5048 sheet.title = title->value;
5049
5050 aModel.sheets.push_back( std::move( sheet ) );
5051 }
5052 }
5053
5054
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,
5058 PADS_SCH_MODEL& aModel )
5059 {
5060 for( size_t record = 0; record < aTextCount; ++record )
5061 {
5062 size_t recordOffset = aTextBase + record * TEXT_RECORD_BYTES;
5063
5064 if( aCursor.U16At( recordOffset + 24 ) != aCursor.U16At( recordOffset + 26 ) )
5065 continue;
5066
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 );
5071
5072 if( stringOffset > aHeapBytes )
5073 {
5074 SOURCE_PROVENANCE offsetSource = textSource;
5075 offsetSource.absoluteOffset += 8;
5076 offsetSource.length = 4;
5077 throwDecodeError( offsetSource, wxS( "free-text string offset leaves controller 2" ) );
5078 }
5079
5080 if( stringBytes == 0 || stringBytes > aHeapBytes - stringOffset )
5081 {
5082 SOURCE_PROVENANCE lengthSource = textSource;
5083 lengthSource.absoluteOffset += 20;
5084 lengthSource.length = 2;
5085 throwDecodeError( lengthSource, wxS( "free-text string length leaves controller 2" ) );
5086 }
5087
5088 if( aBytes[aHeapBase + stringOffset + stringBytes - 1] != 0 )
5089 {
5090 SOURCE_PROVENANCE terminatorSource =
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" ) );
5094 }
5095
5096 SOURCE_PROVENANCE stringSource =
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 );
5102
5104 text.source = textSource;
5105 text.sheet = { aModel.sheets[aSheetIndex].id, textSource };
5106 text.text =
5107 PADS_SCH_BINARY_PARSER::DecodeString( string, DEFAULT_CODE_PAGE, stringSource, aModel.diagnostics );
5108 text.position = { decodeCoordinate( aCursor.U16At( recordOffset + 12 ) ),
5109 decodeCoordinate( aCursor.U16At( recordOffset + 14 ) ), textSource };
5110 text.angle = NormalizeAngle( aCursor.U16At( recordOffset + 16 ) );
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 );
5118
5119 SOURCE_PROVENANCE fontHandleSource = textSource;
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 );
5124
5125 SOURCE_PROVENANCE displaySource = textSource;
5126 displaySource.absoluteOffset += 31;
5127 displaySource.length = 1;
5128 text.presentation.properties.push_back( sourceProperty(
5129 wxS( "display_flags" ), wxString::Format( wxS( "%u" ), displayFlags ), displaySource ) );
5130
5131 SOURCE_PROVENANCE relationshipSource = textSource;
5132 relationshipSource.objectClass = wxS( "free text relationship" );
5133 relationshipSource.absoluteOffset += 28;
5134 relationshipSource.length = 2;
5135 uint16_t relationship = aCursor.U16At( relationshipSource.absoluteOffset );
5136 SOURCE_PROPERTY relationshipProperty;
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 );
5142 relationshipProperty.value.encoding = STRING_ENCODING_STATUS::CODE_PAGE;
5143 relationshipProperty.value.source = relationshipSource;
5144 relationshipProperty.value.codePage = DEFAULT_CODE_PAGE;
5145 relationshipProperty.value.codePageName = wxS( "windows-1252" );
5146 relationshipProperty.disposition = PROPERTY_DISPOSITION::PRESERVED;
5147 relationshipProperty.source = relationshipSource;
5148 text.properties.push_back( std::move( relationshipProperty ) );
5149 aModel.texts.push_back( std::move( text ) );
5150 }
5151 }
5152
5153
5154 void decodeSheetBlocks( const std::vector<uint8_t>& aBytes, const PADS_IO::BINARY_CURSOR& aCursor,
5155 const PADS_SCH_SDB& aSdb, const wxString& aSourceName, PADS_SCH_MODEL& aModel )
5156 {
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 );
5161
5162 if( placementSchema.decoded )
5163 {
5164 placementData = placementGlobals( aSdb, aSourceName, aModel.settings );
5165 connectivityData = connectivityGlobals( aBytes, aCursor, aSdb, aSourceName, aModel );
5166 }
5167
5168 for( const SCH_SDB_BLOCK& block : aSdb.Blocks() )
5169 {
5170 if( block.kind != SCH_SDB_BLOCK_KIND::SHEET )
5171 continue;
5172
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 );
5178
5179 SOURCE_PROVENANCE controllerSource = sourceAt( aSourceName, aModel.version, wxS( "text controller" ), 1, 0,
5180 payload, textBytes, static_cast<int>( sheetIndex ) );
5181
5182 if( textBytes != textCount * TEXT_RECORD_BYTES )
5183 throwDecodeError( controllerSource,
5184 wxS( "text-controller byte count does not match 32-byte records" ) );
5185
5186 size_t heapOffset = payload + textBytes;
5187
5188 if( !placementSchema.decoded )
5189 {
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(
5193 { controllerSource,
5195 { aBytes.begin() + payload, aBytes.begin() + payload + textBytes } } );
5196 aModel.preservedControllerPayloads.push_back(
5197 { heapSource,
5199 { aBytes.begin() + heapOffset, aBytes.begin() + heapOffset + heapBytes } } );
5200 decodeDefinitionsAndParts( aBytes, aCursor, block, sheetIndex, aSourceName, aModel );
5201 ++sheetIndex;
5202 continue;
5203 }
5204
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 );
5210 ++sheetIndex;
5211 }
5212 }
5213
5214
5215 void decodeOleImages( const std::vector<uint8_t>& aBytes, const PADS_SCH_SDB& aSdb, const wxString& aSourceName,
5216 PADS_SCH_MODEL& aModel )
5217 {
5218 for( size_t index = 0; index < aSdb.OleItems().size(); ++index )
5219 {
5220 const SCH_SDB_OLE_ITEM& item = aSdb.OleItems()[index];
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 );
5226 image.id = IMAGE_ID( index );
5227 image.source = source;
5228 image.sheet = { aModel.sheets[item.sheetPlane].id, source };
5229 image.streamName = wxString::FromUTF8( payload.streamName );
5230 image.extent = item.extent;
5231 image.databaseBox = { item.left, item.bottom, item.right, item.top };
5232 SOURCE_PROVENANCE boxSource = source;
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 );
5240
5241 image.position = { left + ( right - left ) / 2, top + ( bottom - top ) / 2, boxSource };
5242 image.size = { std::abs( right - left ), std::abs( bottom - top ), boxSource };
5243 image.mirrorHorizontal = right < left;
5244 image.mirrorVertical = bottom < top;
5245 image.flags = item.flags;
5246 image.data = std::move( payload.data );
5247
5248 switch( payload.type )
5249 {
5255 aModel.diagnostics.emplace_back(
5257 wxS( "embedded OLE object has no supported BMP, DIB, or WMF stream" ) );
5258 break;
5259 }
5260
5261 if( right == left || bottom == top )
5262 {
5264 aModel.diagnostics.emplace_back(
5265 RPT_SEVERITY_WARNING, boxSource,
5266 wxS( "embedded OLE image has a zero-size database box and was skipped" ) );
5267 }
5268
5269 if( item.flags != 1 )
5270 {
5271 SOURCE_PROVENANCE flagsSource = source;
5272 flagsSource.objectClass = wxS( "embedded OLE image flags" );
5273 flagsSource.absoluteOffset = item.boxOffset + 20;
5274 flagsSource.length = 4;
5275 PADS_SCH_BINARY_PARSER::RecordUnknownEnum( wxS( "embedded OLE image flags" ), item.flags, flagsSource,
5276 aModel.diagnostics );
5277 }
5278
5279 aModel.images.push_back( std::move( image ) );
5280 }
5281 }
5282
5283
5284} // namespace
5285
5286
5287wxString FormatParserError( const SOURCE_PROVENANCE& aSource, const wxString& aMessage )
5288{
5289 return wxString::Format(
5290 wxS( "%s: PADS schematic v0x%04X %s (controller %d, record %llu, sheet %d) at offset 0x%llX: %s" ),
5291 aSource.file, aSource.version, aSource.objectClass, aSource.controller,
5292 static_cast<unsigned long long>( aSource.recordIndex ), aSource.sheet,
5293 static_cast<unsigned long long>( aSource.absoluteOffset ), aMessage );
5294}
5295
5296
5298{
5299 return std::tie( source.file, source.version, source.objectClass, source.controller, source.recordIndex,
5300 source.absoluteOffset, source.length, source.sheet, property.name, property.disposition )
5301 < std::tie( aOther.source.file, aOther.source.version, aOther.source.objectClass, aOther.source.controller,
5302 aOther.source.recordIndex, aOther.source.absoluteOffset, aOther.source.length,
5303 aOther.source.sheet, aOther.property.name, aOther.property.disposition );
5304}
5305
5306
5307std::optional<DIAGNOSTIC_PROPERTY_KEY> DiagnosticPropertyKey( const PARSER_DIAGNOSTIC& aDiagnostic )
5308{
5309 if( !aDiagnostic.property )
5310 return std::nullopt;
5311
5312 return DIAGNOSTIC_PROPERTY_KEY{ aDiagnostic.source, *aDiagnostic.property };
5313}
5314
5315
5317 const wxString& aMessage )
5318{
5319 return MakePropertyDiagnostic( aSeverity, aProperty.source, aProperty.name.text, aProperty.disposition, aMessage );
5320}
5321
5322
5323PARSER_DIAGNOSTIC MakePropertyDiagnostic( SEVERITY aSeverity, const SOURCE_PROVENANCE& aSource, const wxString& aName,
5324 PROPERTY_DISPOSITION aDisposition, const wxString& aMessage )
5325{
5326 return { aSeverity, aSource, aMessage, DIAGNOSTIC_PROPERTY_IDENTITY{ aName, aDisposition } };
5327}
5328
5329
5331{
5332 validateIdentity( *this );
5333
5334 const MODEL_REFERENCE_INDEX index( *this );
5335
5336 validateSymbolGraph( *this, index );
5337 validatePlacements( *this, index );
5338 validateSheetBoundContent( *this, index );
5339 validateSheetHierarchy( *this, index );
5340}
5341
5342
5343PADS_SCH_MODEL PADS_SCH_BINARY_PARSER::Parse( const std::vector<uint8_t>& aBytes, const wxString& aSourceName ) const
5344{
5345 PADS_SCH_SDB sdb;
5346 sdb.Load( aBytes );
5347
5348 const PADS_IO::BINARY_CURSOR& cursor = sdb.Cursor();
5350 model.version = sdb.Version();
5351 model.subversion = cursor.U16At( 6 );
5352 model.source = { aSourceName, model.version, wxS( "model" ), -1, 0, 0, aBytes.size(), -1 };
5353 model.settings.codePage = DEFAULT_CODE_PAGE;
5354
5355 const std::vector<MODEL_FIELD> titleFields = decodeDesignSettings( aBytes, cursor, sdb, aSourceName, model );
5356
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();
5363 return model;
5364}
5365
5366
5367SOURCE_STRING PADS_SCH_BINARY_PARSER::DecodeString( const std::vector<uint8_t>& aBytes, uint32_t aCodePage,
5368 const SOURCE_PROVENANCE& aSource,
5369 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics,
5370 const wxString& aRecordedCodePageName )
5371{
5372 SOURCE_STRING result{ aBytes, {}, STRING_ENCODING_STATUS::UTF8, aSource };
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;
5378
5379 if( aCodePage == 1252 )
5381 else if( aCodePage != 65001 )
5383
5384 if( aCodePage != 65001 && aCodePage != 1252 )
5385 {
5386 aDiagnostics.push_back( { RPT_SEVERITY_WARNING, aSource,
5387 wxString::Format( wxS( "unknown code page %u; bytes preserved and "
5388 "non-ASCII bytes decoded as U+FFFD" ),
5389 aCodePage ) } );
5390 }
5391
5392 if( aBytes.empty() )
5393 return result;
5394
5395 if( aCodePage == 1252 )
5396 {
5397 result.text = decodeWindows1252( aBytes );
5398 return result;
5399 }
5400
5401 if( aCodePage != 65001 )
5402 {
5403 result.text = decodeUnknownCodePage( aBytes );
5404 return result;
5405 }
5406
5407 bool invalid = false;
5408 result.text = decodeUtf8( aBytes, invalid );
5409
5410 if( invalid )
5411 {
5413 aDiagnostics.push_back( { RPT_SEVERITY_WARNING, aSource,
5414 wxS( "invalid UTF-8 bytes replaced with U+FFFD; original bytes preserved" ) } );
5415 }
5416
5417 return result;
5418}
5419
5420
5421void PADS_SCH_BINARY_PARSER::RecordUnknownEnum( const wxString& aEnumName, uint32_t aValue,
5422 const SOURCE_PROVENANCE& aSource,
5423 std::vector<PARSER_DIAGNOSTIC>& aDiagnostics )
5424{
5425 aDiagnostics.push_back( { RPT_SEVERITY_WARNING, aSource,
5426 wxString::Format( wxS( "unknown %s %u preserved" ), aEnumName, aValue ) } );
5427}
5428
5429} // namespace PADS_SCH_BINARY
int index
const char * name
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
uint16_t Version() const
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
std::string source
pinElectricalType
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)
Definition base64.cpp:113
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
OLE_IMAGE_PAYLOAD ExtractOleImage(const uint8_t *aCfb, size_t aSize)
Prefer CONTENTS, then OlePres000, then the native stream.
SEVERITY
@ RPT_SEVERITY_WARNING
std::vector< uint8_t > data
Definition ole_image.h:48
std::string streamName
Definition ole_image.h:49
OLE_IMAGE_TYPE type
Definition ole_image.h:47
bool operator<(const DIAGNOSTIC_PROPERTY_KEY &aOther) const
SOURCE_PROVENANCE source
std::optional< DIAGNOSTIC_PROPERTY_IDENTITY > property
std::string path
KIBIS top(path, &reporter)
KIBIS_MODEL * model
KIBIS_PIN * pin
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
const SHAPE_LINE_CHAIN chain
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.