KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pads_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 (C) 2026 KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include "pads_binary_parser.h"
21
22#include <algorithm>
23#include <array>
24#include <cctype>
25#include <chrono>
26#include <cstdio>
27#include <cmath>
28#include <cstdlib>
29#include <cstring>
30#include <limits>
31#include <numbers>
32#include <numeric>
33#include <optional>
34#include <set>
35#include <unordered_set>
36
37#include <fmt/format.h>
38#include <geometry/eda_angle.h>
40#include <ki_exception.h>
41#include <wx/log.h>
42
43namespace PADS_IO
44{
45
46// Section 4 pad-shape codes. The finger shapes 0 (OF) and 1 (RF) carry a non-zero finLength
47// (size B); the round 2 (R) and square 3 (S) never do.
48static const std::map<uint8_t, std::string> PAD_SHAPE_NAMES = {
49 { 0x00, "OF" }, { 0x01, "RF" }, { 0x02, "R" }, { 0x03, "S" },
50 { 0x06, "RT" }, { 0x07, "ST" }, { 0x08, "RA" }, { 0x09, "SA" },
51};
52
53
54// Per-version field layout for the section-4 padstack records. As with the placements, the old
55// and new dialects carry the same geometry fields at different offsets.
57{
58 int padWidthOff = 0;
59 int drillOff = 0;
60 int finLenOff = 0;
61 int cornerOff = 0;
62 int angleOff = 0;
64 int markerOff = 0;
65 int shapeOff = 0;
67 int drillStartOff = -1;
68 int drillEndOff = -1;
69};
70
71
72static const PADSTACK_LAYOUT& padstackLayout( uint16_t aVersion )
73{
74 static constexpr PADSTACK_LAYOUT v2021{ .padWidthOff = 24,
75 .drillOff = 28,
76 .finLenOff = 32,
77 .cornerOff = 36,
78 .angleOff = 40,
79 .layerStartOff = 44,
80 .markerOff = 48,
81 .shapeOff = 49,
82 .layerCountOff = 50,
83 .drillStartOff = -1,
84 .drillEndOff = -1 };
85 static constexpr PADSTACK_LAYOUT v2022{ .padWidthOff = 20,
86 .drillOff = 24,
87 .finLenOff = 28,
88 .cornerOff = 32,
89 .angleOff = 40,
90 .layerStartOff = 44,
91 .markerOff = 48,
92 .shapeOff = 49,
93 .layerCountOff = 50,
94 .drillStartOff = 51,
95 .drillEndOff = 52 };
96 static constexpr PADSTACK_LAYOUT vNew{ .padWidthOff = 28,
97 .drillOff = 32,
98 .finLenOff = 36,
99 .cornerOff = 44,
100 .angleOff = 48,
101 .layerStartOff = 52,
102 .markerOff = 56,
103 .shapeOff = 57,
104 .layerCountOff = 58,
105 .drillStartOff = 59,
106 .drillEndOff = 60 };
107
108 if( aVersion <= 0x2021 )
109 return v2021;
110
111 if( aVersion == 0x2022 )
112 return v2022;
113
114 return vNew;
115}
116
117
118// The 112-byte header shared by the LINES/DRW owner and item records. Several decoders read the
119// same fields (origin, bounding box, run cursors, name, classifier word); one descriptor keeps
120// their offsets in a single place. The +24 word has two record-role-dependent meanings, both
121// named here: CLASS_WORD in the copper/keepout headers and PIECE_COUNT in the owner-run cursor.
122namespace DRW_ITEM
123{
124 constexpr size_t SIZE = 112;
125
126 // Ring rotation shared by every section-10 record access
127 constexpr size_t ROTATION = 68;
128
146} // namespace DRW_ITEM
147
148
149// PADS <= v2022 packs the same record into 100 bytes with its own name and origin offsets
151{
152 constexpr size_t SIZE = 100;
153 constexpr size_t NAME = 32;
154 constexpr size_t ORIGIN_X = 72;
155} // namespace DRW_ITEM_V2022
156
157
158// Block-class tags carried at DRW_ITEM::TYPE_TAG. 0x4D00 also marks the board-outline item and
159// is the library decal marker elsewhere.
160namespace DRW_TAG
161{
162 enum TAG : uint32_t
163 {
164 COPPER_FILL = 0x00004900, // filled copper region
165 COPPER_FILL_B = 0x0000FF00, // second filled-copper tag, same class/shape
166 LINE_ITEM = 0x00004D00 // line/outline item (board outline, v2026 line copper)
167 };
168} // namespace DRW_TAG
169
170
172
173
175
176
177bool BINARY_PARSER::IsBinaryPadsFile( const wxString& aFileName )
178{
179 std::vector<uint8_t> header;
180
181 if( !PADS_IO::ReadFileHeader( aFileName, header, 4 ) || header.size() < 4 )
182 return false;
183
184 if( !PADS_IO::HasSdbMagic( header, 0xFF ) )
185 return false;
186
187 return PADS_SDB::IsSupportedVersion( PADS_IO::getU16LE( header, 2 ) );
188}
189
190
192static void logParsePhase( const char* aWhat, std::chrono::steady_clock::time_point aStart )
193{
194 static const bool enabled = getenv( "KICAD_PADS_PROFILE" ) != nullptr;
195
196 if( !enabled )
197 return;
198
199 const double ms = std::chrono::duration<double, std::milli>( std::chrono::steady_clock::now() - aStart ).count();
200
201 fputs( fmt::format( "PROF {:<32} {:>8.1f} ms\n", aWhat, ms ).c_str(), stderr );
202}
203
204
205void BINARY_PARSER::Parse( const wxString& aFileName )
206{
207 std::vector<uint8_t> bytes;
208
209 if( !PADS_IO::ReadFileToBuffer( aFileName, bytes ) )
210 THROW_IO_ERROR( "Cannot open or read file" );
211
212 m_sdb.Load( std::move( bytes ) );
213
214 m_version = m_sdb.Version();
215 m_originX = m_sdb.Coords().OriginX();
216 m_originY = m_sdb.Coords().OriginY();
217
218 m_parameters.origin.x = static_cast<double>( m_originX );
219 m_parameters.origin.y = static_cast<double>( m_originY );
220
221#define KITIME( call ) \
222 do \
223 { \
224 auto _t0 = std::chrono::steady_clock::now(); \
225 call; \
226 logParsePhase( #call, _t0 ); \
227 } while( 0 )
228
229 // The call order below is load-bearing; the dependency edges noted at each group fix it.
230
231 // Container state loads the version, origin and parameter block.
233
234 // Part placements and the part-cluster groups that reference them.
237
238 // Padstacks and the decal / part-type tables that linkPartsToDecals joins at the end.
243
244 // Sections 10 and 11 are circularly serialized fixed arrays. Reconstruct their direct
245 // owner/piece links before any graphic decoder consumes them.
248
251
252 // Net names first; the net-class and diff-pair passes key off the net records they produce.
256
258
259 // Route-cell coordinate order is selected by each layer's serialized routing direction.
261
262 // Structural geometry.
269
271
272#undef KITIME
273
274 m_parts.erase( std::remove_if( m_parts.begin(), m_parts.end(),
275 []( const PART& p )
276 {
277 return p.name.empty();
278 } ),
279 m_parts.end() );
280}
281
282
283const SDB_SECTION* BINARY_PARSER::getSection( int aIndex ) const
284{
285 return m_sdb.Section( aIndex );
286}
287
288
289double BINARY_PARSER::toBasicCoordX( int32_t aRawValue ) const
290{
291 return static_cast<double>( aRawValue );
292}
293
294
295double BINARY_PARSER::toBasicCoordY( int32_t aRawValue ) const
296{
297 return static_cast<double>( aRawValue );
298}
299
300
301double BINARY_PARSER::toBasicAngle( int32_t aRawAngle ) const
302{
303 if( aRawAngle == 0 )
304 return 0.0;
305
306 return static_cast<double>( aRawAngle ) / static_cast<double>( ANGLE_SCALE );
307}
308
309
311{
312 // MAXIMUMLAYER lives in the same directly framed *PCB* board-setup parameter block as the
313 // coordinate origin.
314 if( !m_sdb.Coords().Found() )
315 THROW_IO_ERROR( "Missing PADS board origin" );
316
317 uint32_t headerBase = m_sdb.Coords().HeaderBase();
318
319 if( !m_cursor.InBounds( headerBase, 20 ) )
320 THROW_IO_ERROR( "Invalid PADS board-setup parameter extent" );
321
322 // Word 4 of the fixed u32 parameter block is the maximum layer count.
323 uint32_t maxLayer = m_sdb.RecordAt( headerBase ).U32( 16 );
324
325 if( maxLayer >= 1 && maxLayer <= 64 )
326 m_parameters.layer_count = static_cast<int>( maxLayer );
327 else
328 THROW_IO_ERROR( "Invalid PADS maximum-layer field" );
329
330 // Binary coordinates are BASIC units (1/38100 mil). MILS is only the display unit;
331 // coordinate handling uses BASIC mode in the wrapper via SetBasicUnitsMode(true).
333}
334
335
336PART BINARY_PARSER::makePlacementPart( const SDB_RECORD& aRec, int aXOff, std::optional<int> aYOff, int aAngleOff,
337 int aNameOff, const std::string& aRefDes ) const
338{
339 PART part;
340 part.name = aRefDes;
341 part.location.x = toBasicCoordX( aRec.I32( aXOff ) );
342 part.location.y = aYOff ? toBasicCoordY( aRec.I32( *aYOff ) ) : 0;
343 part.rotation = toBasicAngle( aRec.I32( aAngleOff ) );
344
345 // The side flag is the word at nameOff+28 in both dialects; bit 0 marks a bottom placement.
346 part.bottom_layer = ( aRec.U8( aNameOff + 28 ) & 0x01 ) != 0;
347 part.units = "M";
348 return part;
349}
350
351
353{
354 const SDB_SECTION* section = getSection( SECTION::Placements );
355
356 constexpr size_t LOGICAL_ROTATION = 44;
357
358 if( !section )
359 THROW_IO_ERROR( "Missing PADS placement controller" );
360
361 if( section->count == 0 )
362 return;
363
364 if( section->physicalCount != section->count || section->physicalOffset < LOGICAL_ROTATION
365 || ( section->stride != 96 && section->stride != 112 ) )
366 THROW_IO_ERROR( "Invalid PADS placement-controller framing" );
367
368 const size_t logicalBase = section->physicalOffset - LOGICAL_ROTATION;
369
370 if( !m_cursor.InBounds( logicalBase, section->totalBytes + LOGICAL_ROTATION ) )
371 THROW_IO_ERROR( "Invalid PADS placement-controller extent" );
372
373 for( uint32_t index = 0; index < section->physicalCount; ++index )
374 {
375 const size_t base = logicalBase + static_cast<size_t>( index ) * section->stride;
376 SDB_RECORD record = m_sdb.RecordAt( static_cast<uint32_t>( base ) );
377 std::string refdes = record.Str( 44, 16 );
378 const size_t nextBase = logicalBase + static_cast<size_t>( index + 1 ) * section->stride;
379 SDB_RECORD nextRecord = m_sdb.RecordAt( static_cast<uint32_t>( nextBase ) );
380
381 PART part = makePlacementPart( record, 60, 64, 68, 44, refdes );
382
383 if( section->stride == 112 )
384 m_partFieldStart[m_parts.size()] = record.I32( 96 );
385
386 if( section->stride == 96 )
387 m_partDecalIndex[m_parts.size()] = nextRecord.U32( 24 );
388 else
389 {
390 m_partTypeIndex[m_parts.size()] = nextRecord.U32( 4 );
391 m_partDecalAlternate[m_parts.size()] = nextRecord.U8( 17 );
392
393 // Flag 0x10 marks a NAME@DECAL placement outside the parttype alternates
394 if( nextRecord.U8( 16 ) & 0x10 )
395 m_partDecalIndex[m_parts.size()] = nextRecord.U32( 8 );
396 }
397
398 if( section->stride == 112 )
399 {
400 int32_t clusterId = record.I32( 108 );
401
402 if( clusterId > 0 )
403 m_partClusterId[m_parts.size()] = clusterId;
404 }
405
407 m_parts.push_back( std::move( part ) );
408 }
409}
410
412{
413 // A part cluster is a fixed 60-byte record, id@+0 and name@+4 (char[16], NUL-padded), in
414 // cluster order. The stored id and the record's 1-based ordinal both equal the CLSTID the
415 // +108 field references. Membership
416 // is captured during parsePartPlacements. The old 96-byte placement layout has no room for
417 // the +108 CLSTID, so old-format boards carry no clusters.
418 //
419 // Section 68 directly precedes section 69 in the physical loader stream.
420 if( isOldFormat() )
421 return;
422
423 const SDB_SECTION* sec68 = getSection( SECTION::Clusters );
424
425 if( !sec68 )
426 THROW_IO_ERROR( "Missing PADS cluster controller" );
427
428 if( sec68->count == 0 )
429 return;
430
431 if( sec68->stride != 60 )
432 THROW_IO_ERROR( "Invalid PADS cluster-controller stride" );
433
434 static constexpr size_t REC_SIZE = 60;
435 size_t sec69Rec0 = layerStackupBase();
436
437 if( sec69Rec0 == 0 )
438 THROW_IO_ERROR( "Missing PADS layer-stackup framing" );
439
440 constexpr size_t SEC69_LEAD_IN = 12;
441
442 if( sec69Rec0 < SEC69_LEAD_IN || sec68->count > ( sec69Rec0 - SEC69_LEAD_IN ) / REC_SIZE )
443 THROW_IO_ERROR( "Invalid PADS cluster-controller extent" );
444
445 size_t base = sec69Rec0 - SEC69_LEAD_IN - static_cast<size_t>( sec68->count ) * REC_SIZE;
446
447 for( uint32_t i = 0; i < sec68->count; ++i )
448 {
449 SDB_RECORD rec = m_sdb.RecordAt( base + i * REC_SIZE );
450 std::string name = rec.Str( 4, 16 );
451
452 // A misaligned base would read non-cluster bytes. The stored ordinal and printable name
453 // confirm the run without constraining retained state fields that vary among boards.
454 if( rec.U32( 0 ) != i + 1 || name.empty() )
455 THROW_IO_ERROR( "Invalid PADS cluster record" );
456
457 PART_CLUSTER cluster;
458 cluster.name = std::move( name );
459 cluster.id = static_cast<int>( i ) + 1;
460 m_clusters.push_back( std::move( cluster ) );
461 }
462}
463
464
466{
467 const SDB_SECTION* entry = getSection( SECTION::PadStacks );
468 const SDB_SECTION* layerSection = getSection( SECTION::PadShapes );
469
470 if( !entry || !layerSection )
471 THROW_IO_ERROR( "Missing PADS padstack controllers" );
472
473 const uint32_t expectedRecordSize = m_version <= 0x2021 ? 52 : m_version == 0x2022 ? 56 : 64;
474
475 if( entry->physicalCount != entry->count
476 || static_cast<uint64_t>( entry->count ) * expectedRecordSize != entry->totalBytes )
477 THROW_IO_ERROR( "Invalid PADS padstack-controller framing" );
478
479 if( entry->count == 0 )
480 return;
481
482 const uint32_t logicalRotation = m_version == 0x2022 ? 20 : m_version <= 0x2021 ? 24 : 28;
483
484 if( entry->physicalOffset < logicalRotation )
485 THROW_IO_ERROR( "Invalid PADS padstack-controller rotation" );
486
487 const PADSTACK_LAYOUT& layout = padstackLayout( m_version );
488 uint32_t recSize = entry->stride;
489
490 // Read one padstack record's default (layer 0) geometry. For finger pads (RF, OF, RC)
491 // finLength is the second dimension; round (R) and square (S) reuse sizeA.
492 auto readLayer = [&]( uint32_t aBase ) -> PAD_STACK_LAYER
493 {
494 SDB_RECORD rec = m_sdb.RecordAt( aBase );
495 std::string shapeName = "R";
496 auto shapeIt = PAD_SHAPE_NAMES.find( rec.U8( layout.shapeOff ) );
497
498 if( shapeIt != PAD_SHAPE_NAMES.end() )
499 shapeName = shapeIt->second;
500
501 int32_t padWidth = rec.I32( layout.padWidthOff );
502 int32_t drill = rec.I32( layout.drillOff );
503 int32_t finLength = rec.I32( layout.finLenOff );
504
505 PAD_STACK_LAYER psl;
506 psl.layer = -2;
507 psl.shape = shapeName;
508 psl.sizeA = static_cast<double>( padWidth );
509 psl.drill = static_cast<double>( drill );
510 psl.corner_radius = std::max( rec.I32( layout.cornerOff ), 0 );
511
512 if( m_version <= 0x2022 )
513 {
514 constexpr int OLD_NPTH_CLEARANCE = 4 * static_cast<int>( SDB_BASIC_PER_MIL );
515 psl.plated = drill > 0 && padWidth - drill > OLD_NPTH_CLEARANCE;
516 }
517 else
518 {
519 psl.plated = drill > 0 && drill < padWidth;
520 }
521
522 bool isFinger = ( shapeName == "RF" || shapeName == "OF" || shapeName == "RC" );
523
524 if( isFinger )
525 psl.rotation = toBasicAngle( rec.I32( layout.angleOff ) );
526
527 if( isFinger && finLength > 0 )
528 psl.sizeB = static_cast<double>( finLength );
529 else
530 psl.sizeB = static_cast<double>( padWidth );
531
532 return psl;
533 };
534
535 const uint32_t poolStart = entry->physicalOffset - logicalRotation;
536 const uint64_t poolBytes = static_cast<uint64_t>( entry->physicalCount ) * recSize;
537
538 if( !m_cursor.InBounds( poolStart, poolBytes ) )
539 THROW_IO_ERROR( "Invalid PADS padstack-pool extent" );
540
541 m_padStackPool.assign( entry->physicalCount, {} );
542 m_padStackDrillSpans.assign( entry->physicalCount, { 0, 0 } );
543 std::vector<int32_t> maxPadDiameter( entry->physicalCount, 0 );
544
545 const uint32_t layerRecordSize = m_version <= 0x2021 ? 20 : 24;
546 const uint32_t layerTableHeaderSize = m_version == 0x2022 ? 64 : m_version <= 0x2021 ? 20 : 24;
547 uint64_t layerTableStart64 = static_cast<uint64_t>( poolStart ) + poolBytes + layerTableHeaderSize;
548 const uint64_t layerTableBytes = static_cast<uint64_t>( layerSection->count ) * layerRecordSize;
549
550 if( layerTableBytes != layerSection->totalBytes || layerTableStart64 > m_data.size()
551 || layerTableBytes > m_data.size() - layerTableStart64 )
552 {
553 THROW_IO_ERROR( "Invalid PADS pad-layer-controller framing" );
554 }
555
556 const uint32_t layerTableStart = static_cast<uint32_t>( layerTableStart64 );
557
558 // Pad stacks are indexed by their position in the object array; part decals reference them by
559 // that stable index.
560 for( uint32_t i = 0; i < entry->physicalCount; ++i )
561 {
562 uint32_t base = poolStart + i * recSize;
563
564 if( m_sdb.RecordAt( base ).U8( layout.markerOff ) != 0xFE )
565 continue;
566
567 PAD_STACK_LAYER defaultLayer = readLayer( base );
568
569 // Slotted-drill metadata is carried by the following physical padstack record. Bit 3
570 // marks the carrier; +8 is the preceding stack's slot length and +12 its orientation.
571 if( m_version >= 0x2024 && defaultLayer.drill > 0 && i + 1 < entry->physicalCount )
572 {
573 SDB_RECORD nextRec = m_sdb.RecordAt( base + recSize );
574
575 if( ( nextRec.U32( 0 ) & 8U ) != 0 )
576 {
577 defaultLayer.slot_length = nextRec.I32( 8 );
578 defaultLayer.slot_orientation = toBasicAngle( nextRec.I32( 12 ) );
579 }
580 }
581
582 std::vector<PAD_STACK_LAYER>& layers = m_padStackPool[i];
583 layers.push_back( defaultLayer );
584 maxPadDiameter[i] = static_cast<int32_t>( defaultLayer.sizeA );
585
586 if( layout.drillStartOff >= 0 && layout.drillEndOff >= 0 )
587 {
588 m_padStackDrillSpans[i] = { m_cursor.U8At( base + layout.drillStartOff ),
589 m_cursor.U8At( base + layout.drillEndOff ) };
590 }
591
592 SDB_RECORD stackRec = m_sdb.RecordAt( base );
593 uint32_t layerStart = stackRec.U32( layout.layerStartOff );
594 uint8_t layerCount = stackRec.U8( layout.layerCountOff );
595 bool endCursor = m_version == 0x2022;
596 bool successorMetadata = endCursor || m_version == 0x2027;
597 bool rawLayerSelector = successorMetadata;
598
599 if( layerCount > 0
600 && ( layerSection->count == 0 || layerCount > layerSection->count
601 || ( endCursor
602 ? layerStart > layerSection->count
603 : layerStart >= layerSection->count || layerCount > layerSection->count - layerStart ) ) )
604 THROW_IO_ERROR( "Invalid PADS pad-layer range" );
605
606 if( layerCount > 0 )
607 {
608 const uint32_t controllerPhase = endCursor ? 2 % layerSection->count : 0;
609
610 for( uint32_t layerIdx = 0; layerIdx < layerCount; ++layerIdx )
611 {
612 // PADS 2022's controller cursor is two rows ahead of the first geometry row.
613 // Both observed dialects put selector/shape in each geometry row's successor.
614 uint32_t geometryIndex = endCursor ? ( layerStart + layerSection->count - controllerPhase + layerIdx )
615 % layerSection->count
616 : layerStart + layerIdx;
617
618 // v0x2022's table is a ring, so its successor wraps; without the modulo the last
619 // geometry row read past the table. v0x2027's successor is not a ring, and for the
620 // last row of the last padstack it lands on the section's exclusive end, which the
621 // framing check does not validate. Fall back to the row's own metadata there
622 // rather than read whatever section follows.
623 uint32_t metadataIndex = geometryIndex;
624
625 if( successorMetadata )
626 {
627 metadataIndex = endCursor ? ( geometryIndex + 1 ) % layerSection->count
628 : geometryIndex + 1;
629
630 if( metadataIndex >= layerSection->count
631 && !m_cursor.InBounds( layerTableStart + metadataIndex * layerRecordSize, layerRecordSize ) )
632 {
633 metadataIndex = geometryIndex;
634 }
635 }
636 uint32_t geometryBase = layerTableStart + geometryIndex * layerRecordSize;
637 uint32_t metadataBase = layerTableStart + metadataIndex * layerRecordSize;
638
639 SDB_RECORD geometryRec = m_sdb.RecordAt( geometryBase );
640 SDB_RECORD metadataRec = m_sdb.RecordAt( metadataBase );
641 uint8_t selector = metadataRec.U8( 0 );
642 uint8_t shapeCode = metadataRec.U8( 1 );
643 auto shapeIt = PAD_SHAPE_NAMES.find( shapeCode );
644 maxPadDiameter[i] = std::max( maxPadDiameter[i], geometryRec.I32( 4 ) );
645
646 if( shapeIt == PAD_SHAPE_NAMES.end() )
647 continue;
648
649 PAD_STACK_LAYER layer = defaultLayer;
650 layer.layer = selector == 0 ? 0
651 : selector == 0xFF ? -1
652 : static_cast<int>( selector ) + ( rawLayerSelector ? 0 : 1 );
653 layer.shape = shapeIt->second;
654 layer.sizeA = static_cast<double>( geometryRec.I32( 4 ) );
655 int32_t sizeB = geometryRec.I32( 8 );
656
657 if( layer.shape == "RT" || layer.shape == "ST" )
658 {
659 layer.sizeB = layer.sizeA;
660 layer.thermal_outer_diameter = std::max( sizeB, 0 );
661 }
662 else
663 {
664 layer.sizeB = sizeB > 0 ? static_cast<double>( sizeB ) : layer.sizeA;
665 }
666
667 layers.push_back( std::move( layer ) );
668 }
669 }
670 }
671}
672
673
675static constexpr int DECAL_NAME_OFFSET = 44;
676
679static void logResolvedBase( int aSection, const char* aWhat, size_t aResolved, uint32_t aPhysical )
680{
681 static const bool enabled = getenv( "KICAD_PADS_SECBASE" ) != nullptr;
682
683 if( !enabled )
684 return;
685
686 fprintf( stderr, "SECBASE %d %s resolved=%zu physical=%u\n", aSection, aWhat, aResolved, aPhysical );
687}
688
689
691{
692 // The complete decal-name table is the logical section-14 ring. Each record is 112 bytes
693 // with the decal NAME at the physical section cursor, a 0xFFFE
694 // sentinel at +64 and the terminal count at +72. Unlike section 10 this table includes vias,
695 // connectors and mounting holes, and is indexed directly (base 0) by a parttype's
696 // decal_index. The first record is always JMPVIA_AAAAA, used as an anchor sanity check. The
697 // +72 count is harvested into m_decalTerminalCount so passives without a section 14
698 // descriptor get exact pad counts.
699 if( m_version <= 0x2022 )
700 {
702 return;
703 }
704
705 // The table is section 14's own records, reached from the corrected payload offset, so no
706 // header-size constant is needed.
707 static constexpr int REC_SIZE = 112;
708 static constexpr int STACK_START_OFFSET = 44;
709 static constexpr int SENTINEL_OFFSET = 64;
710 static constexpr int START_OFFSET = 68;
711 static constexpr int COUNT_OFFSET = 72;
712 static constexpr int STACK_COUNT_OFFSET = 88;
713
715
716 if( !sec14 )
717 THROW_IO_ERROR( "Missing PADS decal controller" );
718
719 if( sec14->count == 0 )
720 return;
721
722 uint32_t start = sec14->physicalOffset;
723
724 if( start + 12 > m_data.size() || m_sdb.RecordAt( start ).Str( 0, 12 ) != "JMPVIA_AAAAA" )
725 THROW_IO_ERROR( "Invalid PADS decal-controller framing" );
726
727 // Bound the file-supplied count before it sizes an allocation or a loop
728 if( static_cast<uint64_t>( sec14->count ) * REC_SIZE > m_data.size() - start )
729 THROW_IO_ERROR( "Invalid PADS decal-name table extent" );
730
731 m_decalNameTable.clear();
732 m_decalNameTable.reserve( sec14->count );
733
734 for( uint32_t k = 0; k < sec14->count; ++k )
735 {
736 uint32_t off = start + k * REC_SIZE;
737 SDB_RECORD rec = m_sdb.RecordAt( off );
738
739 if( off + REC_SIZE > m_data.size() || rec.U16( SENTINEL_OFFSET ) != SDB_RECORD_SENTINEL )
740 {
741 m_decalNameTable.emplace_back();
742 continue;
743 }
744
745 std::string name = rec.Str( 0, 41 );
746 m_decalNameTable.push_back( name );
747
748 int32_t startCursor = rec.I32( START_OFFSET );
749 int32_t count = rec.I32( COUNT_OFFSET );
750
751 if( !name.empty() && count > 0 && count <= 1000 )
752 {
753 m_decalTerminalCount.emplace( name, static_cast<uint32_t>( count ) );
754
755 if( startCursor >= 0 )
756 m_decalTerminalStart.emplace( name, startCursor );
757
758 int32_t stackCount = rec.I32( STACK_COUNT_OFFSET );
759
760 if( stackCount > 0 && stackCount <= 1000 )
761 {
762 m_decalStackCount.emplace( name, stackCount );
763
764 int32_t stackStart = rec.I32( STACK_START_OFFSET );
765
766 if( stackStart >= 0 )
767 m_decalStackStart.emplace( name, stackStart );
768 }
769 }
770 }
771}
772
773
775{
776 // The v0x2017 through v0x2022 dialects carry the same complete decal-name table the newer
777 // ones do, at the same place in their section 14: record 0's name starts at the physical
778 // section cursor, 44 bytes into the logical record. Each record holds NAME @ +0, a 0xFFFE
779 // sentinel @ +64 that terminates the table, and a terminal count @ +72.
780 //
781 // The stride is the section's own declared stride, so the 100-byte old and 112-byte new
782 // records need no version branch. Verified against all 165 corpus files of every version --
783 // the JMPVIA_AAAAA name of record 0 lands exactly on this offset on every one of them, which
784 // is what retired the whole-file signature scan this used to do.
785 if( m_version > 0x2022 )
786 return;
787
788 const SDB_SECTION* sec14 = m_sdb.Section( 14 );
789
790 if( !sec14 || sec14->stride == 0 )
791 THROW_IO_ERROR( "Invalid PADS legacy decal controller" );
792
793 static constexpr int STACK_START_OFFSET = 44;
794 static constexpr int SENTINEL_OFFSET = 64;
795 static constexpr int START_OFFSET = 68;
796 static constexpr int COUNT_OFFSET = 72;
797
798 size_t start = sec14->physicalOffset;
799 size_t stride = sec14->stride;
800
801 std::vector<std::string> table;
802 std::map<std::string, uint32_t> counts;
803 std::map<std::string, int32_t> starts;
804 std::map<std::string, int32_t> stackCounts;
805 std::map<std::string, int32_t> stackStarts;
806
807 if( start > m_data.size()
808 || static_cast<uint64_t>( sec14->count ) * stride > static_cast<uint64_t>( m_data.size() - start ) )
809 {
810 THROW_IO_ERROR( "Invalid PADS legacy decal-controller extent" );
811 }
812
813 table.reserve( sec14->count );
814
815 for( size_t k = 0; k < sec14->count; ++k )
816 {
817 size_t off = start + k * stride;
818 SDB_RECORD rec = m_sdb.RecordAt( static_cast<uint32_t>( off ) );
819
820 if( rec.U16( SENTINEL_OFFSET ) != SDB_RECORD_SENTINEL )
821 {
822 table.emplace_back();
823 continue;
824 }
825
826 std::string name = rec.Str( 0, 40 );
827 table.push_back( name );
828
829 if( off + COUNT_OFFSET + 4 <= m_data.size() )
830 {
831 int32_t count = rec.I32( COUNT_OFFSET );
832 int32_t cursor = rec.I32( START_OFFSET );
833 int32_t stackCount = rec.I32( 88 );
834
835 if( !name.empty() && count > 0 && count <= 1000 )
836 {
837 counts.emplace( name, static_cast<uint32_t>( count ) );
838
839 if( cursor >= 0 )
840 {
841 // v2017/v2019 store positive terminal cursors as one-based pool ordinals;
842 // zero is the shared first slot used by the built-in via decals.
843 starts.emplace( name, m_version <= 0x2019 && cursor > 0 ? cursor - 1 : cursor );
844 }
845
846 if( stackCount > 0 && stackCount <= 1000 )
847 {
848 stackCounts.emplace( name, stackCount );
849
850 // Every dialect stores this cursor, and it has to be read rather than
851 // re-derived by accumulating counts in decal-table order: the slices form
852 // a ring, so the table's first decals do not sit at the front of the pair
853 // pool. On PSTAGE-002 the 36 decals tile 64 slots with STANDARDVIA at 0,
854 // S2 last at 61, then THERMALVIA at 62 and JMPVIA_AAAAA at 63 wrapping
855 // back to 0.
856 int32_t stackStart = rec.I32( STACK_START_OFFSET );
857
858 if( stackStart >= 0 )
859 stackStarts.emplace( name, stackStart );
860 }
861 }
862 }
863 }
864
865 // Record 0 is always the JMPVIA_AAAAA pseudo-decal, so its name doubles as a check that the
866 // structural offset landed on the table rather than on unrelated bytes.
867 if( table.empty() || table[0] != "JMPVIA_AAAAA" )
868 THROW_IO_ERROR( "Invalid PADS legacy decal-controller framing" );
869
870 m_decalNameTable = std::move( table );
871 m_decalTerminalCount = std::move( counts );
872 m_decalTerminalStart = std::move( starts );
873 m_decalStackCount = std::move( stackCounts );
874 m_decalStackStart = std::move( stackStarts );
875}
876
877
879{
880 // The parttype-definition table's record size, decal_index field offset, and header framing
881 // all differ between dialects. The logical record ring starts 44 bytes before section 17's
882 // physical cursor. Modern records are 224 bytes with decal_index at +96; legacy records
883 // are 208 bytes with decal_index at +112 (v0x2021 has no parttype-definition layer at all).
884 // Verified against 2FOC_4.pcb: the decal_index for DSPIC33FJ128MC802/TP-LC/LMC7101/
885 // MOLEX53261_0790 all land on +112 and resolve to their correct ground-truth decal names via
886 // m_decalNameTable. Note placements don't reference this table for v0x2022 -- see
887 // usesDirectDecalChain -- but it is still populated for potential future use (e.g. rules).
888 if( m_version == 0x2021 )
889 return;
890
892
893 if( !sec17 || sec17->count == 0 )
894 return;
895
896 if( sec17->totalBytes % sec17->count != 0 )
897 THROW_IO_ERROR( "Invalid PADS parttype-controller record extent" );
898
899 const uint32_t recSize = sec17->totalBytes / sec17->count;
900
901 if( recSize != 208 && recSize != 224 )
902 THROW_IO_ERROR( "Unsupported PADS parttype-controller record stride" );
903
904 const bool isLegacyLayout = recSize == 208;
905 const uint32_t decalOff = isLegacyLayout ? 112 : 96;
906
907 if( sec17->physicalOffset < DECAL_NAME_OFFSET )
908 THROW_IO_ERROR( "Invalid PADS parttype-controller framing" );
909
910 uint32_t start = sec17->physicalOffset - DECAL_NAME_OFFSET;
911
912 // The parttype's own name (the *PARTTYPE alias, e.g. a manufacturer part number such as
913 // GRM15XR71C103KA86D that resolves to a generic decal like C-0402) sits at +44 in both the
914 // 208-byte and 224-byte records.
915 const uint32_t nameOff = 44;
916
917 if( !m_cursor.InBounds( start, static_cast<size_t>( sec17->count ) * recSize ) )
918 THROW_IO_ERROR( "Invalid PADS parttype-controller extent" );
919
921 m_partTypeDecalIndices.reserve( sec17->count );
922 m_partTypeNames.clear();
923
924 m_partTypeNames.reserve( sec17->count );
925
926 for( uint32_t k = 0; k < sec17->count; ++k )
927 {
928 uint32_t off = start + k * recSize;
929
930 SDB_RECORD record = m_sdb.RecordAt( off );
931 std::vector<int32_t> decalIndices;
932
933 for( uint32_t indexOff = decalOff; !isLegacyLayout && indexOff + 8 <= recSize; indexOff += 8 )
934 {
935 int32_t decalIndex = record.I32( indexOff );
936
937 if( decalIndex < 0 || record.I32( indexOff + 4 ) != decalIndex )
938 break;
939
940 decalIndices.push_back( decalIndex );
941 }
942
943 if( isLegacyLayout && record.I32( decalOff ) >= 0 )
944 decalIndices.push_back( record.I32( decalOff ) );
945
946 m_partTypeDecalIndices.push_back( std::move( decalIndices ) );
947
948 m_partTypeNames.push_back( record.Str( nameOff, 36 ) );
949 }
950}
951
952
954{
955 // Section 14 is the complete PARTDECAL declaration table. Section 10 is the unrelated
956 // board-drawing owner ring; treating its DRW names as decals created phantom definitions.
957 for( const std::string& name : m_decalNameTable )
958 {
959 if( name.empty() )
960 continue;
961
962 PART_DECAL decal;
963 decal.name = name;
964 decal.units = "M";
965 m_decals[name] = decal;
966 }
967
969}
970
971
973{
974 const SDB_SECTION* section = getSection( SECTION::TerminalPool );
975
976 if( !section )
977 THROW_IO_ERROR( "Missing PADS terminal controller" );
978
979 if( section->count == 0 )
980 return;
981
982 const size_t stride = m_version <= 0x2019 ? 20 : 36;
983 const size_t base = static_cast<size_t>( section->physicalOffset ) + ( m_version <= 0x2019 ? 16 : 0 );
984 const size_t bytes = static_cast<size_t>( section->count ) * stride;
985
986 if( base > m_data.size() || bytes > m_data.size() - base )
987 THROW_IO_ERROR( "Invalid PADS terminal-controller extent" );
988
989 struct DIRECT_TERMINAL
990 {
991 int32_t x;
992 int32_t y;
993 std::string name;
994 };
995
996 std::vector<DIRECT_TERMINAL> terminals;
997 terminals.reserve( section->count );
998
999 for( uint32_t index = 0; index < section->count; ++index )
1000 {
1001 SDB_RECORD record = m_sdb.RecordAt( static_cast<uint32_t>( base + index * stride ) );
1002
1003 if( m_version <= 0x2019 )
1004 terminals.push_back( { record.I32( 4 ), record.I32( 8 ), {} } );
1005 else
1006 terminals.push_back( { record.I32( 0 ), record.I32( 4 ), record.Str( 20, 4 ) } );
1007 }
1008
1009 for( auto& [name, decal] : m_decals )
1010 {
1011 auto startIt = m_decalTerminalStart.find( name );
1012 auto countIt = m_decalTerminalCount.find( name );
1013
1014 if( startIt == m_decalTerminalStart.end() || countIt == m_decalTerminalCount.end() || startIt->second < 0 )
1015 {
1016 continue;
1017 }
1018
1019 const size_t start = static_cast<size_t>( startIt->second );
1020 const size_t count = countIt->second;
1021
1022 if( start > terminals.size() || count > terminals.size() - start )
1023 THROW_IO_ERROR( "Invalid PADS decal terminal range" );
1024
1025 decal.terminals.clear();
1026 decal.terminals.reserve( count );
1027
1028 for( size_t index = 0; index < count; ++index )
1029 {
1030 const DIRECT_TERMINAL& serialized = terminals[start + index];
1031 TERMINAL terminal;
1032 terminal.x = toBasicCoordX( serialized.x );
1033 terminal.y = toBasicCoordY( serialized.y );
1034 terminal.name = serialized.name.empty() ? std::to_string( index + 1 ) : serialized.name;
1035 decal.terminals.push_back( std::move( terminal ) );
1036 }
1037 }
1038
1040
1041 size_t pairCount = 0;
1042
1043 for( const auto& [name, start] : m_decalStackStart )
1044 {
1045 auto countIt = m_decalStackCount.find( name );
1046
1047 if( start >= 0 && countIt != m_decalStackCount.end() && countIt->second > 0 )
1048 {
1049 pairCount = std::max( pairCount, static_cast<size_t>( start ) + static_cast<size_t>( countIt->second ) );
1050 }
1051 }
1052
1053 const size_t pairBase = base + bytes - ( m_version <= 0x2019 ? 16 : 0 );
1054
1055 if( pairCount > 0 )
1056 {
1057 if( pairBase > m_data.size() || pairCount * 8 > m_data.size() - pairBase )
1058 THROW_IO_ERROR( "Invalid PADS per-pin padstack extent" );
1059
1060 std::vector<std::pair<int32_t, int32_t>> pairs;
1061 pairs.reserve( pairCount );
1062
1063 for( size_t index = 0; index < pairCount; ++index )
1064 {
1065 SDB_RECORD record = m_sdb.RecordAt( static_cast<uint32_t>( pairBase + index * 8 ) );
1066
1067 pairs.emplace_back( record.I32( 0 ), record.I32( 4 ) );
1068 }
1069
1070 for( const auto& [name, start] : m_decalStackStart )
1071 {
1072 auto decalIt = m_decals.find( name );
1073 auto countIt = m_decalStackCount.find( name );
1074
1075 if( decalIt != m_decals.end() && countIt != m_decalStackCount.end() )
1076 applyPadstackPairs( decalIt->second, pairs, start, countIt->second );
1077 }
1078 }
1079
1080 return;
1081}
1082
1083
1085{
1086 // Global padstack zero is the implicit default until a decal's serialized ordinal-zero pair
1087 // replaces it. Positive pair ordinals override individual one-based terminals.
1088 for( auto& [name, decal] : m_decals )
1089 {
1090 if( decal.terminals.empty() )
1091 continue;
1092
1093 if( !m_padStackPool.empty() && !m_padStackPool[0].empty() )
1094 {
1095 decal.pad_stacks[0] = m_padStackPool[0];
1096
1097 if( !m_padStackDrillSpans.empty() )
1098 decal.drill_spans[0] = m_padStackDrillSpans[0];
1099 }
1100 }
1101}
1102
1103
1104void BINARY_PARSER::applyPadstackPairs( PART_DECAL& aDecal, const std::vector<std::pair<int32_t, int32_t>>& aPairs,
1105 int32_t aStart, int32_t aCount )
1106{
1107 if( aStart < 0 || aCount <= 0 || static_cast<size_t>( aStart ) + static_cast<size_t>( aCount ) > aPairs.size() )
1108 THROW_IO_ERROR( "Invalid PADS per-pin padstack range" );
1109
1110 for( int32_t p = 0; p < aCount; ++p )
1111 {
1112 const std::pair<int32_t, int32_t>& pair = aPairs[static_cast<size_t>( aStart ) + p];
1113
1114 if( pair.first < 0 || static_cast<size_t>( pair.second ) >= m_padStackPool.size()
1115 || m_padStackPool[pair.second].empty() )
1116 {
1117 THROW_IO_ERROR( "Invalid PADS per-pin padstack reference" );
1118 }
1119
1120 if( pair.first > 0 && static_cast<size_t>( pair.first ) > aDecal.terminals.size() )
1121 THROW_IO_ERROR( "Invalid PADS per-pin terminal ordinal" );
1122
1123 aDecal.pad_stacks[pair.first] = m_padStackPool[pair.second];
1124 aDecal.drill_spans[pair.first] = m_padStackDrillSpans[pair.second];
1125 }
1126}
1127
1128
1129bool BINARY_PARSER::isValidNetName( const std::string& aName ) const
1130{
1131 return !aName.empty() && aName != "___Unassigned_Obstacles_";
1132}
1133
1134
1136{
1137 if( m_version <= 0x2022 )
1139 else
1141}
1142
1143
1145{
1146 std::unordered_set<std::string> existing;
1147
1148 // Section 23 is a 44-byte-rotated circular array. Its physical cursor is the logical base
1149 // plus 44 bytes.
1150 const uint32_t netRecordSize = m_version == 0x2024 ? 416 : 424;
1151 constexpr uint32_t NET_NAME = 76;
1152 constexpr uint32_t NET_NAME_LEN = 48;
1153 constexpr uint32_t NET_SELF_PTR = 144;
1154 constexpr uint32_t NET_CLASS_PTR = 148;
1155
1156 const SDB_SECTION* nets = getSection( SECTION::Nets );
1157
1158 if( !nets )
1159 THROW_IO_ERROR( "Missing PADS net controller" );
1160
1161 if( nets->count == 0 )
1162 return;
1163
1164 if( nets->stride != netRecordSize || nets->physicalOffset < 44
1165 || !m_cursor.InBounds( nets->physicalOffset - 44, nets->physicalBytes ) )
1166 {
1167 THROW_IO_ERROR( "Invalid PADS net-controller framing" );
1168 }
1169
1170 const size_t base = nets->physicalOffset - 44;
1171
1172 for( uint32_t i = 0; i < nets->count; ++i )
1173 {
1174 SDB_RECORD rec = m_sdb.RecordAt( base + static_cast<size_t>( i ) * netRecordSize );
1175 std::string name = rec.Str( NET_NAME, NET_NAME_LEN );
1176
1177 if( name.empty() || !isValidNetName( name ) || !existing.insert( name ).second )
1178 continue;
1179
1180 NET net;
1181 net.name = name;
1182 m_nets.push_back( net );
1183 m_sec23RecordToNet[i] = m_nets.size() - 1;
1185 m_netAnchors.push_back( { m_nets.size() - 1, rec.U32( 64 ), rec.U32( 68 ) } );
1186
1187 if( uint32_t owner = rec.U32( NET_CLASS_PTR ) )
1188 m_netClassOwner[name] = owner;
1189
1190 if( uint32_t selfPtr = rec.U32( NET_SELF_PTR ) )
1191 m_netSelfPtrToName[selfPtr] = name;
1192 }
1193
1195}
1196
1197
1199{
1200 constexpr size_t RECORD_SIZE = 68;
1201 constexpr uint32_t MARKER = 0xFE000000;
1202 constexpr uint32_t FLAG = 0x0000FFFE;
1203
1204 const SDB_SECTION* connections = getSection( SECTION::Connections );
1205 const SDB_SECTION* nets = getSection( SECTION::Nets );
1206
1207 const size_t netRecordSize = m_version == 0x2024 ? 416 : 424;
1208
1209 if( !connections || !nets )
1210 THROW_IO_ERROR( "Missing PADS net-connection controllers" );
1211
1212 if( connections->count == 0 )
1213 return;
1214
1215 if( nets->stride != netRecordSize )
1216 THROW_IO_ERROR( "Invalid PADS net-controller stride" );
1217
1218 constexpr size_t RING_PREFIX = 36;
1219 if( connections->physicalBytes != connections->physicalCount * RECORD_SIZE
1220 || connections->physicalOffset < RING_PREFIX
1221 || !m_cursor.InBounds( connections->physicalOffset - RING_PREFIX, connections->physicalBytes + RING_PREFIX ) )
1222 {
1223 THROW_IO_ERROR( "Invalid PADS net-connection ring extent" );
1224 }
1225
1226 auto connectionU32 = [&]( uint32_t aIndex, size_t aField )
1227 {
1228 size_t logical =
1229 connections->physicalOffset - RING_PREFIX + static_cast<size_t>( aIndex ) * RECORD_SIZE + aField;
1230 return m_cursor.U32At( logical );
1231 };
1232
1233 size_t runBase = static_cast<size_t>( connections->physicalOffset ) - RING_PREFIX;
1234 size_t runCount = static_cast<size_t>( connections->count ) + 1;
1235
1236 // Record zero is the topology root. The directory count is the number of edges, so the
1237 // logical ring has one more record than the physical controller: its final 36-byte head is
1238 // serialized after the controller while record zero's 36-byte prefix precedes it.
1239 for( uint32_t recordIndex = 0; recordIndex < runCount; ++recordIndex )
1240 {
1241 if( ( recordIndex > 0 && ( connectionU32( recordIndex, 20 ) & 0xFFFFFFC0U ) != MARKER )
1242 || ( recordIndex < connections->count && ( connectionU32( recordIndex, 52 ) & 0xFFFFU ) != FLAG ) )
1243 {
1244 THROW_IO_ERROR( "Invalid PADS net-connection ring framing" );
1245 }
1246 }
1247
1248 logResolvedBase( 24, "connRun", runBase, connections ? connections->physicalOffset : 0 );
1249
1250 using PIN_ID = std::pair<uint32_t, uint32_t>;
1251
1252 std::map<PIN_ID, size_t> pinIndex;
1253 std::vector<PIN_ID> pins;
1254 std::vector<size_t> parent;
1255
1256 auto intern = [&]( const PIN_ID& aPin )
1257 {
1258 auto [it, inserted] = pinIndex.emplace( aPin, parent.size() );
1259
1260 if( inserted )
1261 {
1262 pins.push_back( aPin );
1263 parent.push_back( parent.size() );
1264 }
1265
1266 return it->second;
1267 };
1268
1269 auto findRoot = [&]( size_t aNode )
1270 {
1271 while( parent[aNode] != aNode )
1272 {
1273 parent[aNode] = parent[parent[aNode]];
1274 aNode = parent[aNode];
1275 }
1276
1277 return aNode;
1278 };
1279
1280 auto join = [&]( const PIN_ID& aPin, const PIN_ID& bPin )
1281 {
1282 const size_t indexA = intern( aPin );
1283 const size_t indexB = intern( bPin );
1284 const size_t rootA = findRoot( indexA );
1285 const size_t rootB = findRoot( indexB );
1286
1287 if( rootA != rootB )
1288 parent[rootA] = rootB;
1289 };
1290
1291 for( uint32_t recordIndex = 0; recordIndex + 1 < runCount; ++recordIndex )
1292 {
1293 join( { connectionU32( recordIndex, 60 ), connectionU32( recordIndex + 1, 0 ) },
1294 { connectionU32( recordIndex, 64 ), connectionU32( recordIndex + 1, 4 ) } );
1295 }
1296
1297 std::map<size_t, size_t> componentNet;
1298
1299 for( const NET_ANCHOR& anchor : m_netAnchors )
1300 {
1301 if( anchor.netIndex >= m_nets.size() || anchor.terminalOrdinal == 0 )
1302 continue;
1303
1304 const size_t root = findRoot( intern( { anchor.placementObject, anchor.terminalOrdinal } ) );
1305 auto [it, inserted] = componentNet.emplace( root, anchor.netIndex );
1306
1307 if( !inserted && it->second != anchor.netIndex )
1308 {
1309 // PADS keeps $$$ autoroute aliases as separate net records even after joining
1310 // their pins into a named signal's connection component.
1311 const bool existingIsAlias = m_nets[it->second].name.rfind( "$$$", 0 ) == 0;
1312 const bool incomingIsAlias = m_nets[anchor.netIndex].name.rfind( "$$$", 0 ) == 0;
1313
1314 if( existingIsAlias && incomingIsAlias )
1315 continue;
1316 else if( existingIsAlias != incomingIsAlias )
1317 it->second = incomingIsAlias ? it->second : anchor.netIndex;
1318 else
1319 THROW_IO_ERROR( "Conflicting PADS net anchors '" + m_nets[it->second].name + "' and '"
1320 + m_nets[anchor.netIndex].name + "'" );
1321 }
1322 }
1323
1324 for( size_t index = 0; index < pins.size(); ++index )
1325 {
1326 auto netIt = componentNet.find( findRoot( index ) );
1327
1328 if( netIt == componentNet.end() )
1329 continue;
1330
1331 const auto [placementObject, terminalOrdinal] = pins[index];
1332 m_netConnectionEndpoints.push_back( { netIt->second, placementObject, terminalOrdinal } );
1333
1334 auto partIt = m_placementObjectToPart.find( placementObject );
1335
1336 if( partIt != m_placementObjectToPart.end() && partIt->second < m_parts.size() )
1337 m_nets[netIt->second].component_refs.push_back( m_parts[partIt->second].name );
1338 }
1339}
1340
1341
1343{
1344 using PIN_KEY = std::pair<std::string, std::string>;
1345
1346 std::map<PIN_KEY, size_t> pinOwners;
1347
1348 auto claim = [&]( const NET_ANCHOR& anchor )
1349 {
1350 if( anchor.netIndex >= m_nets.size() || anchor.terminalOrdinal == 0 )
1351 return;
1352
1353 auto partIt = m_placementObjectToPart.find( anchor.placementObject );
1354
1355 if( partIt == m_placementObjectToPart.end() || partIt->second >= m_parts.size() )
1356 return;
1357
1358 const PART& part = m_parts[partIt->second];
1359 auto decalIt = m_decals.find( part.decal );
1360
1361 if( decalIt == m_decals.end() || anchor.terminalOrdinal > decalIt->second.terminals.size() )
1362 return;
1363
1364 const std::string& terminalName = decalIt->second.terminals[anchor.terminalOrdinal - 1].name;
1365
1366 if( terminalName.empty() )
1367 return;
1368
1369 PIN_KEY key = std::make_pair( part.name, terminalName );
1370 auto [owner, inserted] = pinOwners.emplace( key, anchor.netIndex );
1371
1372 if( inserted || owner->second == anchor.netIndex )
1373 return;
1374
1375 // Zero-edge $$$ placeholders retain a named signal's anchor without owning its pin.
1376 const bool existingIsAlias = m_nets[owner->second].name.rfind( "$$$", 0 ) == 0;
1377 const bool incomingIsAlias = m_nets[anchor.netIndex].name.rfind( "$$$", 0 ) == 0;
1378
1379 if( existingIsAlias && !incomingIsAlias )
1380 owner->second = anchor.netIndex;
1381 else if( !existingIsAlias && incomingIsAlias )
1382 return;
1383 else if( existingIsAlias && incomingIsAlias )
1384 return;
1385 else
1386 THROW_IO_ERROR( "Conflicting PADS net ownership for pin '" + part.name + "." + terminalName + "'" );
1387 };
1388
1389 for( const NET_ANCHOR& endpoint : m_netConnectionEndpoints )
1390 claim( endpoint );
1391
1392 for( const NET_ANCHOR& anchor : m_netAnchors )
1393 claim( anchor );
1394
1395 for( const auto& [key, netIndex] : pinOwners )
1396 {
1397 NET_PIN pin;
1398 pin.ref_des = key.first;
1399 pin.pin_name = key.second;
1400 m_nets[netIndex].pins.push_back( std::move( pin ) );
1401 }
1402}
1403
1404
1406{
1407 std::unordered_set<std::string> existing;
1408 std::unordered_map<std::string, size_t> netIndexByName;
1409
1410 // Route and via records address nets by a dense ordinal into the serialized net table, not by
1411 // the stored net ID. Build the index from that table so a via
1412 // resolves the net PADS wrote: verified against the ASCII exports' own via nets, 2533 of 2533
1413 // vias across the v0x2021 corpus resolve to the right name, none to a wrong one.
1414 m_sec23IndexToNet.clear();
1415
1416 const std::vector<size_t> netOffsets = oldNetRecordOffsets();
1417
1418 for( size_t i = 0; i < netOffsets.size(); ++i )
1419 {
1420 SDB_RECORD rec = m_sdb.RecordAt( static_cast<uint32_t>( netOffsets[i] ) );
1421 std::string name = rec.Str( 12, 48 );
1422
1423 if( name.empty() || !isValidNetName( name ) )
1424 continue;
1425
1426 m_sec23IndexToNet[static_cast<uint32_t>( i )] = name;
1427
1428 if( existing.insert( name ).second )
1429 {
1430 NET net;
1431 net.name = name;
1432 m_nets.push_back( net );
1433 netIndexByName.emplace( name, m_nets.size() - 1 );
1434 }
1435
1436 m_sec23RecordToNet[static_cast<uint32_t>( i )] = netIndexByName.at( name );
1437
1438 if( uint32_t owner = rec.U32( 84 ) )
1439 m_netClassOwner[name] = owner;
1440 }
1441
1443}
1444
1445
1446std::vector<size_t> BINARY_PARSER::oldNetRecordOffsets() const
1447{
1448 constexpr uint32_t NET_RECORD_SIZE = 144;
1449
1450 std::vector<size_t> offsets;
1451 const SDB_SECTION* nets = getSection( SECTION::Nets );
1452
1453 if( !nets || nets->stride != NET_RECORD_SIZE )
1454 THROW_IO_ERROR( "Invalid PADS legacy net-controller framing" );
1455
1456 const uint64_t base = static_cast<uint64_t>( nets->physicalOffset ) + 20;
1457
1458 if( base + static_cast<uint64_t>( nets->count ) * NET_RECORD_SIZE > m_data.size() )
1459 THROW_IO_ERROR( "Invalid PADS legacy net-controller extent" );
1460
1461 for( size_t i = 0; i < nets->count; ++i )
1462 offsets.push_back( base + i * NET_RECORD_SIZE );
1463
1464 return offsets;
1465}
1466
1467
1469{
1470 constexpr size_t RECORD_SIZE = 68;
1471 constexpr uint32_t ENDPOINT_FLAG = 0x0000FFFE;
1472 constexpr uint32_t MARKER = 0xFE000000;
1473 constexpr uint32_t NET_RECORD_SIZE = 144;
1474 constexpr uint32_t NET_FIRST = 8; // index of this net's first connection record
1475 constexpr uint32_t NET_NAME = 12;
1476 constexpr uint32_t NET_COUNT = 92; // number of connection records in this net
1477
1478 const SDB_SECTION* connections = getSection( SECTION::Connections );
1479 const SDB_SECTION* nets = getSection( SECTION::Nets );
1480
1481 if( !connections || !nets )
1482 THROW_IO_ERROR( "Missing PADS legacy net-connection controllers" );
1483
1484 if( connections->count == 0 )
1485 return;
1486
1487 if( nets->stride != NET_RECORD_SIZE )
1488 THROW_IO_ERROR( "Invalid PADS legacy net-controller stride" );
1489
1490 const uint64_t base = static_cast<uint64_t>( connections->physicalOffset ) + 16;
1491
1492 if( base + static_cast<uint64_t>( connections->count ) * RECORD_SIZE > m_data.size() )
1493 {
1494 THROW_IO_ERROR( "Invalid PADS legacy net-connection extent" );
1495 }
1496
1497 const size_t total = connections->count;
1498
1499 // Union-find over pin identities, so each net becomes one connected component of the graph
1500 // the connection records span.
1501 std::map<std::pair<uint32_t, uint32_t>, size_t> pinIndex;
1502 std::vector<size_t> parent;
1503
1504 auto intern = [&]( uint32_t aObject, uint32_t aOrdinal )
1505 {
1506 auto [it, inserted] = pinIndex.emplace( std::make_pair( aObject, aOrdinal ), parent.size() );
1507
1508 if( inserted )
1509 parent.push_back( parent.size() );
1510
1511 return it->second;
1512 };
1513
1514 auto findRoot = [&]( size_t aNode )
1515 {
1516 while( parent[aNode] != aNode )
1517 {
1518 parent[aNode] = parent[parent[aNode]];
1519 aNode = parent[aNode];
1520 }
1521
1522 return aNode;
1523 };
1524
1525 struct CONNECTION
1526 {
1527 uint32_t objectA;
1528 uint32_t ordinalA;
1529 uint32_t objectB;
1530 uint32_t ordinalB;
1531 size_t pinA;
1532 };
1533
1534 std::vector<CONNECTION> stream;
1535 stream.reserve( total );
1536
1537 for( size_t i = 0; i < total; ++i )
1538 {
1539 SDB_RECORD rec = m_sdb.RecordAt( static_cast<uint32_t>( base + i * RECORD_SIZE ) );
1540
1541 if( ( rec.U32( 0 ) & 0xFFFFU ) != ENDPOINT_FLAG || ( rec.U32( 36 ) & 0xFFFFFFC0U ) != MARKER )
1542 {
1543 THROW_IO_ERROR( "Invalid PADS legacy net-connection ring framing" );
1544 }
1545
1546 CONNECTION conn{ rec.U32( 8 ), rec.U32( 16 ), rec.U32( 12 ), rec.U32( 20 ), 0 };
1547
1548 conn.pinA = intern( conn.objectA, conn.ordinalA );
1549 size_t pinB = intern( conn.objectB, conn.ordinalB );
1550
1551 size_t rootA = findRoot( conn.pinA );
1552 size_t rootB = findRoot( pinB );
1553
1554 if( rootA != rootB )
1555 parent[rootA] = rootB;
1556
1557 stream.push_back( conn );
1558 }
1559
1560 std::map<size_t, size_t> componentSize;
1561
1562 for( size_t i = 0; i < stream.size(); ++i )
1563 {
1564 size_t root = findRoot( stream[i].pinA );
1565
1566 ++componentSize[root];
1567 }
1568
1569 auto netRecordName = [&]( size_t aOffset, std::string& aName, uint32_t& aCount, uint32_t& aFirst,
1570 uint32_t& aAnchorObject, uint32_t& aAnchorOrdinal )
1571 {
1572 if( !m_cursor.InBounds( aOffset, NET_RECORD_SIZE ) )
1573 return false;
1574
1575 SDB_RECORD rec = m_sdb.RecordAt( static_cast<uint32_t>( aOffset ) );
1576
1577 aName = rec.Str( NET_NAME, 48 );
1578 aCount = rec.U32( NET_COUNT );
1579 aFirst = rec.U32( NET_FIRST );
1580 aAnchorObject = rec.U32( 0 );
1581 aAnchorOrdinal = rec.U32( 4 );
1582
1583 return !aName.empty() && aCount > 0 && aCount <= connections->count;
1584 };
1585
1586 std::map<std::string, size_t> netIndexByName;
1587
1588 for( size_t i = 0; i < m_nets.size(); ++i )
1589 netIndexByName.emplace( m_nets[i].name, i );
1590
1591 std::set<size_t> assignedComponents;
1592
1593 for( size_t offset : oldNetRecordOffsets() )
1594 {
1595 std::string name;
1596 uint32_t count = 0;
1597 uint32_t edgeIndex = 0;
1598 uint32_t anchorObject = 0;
1599 uint32_t anchorOrdinal = 0;
1600
1601 if( !netRecordName( offset, name, count, edgeIndex, anchorObject, anchorOrdinal ) || !isValidNetName( name ) )
1602 continue;
1603
1604 if( edgeIndex >= stream.size() )
1605 THROW_IO_ERROR( "Invalid PADS legacy net edge reference" );
1606
1607 auto anchor = pinIndex.find( { anchorObject, anchorOrdinal } );
1608
1609 if( anchor == pinIndex.end() )
1610 THROW_IO_ERROR( "Invalid PADS legacy net pin anchor" );
1611
1612 const size_t root = findRoot( anchor->second );
1613
1614 if( findRoot( stream[edgeIndex].pinA ) != root )
1615 THROW_IO_ERROR( "Conflicting PADS legacy net anchors" );
1616
1617 if( count != componentSize[root] )
1618 THROW_IO_ERROR( "Invalid PADS legacy net component size" );
1619
1620 if( !assignedComponents.insert( root ).second )
1621 THROW_IO_ERROR( "Conflicting PADS legacy net component owners" );
1622
1623 auto netIt = netIndexByName.find( name );
1624
1625 if( netIt == netIndexByName.end() )
1626 THROW_IO_ERROR( "Missing PADS legacy net record" );
1627
1628 for( const CONNECTION& conn : stream )
1629 {
1630 if( findRoot( conn.pinA ) != root )
1631 continue;
1632
1633 m_netConnectionEndpoints.push_back( { netIt->second, conn.objectA, conn.ordinalA } );
1634 m_netConnectionEndpoints.push_back( { netIt->second, conn.objectB, conn.ordinalB } );
1635 }
1636 }
1637}
1638
1639
1641{
1642 if( m_netClassOwner.empty() || m_data.size() < 24 )
1643 return;
1644
1645 // Distinct net-class owner pointers; ascending order is net-class declaration order.
1646 std::set<uint32_t> ownerSet;
1647
1648 for( const auto& [name, owner] : m_netClassOwner )
1649 ownerSet.insert( owner );
1650
1651 std::vector<uint32_t> owners( ownerSet.begin(), ownerSet.end() );
1652 std::map<uint32_t, size_t> ownerOrdinal;
1653
1654 for( size_t k = 0; k < owners.size(); ++k )
1655 ownerOrdinal[owners[k]] = k;
1656
1657 std::vector<NET_CLASS_RULE_EDGE> edges = collectNetClassRuleEdges( ownerSet );
1658
1659 if( edges.empty() )
1660 return;
1661
1662 const size_t NAME_STRIDE = m_version <= 0x2022 ? 28 : 280;
1663 constexpr size_t NAME_OFFSET = 8;
1664 const size_t NAME_LEN = m_version <= 0x2022 ? 8 : 48;
1665 const SDB_SECTION* names = getSection( 66 );
1666
1667 if( !names || names->physicalCount < owners.size()
1668 || static_cast<uint64_t>( names->physicalOffset ) + owners.size() * NAME_STRIDE > m_data.size() )
1669 {
1670 return;
1671 }
1672
1673 m_netClasses.clear();
1674 m_netClasses.resize( owners.size() );
1675
1676 for( size_t k = 0; k < owners.size(); ++k )
1677 {
1678 std::string name = m_sdb.RecordAt( names->physicalOffset + k * NAME_STRIDE ).Str( NAME_OFFSET, NAME_LEN );
1679
1680 if( name.empty() || !std::isalnum( static_cast<unsigned char>( name[0] ) ) )
1681 name = "PADS_NetClass_" + std::to_string( k + 1 );
1682
1683 m_netClasses[k].name = name;
1684 }
1685
1686 for( const auto& [net, owner] : m_netClassOwner )
1687 {
1688 auto it = ownerOrdinal.find( owner );
1689
1690 if( it != ownerOrdinal.end() )
1691 m_netClasses[it->second].nets.push_back( net );
1692 }
1693
1694 applyNetClassClearances( edges, ownerOrdinal );
1695
1696 // Sort for reproducible output.
1697 for( BIN_NET_CLASS_DEF& nc : m_netClasses )
1698 {
1699 std::sort( nc.nets.begin(), nc.nets.end() );
1700 std::sort( nc.ruleLayers.begin(), nc.ruleLayers.end() );
1701 nc.ruleLayers.erase( std::unique( nc.ruleLayers.begin(), nc.ruleLayers.end() ), nc.ruleLayers.end() );
1702 }
1703}
1704
1705
1706std::vector<NET_CLASS_RULE_EDGE> BINARY_PARSER::collectNetClassRuleEdges( const std::set<uint32_t>& aOwnerSet )
1707{
1708 constexpr size_t RECORD_SIZE = 28;
1709 constexpr size_t RULE_KIND = 0;
1710 constexpr size_t RULE_DETAIL_HANDLE = 4;
1711 constexpr size_t SCOPE_TYPE = 8;
1712 constexpr uint32_t NET_CLASS_SCOPE = 0x42;
1713 constexpr size_t SCOPE_REFERENCE = 12;
1714 constexpr size_t LAYER = 24;
1715
1716 std::vector<NET_CLASS_RULE_EDGE> edges;
1717 const SDB_SECTION* relationships = getSection( 67 );
1718
1719 if( !relationships || relationships->physicalBytes != relationships->count * RECORD_SIZE )
1720 return edges;
1721
1722 for( uint32_t i = 0; i < relationships->count; ++i )
1723 {
1724 size_t off = relationships->physicalOffset + static_cast<size_t>( i ) * RECORD_SIZE;
1725 SDB_RECORD rec = m_sdb.RecordAt( off );
1726
1727 if( rec.U32( SCOPE_TYPE ) != NET_CLASS_SCOPE )
1728 continue;
1729
1730 uint32_t owner = rec.U32( SCOPE_REFERENCE );
1731
1732 if( !aOwnerSet.count( owner ) )
1733 continue;
1734
1735 edges.push_back( { owner, rec.U32( RULE_KIND ), rec.U32( RULE_DETAIL_HANDLE ),
1736 static_cast<int>( rec.U32( LAYER ) ), off } );
1737 }
1738
1739 return edges;
1740}
1741
1742
1743void BINARY_PARSER::applyNetClassClearances( const std::vector<NET_CLASS_RULE_EDGE>& aEdges,
1744 const std::map<uint32_t, size_t>& aOwnerOrdinal )
1745{
1746 constexpr uint32_t CLEARANCE_RULE_KIND = 0x29;
1747
1748 for( const NET_CLASS_RULE_EDGE& e : aEdges )
1749 {
1750 if( e.ruleKind != CLEARANCE_RULE_KIND )
1751 continue;
1752
1753 auto owner = aOwnerOrdinal.find( e.owner );
1754
1755 if( owner != aOwnerOrdinal.end() )
1756 m_netClasses[owner->second].ruleLayers.push_back( e.layer );
1757 }
1758
1759 const SDB_SECTION* relationships = getSection( 67 );
1760 const SDB_SECTION* values = getSection( 41 );
1761
1762 if( !relationships || !values || values->physicalCount == 0 )
1763 return;
1764
1765 constexpr size_t RELATIONSHIP_SIZE = 28;
1766 uint32_t firstClearanceHandle = UINT32_MAX;
1767
1768 for( uint32_t i = 0; i < relationships->count; ++i )
1769 {
1770 SDB_RECORD rec = m_sdb.RecordAt( relationships->physicalOffset + i * RELATIONSHIP_SIZE );
1771
1772 if( rec.U32( 0 ) == CLEARANCE_RULE_KIND )
1773 firstClearanceHandle = std::min( firstClearanceHandle, rec.U32( 4 ) );
1774 }
1775
1776 if( firstClearanceHandle == UINT32_MAX )
1777 return;
1778
1779 const uint32_t valueStride = m_version == 0x2017 ? 180 : 188;
1780
1781 for( const NET_CLASS_RULE_EDGE& edge : aEdges )
1782 {
1783 if( edge.ruleKind != CLEARANCE_RULE_KIND || edge.layer != 0 || edge.rulePtr < firstClearanceHandle )
1784 continue;
1785
1786 uint32_t delta = edge.rulePtr - firstClearanceHandle;
1787
1788 if( delta % valueStride != 0 )
1789 continue;
1790
1791 uint32_t index = delta / valueStride;
1792
1793 if( index >= values->physicalCount )
1794 continue;
1795
1796 auto owner = aOwnerOrdinal.find( edge.owner );
1797
1798 if( owner == aOwnerOrdinal.end() )
1799 continue;
1800
1801 SDB_RECORD value = m_sdb.RecordAt( values->physicalOffset + index * valueStride );
1802 BIN_NET_CLASS_DEF& netClass = m_netClasses[owner->second];
1803
1804 netClass.clearance = value.I32( 12 );
1805 netClass.viaClearance = value.I32( 20 );
1806 netClass.minTrackWidth = value.I32( 144 );
1807 netClass.trackWidth = value.I32( 148 );
1808 netClass.maxTrackWidth = value.I32( 152 );
1809 netClass.hasRuleValues = true;
1810 }
1811}
1812
1813
1815{
1816 constexpr size_t OBJECT_SIZE = 864;
1817 constexpr double F64_INHERIT = -1.0;
1818 constexpr int32_t I32_INHERIT = -1;
1819
1820 // Field offsets within the 864-byte DIF_PAIR object.
1821 constexpr size_t NET_A_HANDLE = 12; // member-net A; equals a net record's +184 self-handle
1822 constexpr size_t NET_B_HANDLE = 16; // member-net B
1823 constexpr size_t GAP_INHERIT = 40; // f64 gap, used when the override is inherited
1824 constexpr size_t GAP_OVERRIDE = 56; // f64 gap override
1825 constexpr size_t WIDTH_INHERIT = 592; // i32 width, used when the override is inherited
1826 constexpr size_t WIDTH_OVERRIDE = 600; // i32 width override
1827
1828 const SDB_SECTION* records = getSection( 48 );
1829
1830 if( !records )
1831 THROW_IO_ERROR( "Missing PADS differential-pair controller" );
1832
1833 if( records->physicalCount == 0 || m_netSelfPtrToName.empty() )
1834 return;
1835
1836 if( records->physicalBytes != records->physicalCount * OBJECT_SIZE || records->physicalOffset < 8 )
1837 THROW_IO_ERROR( "Invalid PADS differential-pair framing" );
1838
1839 const size_t base = records->physicalOffset - 8;
1840
1841 if( static_cast<uint64_t>( base ) + static_cast<uint64_t>( records->physicalCount ) * OBJECT_SIZE > m_data.size() )
1842 THROW_IO_ERROR( "Invalid PADS differential-pair extent" );
1843
1844 std::set<std::pair<std::string, std::string>> seen;
1845
1846 for( uint32_t i = 0; i < records->physicalCount; ++i )
1847 {
1848 size_t objStart = base + static_cast<size_t>( i ) * OBJECT_SIZE;
1849 SDB_RECORD obj = m_sdb.RecordAt( objStart );
1850
1851 if( !m_netSelfPtrToName.count( obj.U32( NET_A_HANDLE ) )
1852 || !m_netSelfPtrToName.count( obj.U32( NET_B_HANDLE ) ) )
1853 {
1854 continue;
1855 }
1856
1857 const std::string& nameA = m_netSelfPtrToName.at( obj.U32( NET_A_HANDLE ) );
1858 const std::string& nameB = m_netSelfPtrToName.at( obj.U32( NET_B_HANDLE ) );
1859
1860 if( !seen.insert( { nameA, nameB } ).second )
1861 continue;
1862
1863 double gapOverride = obj.F64( GAP_OVERRIDE );
1864 double gap = ( gapOverride != F64_INHERIT ) ? gapOverride : obj.F64( GAP_INHERIT );
1865 int32_t widthOverride = obj.I32( WIDTH_OVERRIDE );
1866 double width = ( widthOverride != I32_INHERIT ) ? static_cast<double>( widthOverride )
1867 : static_cast<double>( obj.I32( WIDTH_INHERIT ) );
1868
1869 DIFF_PAIR_DEF dp;
1870 dp.name = nameA + "_" + nameB;
1871 dp.positive_net = nameA;
1872 dp.negative_net = nameB;
1873 dp.gap = ( gap != F64_INHERIT ) ? gap : 0.0;
1874 dp.width = ( width != static_cast<double>( I32_INHERIT ) ) ? width : 0.0;
1875
1876 m_diffPairs.push_back( std::move( dp ) );
1877 }
1878}
1879
1880
1882{
1885
1886 constexpr size_t GEOMETRY_BYTES = 36;
1887 const size_t recordSize = s8 ? s8->stride : 0;
1888 const size_t ringRotation = recordSize >= GEOMETRY_BYTES ? recordSize - GEOMETRY_BYTES : 0;
1889
1890 if( !s8 || !s9 )
1891 THROW_IO_ERROR( "Missing PADS text controllers" );
1892
1893 if( s8->physicalCount == 0 )
1894 return;
1895
1896 const bool validStringPool =
1897 ( s9->physicalBytes == 0 && s9->count == 0 ) || ( s9->stride == 1 && s9->physicalBytes == s9->count );
1898
1899 if( ( recordSize != 64 && recordSize != 72 ) || s8->physicalOffset < ringRotation || !validStringPool
1900 || s9->physicalOffset != s8->physicalOffset + s8->physicalBytes )
1901 THROW_IO_ERROR( "Invalid PADS text-controller framing" );
1902
1903 const size_t recordBase = s8->physicalOffset - ringRotation;
1904 const size_t poolBase = s9->physicalOffset;
1905 const size_t poolHi = poolBase + s9->physicalBytes;
1906
1907 // The final record's lagged metadata occupies the 36-byte circular-controller tail ending
1908 // at section 9. Only fields through +28 are consumed from it.
1909 if( !m_cursor.InBounds( recordBase, s8->physicalBytes + ringRotation )
1910 || !m_cursor.InBounds( poolBase, s9->physicalBytes ) )
1911 {
1912 THROW_IO_ERROR( "Invalid PADS text-controller extent" );
1913 }
1914
1915 parsePlacementFields( *s8, recordBase, recordSize, ringRotation );
1916 parseFreeText( *s8, recordBase, recordSize, ringRotation, poolBase, poolHi );
1917}
1918
1919
1920void BINARY_PARSER::parsePlacementFields( const SDB_SECTION& aText, size_t aRecordBase, size_t aRecordSize,
1921 size_t aRingRotation )
1922{
1923 auto fieldAttribute = [&]( uint32_t aIndex )
1924 {
1925 SDB_RECORD record = m_sdb.RecordAt( aRecordBase + static_cast<size_t>( aIndex ) * aRecordSize );
1926 ATTRIBUTE attribute;
1927 attribute.height = record.I32( aRingRotation );
1928 attribute.width = record.I32( aRingRotation + 4 );
1929 attribute.x = record.I32( aRingRotation + 8 );
1930 attribute.y = record.I32( aRingRotation + 12 );
1931 attribute.orientation = toBasicAngle( record.I32( aRingRotation + 16 ) );
1932 attribute.mirrored = record.I32( aRingRotation + 20 ) != 0;
1933 return attribute;
1934 };
1935
1936 for( const auto& [partIndex, fieldStart] : m_partFieldStart )
1937 {
1938 if( fieldStart < 0 )
1939 continue;
1940
1941 if( partIndex >= m_parts.size() || static_cast<uint32_t>( fieldStart ) >= aText.physicalCount )
1942 THROW_IO_ERROR( "Invalid PADS placement field-presentation link" );
1943
1944 std::vector<ATTRIBUTE> attributes;
1945 std::set<uint32_t> visited;
1946 uint32_t fieldIndex = static_cast<uint32_t>( fieldStart );
1947
1948 while( true )
1949 {
1950 if( !visited.insert( fieldIndex ).second )
1951 THROW_IO_ERROR( "Cyclic PADS placement field-list link" );
1952
1953 if( fieldIndex >= aText.physicalCount )
1954 THROW_IO_ERROR( "Invalid PADS placement field-list link" );
1955
1956 ATTRIBUTE attribute = fieldAttribute( fieldIndex );
1957 SDB_RECORD metadata = m_sdb.RecordAt( aRecordBase + static_cast<size_t>( fieldIndex + 1 ) * aRecordSize );
1958 uint32_t presentation = metadata.U32( 24 );
1959 uint8_t fieldKind = static_cast<uint8_t>( presentation >> 16 );
1960 attribute.visible = ( fieldKind & 0x20 ) != 0;
1961
1962 if( ( presentation & 0x11000000U ) == 0x11000000U )
1963 {
1964 attribute.hjust = "CENTER";
1965 attribute.vjust = "CENTER";
1966 }
1967 else
1968 {
1969 attribute.hjust = "LEFT";
1970 attribute.vjust = ( presentation & 0x20000000U ) ? "UP" : "DOWN";
1971 }
1972
1973 if( ( fieldKind & 0x1FU ) == 0x03 )
1974 attribute.name = "Part Type";
1975 else if( ( fieldKind & 0x1FU ) == 0x02 )
1976 attribute.name = "Ref.Des.";
1977
1978 if( !attribute.name.empty() )
1979 attributes.push_back( std::move( attribute ) );
1980
1981 uint32_t association = metadata.U32( 12 );
1982
1983 uint8_t associationKind = static_cast<uint8_t>( association >> 24 );
1984
1985 if( associationKind == 0x16 )
1986 {
1987 if( ( association & 0x00FFFFFFU ) != partIndex )
1988 THROW_IO_ERROR( "Mismatched PADS placement field-list owner" );
1989
1990 break;
1991 }
1992
1993 if( associationKind != 0x08 )
1994 THROW_IO_ERROR( "Invalid PADS placement field-list terminator" );
1995
1996 fieldIndex = association & 0x00FFFFFFU;
1997 }
1998
1999 m_parts[partIndex].attributes = std::move( attributes );
2000 }
2001}
2002
2003
2004void BINARY_PARSER::parseFreeText( const SDB_SECTION& aText, size_t aRecordBase, size_t aRecordSize,
2005 size_t aRingRotation, size_t aPoolBase, size_t aPoolHi )
2006{
2007 auto cStringStartAt = [this, aPoolHi]( size_t aAbs ) -> bool
2008 {
2009 if( aAbs >= aPoolHi )
2010 return false;
2011
2012 size_t e = aAbs;
2013
2014 while( e < aPoolHi && m_data[e] != 0 )
2015 {
2016 if( m_data[e] < 0x20 || m_data[e] >= 0x7F )
2017 return false;
2018
2019 ++e;
2020 }
2021
2022 return e > aAbs;
2023 };
2024
2025 for( uint32_t index = 0; index < aText.physicalCount; ++index )
2026 {
2027 SDB_RECORD geom = m_sdb.RecordAt( aRecordBase + static_cast<size_t>( index ) * aRecordSize );
2028 SDB_RECORD meta = m_sdb.RecordAt( aRecordBase + static_cast<size_t>( index + 1 ) * aRecordSize );
2029
2030 if( meta.U16( 4 ) != 0xFFFE || meta.U32( 12 ) != 0 || ( aRecordSize == 72 && meta.U32( 28 ) != 0x49000000 ) )
2031 continue;
2032
2033 uint32_t layerWord = meta.U32( 24 );
2034
2035 if( ( layerWord >> 16 ) != 0x0020 || geom.I32( aRingRotation ) <= 0 || geom.I32( aRingRotation + 4 ) <= 0 )
2036 continue;
2037
2038 size_t soff = aPoolBase + meta.U32( 8 );
2039
2040 if( soff < aPoolBase || soff >= aPoolHi || ( soff != aPoolBase && m_data[soff - 1] != 0 )
2041 || !cStringStartAt( soff ) )
2042 {
2043 continue;
2044 }
2045
2046 std::string content = m_sdb.RecordAt( soff ).Str( 0, aPoolHi - soff );
2047
2048 if( content.empty() )
2049 continue;
2050
2051 int32_t height = geom.I32( aRingRotation );
2052 int32_t linewidth = geom.I32( aRingRotation + 4 );
2053 int32_t x = geom.I32( aRingRotation + 8 );
2054 int32_t y = geom.I32( aRingRotation + 12 );
2055 int32_t angleRaw = geom.I32( aRingRotation + 16 );
2056
2057 TEXT text;
2058 text.content = content;
2059 text.location.x = toBasicCoordX( x );
2060 text.location.y = toBasicCoordY( y );
2061 text.height = static_cast<double>( height );
2062 text.width = static_cast<double>( linewidth );
2063 text.layer = static_cast<int>( layerWord & 0xFF );
2064 text.rotation = toBasicAngle( angleRaw );
2065 text.mirrored = geom.I32( aRingRotation + 20 ) != 0;
2066
2067 m_texts.push_back( text );
2068 }
2069}
2070
2071
2072// Section 60 is a heterogeneous node table (via records, route corner nodes, free slots),
2073// discriminated by a type byte four bytes from the end of its circular fixed-stride record.
2074// Every other field is defined relative to that byte T and is stride-independent:
2075// T-27 i32 raw X T-23 i32 raw Y
2076// T+0 u8 type (0x0E = via) T+1 u16 net index, biased by 3 (see parseNetNamesNew)
2077// T+5 u8 saved start layer T+6 u8 saved end layer
2078// The layer numbers are stored in the low five bits of the following logical record's head.
2079// Valid, unequal in-range endpoints distinguish vias from other 0x0E junctions.
2080// The logical ring begins stride-31 bytes before the direct physical section-60 extent. Verified
2081// against the compiled Kaitai view on all 597 distinct corpus binaries.
2082//
2083// The T+1 net index is real and exact for vias. Grouping vias by its raw value reproduces the
2084// true per-net partition at 100% purity on BR350430B (42 vias) and OC_LTE_BASEBAND (3943),
2085// against a 7-9% shuffled-value control, so the field identifies the net even where the name
2086// lookup cannot. Only the 0-2 slots, whose nets live outside section 23, fail to resolve.
2087//
2088// The other row types are a different matter. No u16 field anywhere in the record resolves a net
2089// for the 0x16 or 0x00 rows above 4.2%, against a 0.14% random-assignment control and a
2090// section-23 name table independently verified as 979 of 980 real net names, so per-node net
2091// membership for non-via nodes is not in this table and has to come from somewhere else. The
2092// section-23 self-pointer route is untested rather than negative -- only 73 of 983 records carry
2093// that field on the file it was tried on.
2094static constexpr int VIA_TYPE = 0x0E;
2095
2096
2097static bool viaRecordValid( const BINARY_CURSOR& aCur, size_t aTypeByte )
2098{
2099 return aCur.U8At( aTypeByte ) == VIA_TYPE && aCur.U8At( aTypeByte + 4 ) == 0x17
2100 && ( aCur.U8At( aTypeByte + 5 ) & 0x02 ) != 0;
2101}
2102
2103
2104std::map<uint32_t, size_t> BINARY_PARSER::parseRouteJunctionNets() const
2105{
2106 constexpr uint32_t JUNCTION_TAG = 0x3C000000;
2107 constexpr uint32_t ROUTE_CHAIN_TAG = 0x18000000;
2108 constexpr uint32_t TAG_MASK = 0xFF000000;
2109 constexpr uint32_t INDEX_MASK = 0x00FFFFFF;
2110
2111 const SDB_SECTION* relationships = getSection( 49 );
2112 const SDB_SECTION* junctions = getSection( SECTION::Vias );
2113 const SDB_SECTION* nets = getSection( SECTION::Nets );
2114 const SDB_SECTION* routeChains = getSection( SECTION::Connections );
2115
2116 if( !relationships || !junctions || !nets || !routeChains )
2117 THROW_IO_ERROR( "Missing PADS route-relationship controllers" );
2118
2119 std::map<uint32_t, size_t> result;
2120 std::vector<std::pair<uint32_t, size_t>> junctionSignals;
2121 size_t cursor = relationships->physicalOffset;
2122 const size_t end = cursor + relationships->physicalBytes;
2123 size_t signalIndex = 0;
2124
2125 auto readU32 = [&]()
2126 {
2127 if( cursor > end || end - cursor < 4 )
2128 THROW_IO_ERROR( "Invalid PADS route-relationship extent" );
2129
2130 uint32_t value = m_cursor.U32At( cursor );
2131 cursor += 4;
2132 return value;
2133 };
2134
2135 while( cursor < end )
2136 {
2137 if( signalIndex >= nets->count )
2138 THROW_IO_ERROR( "Invalid PADS route-relationship signal count" );
2139
2140 for( int direction = 0; direction < 2; ++direction )
2141 {
2142 uint32_t numRelationships = readU32();
2143
2144 for( uint32_t relationship = 0; relationship < numRelationships; ++relationship )
2145 {
2146 uint32_t objectId = readU32();
2147 uint32_t numValues = readU32();
2148
2149 if( numValues > ( end - cursor ) / 4 )
2150 THROW_IO_ERROR( "Invalid PADS route-relationship value count" );
2151
2152 uint32_t expectedObjectTag = direction == 0 ? JUNCTION_TAG : ROUTE_CHAIN_TAG;
2153 uint32_t objectIndex = objectId & INDEX_MASK;
2154 uint32_t objectLimit = direction == 0 ? junctions->count : routeChains->count;
2155
2156 if( ( objectId & TAG_MASK ) != expectedObjectTag || objectIndex >= objectLimit )
2157 THROW_IO_ERROR( "Invalid PADS route-relationship object identifier" );
2158
2159 if( direction == 0 )
2160 {
2161 junctionSignals.emplace_back( objectIndex, signalIndex );
2162 }
2163
2164 uint32_t expectedValueTag = direction == 0 ? ROUTE_CHAIN_TAG : JUNCTION_TAG;
2165 uint32_t valueLimit = direction == 0 ? routeChains->count : junctions->count;
2166
2167 for( uint32_t valueIndex = 0; valueIndex < numValues; ++valueIndex )
2168 {
2169 uint32_t value = readU32();
2170
2171 if( ( value & TAG_MASK ) != expectedValueTag || ( value & INDEX_MASK ) >= valueLimit )
2172 THROW_IO_ERROR( "Invalid PADS route-relationship member identifier" );
2173 }
2174 }
2175 }
2176
2177 ++signalIndex;
2178 }
2179
2180 if( cursor != end || ( signalIndex != m_nets.size() && signalIndex != nets->count ) )
2181 THROW_IO_ERROR( "Invalid PADS route-relationship framing" );
2182
2183 for( const auto& [junctionIndex, sourceSignalIndex] : junctionSignals )
2184 {
2185 std::optional<size_t> netIndex;
2186
2187 if( signalIndex == nets->count )
2188 {
2189 auto netIt = m_sec23RecordToNet.find( static_cast<uint32_t>( sourceSignalIndex ) );
2190
2191 if( netIt != m_sec23RecordToNet.end() )
2192 netIndex = netIt->second;
2193 }
2194 else
2195 {
2196 netIndex = sourceSignalIndex;
2197 }
2198
2199 if( !netIndex )
2200 continue;
2201
2202 auto [it, inserted] = result.emplace( junctionIndex, *netIndex );
2203
2204 if( !inserted && it->second != *netIndex )
2205 THROW_IO_ERROR( "Conflicting PADS route-junction relationship" );
2206 }
2207
2208 return result;
2209}
2210
2211
2213{
2214 // Section 60 identifies via instances and their net/via-definition ordinals. Sections
2215 // 62-64 store routed copper as 48-byte object descriptors, a layer table, and compressed
2216 // 12-byte geometry cells; a separate 32-byte header arena carries width, layer, and links.
2217 const SDB_SECTION* entry60 = getSection( SECTION::Vias );
2218
2219 if( !entry60 )
2220 THROW_IO_ERROR( "Missing PADS via controller" );
2221
2222 if( entry60->count == 0 )
2223 return;
2224
2225 std::map<std::string, ROUTE> routes = seedRoutesFromVias( decodeViaLocations() );
2226
2227 decodeRoutedCopper( routes );
2228
2229 // Vias seeded from the junction controller are emitted even when the route-object
2230 // controller is empty, so a board with stitching but no routed copper keeps them.
2231 for( auto& [netName, route] : routes )
2232 {
2233 if( route.tracks.empty() && route.vias.empty() )
2234 continue;
2235
2236 m_routes.push_back( std::move( route ) );
2237 }
2238}
2239
2240
2241std::vector<BINARY_PARSER::VIA_LOCATION> BINARY_PARSER::decodeViaLocations()
2242{
2243 m_junctionHandleNets.clear();
2244
2245 const SDB_SECTION* entry60 = getSection( SECTION::Vias );
2246
2247 if( !entry60 )
2248 THROW_IO_ERROR( "Missing PADS via controller" );
2249
2250 if( entry60->stride == 0 )
2251 THROW_IO_ERROR( "Invalid PADS via-controller stride" );
2252
2253 uint32_t stride = entry60->stride;
2254
2255 if( stride < 31 || entry60->physicalCount != entry60->count )
2256 THROW_IO_ERROR( "Invalid PADS via-controller framing" );
2257
2258 // Section 60 is a ring rotated left to its X field. Its logical record-grid
2259 // origin is therefore stride-31 bytes before the directly framed physical range.
2260 std::vector<size_t> typeBytes;
2261 const size_t ringRotation = stride - 31;
2262
2263 if( entry60->physicalOffset >= ringRotation
2264 && m_cursor.InBounds( entry60->physicalOffset, entry60->physicalBytes ) )
2265 {
2266 const size_t base = entry60->physicalOffset - ringRotation;
2267
2268 for( uint32_t rec = 0; rec < entry60->physicalCount; ++rec )
2269 typeBytes.push_back( base + static_cast<size_t>( rec ) * stride + stride - 4 );
2270
2271 logResolvedBase( 60, "physicalRing", base, entry60->physicalOffset );
2272 }
2273
2274 // A nonempty controller must have one directly framed physical record per directory item.
2275 if( typeBytes.empty() )
2276 THROW_IO_ERROR( "Invalid PADS via-controller extent" );
2277
2278 const std::map<uint32_t, size_t> junctionNets = parseRouteJunctionNets();
2279
2280 for( size_t junction = 0; junction < typeBytes.size(); ++junction )
2281 {
2282 auto netIt = junctionNets.find( static_cast<uint32_t>( junction ) );
2283
2284 if( netIt == junctionNets.end() )
2285 continue;
2286
2287 if( netIt->second >= m_nets.size() || typeBytes[junction] < 27 )
2288 THROW_IO_ERROR( "Invalid PADS route-junction net mapping" );
2289
2290 const size_t typeByte = typeBytes[junction];
2291 uint32_t objectHandle = m_cursor.U32At( typeByte - 19 );
2292
2293 if( objectHandle != 0 )
2294 m_junctionHandleNets[objectHandle].insert( netIt->second );
2295 }
2296
2297 std::vector<VIA_LOCATION> viaLocations;
2298
2299 for( size_t junction = 0; junction < typeBytes.size(); ++junction )
2300 {
2301 size_t typeByte = typeBytes[junction];
2302 uint8_t type = m_cursor.U8At( typeByte );
2303 bool isVia = type == VIA_TYPE && viaRecordValid( m_cursor, typeByte );
2304
2305 if( !isVia )
2306 continue;
2307
2308 if( typeByte < 27 || !m_cursor.InBounds( typeByte - 27, 8 ) )
2309 continue;
2310
2311 int32_t vx = m_cursor.I32At( typeByte - 27 );
2312 int32_t vy = m_cursor.I32At( typeByte - 23 );
2313
2314 std::string netName;
2315 uint32_t netIdx = m_cursor.U16At( typeByte + 1 );
2316 auto it = m_sec23IndexToNet.find( netIdx );
2317 auto relationshipIt = junctionNets.find( static_cast<uint32_t>( junction ) );
2318
2319 if( relationshipIt != junctionNets.end() && relationshipIt->second < m_nets.size() )
2320 {
2321 netName = m_nets[relationshipIt->second].name;
2322 }
2323 else if( it != m_sec23IndexToNet.end() )
2324 {
2325 netName = it->second;
2326 }
2327
2329 via.x = vx;
2330 via.y = vy;
2331 via.netName = std::move( netName );
2332 via.viaIndex = m_cursor.U8At( typeByte - 3 );
2333 via.relationshipNet = relationshipIt != junctionNets.end();
2334 viaLocations.push_back( std::move( via ) );
2335 }
2336
2337 // Co-located vias are one physical via serialized once per junction that touches it, so the
2338 // survivor takes the strongest net evidence any of them carries.
2339 std::map<std::pair<int32_t, int32_t>, VIA_LOCATION> uniqueVias;
2340
2341 for( VIA_LOCATION& via : viaLocations )
2342 {
2343 auto [it, inserted] = uniqueVias.try_emplace( std::make_pair( via.x, via.y ) );
2344
2345 if( inserted )
2346 {
2347 it->second = std::move( via );
2348 continue;
2349 }
2350
2351 VIA_LOCATION& existing = it->second;
2352
2353 if( existing.viaIndex != via.viaIndex )
2354 THROW_IO_ERROR( "Conflicting co-located PADS via definitions" );
2355
2356 if( via.relationshipNet )
2357 {
2358 if( existing.relationshipNet && existing.netName != via.netName )
2359 THROW_IO_ERROR( "Conflicting co-located PADS via relationships" );
2360
2361 existing.netName = std::move( via.netName );
2362 existing.relationshipNet = true;
2363 }
2364 else if( !existing.relationshipNet && !via.netName.empty() )
2365 {
2366 if( !existing.netName.empty() && existing.netName != via.netName )
2367 THROW_IO_ERROR( "Conflicting co-located PADS via net state" );
2368
2369 existing.netName = std::move( via.netName );
2370 }
2371 }
2372
2373 std::vector<VIA_LOCATION> deduplicated;
2374 deduplicated.reserve( uniqueVias.size() );
2375
2376 for( auto& [coordinate, via] : uniqueVias )
2377 deduplicated.push_back( std::move( via ) );
2378
2379 return deduplicated;
2380}
2381
2382
2383std::map<std::string, ROUTE> BINARY_PARSER::seedRoutesFromVias( const std::vector<VIA_LOCATION>& aVias ) const
2384{
2385 std::map<std::string, ROUTE> routes;
2386
2387 for( const VIA_LOCATION& via : aVias )
2388 {
2389 ROUTE& route = routes[via.netName];
2390 route.net_name = via.netName;
2391
2392 VIA viaDef;
2393 viaDef.location.x = static_cast<double>( via.x );
2394 viaDef.location.y = static_cast<double>( via.y );
2395 viaDef.start_layer = 1;
2396 viaDef.end_layer = m_parameters.layer_count;
2397
2398 if( via.viaIndex >= 0 && static_cast<size_t>( via.viaIndex ) < m_decalNameTable.size() )
2399 {
2400 auto decalIt = m_decals.find( m_decalNameTable[via.viaIndex] );
2401
2402 if( decalIt != m_decals.end() )
2403 {
2404 auto stackIt = decalIt->second.pad_stacks.find( 1 );
2405
2406 if( stackIt == decalIt->second.pad_stacks.end() )
2407 stackIt = decalIt->second.pad_stacks.find( 0 );
2408
2409 if( stackIt != decalIt->second.pad_stacks.end() && !stackIt->second.empty() )
2410 {
2411 viaDef.stack = stackIt->second;
2412
2413 auto spanIt = decalIt->second.drill_spans.find( stackIt->first );
2414
2415 if( spanIt != decalIt->second.drill_spans.end() && spanIt->second.first > 0
2416 && spanIt->second.second > 0 )
2417 {
2418 // The pair is stored in either order and is not bounded by the layer
2419 // count, so normalize and range-check it here the way the ASCII path
2420 // does rather than let a stale byte surface as an unusable via span
2421 int spanStart = std::min( spanIt->second.first, spanIt->second.second );
2422 int spanEnd = std::max( spanIt->second.first, spanIt->second.second );
2423
2424 if( spanEnd <= m_parameters.layer_count )
2425 {
2426 viaDef.start_layer = spanStart;
2427 viaDef.end_layer = spanEnd;
2428 }
2429 }
2430 }
2431 }
2432 }
2433
2434 if( viaDef.stack.empty() )
2435 {
2436 const std::string name = via.viaIndex >= 0 && static_cast<size_t>( via.viaIndex ) < m_decalNameTable.size()
2437 ? m_decalNameTable[via.viaIndex]
2438 : std::string( "<out-of-range>" );
2440 wxString::Format( "Invalid PADS via padstack reference %d (%s)", via.viaIndex, name.c_str() ) );
2441 }
2442
2443 route.vias.push_back( std::move( viaDef ) );
2444 }
2445
2446 return routes;
2447}
2448
2449
2450void BINARY_PARSER::decodeRoutedCopper( std::map<std::string, ROUTE>& aRoutes )
2451{
2452 const SDB_SECTION* routeObjects = getSection( SECTION::RouteObjects );
2453 const SDB_SECTION* routeLayers = getSection( SECTION::RouteLayers );
2454 const SDB_SECTION* routeCells = getSection( SECTION::RouteCells );
2455
2456 if( !routeObjects || !routeLayers || !routeCells )
2457 THROW_IO_ERROR( "Missing PADS route controllers" );
2458
2459 if( routeLayers->count == 0 || static_cast<uint64_t>( routeLayers->count ) * 2 != routeLayers->totalBytes )
2460 {
2461 THROW_IO_ERROR( "Invalid PADS route-layer controller extent" );
2462 }
2463
2464 if( static_cast<uint64_t>( routeCells->count ) * 12 != routeCells->totalBytes )
2465 THROW_IO_ERROR( "Invalid PADS route-cell controller extent" );
2466
2467 if( routeObjects->count == 0 )
2468 {
2469 if( routeObjects->totalBytes != 0 || routeCells->count != 0 )
2470 THROW_IO_ERROR( "Invalid empty PADS route-object controller" );
2471
2472 return;
2473 }
2474
2475 if( ( routeObjects->stride != 36 && routeObjects->stride != 48 )
2476 || static_cast<uint64_t>( routeObjects->count ) * routeObjects->stride != routeObjects->totalBytes )
2477 {
2478 THROW_IO_ERROR( "Invalid PADS route-object controller extent" );
2479 }
2480
2481 struct ROUTE_OBJECT
2482 {
2483 int32_t width = 0;
2484 uint32_t style = 0;
2485 uint32_t cellCount = 0;
2486 };
2487
2488 size_t objectBytes = routeObjects->physicalBytes;
2489 size_t layerTable = routeLayers->physicalOffset;
2490 std::vector<int> serializedLayerOrder;
2491 bool legacyObjects = routeObjects->stride == 36;
2492 size_t objectStride = legacyObjects ? 36 : 48;
2493 size_t widthOffset = legacyObjects ? 8 : 20;
2494 size_t cellCountOffset = legacyObjects ? 24 : 36;
2495
2496 auto ringU32 = [&]( size_t aRingStart, size_t aOffset )
2497 {
2498 uint32_t value = 0;
2499
2500 for( size_t byte = 0; byte < 4; ++byte )
2501 {
2502 size_t physical = aRingStart + ( aOffset + byte ) % objectBytes;
2503 value |= static_cast<uint32_t>( m_cursor.U8At( physical ) ) << ( byte * 8 );
2504 }
2505
2506 return value;
2507 };
2508
2509 std::vector<bool> seenLayers( routeLayers->physicalCount, false );
2510 serializedLayerOrder.reserve( routeLayers->physicalCount );
2511
2512 for( uint32_t layer = 0; layer < routeLayers->physicalCount; ++layer )
2513 {
2514 uint16_t serializedLayer = m_cursor.U16At( layerTable + static_cast<size_t>( layer ) * 2 );
2515
2516 if( serializedLayer >= routeLayers->physicalCount || seenLayers[serializedLayer] )
2517 THROW_IO_ERROR( "Invalid PADS route-layer permutation" );
2518
2519 seenLayers[serializedLayer] = true;
2520 serializedLayerOrder.push_back( serializedLayer );
2521 }
2522
2523 if( layerTable == 0 )
2524 return;
2525
2526 size_t ringStart = routeObjects->physicalOffset;
2527 std::vector<ROUTE_OBJECT> objects;
2528
2529 for( uint32_t i = 0; i < routeObjects->physicalCount; ++i )
2530 {
2531 size_t base = ( 32 + static_cast<size_t>( i ) * objectStride ) % objectBytes;
2532 ROUTE_OBJECT object;
2533
2534 object.width = static_cast<int32_t>( ringU32( ringStart, base + widthOffset ) ) * 4;
2535 object.style = ringU32( ringStart, base + ( legacyObjects ? 20 : 32 ) );
2536 object.cellCount = ringU32( ringStart, base + cellCountOffset );
2537 objects.push_back( object );
2538 }
2539
2540 struct ROUTE_CELL
2541 {
2542 int32_t x1 = 0;
2543 int32_t y = 0;
2544 int32_t x2 = 0;
2545 };
2546
2547 size_t cellStart = routeCells->physicalOffset;
2548 std::vector<ROUTE_CELL> cells;
2549
2550 for( uint32_t i = 0; i < routeCells->count; ++i )
2551 {
2552 size_t base = cellStart + static_cast<size_t>( i ) * 12;
2553 int32_t first = m_cursor.I32At( base );
2554 int32_t second = m_cursor.I32At( base + 4 );
2555 int32_t third = m_cursor.I32At( base + 8 );
2556
2557 cells.push_back( { first, second, third } );
2558 }
2559
2560 size_t cursor = 0;
2561
2562 struct DECODED_TRACK
2563 {
2564 TRACK track;
2565 std::string netName;
2566 };
2567
2568 std::vector<DECODED_TRACK> decodedPieces;
2569
2570 // Each object's layer, its route-node handle and the nets that handle reaches come from the
2571 // section-25/26/27/29/61 allocator graph, which is decoded whole before any cell is read.
2572 const ROUTE_OBJECT_NODES nodes = resolveRouteObjectNodes( *routeLayers, objects.size(), serializedLayerOrder );
2573
2574 const std::vector<int>& objectLayers = nodes.layers;
2575 const std::vector<uint32_t>& objectHandles = nodes.handles;
2576 const std::map<uint32_t, std::set<size_t>>& routeNodeNets = nodes.handleNets;
2577
2578 struct ROUTE_CHUNK
2579 {
2580 size_t objectIndex = 0;
2581 size_t cellStart = 0;
2582 };
2583
2584 std::vector<ROUTE_CHUNK> chunks;
2585
2586 // The object array is a ring whose logical base is 32 bytes into its physical
2587 // storage. Its last descriptor therefore owns the first cell chunk, followed by
2588 // descriptors 0..N-2. The descriptor cell counts partition the cell stream exactly.
2589 for( size_t sequence = 0; sequence < objects.size(); ++sequence )
2590 {
2591 size_t match = ( sequence + objects.size() - 1 ) % objects.size();
2592
2593 if( cursor + objects[match].cellCount > cells.size() )
2594 THROW_IO_ERROR( "Invalid PADS route-cell partition" );
2595
2596 const ROUTE_OBJECT& object = objects[match];
2597
2598 // 0x100 and 0x1000 are the serialized jumper and via/special bits used by
2599 // the PADS ROUTE writer. Their cells belong to those auxiliary objects, not
2600 // ordinary routed-copper polylines.
2601 if( object.width > 0 && ( object.style & 0x1100 ) == 0 )
2602 chunks.push_back( { match, cursor } );
2603
2604 cursor += object.cellCount;
2605 }
2606
2607 if( cursor != cells.size() )
2608 THROW_IO_ERROR( "Invalid PADS route-cell extent" );
2609
2610 for( const ROUTE_CHUNK& chunk : chunks )
2611 {
2612 const ROUTE_OBJECT& object = objects[chunk.objectIndex];
2613
2614 TRACK track;
2615 track.layer = objectLayers[chunk.objectIndex];
2616 track.width = object.width;
2617
2618 if( track.layer <= 0 || static_cast<size_t>( track.layer ) >= m_layerInfos.size() )
2619 THROW_IO_ERROR( "Invalid PADS route-object layer" );
2620
2621 int routingDirection = m_layerInfos[track.layer].routing_direction;
2622
2623 if( routingDirection < 0 || routingDirection > 4 )
2624 THROW_IO_ERROR( "Invalid PADS routing direction" );
2625
2626 bool fixedIsX = routingDirection == 1;
2627
2628 for( size_t j = 0; j < object.cellCount; ++j )
2629 {
2630 const ROUTE_CELL& cell = cells[chunk.cellStart + j];
2631 double x1 = fixedIsX ? cell.x1 : cell.y;
2632 double y1 = fixedIsX ? cell.y : cell.x1;
2633 double x2 = fixedIsX ? cell.x2 : cell.y;
2634 double y2 = fixedIsX ? cell.y : cell.x2;
2635
2636 if( track.points.empty() || track.points.back().x != x1 || track.points.back().y != y1 )
2637 {
2638 track.points.emplace_back( x1, y1 );
2639 }
2640
2641 if( x1 != x2 || y1 != y2 )
2642 track.points.emplace_back( x2, y2 );
2643 }
2644
2645 if( track.points.size() < 2 )
2646 continue;
2647
2648 auto handleIt = routeNodeNets.find( objectHandles[chunk.objectIndex] );
2649 std::optional<size_t> netIndex;
2650
2651 if( handleIt == routeNodeNets.end() )
2652 THROW_IO_ERROR( "Missing PADS route-object node relationship" );
2653
2654 const std::set<size_t>& handleNets = handleIt->second;
2655
2656 if( handleNets.size() > 1 )
2657 THROW_IO_ERROR( wxString::Format( "Conflicting PADS route-object handle nets "
2658 "(object %zu, handle 0x%08X, nets %zu)",
2659 chunk.objectIndex, objectHandles[chunk.objectIndex],
2660 handleNets.size() ) );
2661
2662 if( handleNets.size() == 1 )
2663 netIndex = *handleNets.begin();
2664
2665 if( !netIndex || *netIndex >= m_nets.size() )
2666 {
2667 const ARC_POINT& first = track.points.front();
2668 const ARC_POINT& last = track.points.back();
2669 THROW_IO_ERROR( fmt::format( "Missing PADS route-object net relationship "
2670 "(object {}, handle 0x{:08X}, layer {}, cells {}, "
2671 "first {:.0f},{:.0f}, last {:.0f},{:.0f})",
2672 chunk.objectIndex, objectHandles[chunk.objectIndex], track.layer,
2673 object.cellCount, first.x, first.y, last.x, last.y ) );
2674 }
2675
2676 decodedPieces.push_back( { std::move( track ), m_nets[*netIndex].name } );
2677 }
2678
2679 for( DECODED_TRACK& decoded : decodedPieces )
2680 {
2681 ROUTE& route = aRoutes[decoded.netName];
2682 route.net_name = decoded.netName;
2683 route.tracks.push_back( std::move( decoded.track ) );
2684 }
2685}
2686
2687
2689BINARY_PARSER::resolveRouteObjectNodes( const SDB_SECTION& aRouteLayers, size_t aObjectCount,
2690 const std::vector<int>& aSerializedLayerOrder )
2691{
2692 ROUTE_OBJECT_NODES nodes;
2693 nodes.layers.assign( aObjectCount, 0 );
2694 nodes.handles.assign( aObjectCount, 0 );
2695
2696 auto padsLayerForSerializedIndex = [&]( size_t aIndex )
2697 {
2698 return aIndex < aSerializedLayerOrder.size() ? aSerializedLayerOrder[aIndex] + 1
2699 : static_cast<int>( aIndex ) + 1;
2700 };
2701
2702 const SDB_SECTION* routeController = getSection( 25 );
2703 const SDB_SECTION* allocatorDescriptors = getSection( 26 );
2704 const SDB_SECTION* layerObjectCounts = getSection( 27 );
2705 const SDB_SECTION* layerObjectHandles = getSection( 29 );
2706 const SDB_SECTION* routeNodes = getSection( 61 );
2707
2708 if( !routeController || !allocatorDescriptors || !layerObjectCounts || !layerObjectHandles || !routeNodes
2709 || !m_cursor.InBounds( routeController->physicalOffset + 180, 8 )
2710 || layerObjectCounts->physicalCount != aRouteLayers.physicalCount )
2711 {
2712 THROW_IO_ERROR( "Invalid PADS route allocator controllers" );
2713 }
2714
2715 std::array<uint16_t, 4> allocatorPageCounts;
2716
2717 for( size_t group = 0; group < allocatorPageCounts.size(); ++group )
2718 allocatorPageCounts[group] = m_cursor.U16At( routeController->physicalOffset + 180 + group * 2 );
2719
2720 size_t nodePageStart =
2721 static_cast<size_t>( allocatorPageCounts[0] ) + allocatorPageCounts[1] + allocatorPageCounts[2];
2722 size_t nodePageCount = allocatorPageCounts[3];
2723
2724 if( nodePageCount == 0 || nodePageStart + nodePageCount > allocatorDescriptors->physicalCount )
2725 THROW_IO_ERROR( "Invalid PADS route node page group" );
2726
2727 struct NODE_PAGE
2728 {
2729 uint32_t base = 0;
2730 uint32_t liveCount = 0;
2731 size_t firstOrdinal = 0;
2732 };
2733
2734 std::vector<NODE_PAGE> nodePages;
2735 size_t allocatedNodes = 0;
2736
2737 for( size_t page = 0; page < nodePageCount; ++page )
2738 {
2739 size_t descriptor = allocatorDescriptors->physicalOffset + ( nodePageStart + page ) * 12;
2740 uint32_t liveCount;
2741
2742 if( page + 1 < nodePageCount )
2743 liveCount = m_cursor.U32At( descriptor + 20 );
2744 else if( allocatedNodes <= routeNodes->physicalCount )
2745 liveCount = routeNodes->physicalCount - allocatedNodes;
2746 else
2747 THROW_IO_ERROR( "Invalid PADS route node page counts" );
2748
2749 nodePages.push_back( { m_cursor.U32At( descriptor ), liveCount, allocatedNodes } );
2750 allocatedNodes += liveCount;
2751 }
2752
2753 if( allocatedNodes != routeNodes->physicalCount )
2754 THROW_IO_ERROR( "Invalid PADS route node extent" );
2755
2756 std::vector<uint32_t> routeNodeHandles;
2757 routeNodeHandles.reserve( routeNodes->physicalCount );
2758
2759 for( const NODE_PAGE& page : nodePages )
2760 {
2761 for( uint32_t index = 0; index < page.liveCount; ++index )
2762 routeNodeHandles.push_back( page.base + index * 56 );
2763 }
2764
2765 std::map<uint32_t, size_t> routeNodeOrdinals;
2766
2767 for( size_t ordinal = 0; ordinal < routeNodeHandles.size(); ++ordinal )
2768 routeNodeOrdinals.emplace( routeNodeHandles[ordinal], ordinal );
2769
2770 std::vector<std::vector<size_t>> routeNodeLinks( routeNodeHandles.size() );
2771
2772 for( size_t ordinal = 0; ordinal < routeNodeHandles.size(); ++ordinal )
2773 {
2774 size_t nodeOffset = routeNodes->physicalOffset + ordinal * 12;
2775
2776 for( uint32_t linkedHandle : { m_cursor.U32At( nodeOffset ), m_cursor.U32At( nodeOffset + 4 ) } )
2777 {
2778 auto linkedIt = routeNodeOrdinals.find( linkedHandle );
2779
2780 if( linkedIt == routeNodeOrdinals.end() )
2781 continue;
2782
2783 routeNodeLinks[linkedIt->second].push_back( ordinal );
2784 }
2785 }
2786
2787 // A node's nets are those of the nearest junctions reachable from it, taking every junction
2788 // at that first distance and stopping there rather than draining the whole component -- a
2789 // deeper junction belongs to a different net and must not bleed into this one. The visited
2790 // marks are stamped with the root ordinal so the buffers survive across roots unallocated.
2791 std::map<uint32_t, std::set<size_t>>& routeNodeNets = nodes.handleNets;
2792 std::vector<uint32_t> visitedStamp( routeNodeHandles.size(), UINT32_MAX );
2793 std::vector<size_t> frontier;
2794 std::vector<size_t> next;
2795
2796 for( size_t root = 0; root < routeNodeHandles.size(); ++root )
2797 {
2798 std::set<size_t> componentNets;
2799
2800 visitedStamp[root] = static_cast<uint32_t>( root );
2801 frontier.assign( 1, root );
2802
2803 while( !frontier.empty() && componentNets.empty() )
2804 {
2805 next.clear();
2806
2807 for( size_t ordinal : frontier )
2808 {
2809 auto netIt = m_junctionHandleNets.find( routeNodeHandles[ordinal] );
2810
2811 if( netIt != m_junctionHandleNets.end() )
2812 componentNets.insert( netIt->second.begin(), netIt->second.end() );
2813
2814 for( size_t linked : routeNodeLinks[ordinal] )
2815 {
2816 if( visitedStamp[linked] == static_cast<uint32_t>( root ) )
2817 continue;
2818
2819 visitedStamp[linked] = static_cast<uint32_t>( root );
2820 next.push_back( linked );
2821 }
2822 }
2823
2824 frontier.swap( next );
2825 }
2826
2827 routeNodeNets.emplace( routeNodeHandles[root], std::move( componentNets ) );
2828 }
2829
2830 auto nodeOrdinal = [&]( uint32_t aHandle ) -> std::optional<size_t>
2831 {
2832 auto it = routeNodeOrdinals.find( aHandle );
2833
2834 if( it != routeNodeOrdinals.end() )
2835 return it->second;
2836
2837 return std::nullopt;
2838 };
2839
2840 std::vector<int> serializedObjectLayers;
2841 std::vector<uint32_t> serializedObjectHandles;
2842 std::map<uint32_t, int> routeHandleLayers;
2843 size_t handleOrdinal = 0;
2844
2845 for( size_t layer = 0; layer < layerObjectCounts->physicalCount; ++layer )
2846 {
2847 uint32_t count = m_cursor.U32At( layerObjectCounts->physicalOffset + layer * 4 );
2848
2849 if( handleOrdinal + count > layerObjectHandles->physicalCount )
2850 THROW_IO_ERROR( "Invalid PADS per-layer route handle counts" );
2851
2852 for( size_t index = 0; index < count; ++index, ++handleOrdinal )
2853 {
2854 uint32_t handle = m_cursor.U32At( layerObjectHandles->physicalOffset + handleOrdinal * 4 );
2855
2856 if( handle == 0 )
2857 continue;
2858
2859 int padsLayer = padsLayerForSerializedIndex( layer );
2860 auto [layerIt, inserted] = routeHandleLayers.emplace( handle, padsLayer );
2861
2862 if( !inserted && layerIt->second != padsLayer )
2863 THROW_IO_ERROR( "Conflicting PADS route-handle layers" );
2864
2865 auto ordinal = nodeOrdinal( handle );
2866
2867 if( !ordinal )
2868 THROW_IO_ERROR( "Invalid PADS route node handle" );
2869
2870 uint32_t classTag = m_cursor.U32At( routeNodes->physicalOffset + *ordinal * 12 + 8 );
2871
2872 if( ( classTag & 0x00800000 ) != 0 )
2873 {
2874 serializedObjectLayers.push_back( padsLayer );
2875 serializedObjectHandles.push_back( handle );
2876 }
2877 }
2878 }
2879
2880 if( handleOrdinal != layerObjectHandles->physicalCount || serializedObjectLayers.size() != aObjectCount )
2881 {
2882 THROW_IO_ERROR( "Invalid PADS route object-node mapping" );
2883 }
2884
2885 for( size_t sequence = 0; sequence < serializedObjectLayers.size(); ++sequence )
2886 {
2887 size_t object = ( sequence + aObjectCount - 1 ) % aObjectCount;
2888 nodes.layers[object] = serializedObjectLayers[sequence];
2889 nodes.handles[object] = serializedObjectHandles[sequence];
2890 }
2891
2892 return nodes;
2893}
2894
2895
2897{
2898 const SDB_SECTION* sec10 = getSection( SECTION::DrwItems );
2900 const SDB_SECTION* sec12 = getSection( SECTION::Vertices );
2901
2902 if( m_version <= 0x2022 )
2903 return;
2904
2905 if( !sec10 || !sec11 || !sec12 )
2906 THROW_IO_ERROR( "Missing PADS copper-shape controllers" );
2907
2908 const size_t pieceStride = m_version <= 0x2024 ? 16 : 20;
2909
2910 if( sec10->stride != DRW_ITEM::SIZE || sec11->stride != pieceStride || sec12->stride != 12 )
2911 THROW_IO_ERROR( "Invalid PADS copper-shape controller framing" );
2912
2913 constexpr size_t MAX_COPPER_SHAPE_EDGES = 80;
2914
2915 // Section 10 is a circular controller. buildOwnerRuns follows its declared count and the
2916 // serialized owner-to-piece cursors; section 12 vertices start at their physical offset.
2917 for( const auto& [name, run] : m_ownerRuns )
2918 {
2919 if( name.size() < 4 || name.substr( 0, 3 ) != "DRW" )
2920 continue;
2921
2922 const size_t ownerStride = m_version <= 0x2022 ? DRW_ITEM_V2022::SIZE : DRW_ITEM::SIZE;
2923
2924 if( ( run.itemKind & 0xFFFFU ) != 3 )
2925 continue;
2926
2927 uint32_t sec11Index = static_cast<uint32_t>( run.pieceStart );
2928
2929 if( sec11Index >= sec11->count )
2930 continue;
2931
2932 int32_t originX = ringI32( *sec10, DRW_ITEM::ROTATION, ownerStride, run.ownerIndex, DRW_ITEM::ORIGIN_X );
2933 int32_t originY = ringI32( *sec10, DRW_ITEM::ROTATION, ownerStride, run.ownerIndex, DRW_ITEM::ORIGIN_Y );
2934
2935 // fetchOwnerLoop already strips the duplicate closing point, so its own >= 3 success
2936 // condition is the true minimum for a valid polygon (a triangle). The previous minEdges
2937 // of 5 (4 for v2026) was excluding legitimate 4-corner rectangles -- PADS' own corner
2938 // count includes that closing repeat, so a "5 corner" ASCII COPCLS is a plain rectangle,
2939 // not a pentagon. Verified against MC4_PLUS_CSHAPE.pcb's DRW43215695/DRW89204466 (both
2940 // real 4-corner COPCLS rectangles, dropped by the old threshold) and the eight
2941 // DRW_TAG::COPPER_FILL_B rectangles alongside them.
2942 std::vector<VECTOR2I> loop;
2943
2944 if( fetchOwnerLoop( name, MAX_COPPER_SHAPE_EDGES, loop ) )
2945 {
2946 }
2947 else
2948 {
2949 // A circular copper fill (PADS' COPCIR piece type) stores exactly two diametrically
2950 // opposite endpoints -- fetchOwnerLoop above always rejects that shape since it
2951 // never finds a closing point. The bbox-equality cross-check still applies, now
2952 // against the circle's own derived extent (center = midpoint, radius = half the
2953 // point-to-point span): verified against MC4_PLUS_CSHAPE.pcb's DRW9467290, whose
2954 // derived circle bbox matches its declared header bbox exactly.
2955 VECTOR2I p0, p1;
2956
2957 if( !fetchOwnerCirclePoints( name, p0, p1 ) )
2958 continue;
2959
2960 const double cx = ( p0.x + p1.x ) / 2.0;
2961 const double cy = ( p0.y + p1.y ) / 2.0;
2962 const double radius = std::hypot( p1.x - p0.x, p1.y - p0.y ) / 2.0;
2963
2964 constexpr int CIRCLE_SEGMENTS = 32;
2965 loop.clear();
2966
2967 for( int i = 0; i < CIRCLE_SEGMENTS; ++i )
2968 {
2969 double angle = ( 2.0 * M_PI * static_cast<double>( i ) ) / static_cast<double>( CIRCLE_SEGMENTS );
2970 loop.emplace_back( static_cast<int32_t>( std::lround( cx + radius * std::cos( angle ) ) ),
2971 static_cast<int32_t>( std::lround( cy + radius * std::sin( angle ) ) ) );
2972 }
2973 }
2974
2975 COPPER_SHAPE copper;
2976 copper.name = name;
2977 copper.filled = true;
2978
2979 size_t pieceRotation = sec11->totalBytes - ( pieceStride - 8 );
2980 uint32_t levelIndex = ( sec11Index + 1 ) % sec11->count;
2981 uint8_t level = ringU8( *sec11, pieceRotation, pieceStride, levelIndex, 1 );
2982 copper.width =
2983 static_cast<double>( ringI32( *sec11, pieceRotation, pieceStride, sec11Index, pieceStride - 8 ) );
2984 copper.layer = level;
2985
2986 for( const VECTOR2I& pt : loop )
2987 {
2988 int32_t rawX = static_cast<int32_t>( originX + pt.x );
2989 int32_t rawY = static_cast<int32_t>( originY + pt.y );
2990 copper.outline.emplace_back( toBasicCoordX( rawX ), toBasicCoordY( rawY ) );
2991 }
2992
2993 m_copper_shapes.push_back( std::move( copper ) );
2994 }
2995}
2996
2997
2999{
3000 const SDB_SECTION* sec10 = getSection( SECTION::DrwItems );
3001
3002 if( !sec10 || m_version <= 0x2022 || m_ownerRuns.empty() )
3003 return;
3004
3005 // A dimension's leader geometry is the sec12 vertex run of its DIM* DRW owner, laid out in
3006 // sub-piece order: BASPNT1(2v) BASPNT2(2v) ARWLN1(2v) ARWHD1(4v) ARWLN2(2v) ARWHD2(4v)
3007 // EXTLN1(2v) EXTLN2(2v). The measurement endpoints are the two BASPNT first points (run rows
3008 // 0 and 2); the crossbar is the ARWLN1 first point (run row 4). The vertices are absolute
3009 // design coords (no owner-origin shift).
3010 //
3011 // The value-label text lives in a sec8 record bound to the dimension only by anchor
3012 // proximity, which is unreliable when title-block notes share the dimension layer and
3013 // overlap the leader extent. We emit only the exact geometry and leave the override text
3014 // empty, so KiCad recomputes the displayed value from start/end (which equals the PADS value).
3015 for( uint32_t rec = 0; rec < sec10->count; ++rec )
3016 {
3017 std::string name = ringStr( *sec10, DRW_ITEM::ROTATION, DRW_ITEM::SIZE, rec, DRW_ITEM::NAME, 24 );
3018
3019 if( name.size() < 4 || name.substr( 0, 3 ) != "DIM" )
3020 continue;
3021
3022 auto it = m_ownerRuns.find( name );
3023
3024 if( it == m_ownerRuns.end() )
3025 continue;
3026
3027 int32_t startRow = it->second.vertexStart;
3028
3029 int32_t bp1x = 0, bp1y = 0, bp2x = 0, bp2y = 0, arwx = 0, arwy = 0, attr = 0;
3030
3031 if( !sec12Vertex( startRow + 0, bp1x, bp1y, attr ) || !sec12Vertex( startRow + 2, bp2x, bp2y, attr )
3032 || !sec12Vertex( startRow + 4, arwx, arwy, attr ) )
3033 {
3034 continue;
3035 }
3036
3037 DIMENSION dim;
3038 dim.name = name;
3039 dim.x = toBasicCoordX( bp1x );
3040 dim.y = toBasicCoordY( bp1y );
3041
3042 POINT pt1{ toBasicCoordX( bp1x ), toBasicCoordY( bp1y ) };
3043 POINT pt2{ toBasicCoordX( bp2x ), toBasicCoordY( bp2y ) };
3044 dim.points.push_back( pt1 );
3045 dim.points.push_back( pt2 );
3046
3047 // Horizontal vs vertical from the larger BASPNT delta; crossbar_pos is the ARWLN1 first
3048 // point projected onto the measured axis.
3049 dim.is_horizontal = std::abs( bp2x - bp1x ) > std::abs( bp2y - bp1y );
3050 dim.crossbar_pos = dim.is_horizontal ? toBasicCoordY( arwy ) : toBasicCoordX( arwx );
3051
3052 m_dimensions.push_back( std::move( dim ) );
3053 }
3054}
3055
3056
3058{
3059 m_sec12CleanRows = 0;
3060
3061 const SDB_SECTION* sec12 = getSection( SECTION::Vertices );
3062
3063 if( !sec12 )
3064 THROW_IO_ERROR( "Missing PADS vertex controller" );
3065
3066 if( sec12->totalBytes != static_cast<uint64_t>( sec12->count ) * 12 )
3067 THROW_IO_ERROR( "Invalid PADS vertex-controller extent" );
3068
3069 m_sec12CleanRows = static_cast<int32_t>( sec12->count );
3070}
3071
3072
3073uint8_t BINARY_PARSER::ringU8( const SDB_SECTION& aSection, size_t aRotation, size_t aStride, uint32_t aIndex,
3074 size_t aField ) const
3075{
3076 if( aSection.totalBytes == 0 || aIndex >= aSection.count || aField >= aStride )
3077 THROW_IO_ERROR( "Invalid PADS circular-controller record access" );
3078
3079 size_t logical = static_cast<size_t>( aIndex ) * aStride + aField;
3080 size_t physical = ( aRotation + logical ) % aSection.totalBytes;
3081 return m_cursor.U8At( aSection.physicalOffset + physical );
3082}
3083
3084
3085uint32_t BINARY_PARSER::ringU32( const SDB_SECTION& aSection, size_t aRotation, size_t aStride, uint32_t aIndex,
3086 size_t aField ) const
3087{
3088 uint32_t value = 0;
3089
3090 for( size_t byte = 0; byte < 4; ++byte )
3091 value |= static_cast<uint32_t>( ringU8( aSection, aRotation, aStride, aIndex, aField + byte ) ) << ( byte * 8 );
3092
3093 return value;
3094}
3095
3096
3097int32_t BINARY_PARSER::ringI32( const SDB_SECTION& aSection, size_t aRotation, size_t aStride, uint32_t aIndex,
3098 size_t aField ) const
3099{
3100 return static_cast<int32_t>( ringU32( aSection, aRotation, aStride, aIndex, aField ) );
3101}
3102
3103
3104std::string BINARY_PARSER::ringStr( const SDB_SECTION& aSection, size_t aRotation, size_t aStride, uint32_t aIndex,
3105 size_t aField, size_t aLength ) const
3106{
3107 std::string value;
3108 value.reserve( aLength );
3109
3110 for( size_t byte = 0; byte < aLength; ++byte )
3111 {
3112 char c = static_cast<char>( ringU8( aSection, aRotation, aStride, aIndex, aField + byte ) );
3113
3114 if( c == '\0' )
3115 break;
3116
3117 value.push_back( c );
3118 }
3119
3120 return value;
3121}
3122
3123
3125{
3126 m_ownerRuns.clear();
3127
3128 const SDB_SECTION* sec10 = getSection( SECTION::DrwItems );
3129
3130 if( !sec10 )
3131 THROW_IO_ERROR( "Missing PADS drawing controller" );
3132
3133 if( sec10->count == 0 )
3134 return;
3135
3136 const size_t stride = m_version <= 0x2022 ? DRW_ITEM_V2022::SIZE : DRW_ITEM::SIZE;
3137 const size_t nameOffset = m_version <= 0x2022 ? DRW_ITEM_V2022::NAME : DRW_ITEM::NAME;
3138
3139 if( sec10->totalBytes != static_cast<uint64_t>( sec10->count ) * stride )
3140 THROW_IO_ERROR( "Invalid PADS drawing-controller extent" );
3141
3142 for( uint32_t ownerIndex = 0; ownerIndex < sec10->count; ++ownerIndex )
3143 {
3144 std::string name = ringStr( *sec10, DRW_ITEM::ROTATION, stride, ownerIndex, nameOffset, stride - nameOffset );
3145
3146 if( name.empty() || m_ownerRuns.count( name ) )
3147 continue;
3148
3149 uint32_t lagIndex = ( ownerIndex + 1 ) % sec10->count;
3150 OWNER_RUN run;
3151 run.pieceStart = ringI32( *sec10, DRW_ITEM::ROTATION, stride, lagIndex, DRW_ITEM::PIECE_START );
3152 run.vertexStart = ringI32( *sec10, DRW_ITEM::ROTATION, stride, lagIndex, DRW_ITEM::VERTEX_START );
3153 run.arcStart = ringI32( *sec10, DRW_ITEM::ROTATION, stride, lagIndex, DRW_ITEM::ARC_START );
3154 run.pieceCount = ringI32( *sec10, DRW_ITEM::ROTATION, stride, lagIndex, DRW_ITEM::PIECE_COUNT );
3155 run.itemKind = ringU32( *sec10, DRW_ITEM::ROTATION, stride, lagIndex, DRW_ITEM::SUBTYPE_WORD );
3156 run.ownerIndex = ownerIndex;
3157 m_ownerRuns.emplace( std::move( name ), run );
3158 }
3159}
3160
3161
3162SDB_RECORD BINARY_PARSER::arcRecordFor( const SDB_SECTION& aArcParameters, int32_t aArcStart, int32_t aAttr,
3163 const char* aWhat ) const
3164{
3165 uint64_t arcIndex = static_cast<uint64_t>( aArcStart ) + static_cast<uint32_t>( aAttr );
3166
3167 if( aArcStart < 0 || arcIndex >= aArcParameters.count
3168 || aArcParameters.totalBytes != static_cast<uint64_t>( aArcParameters.count ) * 20 )
3169 {
3170 THROW_IO_ERROR( wxString::Format( "Invalid PADS %s arc range", aWhat ) );
3171 }
3172
3173 return m_sdb.RecordAt( aArcParameters.physicalOffset + arcIndex * 20 );
3174}
3175
3176
3177// An arc-parameter record carries only the arc's bounding box, so the center and radius are
3178// derived from it and the sweep from the two corners' angles about that center. The corners are
3179// owner-relative, so the returned center is offset back into the same frame the caller emits.
3180static ARC deriveArc( const SDB_RECORD& aArcRecord, const ARC_VERTEX& aStart, const ARC_VERTEX& aEnd, double aOriginX,
3181 double aOriginY )
3182{
3183 double xmin = aArcRecord.I32( 0 );
3184 double ymin = aArcRecord.I32( 4 );
3185 double xmax = aArcRecord.I32( 8 );
3186 double ymax = aArcRecord.I32( 12 );
3187 double centerX = ( xmin + xmax ) / 2.0;
3188 double centerY = ( ymin + ymax ) / 2.0;
3189 double startAngle = std::atan2( aStart.y - centerY, aStart.x - centerX ) * 180.0 / M_PI;
3190 double endAngle = std::atan2( aEnd.y - centerY, aEnd.x - centerX ) * 180.0 / M_PI;
3191
3192 ARC arc{};
3193 arc.cx = centerX + aOriginX;
3194 arc.cy = centerY + aOriginY;
3195 arc.radius = ( xmax - xmin ) / 2.0;
3196 arc.start_angle = startAngle;
3197 arc.delta_angle = EDA_ANGLE( endAngle - startAngle, DEGREES_T ).Normalize180().AsDegrees();
3198
3199 return arc;
3200}
3201
3202
3204{
3205 const SDB_SECTION* owners = getSection( SECTION::DrwItems );
3207 const SDB_SECTION* vertices = getSection( SECTION::Vertices );
3208 const SDB_SECTION* arcParameters = getSection( SECTION::DecalLibrary );
3209
3210 if( !owners || !pieces || !vertices || !arcParameters )
3211 THROW_IO_ERROR( "Missing PADS outline controllers" );
3212
3213 const size_t ownerStride = m_version <= 0x2022 ? DRW_ITEM_V2022::SIZE : DRW_ITEM::SIZE;
3214 const size_t pieceStride = m_version <= 0x2024 ? 16 : 20;
3215 const size_t pieceHead = pieceStride == 16 ? 8 : 12;
3216 const size_t cornerField = pieceStride == 16 ? 12 : 16;
3217 const size_t originXField = ownerStride == DRW_ITEM_V2022::SIZE ? DRW_ITEM_V2022::ORIGIN_X : DRW_ITEM::ORIGIN_X;
3218 const size_t originYField = originXField + 4;
3219 const size_t pieceRotation = pieces->totalBytes - pieceHead;
3220
3221 for( const auto& [name, run] : m_ownerRuns )
3222 {
3223 if( ( run.itemKind & 0xFFFFU ) != 1 || run.pieceCount <= 0 || run.pieceStart < 0 || run.vertexStart < 0 )
3224 continue;
3225
3226 if( static_cast<uint64_t>( run.pieceStart ) + static_cast<uint64_t>( run.pieceCount ) > pieces->count )
3227 THROW_IO_ERROR( "Invalid PADS board-outline piece range" );
3228
3229 int32_t originX = ringI32( *owners, DRW_ITEM::ROTATION, ownerStride, run.ownerIndex, originXField );
3230 int32_t originY = ringI32( *owners, DRW_ITEM::ROTATION, ownerStride, run.ownerIndex, originYField );
3231 int32_t vertexCursor = run.vertexStart;
3232
3233 for( int32_t piece = 0; piece < run.pieceCount; ++piece )
3234 {
3235 uint32_t pieceIndex = static_cast<uint32_t>( run.pieceStart + piece );
3236 int32_t corners = ringI32( *pieces, pieceRotation, pieceStride, pieceIndex, cornerField );
3237
3238 if( corners < 1
3239 || static_cast<uint64_t>( vertexCursor ) + static_cast<uint64_t>( corners ) > vertices->count )
3240 THROW_IO_ERROR( "Invalid PADS board-outline vertex range" );
3241
3242 std::vector<ARC_VERTEX> decoded;
3243 decoded.reserve( static_cast<size_t>( corners ) );
3244
3245 for( int32_t corner = 0; corner < corners; ++corner )
3246 {
3247 size_t offset = vertices->physicalOffset + static_cast<size_t>( vertexCursor + corner ) * 12;
3248 SDB_RECORD record = m_sdb.RecordAt( offset );
3249 decoded.push_back( { record.I32( 0 ), record.I32( 4 ), record.I32( 8 ) } );
3250 }
3251
3252 vertexCursor += corners;
3253
3254 POLYLINE outline;
3255 outline.layer = 1;
3256 outline.width =
3257 static_cast<double>( ringI32( *pieces, pieceRotation, pieceStride, pieceIndex, pieceStride - 8 ) );
3258 outline.closed = decoded.size() >= 3 && decoded.front().x == decoded.back().x
3259 && decoded.front().y == decoded.back().y;
3260
3261 for( size_t index = 0; index < decoded.size(); ++index )
3262 {
3263 const ARC_VERTEX& vertex = decoded[index];
3264 double rawX = static_cast<double>( vertex.x ) + originX;
3265 double rawY = static_cast<double>( vertex.y ) + originY;
3266
3267 if( index > 0 && decoded[index - 1].attr >= 0 )
3268 {
3269 SDB_RECORD arcRecord =
3270 arcRecordFor( *arcParameters, run.arcStart, decoded[index - 1].attr, "board-outline" );
3271
3272 outline.points.emplace_back( rawX, rawY,
3273 deriveArc( arcRecord, decoded[index - 1], vertex, originX, originY ) );
3274 }
3275 else
3276 {
3277 outline.points.emplace_back( rawX, rawY );
3278 }
3279 }
3280
3281 m_boardOutlines.push_back( std::move( outline ) );
3282 }
3283 }
3284}
3285
3286
3288{
3289 const SDB_SECTION* owners = getSection( SECTION::DrwItems );
3291 const SDB_SECTION* vertices = getSection( SECTION::Vertices );
3292 const SDB_SECTION* arcParameters = getSection( SECTION::DecalLibrary );
3293
3294 if( !owners || !pieces || !vertices || !arcParameters )
3295 THROW_IO_ERROR( "Missing PADS graphic controllers" );
3296
3297 const size_t ownerStride = m_version <= 0x2022 ? DRW_ITEM_V2022::SIZE : DRW_ITEM::SIZE;
3298 const size_t pieceStride = m_version <= 0x2024 ? 16 : 20;
3299 const size_t pieceHead = pieceStride - 8;
3300 const size_t cornerField = pieceStride - 4;
3301 const size_t originXField = ownerStride == DRW_ITEM_V2022::SIZE ? DRW_ITEM_V2022::ORIGIN_X : DRW_ITEM::ORIGIN_X;
3302 const size_t originYField = originXField + 4;
3303 const size_t pieceRotation = pieces->totalBytes - pieceHead;
3304
3305 if( vertices->totalBytes != static_cast<uint64_t>( vertices->count ) * 12
3306 || arcParameters->totalBytes != static_cast<uint64_t>( arcParameters->count ) * 20 )
3307 {
3308 THROW_IO_ERROR( "Invalid PADS graphic-controller framing" );
3309 }
3310
3311 for( const auto& [name, run] : m_ownerRuns )
3312 {
3313 if( ( run.itemKind & 0xFFFFU ) != 0 || name.compare( 0, 3, "DRW" ) != 0 || run.pieceCount <= 0
3314 || run.pieceStart < 0 || run.vertexStart < 0 )
3315 {
3316 continue;
3317 }
3318
3319 if( static_cast<uint64_t>( run.pieceStart ) + static_cast<uint64_t>( run.pieceCount ) > pieces->count )
3320 THROW_IO_ERROR( "Invalid PADS graphic piece range" );
3321
3322 int32_t originX = ringI32( *owners, DRW_ITEM::ROTATION, ownerStride, run.ownerIndex, originXField );
3323 int32_t originY = ringI32( *owners, DRW_ITEM::ROTATION, ownerStride, run.ownerIndex, originYField );
3324 int32_t vertexCursor = run.vertexStart;
3325
3326 for( int32_t piece = 0; piece < run.pieceCount; ++piece )
3327 {
3328 uint32_t pieceIndex = static_cast<uint32_t>( run.pieceStart + piece );
3329 int32_t corners = ringI32( *pieces, pieceRotation, pieceStride, pieceIndex, cornerField );
3330
3331 if( corners < 1
3332 || static_cast<uint64_t>( vertexCursor ) + static_cast<uint64_t>( corners ) > vertices->count )
3333 {
3334 THROW_IO_ERROR( wxString::Format( "Invalid PADS graphic vertex range (%s piece %d, start %d, "
3335 "corners %d, count %u)",
3336 name.c_str(), piece, vertexCursor, corners, vertices->count ) );
3337 }
3338
3339 GRAPHIC_LINE graphic;
3340 graphic.name = name;
3341 graphic.width = ringI32( *pieces, pieceRotation, pieceStride, pieceIndex, pieceStride - 8 );
3342 graphic.layer = ringU8( *pieces, pieceRotation, pieceStride, ( pieceIndex + 1 ) % pieces->count, 1 );
3343 graphic.points.reserve( static_cast<size_t>( corners ) );
3344
3345 std::vector<ARC_VERTEX> decoded;
3346 decoded.reserve( static_cast<size_t>( corners ) );
3347
3348 for( int32_t corner = 0; corner < corners; ++corner )
3349 {
3350 SDB_RECORD record = m_sdb.RecordAt( vertices->physicalOffset
3351 + static_cast<uint32_t>( vertexCursor + corner ) * 12 );
3352 decoded.push_back( { record.I32( 0 ), record.I32( 4 ), record.I32( 8 ) } );
3353 }
3354
3355 vertexCursor += corners;
3356 graphic.closed = decoded.size() >= 3 && decoded.front().x == decoded.back().x
3357 && decoded.front().y == decoded.back().y;
3358
3359 uint8_t pieceType = ringU8( *pieces, pieceRotation, pieceStride, ( pieceIndex + 1 ) % pieces->count, 0 );
3360
3361 if( pieceType == 2 && decoded.size() == 2 )
3362 {
3363 double centerX = ( decoded[0].x + decoded[1].x ) / 2.0 + originX;
3364 double centerY = ( decoded[0].y + decoded[1].y ) / 2.0 + originY;
3365 double radius = std::hypot( decoded[1].x - decoded[0].x, decoded[1].y - decoded[0].y ) / 2.0;
3366 ARC arc{};
3367 arc.cx = centerX;
3368 arc.cy = centerY;
3369 arc.radius = radius;
3370 arc.start_angle = 0.0;
3371 arc.delta_angle = 360.0;
3372 graphic.closed = true;
3373 graphic.points.emplace_back( centerX + radius, centerY, arc );
3374 m_graphicLines.push_back( std::move( graphic ) );
3375 continue;
3376 }
3377
3378 for( size_t index = 0; index < decoded.size(); ++index )
3379 {
3380 const ARC_VERTEX& vertex = decoded[index];
3381 double rawX = static_cast<double>( vertex.x ) + originX;
3382 double rawY = static_cast<double>( vertex.y ) + originY;
3383
3384 if( index > 0 && decoded[index - 1].attr >= 0 )
3385 {
3386 SDB_RECORD arcRecord =
3387 arcRecordFor( *arcParameters, run.arcStart, decoded[index - 1].attr, "graphic" );
3388
3389 graphic.points.emplace_back( rawX, rawY,
3390 deriveArc( arcRecord, decoded[index - 1], vertex, originX, originY ) );
3391 }
3392 else
3393 {
3394 graphic.points.emplace_back( rawX, rawY );
3395 }
3396 }
3397
3398 m_graphicLines.push_back( std::move( graphic ) );
3399 }
3400 }
3401}
3402
3403
3404bool BINARY_PARSER::sec12Vertex( int32_t aRow, int32_t& aX, int32_t& aY, int32_t& aAttr ) const
3405{
3406 const SDB_SECTION* sec12 = getSection( SECTION::Vertices );
3407
3408 if( !sec12 || aRow < 0 || aRow >= m_sec12CleanRows )
3409 return false;
3410
3411 if( sec12->physicalOffset + static_cast<size_t>( aRow + 1 ) * 12 > m_data.size() )
3412 return false;
3413
3414 SDB_RECORD rec = m_sdb.RecordAt( sec12->physicalOffset + static_cast<uint32_t>( aRow ) * 12 );
3415 aX = rec.I32( 0 );
3416 aY = rec.I32( 4 );
3417 aAttr = rec.I32( 8 );
3418 return true;
3419}
3420
3421
3422bool BINARY_PARSER::fetchOwnerLoop( const std::string& aName, size_t aMaxVerts, std::vector<VECTOR2I>& aOut ) const
3423{
3424 aOut.clear();
3425
3426 auto it = m_ownerRuns.find( aName );
3427
3428 if( it == m_ownerRuns.end() )
3429 return false;
3430
3432
3433 if( !pieces || it->second.pieceCount < 1 || it->second.pieceStart < 0 )
3434 return false;
3435
3436 size_t pieceStride = m_version <= 0x2024 ? 16 : 20;
3437 size_t pieceHead = pieceStride == 16 ? 8 : 12;
3438 size_t cornerField = pieceStride == 16 ? 12 : 16;
3439 size_t pieceRotation = pieces->totalBytes - pieceHead;
3440 int32_t corners =
3441 ringI32( *pieces, pieceRotation, pieceStride, static_cast<uint32_t>( it->second.pieceStart ), cornerField );
3442
3443 if( corners < 4 || static_cast<size_t>( corners ) > aMaxVerts + 1 )
3444 return false;
3445
3446 int32_t startRow = it->second.vertexStart;
3447
3448 int32_t firstX = 0;
3449 int32_t firstY = 0;
3450 int32_t attr = 0;
3451
3452 if( !sec12Vertex( startRow, firstX, firstY, attr ) )
3453 return false;
3454
3455 for( int32_t corner = 0; corner < corners - 1; ++corner )
3456 {
3457 int32_t x = 0;
3458 int32_t y = 0;
3459
3460 if( !sec12Vertex( startRow + corner, x, y, attr ) )
3461 return false;
3462
3463 aOut.emplace_back( x, y );
3464 }
3465
3466 int32_t lastX = 0;
3467 int32_t lastY = 0;
3468
3469 if( !sec12Vertex( startRow + corners - 1, lastX, lastY, attr ) || lastX != firstX || lastY != firstY )
3470 {
3471 aOut.clear();
3472 return false;
3473 }
3474
3475 return true;
3476}
3477
3478
3479bool BINARY_PARSER::fetchOwnerCirclePoints( const std::string& aName, VECTOR2I& aP0, VECTOR2I& aP1 ) const
3480{
3481 auto it = m_ownerRuns.find( aName );
3482
3483 if( it == m_ownerRuns.end() )
3484 return false;
3485
3487
3488 if( !pieces || it->second.pieceCount < 1 || it->second.pieceStart < 0 )
3489 return false;
3490
3491 size_t pieceStride = m_version <= 0x2024 ? 16 : 20;
3492 size_t pieceHead = pieceStride == 16 ? 8 : 12;
3493 size_t cornerField = pieceStride == 16 ? 12 : 16;
3494 size_t pieceRotation = pieces->totalBytes - pieceHead;
3495
3496 if( ringI32( *pieces, pieceRotation, pieceStride, static_cast<uint32_t>( it->second.pieceStart ), cornerField )
3497 != 2 )
3498 {
3499 return false;
3500 }
3501
3502 int32_t startRow = it->second.vertexStart;
3503
3504 int32_t x0 = 0, y0 = 0, x1 = 0, y1 = 0, attr = 0;
3505
3506 if( !sec12Vertex( startRow, x0, y0, attr ) || !sec12Vertex( startRow + 1, x1, y1, attr ) )
3507 return false;
3508
3509 if( x0 == x1 && y0 == y1 )
3510 return false;
3511
3512 aP0 = VECTOR2I( x0, y0 );
3513 aP1 = VECTOR2I( x1, y1 );
3514 return true;
3515}
3516
3517
3519{
3520 const SDB_SECTION* sec10 = getSection( SECTION::DrwItems );
3521 const SDB_SECTION* sec12 = getSection( SECTION::Vertices );
3522
3523 if( m_version <= 0x2022 )
3524 return;
3525
3526 if( !sec10 || !sec12 )
3527 THROW_IO_ERROR( "Missing PADS keepout controllers" );
3528
3529 if( sec10->stride < DRW_ITEM::SIZE || sec12->stride < 12 )
3530 THROW_IO_ERROR( "Invalid PADS keepout-controller framing" );
3531
3532 struct Owner
3533 {
3534 std::string name;
3535 int32_t originX = 0;
3536 int32_t originY = 0;
3537 int64_t minX = 0;
3538 int64_t minY = 0;
3539 int64_t maxX = 0;
3540 int64_t maxY = 0;
3541 };
3542
3543 std::vector<Owner> owners;
3544
3545 for( const auto& [name, run] : m_ownerRuns )
3546 {
3547 if( ( run.itemKind & 0xFFFFU ) != 10 )
3548 continue;
3549
3550 Owner owner;
3551 owner.name = name;
3552 owner.originX = ringI32( *sec10, DRW_ITEM::ROTATION, DRW_ITEM::SIZE, run.ownerIndex, DRW_ITEM::ORIGIN_X );
3553 owner.originY = ringI32( *sec10, DRW_ITEM::ROTATION, DRW_ITEM::SIZE, run.ownerIndex, DRW_ITEM::ORIGIN_Y );
3554 owner.minX = static_cast<int64_t>( ringI32( *sec10, DRW_ITEM::ROTATION, DRW_ITEM::SIZE, run.ownerIndex,
3556 - owner.originX;
3557 owner.minY = static_cast<int64_t>( ringI32( *sec10, DRW_ITEM::ROTATION, DRW_ITEM::SIZE, run.ownerIndex,
3559 - owner.originY;
3560 owner.maxX = static_cast<int64_t>( ringI32( *sec10, DRW_ITEM::ROTATION, DRW_ITEM::SIZE, run.ownerIndex,
3562 - owner.originX;
3563 owner.maxY = static_cast<int64_t>( ringI32( *sec10, DRW_ITEM::ROTATION, DRW_ITEM::SIZE, run.ownerIndex,
3565 - owner.originY;
3566
3567 owners.push_back( std::move( owner ) );
3568 }
3569
3570 if( owners.empty() )
3571 return;
3572
3573 constexpr size_t MAX_KEEP_OUT_VERTICES = 80;
3574
3575 for( const Owner& owner : owners )
3576 {
3577 KEEPOUT keepout;
3578 keepout.type = KEEPOUT_TYPE::ALL;
3579
3580 // The owner's vertexStart cursor anchors a contiguous run in sec12 that closes back to
3581 // its first vertex. Vertices are design coordinates; add the DRW raw origin to get RAW.
3582 std::vector<VECTOR2I> structuralLoop;
3583
3584 if( fetchOwnerLoop( owner.name, MAX_KEEP_OUT_VERTICES, structuralLoop ) )
3585 {
3586 for( const VECTOR2I& vertex : structuralLoop )
3587 {
3588 int32_t rawX = owner.originX + static_cast<int32_t>( vertex.x );
3589 int32_t rawY = owner.originY + static_cast<int32_t>( vertex.y );
3590 keepout.outline.emplace_back( toBasicCoordX( rawX ), toBasicCoordY( rawY ) );
3591 }
3592
3593 m_keepouts.push_back( std::move( keepout ) );
3594 continue;
3595 }
3596
3597 // A circle keepout has a degenerate (2-point) sec12 run that does not close. Its geometry
3598 // is the owner record's +96..+108 bbox: center = midpoint, radius = (xmax - xmin) / 2.
3599 int64_t spanX = owner.maxX - owner.minX;
3600 int64_t spanY = owner.maxY - owner.minY;
3601
3602 if( spanX <= 0 || spanX != spanY )
3603 continue;
3604
3605 constexpr int ELLIPSE_SEGMENTS = 32;
3606 double cx = static_cast<double>( owner.minX + owner.maxX ) / 2.0;
3607 double cy = static_cast<double>( owner.minY + owner.maxY ) / 2.0;
3608 double radius = static_cast<double>( spanX ) / 2.0;
3609
3610 for( int i = 0; i < ELLIPSE_SEGMENTS; ++i )
3611 {
3612 double angle = ( 2.0 * M_PI * static_cast<double>( i ) ) / static_cast<double>( ELLIPSE_SEGMENTS );
3613 int32_t rawX = owner.originX + static_cast<int32_t>( std::lround( cx + radius * std::cos( angle ) ) );
3614 int32_t rawY = owner.originY + static_cast<int32_t>( std::lround( cy + radius * std::sin( angle ) ) );
3615 keepout.outline.emplace_back( toBasicCoordX( rawX ), toBasicCoordY( rawY ) );
3616 }
3617
3618 m_keepouts.push_back( std::move( keepout ) );
3619 }
3620}
3621
3622
3624{
3625 // Section 52 is the declared 88-byte outline-owner array. The four-byte state stream after
3626 // section 49 has one word per live section-46 slot; accounting for it places sections 52--55
3627 // directly, with no signature search or phase selection.
3628 //
3629 // Owner record (88 bytes):
3630 // +0 u32 first piece index
3631 // +4 u32 first vertex index
3632 // +8 u32 first arc index (arcs are not yet imported)
3633 // +12 i32 section-23 net record index, -1 when the pour has no net
3634 // +24 i32 raw XLOC -- each pour owns its own anchor, not a shared board anchor
3635 // +28 i32 raw YLOC
3636 // +70 char name[16]
3637 //
3638 // Piece record (16 bytes), addressed by the owner's piece index:
3639 // +0 u32 corner count
3640 // +4 u32 arc count
3641 // +8 i32 width, BASIC units
3642 // +12 u8 piece type: 0x32 = polygon, 0x33 = circle (two diametrically-opposite corners,
3643 // not a 2-point polygon)
3644 // +13 u8 layer
3645 //
3646 // The vertex array is a flat run of 8-byte local (i32 x, i32 y) pairs.
3647 // Arc records decorate specific corner-to-corner segments with a curve rather than adding
3648 // extra boundary points, so the corner list alone still yields a closed (if not smoothly
3649 // curved) outline; arc-to-curve conversion is not implemented.
3650 static constexpr size_t OWNER_SIZE = 88;
3651 static constexpr size_t PIECE_SIZE = 16;
3652 static constexpr size_t VERTEX_SIZE = 8;
3653
3654 struct POUR_OWNER
3655 {
3656 uint32_t pieceStart = 0;
3657 uint32_t vertexStart = 0;
3658 uint32_t pieceCount = 0;
3659 int32_t rawX = 0;
3660 int32_t rawY = 0;
3661 std::string name;
3662 std::string netName;
3663 };
3664
3665 std::vector<POUR_OWNER> owners;
3666
3670
3671 if( !sec52 || !sec53 || !sec54 )
3672 THROW_IO_ERROR( "Missing PADS copper-pour controllers" );
3673
3674 if( sec52->physicalBytes != sec52->count * OWNER_SIZE || sec53->physicalBytes != sec53->count * PIECE_SIZE
3675 || sec54->physicalBytes != sec54->count * VERTEX_SIZE )
3676 THROW_IO_ERROR( "Invalid PADS copper-pour controller framing" );
3677
3678 for( uint32_t index = 0; index < sec52->count; ++index )
3679 {
3680 const size_t offset = sec52->physicalOffset + static_cast<size_t>( index ) * OWNER_SIZE;
3681 const uint8_t outlineType = m_cursor.U8At( offset + 87 );
3682 std::string name = m_cursor.StringAt( offset + 70, 14 );
3683
3684 if( outlineType != 0x32 || name.rfind( "POR", 0 ) != 0 )
3685 continue;
3686
3687 POUR_OWNER owner;
3688 owner.pieceStart = m_cursor.U32At( offset );
3689 owner.vertexStart = m_cursor.U32At( offset + 4 );
3690 owner.rawX = m_cursor.I32At( offset + 24 );
3691 owner.rawY = m_cursor.I32At( offset + 28 );
3692 owner.pieceCount = m_cursor.U32At( offset + 64 );
3693 owner.name = std::move( name );
3694
3695 if( auto netIt = m_sec23IndexToNet.find( m_cursor.U32At( offset + 12 ) ); netIt != m_sec23IndexToNet.end() )
3696 owner.netName = netIt->second;
3697
3698 owners.push_back( std::move( owner ) );
3699 }
3700
3701 for( const POUR_OWNER& owner : owners )
3702 {
3703 uint32_t vertexIndex = owner.vertexStart;
3704
3705 for( uint32_t pieceOrdinal = 0; pieceOrdinal < owner.pieceCount; ++pieceOrdinal )
3706 {
3707 const uint32_t pieceIndex = owner.pieceStart + pieceOrdinal;
3708
3709 if( pieceIndex >= sec53->count )
3710 THROW_IO_ERROR( "Invalid PADS copper-pour piece range" );
3711
3712 const size_t pieceOff = sec53->physicalOffset + static_cast<size_t>( pieceIndex ) * PIECE_SIZE;
3713 uint32_t cornerCount = m_cursor.U32At( pieceOff );
3714 int32_t width = m_cursor.I32At( pieceOff + 8 );
3715 uint8_t pieceType = m_cursor.U8At( pieceOff + 12 );
3716 uint8_t layer = m_cursor.U8At( pieceOff + 13 );
3717
3718 if( cornerCount == 0 || vertexIndex > sec54->count || cornerCount > sec54->count - vertexIndex )
3719 THROW_IO_ERROR( "Invalid PADS copper-pour vertex range" );
3720
3721 const size_t vOff = sec54->physicalOffset + static_cast<size_t>( vertexIndex ) * VERTEX_SIZE;
3722 vertexIndex += cornerCount;
3723
3724 POUR pour;
3725 pour.owner_pour = owner.name;
3726 pour.net_name = owner.netName;
3727 pour.width = static_cast<double>( width );
3728 pour.layer = static_cast<int>( layer );
3729
3730 if( pieceType == 0x33 && cornerCount == 2 )
3731 {
3732 // Circle piece: the two "corners" are diametrically opposite endpoints, not a
3733 // 2-point polygon -- the downstream zone builder requires at least 3 points and
3734 // would silently drop it. Synthesize a regular polygon approximation instead.
3735 int32_t x0 = owner.rawX + m_cursor.I32At( vOff );
3736 int32_t y0 = owner.rawY + m_cursor.I32At( vOff + 4 );
3737 int32_t x1 = owner.rawX + m_cursor.I32At( vOff + VERTEX_SIZE );
3738 int32_t y1 = owner.rawY + m_cursor.I32At( vOff + VERTEX_SIZE + 4 );
3739
3740 double cx = ( x0 + x1 ) / 2.0;
3741 double cy = ( y0 + y1 ) / 2.0;
3742 double radius = std::hypot( x1 - x0, y1 - y0 ) / 2.0;
3743
3744 static constexpr int CIRCLE_SEGMENTS = 48;
3745
3746 for( int s = 0; s < CIRCLE_SEGMENTS; ++s )
3747 {
3748 double angle = 2.0 * M_PI * s / CIRCLE_SEGMENTS;
3749 int32_t rawX = static_cast<int32_t>( std::lround( cx + radius * std::cos( angle ) ) );
3750 int32_t rawY = static_cast<int32_t>( std::lround( cy + radius * std::sin( angle ) ) );
3751
3752 pour.points.emplace_back( toBasicCoordX( rawX ), toBasicCoordY( rawY ) );
3753 }
3754 }
3755 else
3756 {
3757 for( uint32_t vertex = 0; vertex < cornerCount; ++vertex )
3758 {
3759 size_t offset = vOff + static_cast<size_t>( vertex ) * VERTEX_SIZE;
3760 int32_t localX = m_cursor.I32At( offset );
3761 int32_t localY = m_cursor.I32At( offset + 4 );
3762
3763 pour.points.emplace_back( toBasicCoordX( owner.rawX + localX ),
3764 toBasicCoordY( owner.rawY + localY ) );
3765 }
3766 }
3767
3768 m_pours.push_back( std::move( pour ) );
3769 }
3770 }
3771}
3772
3773
3776{
3777 const SDB_SECTION* section = m_sdb.Section( 69 );
3778
3779 if( !section || section->physicalCount == 0 )
3780 return 0;
3781
3782 constexpr uint64_t CONTROLLER_LEAD_IN = 12;
3783 const uint64_t base = static_cast<uint64_t>( section->physicalOffset ) + CONTROLLER_LEAD_IN;
3784 const uint64_t bytes = static_cast<uint64_t>( section->physicalCount ) * section->stride;
3785
3786 return base + bytes <= m_data.size() ? static_cast<size_t>( base ) : 0;
3787}
3788
3790{
3791 m_layerInfos.clear();
3792
3793 const SDB_SECTION* section = getSection( SECTION::LayerTable );
3794
3795 if( !section )
3796 THROW_IO_ERROR( "Missing PADS layer-stackup controller" );
3797
3798 if( section->stride != 128 && section->stride != 136 && section->stride != 152 )
3799 THROW_IO_ERROR( "Invalid PADS layer-stackup stride" );
3800
3801 static constexpr size_t NAME_LEN = 24;
3802 static constexpr size_t OFF_ROUT = 32;
3803 static constexpr size_t OFF_LAYTH = 52;
3804 static constexpr size_t OFF_COPTH = 56;
3805 static constexpr size_t OFF_DIEL = 60;
3806
3807 auto layerFunction = []( int32_t aSerializedType )
3808 {
3809 switch( aSerializedType )
3810 {
3811 case 0: return PADS_LAYER_FUNCTION::UNASSIGNED;
3812 case 1: return PADS_LAYER_FUNCTION::ROUTING;
3813 case 2: return PADS_LAYER_FUNCTION::DRILL;
3814 case 3: return PADS_LAYER_FUNCTION::SILK_SCREEN;
3815 case 4: return PADS_LAYER_FUNCTION::PASTE_MASK;
3816 case 5: return PADS_LAYER_FUNCTION::SOLDER_MASK;
3817 case 6: return PADS_LAYER_FUNCTION::ASSEMBLY;
3818 default: return PADS_LAYER_FUNCTION::UNKNOWN;
3819 }
3820 };
3821
3822 size_t recordBase = layerStackupBase();
3823
3824 if( recordBase == 0 )
3825 THROW_IO_ERROR( "Missing PADS layer-stackup framing" );
3826
3827 if( !m_cursor.InBounds( recordBase, static_cast<size_t>( section->physicalCount ) * section->stride ) )
3828 THROW_IO_ERROR( "Invalid PADS layer-stackup extent" );
3829
3830 for( size_t k = 0; k < section->physicalCount; ++k )
3831 {
3832 size_t rec = recordBase + k * section->stride;
3833
3834 SDB_RECORD layerRec = m_sdb.RecordAt( rec );
3836 info.number = static_cast<int>( k );
3837 info.name = layerRec.Str( 0, NAME_LEN );
3838
3839 int32_t routingDir = layerRec.I32( OFF_ROUT );
3840 info.routing_direction = routingDir;
3841
3842 info.layer_thickness = static_cast<double>( layerRec.I32( OFF_LAYTH ) );
3843 info.copper_thickness = static_cast<double>( layerRec.I32( OFF_COPTH ) );
3844
3845 float dielectric = 0.0f;
3846 std::memcpy( &dielectric, &m_data[rec + OFF_DIEL], sizeof( float ) );
3847 info.dielectric_constant = static_cast<double>( dielectric );
3848
3849 // The final word of record K-1 owns record K's LAYER_TYPE. The lag leaves the final
3850 // record's word as retained carrier state, like the other rotated flat controllers.
3851 const int32_t serializedType = k > 0 ? m_cursor.I32At( rec - 4 ) : 0;
3852 info.layer_type = k > 0 ? layerFunction( serializedType ) : PADS_LAYER_FUNCTION::UNASSIGNED;
3853
3854 if( info.layer_type == PADS_LAYER_FUNCTION::UNKNOWN )
3855 THROW_IO_ERROR( "Invalid PADS serialized layer type" );
3856
3857 info.is_copper = info.layer_type == PADS_LAYER_FUNCTION::ROUTING;
3858 info.required = info.is_copper;
3859
3860 m_layerInfos.push_back( std::move( info ) );
3861 }
3862}
3863
3864
3865std::vector<LAYER_INFO> BINARY_PARSER::GetLayerInfos() const
3866{
3867 return m_layerInfos;
3868}
3869
3870
3872{
3873 if( m_parts.empty() || m_decals.empty() )
3874 return;
3875
3876 if( usesDirectDecalChain() )
3877 {
3878 // Both old dialects resolve a placement's decal via the direct index in
3879 // m_partDecalIndex, against the decal-name table -- not through the parttype-index chain
3880 // below (v0x2022 does have a parttype-definition table, see parsePartTypeTable, but
3881 // placements don't reference it for their decal).
3882 if( m_partDecalIndex.empty() || m_decalNameTable.empty() )
3883 return;
3884
3885 for( size_t partIdx = 0; partIdx < m_parts.size(); ++partIdx )
3886 {
3887 PART& part = m_parts[partIdx];
3888
3889 if( !part.decal.empty() )
3890 continue;
3891
3892 auto hintIt = m_partDecalIndex.find( partIdx );
3893
3894 if( hintIt == m_partDecalIndex.end() )
3895 continue;
3896
3897 uint32_t decalIndex = hintIt->second;
3898
3899 if( decalIndex >= m_decalNameTable.size() )
3900 continue;
3901
3902 const std::string& decalName = m_decalNameTable[decalIndex];
3903
3904 if( !decalName.empty() && m_decals.count( decalName ) )
3905 part.decal = decalName;
3906 }
3907
3908 return;
3909 }
3910
3911 // Placement -> decal chain: parttype index I from m_partTypeIndex, then
3912 // m_partTypeDecalIndices[I] for the decal_index, then m_decalNameTable[decal_index] for the
3913 // name. The decal-name table covers connectors and mounting holes section 10 lacks, so this
3914 // resolves the full placed set.
3915 if( m_partTypeDecalIndices.empty() || m_decalNameTable.empty() )
3916 return;
3917
3918 for( size_t partIdx = 0; partIdx < m_parts.size(); ++partIdx )
3919 {
3920 PART& part = m_parts[partIdx];
3921
3922 if( !part.decal.empty() )
3923 continue;
3924
3925 auto hintIt = m_partTypeIndex.find( partIdx );
3926
3927 if( hintIt == m_partTypeIndex.end() )
3928 continue;
3929
3930 uint32_t partTypeIdx = hintIt->second;
3931
3932 if( partTypeIdx >= m_partTypeDecalIndices.size() )
3933 continue;
3934
3935 uint8_t alternate = 0;
3936 auto alternateIt = m_partDecalAlternate.find( partIdx );
3937
3938 if( alternateIt != m_partDecalAlternate.end() )
3939 alternate = alternateIt->second;
3940
3941 const std::vector<int32_t>& decalIndices = m_partTypeDecalIndices[partTypeIdx];
3942 int32_t decalIndex = decalIndices.empty() ? -1 : decalIndices.front();
3943
3944 if( alternate < decalIndices.size() )
3945 decalIndex = decalIndices[alternate];
3946
3947 // An explicit placement overrides the parttype alternates
3948 auto placedIt = m_partDecalIndex.find( partIdx );
3949
3950 if( placedIt != m_partDecalIndex.end() && placedIt->second < m_decalNameTable.size()
3951 && m_decals.count( m_decalNameTable[placedIt->second] ) )
3952 {
3953 decalIndex = static_cast<int32_t>( placedIt->second );
3954 }
3955
3956 if( decalIndex < 0 || static_cast<size_t>( decalIndex ) >= m_decalNameTable.size() )
3957 continue;
3958
3959 const std::string& decalName = m_decalNameTable[decalIndex];
3960
3961 if( !decalName.empty() && m_decals.count( decalName ) )
3962 part.decal = decalName;
3963
3964 // The *PARTTYPE alias (often a manufacturer part number) is more useful as the
3965 // footprint's BOM value than the physical decal name it resolves to -- e.g. a part
3966 // referencing PARTTYPE GRM15XR71C103KA86D that resolves to decal C-0402 should show
3967 // the part number, not "C-0402", as its value.
3968 if( part.value.empty() && partTypeIdx < m_partTypeNames.size() )
3969 {
3970 const std::string& typeName = m_partTypeNames[partTypeIdx];
3971
3972 if( !typeName.empty() && typeName != part.decal )
3973 part.value = typeName;
3974 }
3975 }
3976}
3977
3978
3979} // namespace PADS_IO
int index
const char * name
double AsDegrees() const
Definition eda_angle.h:115
EDA_ANGLE Normalize180()
Definition eda_angle.h:273
Bounds-checked little-endian read cursor over a PADS binary buffer.
uint8_t U8At(size_t aOffset) const
void decodeRoutedCopper(std::map< std::string, ROUTE > &aRoutes)
std::map< uint32_t, std::string > m_netSelfPtrToName
uint8_t ringU8(const SDB_SECTION &aSection, size_t aRotation, size_t aStride, uint32_t aIndex, size_t aField) const
double toBasicCoordY(int32_t aRawValue) const
ROUTE_OBJECT_NODES resolveRouteObjectNodes(const SDB_SECTION &aRouteLayers, size_t aObjectCount, const std::vector< int > &aSerializedLayerOrder)
std::vector< NET > m_nets
std::string ringStr(const SDB_SECTION &aSection, size_t aRotation, size_t aStride, uint32_t aIndex, size_t aField, size_t aLength) const
bool isValidNetName(const std::string &aName) const
std::map< std::string, uint32_t > m_decalTerminalCount
std::map< size_t, int > m_partClusterId
std::map< size_t, uint32_t > m_partDecalIndex
std::vector< NET_CLASS_RULE_EDGE > collectNetClassRuleEdges(const std::set< uint32_t > &aOwnerSet)
std::map< std::string, ROUTE > seedRoutesFromVias(const std::vector< VIA_LOCATION > &aVias) const
size_t layerStackupBase() const
Base of section 69's layer records after its fixed controller lead-in.
void parsePlacementFields(const SDB_SECTION &aText, size_t aRecordBase, size_t aRecordSize, size_t aRingRotation)
std::vector< VIA_LOCATION > decodeViaLocations()
std::map< uint32_t, size_t > parseRouteJunctionNets() const
std::vector< PART > m_parts
std::map< uint32_t, size_t > m_sec23RecordToNet
std::vector< NET_ANCHOR > m_netAnchors
std::map< size_t, uint8_t > m_partDecalAlternate
std::map< std::string, uint32_t > m_netClassOwner
std::vector< COPPER_SHAPE > m_copper_shapes
void applyPadstackPairs(PART_DECAL &aDecal, const std::vector< std::pair< int32_t, int32_t > > &aPairs, int32_t aStart, int32_t aCount)
static constexpr int32_t ANGLE_SCALE
std::vector< POUR > m_pours
static bool IsBinaryPadsFile(const wxString &aFileName)
Check if a file appears to be a PADS binary PCB file.
std::map< std::string, PART_DECAL > m_decals
std::vector< DIFF_PAIR_DEF > m_diffPairs
std::map< std::string, int32_t > m_decalTerminalStart
std::vector< POLYLINE > m_boardOutlines
void parseFreeText(const SDB_SECTION &aText, size_t aRecordBase, size_t aRecordSize, size_t aRingRotation, size_t aPoolBase, size_t aPoolHi)
bool fetchOwnerCirclePoints(const std::string &aName, VECTOR2I &aP0, VECTOR2I &aP1) const
std::vector< size_t > oldNetRecordOffsets() const
std::map< std::string, int32_t > m_decalStackStart
std::vector< KEEPOUT > m_keepouts
std::map< std::string, int32_t > m_decalStackCount
uint32_t ringU32(const SDB_SECTION &aSection, size_t aRotation, size_t aStride, uint32_t aIndex, size_t aField) const
std::map< size_t, uint32_t > m_partTypeIndex
std::map< uint32_t, size_t > m_placementObjectToPart
std::vector< std::pair< int, int > > m_padStackDrillSpans
const SDB_SECTION * getSection(int aIndex) const
std::vector< DIMENSION > m_dimensions
std::vector< LAYER_INFO > m_layerInfos
void Parse(const wxString &aFileName)
int32_t ringI32(const SDB_SECTION &aSection, size_t aRotation, size_t aStride, uint32_t aIndex, size_t aField) const
double toBasicCoordX(int32_t aRawValue) const
std::vector< std::vector< int32_t > > m_partTypeDecalIndices
void applyNetClassClearances(const std::vector< NET_CLASS_RULE_EDGE > &aEdges, const std::map< uint32_t, size_t > &aOwnerOrdinal)
bool fetchOwnerLoop(const std::string &aName, size_t aMaxVerts, std::vector< VECTOR2I > &aOut) const
PART makePlacementPart(const SDB_RECORD &aRec, int aXOff, std::optional< int > aYOff, int aAngleOff, int aNameOff, const std::string &aRefDes) const
bool sec12Vertex(int32_t aRow, int32_t &aX, int32_t &aY, int32_t &aAttr) const
const std::vector< uint8_t > & m_data
std::vector< std::string > m_partTypeNames
std::map< uint32_t, std::string > m_sec23IndexToNet
std::vector< NET_ANCHOR > m_netConnectionEndpoints
std::vector< std::vector< PAD_STACK_LAYER > > m_padStackPool
std::map< uint32_t, std::set< size_t > > m_junctionHandleNets
std::map< size_t, int32_t > m_partFieldStart
std::vector< ROUTE > m_routes
std::vector< TEXT > m_texts
std::vector< GRAPHIC_LINE > m_graphicLines
std::vector< PART_CLUSTER > m_clusters
std::vector< BIN_NET_CLASS_DEF > m_netClasses
std::vector< std::string > m_decalNameTable
double toBasicAngle(int32_t aRawAngle) const
std::vector< LAYER_INFO > GetLayerInfos() const
std::map< std::string, OWNER_RUN > m_ownerRuns
SDB_RECORD arcRecordFor(const SDB_SECTION &aArcParameters, int32_t aArcStart, int32_t aAttr, const char *aWhat) const
static bool IsSupportedVersion(uint16_t aVersion)
Definition pads_sdb.cpp:43
A bounds-checked reader positioned at one record inside a buffer.
uint32_t U32(size_t aOffset) const
uint8_t U8(size_t aOffset) const
uint16_t U16(size_t aOffset) const
int32_t I32(size_t aOffset) const
std::string Str(size_t aOffset, size_t aMaxLen) const
#define LAYER(n, l)
@ DEGREES_T
Definition eda_angle.h:30
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
constexpr size_t ROTATION
bool ReadFileHeader(const wxString &aFileName, std::vector< uint8_t > &aOut, size_t aCount)
Read at most aCount leading bytes of aFileName into aOut, which is sized to what was actually read.
static bool viaRecordValid(const BINARY_CURSOR &aCur, size_t aTypeByte)
bool HasSdbMagic(const std::vector< uint8_t > &aData, uint8_t aMagic1)
Check the PADS SDB container magic, a leading 0x00 followed by a format-specific second byte.
constexpr uint16_t SDB_RECORD_SENTINEL
constexpr double SDB_BASIC_PER_MIL
static constexpr int DECAL_NAME_OFFSET
Rotation between the physical section cursor and the logical record base.
static void logParsePhase(const char *aWhat, std::chrono::steady_clock::time_point aStart)
Enabled by setting KICAD_PADS_PROFILE.
static ARC deriveArc(const SDB_RECORD &aArcRecord, const ARC_VERTEX &aStart, const ARC_VERTEX &aEnd, double aOriginX, double aOriginY)
static void logResolvedBase(int aSection, const char *aWhat, size_t aResolved, uint32_t aPhysical)
Report a structurally derived physical section base for cross-checking the Kaitai grammar.
bool ReadFileToBuffer(const wxString &aFileName, std::vector< uint8_t > &aOut)
Read an entire file into aOut.
static const std::map< uint8_t, std::string > PAD_SHAPE_NAMES
uint16_t getU16LE(const std::vector< uint8_t > &aData, size_t aOffset)
static const PADSTACK_LAYOUT & padstackLayout(uint16_t aVersion)
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
#define KITIME(call)
CITER next(CITER it)
Definition ptree.cpp:120
A polyline point that may instead be an arc segment.
Definition pads_parser.h:64
One board-outline vertex triplet: [i32 X, i32 Y, i32 attr] where attr -1 is a plain corner and attr >...
Arc as center, radius and angles.
Definition pads_parser.h:50
std::string hjust
std::string vjust
Every routed-copper object's PADS layer and route-node handle, indexed by object ordinal,...
std::map< uint32_t, std::set< size_t > > handleNets
One placed via recovered from the section-60 junction ring.
A PADS net class recovered from the binary design-rule graph.
Standalone copper area from the LINES section (type=COPPER), not part of a pour.
std::vector< ARC_POINT > outline
bool filled
COPCLS, COPCIR.
double width
For open polylines.
double x
Origin.
double crossbar_pos
Y for horizontal, X for vertical.
std::vector< POINT > points
Measurement endpoints.
Non-electrical drawing item from the LINES section (type=LINES).
std::vector< ARC_POINT > points
std::vector< ARC_POINT > outline
KEEPOUT_TYPE type
One type-66 net-class rule edge: its owner pointer, rule-detail page, full rule pointer (declaration ...
std::string name
double drill
0 for SMD
std::string shape
R, S, A, O, OF, RF, RT, ST, RA, SA, RC, OC.
bool plated
PTH vs NPTH.
double thermal_outer_diameter
Thermal or void in plane.
double slot_orientation
0-179.999 degrees
double sizeB
Height for rectangles/ovals.
double corner_radius
Always positive.
double sizeA
Diameter or width.
A PADS part cluster (named group of parts).
std::map< int, std::pair< int, int > > drill_spans
std::vector< TERMINAL > terminals
std::map< int, std::vector< PAD_STACK_LAYER > > pad_stacks
std::string value
std::string decal
Primary decal (first in colon-separated list)
std::string name
std::string units
A polyline that may contain arc segments, used for board outlines and graphics.
std::vector< ARC_POINT > points
std::string net_name
std::string owner_pour
Parent pour, 7th header field.
std::vector< ARC_POINT > points
std::vector< VIA > vias
std::vector< TRACK > tracks
std::string net_name
The PADS PowerPCB .pcb file is a serialized snapshot of PADS' in-memory SDB (System DataBase) object ...
Definition pads_sdb.h:58
uint32_t physicalCount
Definition pads_sdb.h:66
uint32_t physicalOffset
Definition pads_sdb.h:64
uint32_t physicalBytes
Definition pads_sdb.h:65
uint32_t totalBytes
Definition pads_sdb.h:61
std::string name
std::vector< ARC_POINT > points
std::vector< PAD_STACK_LAYER > stack
static std::vector< uint8_t > bytes(const std::string &aText)
static std::string decoded(const std::string &aBase64)
const std::string table
KIBIS_PIN * pin
KIBIS_PIN * pinA
int radius
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.
int delta
#define M_PI
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708