KiCad PCB EDA Suite
Loading...
Searching...
No Matches
allegro_builder.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 Quilter
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 3
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include "allegro_builder.h"
22#include "allegro_db_utils.h"
23
24#include <algorithm>
25#include <array>
26#include <cmath>
27#include <limits>
28#include <regex>
29#include <set>
30#include <string>
31#include <tuple>
32#include <unordered_set>
33
35
36#include <wx/arrstr.h>
37#include <wx/log.h>
38
39#include <core/profile.h>
40#include <core/throttle.h>
41
42#include <base_units.h>
46#include <trigo.h>
47#include <hash.h>
49#include <footprint.h>
50#include <lib_id.h>
51#include <netclass.h>
52#include <pad.h>
53#include <pcb_group.h>
54#include <pcb_text.h>
55#include <pcb_shape.h>
56#include <pcb_track.h>
58#include <zone.h>
59#include <zone_utils.h>
60
61
62using namespace ALLEGRO;
63
64
72static const wxChar* const traceAllegroBuilder = wxT( "KICAD_ALLEGRO_BUILDER" );
73static const wxChar* const traceAllegroPerf = wxT( "KICAD_ALLEGRO_PERF" );
74
75
76#define BLK_FIELD( BLK_T, FIELD ) BlockDataAs<BLK_T>( aBlock ).FIELD
77
78
82static uint32_t PadGetNextInFootprint( const BLOCK_BASE& aBlock )
83{
84 const uint8_t type = aBlock.GetBlockType();
85
86 if( type != 0x32 )
87 {
88 THROW_IO_ERRORF( wxT( "Unexpected next item in 0x32 pad list: block type %#04x, offset %#lx, key %#010x" ),
89 type,
90 aBlock.GetOffset(),
91 aBlock.GetKey() );
92 }
93
94 // When iterating in a footprint use this field, not m_Next.
95 return BLK_FIELD( BLK_0x32_PLACED_PAD, m_NextInFp );
96}
97
98
99template <>
100struct std::hash<LAYER_INFO>
101{
102 size_t operator()( const LAYER_INFO& aLayerInfo ) const noexcept
103 {
104 return ( aLayerInfo.m_Class << 8 ) + aLayerInfo.m_Subclass;
105 }
106};
107
108
116// clang-format off
117static const std::unordered_map<LAYER_INFO, PCB_LAYER_ID> s_LayerKiMap = {
118
125
128
131
140
145
148};
149
157static const std::unordered_map<LAYER_INFO, wxString> s_OptionalFixedMappings = {
161
163
165
170
175
180
185
187};
188
189// clang-format on
190
191
198static wxString layerInfoDisplayName( const LAYER_INFO& aLayerInfo )
199{
200 // clang-format off
201 static const std::unordered_map<uint8_t, wxString> s_ClassNames = {
202 { LAYER_INFO::CLASS::BOARD_GEOMETRY, wxS( "Board Geometry" ) },
203 { LAYER_INFO::CLASS::COMPONENT_VALUE, wxS( "Component Value" ) },
204 { LAYER_INFO::CLASS::DEVICE_TYPE, wxS( "Device Type" ) },
205 { LAYER_INFO::CLASS::DRAWING_FORMAT, wxS( "Drawing Format" ) },
206 { LAYER_INFO::CLASS::ETCH, wxS( "Etch" ) },
207 { LAYER_INFO::CLASS::MANUFACTURING, wxS( "Manufacturing" ) },
208 { LAYER_INFO::CLASS::PACKAGE_GEOMETRY, wxS( "Package Geometry" ) },
209 { LAYER_INFO::CLASS::PACKAGE_KEEPIN, wxS( "Package Keepin" ) },
210 { LAYER_INFO::CLASS::PACKAGE_KEEPOUT, wxS( "Package Keepout" ) },
211 { LAYER_INFO::CLASS::PIN, wxS( "Pin" ) },
212 { LAYER_INFO::CLASS::REF_DES, wxS( "Ref Des" ) },
213 { LAYER_INFO::CLASS::ROUTE_KEEPIN, wxS( "Route Keepin" ) },
214 { LAYER_INFO::CLASS::ROUTE_KEEPOUT, wxS( "Route Keepout" ) },
215 { LAYER_INFO::CLASS::TOLERANCE, wxS( "Tolerance" ) },
216 { LAYER_INFO::CLASS::USER_PART_NUMBER, wxS( "User Part Number" ) },
217 { LAYER_INFO::CLASS::VIA_CLASS, wxS( "Via Class" ) },
218 { LAYER_INFO::CLASS::VIA_KEEPOUT, wxS( "Via Keepout" ) },
219 { LAYER_INFO::CLASS::ANTI_ETCH, wxS( "Anti Etch" ) },
220 { LAYER_INFO::CLASS::BOUNDARY, wxS( "Boundary" ) },
221 { LAYER_INFO::CLASS::CONSTRAINTS_REGION, wxS( "Constraints Region" ) },
222 };
223
224 static const std::unordered_map<uint8_t, wxString> s_BoardGeomSubclassNames = {
225 { LAYER_INFO::SUBCLASS::BGEOM_OUTLINE, wxS( "Outline" ) },
226 { LAYER_INFO::SUBCLASS::BGEOM_CONSTRAINT_AREA, wxS( "Constraint Area" ) },
227 { LAYER_INFO::SUBCLASS::BGEOM_OFF_GRID_AREA, wxS( "Off Grid Area" ) },
228 { LAYER_INFO::SUBCLASS::BGEOM_SOLDERMASK_BOTTOM, wxS( "Soldermask Bottom" ) },
229 { LAYER_INFO::SUBCLASS::BGEOM_SOLDERMASK_TOP, wxS( "Soldermask Top" ) },
230 { LAYER_INFO::SUBCLASS::BGEOM_ASSEMBLY_DETAIL, wxS( "Assembly Detail" ) },
231 { LAYER_INFO::SUBCLASS::BGEOM_SILKSCREEN_BOTTOM, wxS( "Silkscreen Bottom" ) },
232 { LAYER_INFO::SUBCLASS::BGEOM_SILKSCREEN_TOP, wxS( "Silkscreen Top" ) },
233 { LAYER_INFO::SUBCLASS::BGEOM_SWITCH_AREA_BOTTOM, wxS( "Switch Area Bottom" ) },
234 { LAYER_INFO::SUBCLASS::BGEOM_SWITCH_AREA_TOP, wxS( "Switch Area Top" ) },
235 { LAYER_INFO::SUBCLASS::BGEOM_BOTH_ROOMS, wxS( "Both Rooms" ) },
236 { LAYER_INFO::SUBCLASS::BGEOM_BOTTOM_ROOM, wxS( "Bottom Room" ) },
237 { LAYER_INFO::SUBCLASS::BGEOM_TOP_ROOM, wxS( "Top Room" ) },
238 { LAYER_INFO::SUBCLASS::BGEOM_PLACE_GRID_BOTTOM, wxS( "Place Grid Bottom" ) },
239 { LAYER_INFO::SUBCLASS::BGEOM_PLACE_GRID_TOP, wxS( "Place Grid Top" ) },
240 { LAYER_INFO::SUBCLASS::BGEOM_DIMENSION, wxS( "Dimension" ) },
241 { LAYER_INFO::SUBCLASS::BGEOM_TOOLING_CORNERS, wxS( "Tooling Corners" ) },
242 { LAYER_INFO::SUBCLASS::BGEOM_ASSEMBLY_NOTES, wxS( "Assembly Notes" ) },
243 { LAYER_INFO::SUBCLASS::BGEOM_PLATING_BAR, wxS( "Plating Bar" ) },
244 { LAYER_INFO::SUBCLASS::BGEOM_DESIGN_OUTLINE, wxS( "Design Outline" ) },
245
246 };
247
248 static const std::unordered_map<uint8_t, wxString> s_ComponentValueSubclassNames = {
249 { LAYER_INFO::SUBCLASS::DISPLAY_BOTTOM, wxS( "Display Bottom" ) },
250 { LAYER_INFO::SUBCLASS::DISPLAY_TOP, wxS( "Display Top" ) },
251 { LAYER_INFO::SUBCLASS::SILKSCREEN_BOTTOM, wxS( "Silkscreen Bottom" ) },
252 { LAYER_INFO::SUBCLASS::SILKSCREEN_TOP, wxS( "Silkscreen Top" ) },
253 { LAYER_INFO::SUBCLASS::ASSEMBLY_BOTTOM, wxS( "Assembly Bottom" ) },
254 { LAYER_INFO::SUBCLASS::ASSEMBLY_TOP, wxS( "Assembly Top" ) },
255 };
256
257 static const std::unordered_map<uint8_t, wxString> s_DrawingFormatSubclassNames = {
258 { LAYER_INFO::SUBCLASS::DFMT_REVISION_DATA, wxS( "Revision Data" ) },
259 { LAYER_INFO::SUBCLASS::DFMT_REVISION_BLOCK, wxS( "Revision Block" ) },
260 { LAYER_INFO::SUBCLASS::DFMT_TITLE_DATA, wxS( "Title Data" ) },
261 { LAYER_INFO::SUBCLASS::DFMT_TITLE_BLOCK, wxS( "Title Block" ) },
262 { LAYER_INFO::SUBCLASS::DFMT_OUTLINE, wxS( "Outline" ) },
263 };
264
265 static const std::unordered_map<uint8_t, wxString> s_PackageGeometrySubclassNames = {
266 { LAYER_INFO::SUBCLASS::PGEOM_PASTEMASK_BOTTOM, wxS( "Pastemask Bottom" ) },
267 { LAYER_INFO::SUBCLASS::PGEOM_PASTEMASK_TOP, wxS( "Pastemask Top" ) },
268 { LAYER_INFO::SUBCLASS::PGEOM_DFA_BOUND_BOTTOM, wxS( "DFA Bound Bottom" ) },
269 { LAYER_INFO::SUBCLASS::PGEOM_DFA_BOUND_TOP, wxS( "DFA Bound Top" ) },
270 { LAYER_INFO::SUBCLASS::PGEOM_DISPLAY_BOTTOM, wxS( "Display Bottom" ) },
271 { LAYER_INFO::SUBCLASS::PGEOM_DISPLAY_TOP, wxS( "Display Top" ) },
272 { LAYER_INFO::SUBCLASS::PGEOM_SOLDERMASK_BOTTOM, wxS( "Soldermask Bottom" ) },
273 { LAYER_INFO::SUBCLASS::PGEOM_SOLDERMASK_TOP, wxS( "Soldermask Top" ) },
274 { LAYER_INFO::SUBCLASS::PGEOM_BODY_CENTER, wxS( "Body Center" ) },
275 { LAYER_INFO::SUBCLASS::PGEOM_SILKSCREEN_BOTTOM, wxS( "Silkscreen Bottom" ) },
276 { LAYER_INFO::SUBCLASS::PGEOM_SILKSCREEN_TOP, wxS( "Silkscreen Top" ) },
277 { LAYER_INFO::SUBCLASS::PGEOM_PAD_STACK_NAME, wxS( "Pad Stack Name" ) },
278 { LAYER_INFO::SUBCLASS::PGEOM_PIN_NUMBER, wxS( "Pin Number" ) },
279 { LAYER_INFO::SUBCLASS::PGEOM_PLACE_BOUND_BOTTOM, wxS( "Place Bound Bottom" ) },
280 { LAYER_INFO::SUBCLASS::PGEOM_PLACE_BOUND_TOP, wxS( "Place Bound Top" ) },
281 { LAYER_INFO::SUBCLASS::PGEOM_ASSEMBLY_BOTTOM, wxS( "Assembly Bottom" ) },
282 { LAYER_INFO::SUBCLASS::PGEOM_ASSEMBLY_TOP, wxS( "Assembly Top" ) },
283 };
284
285 static const std::unordered_map<uint8_t, wxString> s_ManufacturingSubclassNames = {
286 { LAYER_INFO::SUBCLASS::MFR_XSECTION_CHART, wxS( "X-Section Chart" ) },
287 { LAYER_INFO::SUBCLASS::MFR_NO_PROBE_BOTTOM, wxS( "No Probe Bottom" ) },
288 { LAYER_INFO::SUBCLASS::MFR_NO_PROBE_TOP, wxS( "No Probe Top" ) },
289 { LAYER_INFO::SUBCLASS::MFR_AUTOSILK_BOTTOM, wxS( "AutoSilk Bottom" ) },
290 { LAYER_INFO::SUBCLASS::MFR_AUTOSILK_TOP, wxS( "AutoSilk Top" ) },
291 { LAYER_INFO::SUBCLASS::MFR_PROBE_BOTTOM, wxS( "Probe Bottom" ) },
292 { LAYER_INFO::SUBCLASS::MFR_PROBE_TOP, wxS( "Probe Top" ) },
293 { LAYER_INFO::SUBCLASS::MFR_NCDRILL_FIGURE, wxS( "NC Drill Figure" ) },
294 { LAYER_INFO::SUBCLASS::MFR_NCDRILL_LEGEND, wxS( "NC Drill Legend" ) },
295 { LAYER_INFO::SUBCLASS::MFR_NO_GLOSS_INTERNAL, wxS( "No Gloss Internal" ) },
296 { LAYER_INFO::SUBCLASS::MFR_NO_GLOSS_BOTTOM, wxS( "No Gloss Bottom" ) },
297 { LAYER_INFO::SUBCLASS::MFR_NO_GLOSS_TOP, wxS( "No Gloss Top" ) },
298 { LAYER_INFO::SUBCLASS::MFR_NO_GLOSS_ALL, wxS( "No Gloss All" ) },
299 { LAYER_INFO::SUBCLASS::MFR_PHOTOPLOT_OUTLINE, wxS( "Photoplot Outline" ) },
300 };
301
302 static const std::unordered_map<uint8_t, wxString> s_AnalysisSubclassNames = {
303 { LAYER_INFO::SUBCLASS::ANALYSIS_PCB_TEMPERATURE, wxS( "PCB Temperature" ) },
304 { LAYER_INFO::SUBCLASS::ANALYSIS_HIGH_ISOCONTOUR, wxS( "High IsoContour" ) },
305 { LAYER_INFO::SUBCLASS::ANALYSIS_MEDIUM3_ISOCONTOUR, wxS( "Medium3 IsoContour" ) },
306 { LAYER_INFO::SUBCLASS::ANALYSIS_MEDIUM2_ISOCONTOUR, wxS( "Medium2 IsoContour" ) },
307 { LAYER_INFO::SUBCLASS::ANALYSIS_MEDIUM1_ISOCONTOUR, wxS( "Medium1 IsoContour" ) },
308 { LAYER_INFO::SUBCLASS::ANALYSIS_LOW_ISOCONTOUR, wxS( "Low IsoContour" ) },
309 };
310
311 static const std::unordered_map<uint8_t, wxString> s_ConstraintSubclassNames = {
312 { LAYER_INFO::SUBCLASS::CREG_ALL, wxS( "All" ) },
313 };
314
315 static const std::unordered_map<uint8_t, wxString> s_KeepinSubclassNames = {
316 { LAYER_INFO::SUBCLASS::KEEPIN_ALL, wxS( "All" ) },
317 };
318
319 static const std::unordered_map<uint8_t, wxString> s_KeepoutSubclassNames = {
320 { LAYER_INFO::SUBCLASS::KEEPOUT_ALL, wxS( "All" ) },
321 { LAYER_INFO::SUBCLASS::KEEPOUT_TOP, wxS( "Top" ) },
322 { LAYER_INFO::SUBCLASS::KEEPOUT_BOTTOM, wxS( "Bottom" ) },
323 };
324
325 static const std::unordered_map<uint8_t, const std::unordered_map<uint8_t, wxString>&> s_SubclassNameMaps = {
326 { LAYER_INFO::CLASS::BOARD_GEOMETRY, s_BoardGeomSubclassNames },
327
328 // These classes all share the same subclass names
329 { LAYER_INFO::CLASS::COMPONENT_VALUE, s_ComponentValueSubclassNames },
330 { LAYER_INFO::CLASS::DEVICE_TYPE, s_ComponentValueSubclassNames },
331 { LAYER_INFO::CLASS::REF_DES, s_ComponentValueSubclassNames },
332 { LAYER_INFO::CLASS::TOLERANCE, s_ComponentValueSubclassNames },
333 { LAYER_INFO::CLASS::USER_PART_NUMBER, s_ComponentValueSubclassNames },
334
335 { LAYER_INFO::CLASS::DRAWING_FORMAT, s_DrawingFormatSubclassNames },
336 { LAYER_INFO::CLASS::PACKAGE_GEOMETRY, s_PackageGeometrySubclassNames },
337 { LAYER_INFO::CLASS::MANUFACTURING, s_ManufacturingSubclassNames },
338 { LAYER_INFO::CLASS::ANALYSIS, s_AnalysisSubclassNames },
339 { LAYER_INFO::CLASS::CONSTRAINTS_REGION, s_ConstraintSubclassNames },
340 { LAYER_INFO::CLASS::PACKAGE_KEEPIN, s_KeepinSubclassNames },
341 { LAYER_INFO::CLASS::PACKAGE_KEEPOUT, s_KeepoutSubclassNames },
342 { LAYER_INFO::CLASS::ROUTE_KEEPIN, s_KeepinSubclassNames },
343 { LAYER_INFO::CLASS::ROUTE_KEEPOUT, s_KeepoutSubclassNames },
344 { LAYER_INFO::CLASS::VIA_KEEPOUT, s_KeepoutSubclassNames },
345 };
346 // clang-format on
347
348 wxString className;
349 const auto classIt = s_ClassNames.find( aLayerInfo.m_Class );
350
351 if( classIt != s_ClassNames.end() )
352 className = classIt->second;
353 else
354 className = wxString::Format( wxS( "Class_%02X" ), aLayerInfo.m_Class );
355
356 wxString subclassName;
357
358 // Find the right subclass name map for this class
359 auto classMapIt = s_SubclassNameMaps.find( aLayerInfo.m_Class );
360
361 if( classMapIt != s_SubclassNameMaps.end() )
362 {
363 const std::unordered_map<uint8_t, wxString>& subclassMap = classMapIt->second;
364
365 const auto subIt = subclassMap.find( aLayerInfo.m_Subclass );
366
367 if( subIt != subclassMap.end() )
368 subclassName = subIt->second;
369 else
370 {
371 // This subclass seems not to have a known name
372 subclassName = wxString::Format( wxS( "Subclass_%02X" ), aLayerInfo.m_Subclass );
373 }
374 }
375 else
376 {
377 // Don't have a specific map for this class, just do a generic one.
378 subclassName = wxString::Format( wxS( "Subclass_%02X" ), aLayerInfo.m_Subclass );
379 }
380
381 return className + wxS( "/" ) + subclassName;
382}
383
384
394static bool layerIsZone( const LAYER_INFO& aLayerInfo )
395{
397 aLayerInfo.m_Class == LAYER_INFO::CLASS::BOUNDARY ||
403 return true;
404
405 return false;
406}
407
408
412static std::optional<LAYER_INFO> tryLayerFromBlock( const BLOCK_BASE& aBlock )
413{
414 switch( aBlock.GetBlockType() )
415 {
416 case 0x0e:
417 {
418 const auto& net = BlockDataAs<BLK_0x0E_RECT>( aBlock );
419 return net.m_Layer;
420 }
421 case 0x14:
422 {
423 const auto& trace = BlockDataAs<BLK_0x14_GRAPHIC>( aBlock );
424 return trace.m_Layer;
425 }
426 case 0x24:
427 {
428 const auto& rect = BlockDataAs<BLK_0x24_RECT>( aBlock );
429 return rect.m_Layer;
430 }
431 case 0x28:
432 {
433 const auto& shape = BlockDataAs<BLK_0x28_SHAPE>( aBlock );
434 return shape.m_Layer;
435 }
436 }
437
438 return std::nullopt;
439}
440
441
448{
449 std::optional<LAYER_INFO> layerInfo = tryLayerFromBlock( aBlock );
450
451 // Programming error - should only call this function if we're sure the block has layer info
452 wxCHECK( layerInfo.has_value(), LAYER_INFO() );
453
454 return layerInfo.value();
455}
456
457
459static PCB_LAYER_ID nthCopperLayerId( int aIndex, int aTotal )
460{
461 if( aIndex <= 0 )
462 return F_Cu;
463
464 if( aIndex >= aTotal - 1 )
465 return B_Cu;
466
467 return ToLAYER_ID( In1_Cu + ( aIndex - 1 ) * 2 );
468}
469
470
472static constexpr uint32_t LAYER_PROP_PLANE = 0x100;
473
478{
485 {
486 wxString m_Name;
487 uint32_t m_Properties = 0;
488 // LAYER_ARTWORK: POSITIVE/NEGATIVE
489 // LAYER_USE: empty, EMBEDDED_PLANE, ...?
490 // bool m_IsConductor;
491 };
492
493public:
494 LAYER_MAPPER( const BRD_DB& aRawBoard, BOARD& aBoard, const LAYER_MAPPING_HANDLER& aLayerMappingHandler ) :
495 m_layerMappingHandler( aLayerMappingHandler ),
496 m_brdDb( aRawBoard ),
497 m_board( aBoard )
498 {}
499
500 void ProcessLayerList( uint8_t aClass, const BLK_0x2A_LAYER_LIST& aList )
501 {
502 // If we haven't seen this list yet, create and store the CUSTOM_LAYER list
503 if( m_Lists.count( &aList ) == 0 )
504 {
505 std::vector<CUSTOM_LAYER>& classLayers = m_Lists[&aList];
506
507 if( aList.m_RefEntries.has_value() )
508 {
509 for( const BLK_0x2A_LAYER_LIST::REF_ENTRY& entry : aList.m_RefEntries.value() )
510 {
511 const wxString& layerName = m_brdDb.GetString( entry.mLayerNameId );
512
513 CUSTOM_LAYER layer( layerName );
514 layer.m_Properties = entry.m_Properties;
515
516 classLayers.emplace_back( std::move( layer ) );
517 }
518 }
519 else if( aList.m_NonRefEntries.has_value() )
520 {
521 for( const BLK_0x2A_LAYER_LIST::NONREF_ENTRY& entry : aList.m_NonRefEntries.value() )
522 {
523 CUSTOM_LAYER layer( entry.m_Name );
524 layer.m_Properties = entry.m_Properties;
525
526 classLayers.emplace_back( std::move( layer ) );
527 }
528 }
529 else
530 {
531 // Presumably a parsing error.
532 THROW_IO_ERROR( "No ETCH layer list found." );
533 }
534
535 wxLogTrace( traceAllegroBuilder, "Added %zu layers for class %#04x, from 0x2A key %#010x",
536 classLayers.size(), aClass, aList.m_Key );
537 }
538
539 // Store the class ID -> 0x2A mapping
540 m_ClassCustomLayerLists[aClass] = &m_Lists[&aList];
541 }
542
549 {
550 auto customLayerIt = m_ClassCustomLayerLists.find( LAYER_INFO::CLASS::ETCH );
551
552 if( customLayerIt == m_ClassCustomLayerLists.end() || !customLayerIt->second )
553 {
554 wxLogTrace( traceAllegroBuilder, "No ETCH layer class found; cannot finalize layers" );
555 return;
556 }
557
558 const std::vector<CUSTOM_LAYER>& etchLayers = *customLayerIt->second;
559 const size_t numCuLayers = etchLayers.size();
560
561 m_etchLayerCount = static_cast<int>( numCuLayers );
562
563 // KiCad boards need an even copper layer count, so an odd stackup gets an empty inner layer
564 m_board.GetDesignSettings().SetCopperLayerCount( static_cast<int>( numCuLayers + numCuLayers % 2 ) );
565
566 std::vector<INPUT_LAYER_DESC> inputLayers;
567
568 for( size_t li = 0; li < numCuLayers; ++li )
569 {
570 INPUT_LAYER_DESC desc;
571 desc.Name = etchLayers[li].m_Name;
572 desc.AutoMapLayer = getNthCopperLayer( li, numCuLayers );
574 desc.Required = true;
575 inputLayers.push_back( desc );
576 }
577
578 // Add non-ETCH custom layers so they appear in the layer mapping dialog
579 const std::vector<CUSTOM_LAYER>* etchList = m_ClassCustomLayerLists[LAYER_INFO::CLASS::ETCH];
580 int nextAutoUser = 0;
581
582 for( const auto& [classId, layerList] : m_ClassCustomLayerLists )
583 {
584 if( classId == LAYER_INFO::CLASS::ETCH || layerList == etchList )
585 continue;
586
587 for( size_t si = 0; si < layerList->size(); ++si )
588 {
589 const LAYER_INFO li{ classId, static_cast<uint8_t>( si ) };
590
591 // Skip entries already covered by s_LayerKiMap
592 if( s_LayerKiMap.count( li ) )
593 continue;
594
595 INPUT_LAYER_DESC desc;
596 desc.Name = layerInfoDisplayName( li );
597
598 if( layerList->at( si ).m_Name.length() > 0 )
599 desc.Name = layerList->at( si ).m_Name;
600
601 desc.AutoMapLayer = getNthUserLayer( nextAutoUser++ );
603 desc.Required = false;
604 inputLayers.push_back( desc );
605
607 }
608 }
609
610 // The layers that maybe lump together multiple Allegro class:subclasses
611 // into a single, named, KiCad layer
612 for( const auto& [layerName, kiLayer] : m_MappedOptionalLayers )
613 {
614 INPUT_LAYER_DESC desc;
615 desc.Name = layerName;
616 desc.AutoMapLayer = kiLayer;
618 desc.Required = false;
619 inputLayers.push_back( desc );
620 }
621
622 for( const auto& [layerInfo, kiLayer] : s_LayerKiMap )
623 {
624 INPUT_LAYER_DESC desc;
625 desc.Name = layerInfoDisplayName( layerInfo );
626 desc.AutoMapLayer = kiLayer;
628 desc.Required = false;
629 inputLayers.push_back( desc );
630 }
631
632 std::map<wxString, PCB_LAYER_ID> resolvedMapping = m_layerMappingHandler( inputLayers );
633
634 // Apply copper layer mapping
635 for( size_t li = 0; li < numCuLayers; ++li )
636 {
637 const LAYER_INFO layerInfo{ LAYER_INFO::CLASS::ETCH, static_cast<uint8_t>( li ) };
638 const wxString& layerName = etchLayers[li].m_Name;
639
640 auto it = resolvedMapping.find( layerName );
641 PCB_LAYER_ID lId = ( it != resolvedMapping.end() ) ? it->second
642 : getNthCopperLayer( li, numCuLayers );
643
644 m_customLayerToKiMap[layerInfo] = lId;
645 m_board.SetLayerName( lId, layerName );
646 }
647
648 // Apply non-copper static layer mapping from the handler result
649 for( const auto& [layerInfo, defaultKiLayer] : s_LayerKiMap )
650 {
651 const wxString displayName = layerInfoDisplayName( layerInfo );
652
653 auto rmIt = resolvedMapping.find( displayName );
654
655 if( rmIt != resolvedMapping.end() && rmIt->second != PCB_LAYER_ID::UNDEFINED_LAYER )
656 {
657 m_staticLayerOverrides[layerInfo] = rmIt->second;
658 }
659 }
660
661 // Apply custom layer mapping from the handler result
662 for( const auto& [layerInfo, dialogName] : m_customLayerDialogNames )
663 {
664 auto rmIt = resolvedMapping.find( dialogName );
665
666 if( rmIt != resolvedMapping.end() && rmIt->second != PCB_LAYER_ID::UNDEFINED_LAYER )
667 {
668 m_customLayerToKiMap[layerInfo] = rmIt->second;
669 m_board.SetLayerName( rmIt->second, dialogName );
670 }
671 }
672
673 // Enable all the layers we ended up mapping to
674 LSET enabledLayersMask = m_board.GetEnabledLayers();
675 int userLayers = 0;
676 for( const auto& [name, layerId] : resolvedMapping )
677 {
678 if( layerId != PCB_LAYER_ID::UNDEFINED_LAYER )
679 enabledLayersMask |= LSET{ layerId };
680
681 if( IsUserLayer( layerId ) )
682 userLayers++;
683
684 wxLogTrace( traceAllegroBuilder, "Mapping Allegro layer '%s' to KiCad layer '%s' (%d)", name,
685 m_board.GetLayerName( layerId ), layerId );
686
687 m_board.SetLayerName( layerId, name );
688 }
689 m_board.SetEnabledLayers( enabledLayersMask );
690 wxLogTrace( traceAllegroBuilder, "After mapping, there are %d user layers", userLayers );
691 m_board.GetDesignSettings().SetUserDefinedLayerCount( userLayers );
692 }
693
694 PCB_LAYER_ID GetLayer( const LAYER_INFO& aLayerInfo )
695 {
696 // We already mapped and created the layer
697 if( m_customLayerToKiMap.count( aLayerInfo ) )
698 return m_customLayerToKiMap.at( aLayerInfo );
699
700 // Check for user-remapped static layers first
701 if( m_staticLayerOverrides.count( aLayerInfo ) )
702 return m_staticLayerOverrides.at( aLayerInfo );
703
704 // Next, have a look and see if the class:subclass was recorded as a custom layer
705 if( m_ClassCustomLayerLists.count( aLayerInfo.m_Class ) )
706 {
707 const std::vector<CUSTOM_LAYER>* cLayerList = m_ClassCustomLayerLists.at( aLayerInfo.m_Class );
708
709 // If it is using the copper layer list and the subclass is within the
710 // copper layer range, return the mapped copper layer. Non-ETCH classes
711 // can share the same layer list pointer, but their subclass values may
712 // exceed the copper layer count and must fall through to the custom
713 // layer mapping below.
714 const auto etchIt = m_ClassCustomLayerLists.find( LAYER_INFO::CLASS::ETCH );
715
716 if( etchIt != m_ClassCustomLayerLists.end()
717 && cLayerList == etchIt->second
718 && aLayerInfo.m_Subclass < cLayerList->size() )
719 {
720 const PCB_LAYER_ID cuLayer = getNthCopperLayer( aLayerInfo.m_Subclass, cLayerList->size() );
721 // Remember this mapping
722 m_customLayerToKiMap[aLayerInfo] = cuLayer;
723 return cuLayer;
724 }
725
726 if( aLayerInfo.m_Subclass < cLayerList->size() )
727 {
728 // This subclass maps to a custom layer in this class
729 const CUSTOM_LAYER& cLayer = cLayerList->at( aLayerInfo.m_Subclass );
730 return MapCustomLayer( aLayerInfo, cLayer.m_Name );
731 }
732 }
733
734 // Now, there may be layers that map to custom layers in KiCad, but are fixed in Allegro
735 // (perhaps, DFA_BOUND_TOP), which means we won't find them in the layer lists.
736 // We add them if we encounter them, with the names defined.
737 if( s_OptionalFixedMappings.count( aLayerInfo ) )
738 {
739 const wxString& layerName = s_OptionalFixedMappings.at( aLayerInfo );
740 return MapCustomLayer( aLayerInfo, layerName );
741 }
742
743 // Finally, fallback to the static mapping for any layers we haven't got a custom map for
744 // We do this last so that it can be overridden for example if we want to remap
745 // OUTLINE and DESIGN_OUTLINE to different layers.
746 if( s_LayerKiMap.count( aLayerInfo ) )
747 return s_LayerKiMap.at( aLayerInfo );
748
749 // Keep a record of what we failed to map
750 if( m_unknownLayers.count( aLayerInfo ) == 0 )
751 {
752 wxLogTrace( traceAllegroBuilder, "Failed to map class:subclass to layer: %#04x:%#04x", aLayerInfo.m_Class,
753 aLayerInfo.m_Subclass );
754 m_unknownLayers[aLayerInfo] = 1;
755 }
756 m_unknownLayers[aLayerInfo]++;
757
758 // Dump everything else here
759 return m_unmappedLayer;
760 }
761
766 bool IsPlaneLayer( const LAYER_INFO& aLayerInfo ) const
767 {
768 const auto etchIt = m_ClassCustomLayerLists.find( LAYER_INFO::CLASS::ETCH );
769 const auto classIt = m_ClassCustomLayerLists.find( aLayerInfo.m_Class );
770
771 // Other classes can draw on the copper layers through the same list
772 if( etchIt == m_ClassCustomLayerLists.end() || classIt == m_ClassCustomLayerLists.end()
773 || classIt->second != etchIt->second || !etchIt->second
774 || aLayerInfo.m_Subclass >= etchIt->second->size() )
775 {
776 return false;
777 }
778
779 return ( etchIt->second->at( aLayerInfo.m_Subclass ).m_Properties & LAYER_PROP_PLANE ) != 0;
780 }
781
785 int GetEtchLayerCount() const { return m_etchLayerCount; }
786
787 bool IsLayerMapped( PCB_LAYER_ID aLayerId ) const
788 {
789 return aLayerId != m_unmappedLayer;
790 }
791
798
800 {
801 const wxString name = aTop ? "PLACE_BOUND_TOP" : "PLACE_BOUND_BOTTOM";
802 return mapCustomLayerByName( name );
803 }
804
809 bool IsOutlineLayer( const LAYER_INFO& aLayerInfo ) const
810 {
813 {
814 return false;
815 }
816
819 }
820
828 PCB_LAYER_ID MapCustomLayer( const LAYER_INFO& aLayerInfo, const wxString& aLayerName )
829 {
830 // See if we have mapped this layer name under a different class:subclass
831 if( m_MappedOptionalLayers.count( aLayerName ) )
832 {
833 const PCB_LAYER_ID existingLId = m_MappedOptionalLayers.at( aLayerName );
834 // Record the reuse
835 m_customLayerToKiMap[aLayerInfo] = existingLId;
836 return existingLId;
837 }
838
839 // First time we needed this name:
840 // Add as a user layer and store for next time
841 const PCB_LAYER_ID lId = addUserLayer( aLayerName );
842 m_customLayerToKiMap[aLayerInfo] = lId;
843 m_MappedOptionalLayers[aLayerName] = lId;
844
845 wxLogTrace( traceAllegroBuilder, "Adding mapping for %#04x:%#04x to %s", aLayerInfo.m_Class,
846 aLayerInfo.m_Subclass, aLayerName );
847 return lId;
848 }
849
850
851 LSET GetRuleAreaLayers( const LAYER_INFO& aLayerInfo )
852 {
853 LSET layerSet{};
854
855 switch( aLayerInfo.m_Class )
856 {
860 {
861 switch( aLayerInfo.m_Subclass )
862 {
864 layerSet = LSET::AllCuMask();
865 break;
867 layerSet = LSET{ F_Cu };
868 break;
870 layerSet = LSET{ B_Cu };
871 break;
872 default:
873 layerSet = LSET{ GetLayer( aLayerInfo ) };
874 break;
875 }
876 break;
877 }
880 {
881 // This can be ALL, but can it be anything else?
883 layerSet = LSET::AllCuMask();
884 else
885 layerSet = LSET{ GetLayer( aLayerInfo ) };
886 break;
887 }
888 default:
889 wxLogTrace( traceAllegroBuilder, " Unhandled non-copper zone layer class %#02x, using default layers",
890 aLayerInfo.m_Class );
891 layerSet = LSET{ GetLayer( aLayerInfo ) };
892 break;
893 }
894
895 return layerSet;
896 }
897
898private:
899 static PCB_LAYER_ID getNthCopperLayer( int aNum, int aTotal )
900 {
901 return nthCopperLayerId( aNum, aTotal );
902 }
903
904 static PCB_LAYER_ID getNthUserLayer( int aNum )
905 {
906 aNum = std::min( aNum, MAX_USER_DEFINED_LAYERS - 1 );
907 return ToLAYER_ID( static_cast<int>( User_1 ) + 2 * aNum );
908 }
909
916 PCB_LAYER_ID mapCustomLayerByName( const wxString& aLayerName )
917 {
918 // If it's been added already, use it
919 if( m_MappedOptionalLayers.count( aLayerName ) )
920 {
921 return m_MappedOptionalLayers.at( aLayerName );
922 }
923
924 const PCB_LAYER_ID newLId = addUserLayer( aLayerName );
925 m_MappedOptionalLayers[aLayerName] = newLId;
926 return newLId;
927 }
928
929 PCB_LAYER_ID addUserLayer( const wxString& aName )
930 {
932 m_board.GetDesignSettings().SetUserDefinedLayerCount( m_board.GetDesignSettings().GetUserDefinedLayerCount() + 1 );
933 m_board.SetLayerName( lId, aName );
934 wxLogTrace( traceAllegroBuilder, "Adding user layer %s: %s", LayerName( lId ), aName );
935 return lId;
936 }
937
938 // Map of original layer list - we use this to store the CUSTOM_LAYERs, as well
939 // as check that we only handle each one once
940 std::unordered_map<const BLK_0x2A_LAYER_LIST*, std::vector<CUSTOM_LAYER>> m_Lists;
941
942 // Which classes point to which layer lists (more than one class can point to one list.
943 std::unordered_map<uint8_t, std::vector<CUSTOM_LAYER>*> m_ClassCustomLayerLists;
944
951 std::unordered_map<LAYER_INFO, PCB_LAYER_ID> m_customLayerToKiMap;
953
959 std::unordered_map<wxString, PCB_LAYER_ID> m_MappedOptionalLayers;
960
964 std::unordered_map<LAYER_INFO, PCB_LAYER_ID> m_staticLayerOverrides;
965
970 std::unordered_map<LAYER_INFO, wxString> m_customLayerDialogNames;
971
975 std::unordered_map<LAYER_INFO, int> m_unknownLayers;
976
978
979 // The layer to use for mapping failures;
981
983
986};
987
988
989BOARD_BUILDER::BOARD_BUILDER( const BRD_DB& aRawBoard, BOARD& aBoard, REPORTER& aReporter,
990 PROGRESS_REPORTER* aProgressReporter,
991 const LAYER_MAPPING_HANDLER& aLayerMappingHandler ) :
992 m_brdDb( aRawBoard ), m_board( aBoard ), m_reporter( aReporter ), m_progressReporter( aProgressReporter ),
993 m_layerMappingHandler( aLayerMappingHandler ),
995{
996 // Internal coordinates are stored in <base> / <divisor> units.
997
998 const std::map<BOARD_UNITS, int> c_baseScales = { { BOARD_UNITS::MILS, pcbIUScale.MilsToIU( 1 ) },
999 { BOARD_UNITS::INCHES, pcbIUScale.MilsToIU( 1000 ) },
1000 { BOARD_UNITS::MILLIMETERS, pcbIUScale.mmToIU( 1 ) },
1001 { BOARD_UNITS::CENTIMETERS, pcbIUScale.mmToIU( 10 ) },
1002 { BOARD_UNITS::MICROMETERS, pcbIUScale.mmToIU( 0.001 ) } };
1003
1004 if( m_brdDb.m_Header->m_UnitsDivisor == 0 )
1005 THROW_IO_ERROR( "Board units divisor is 0" );
1006
1007 if( !c_baseScales.contains( m_brdDb.m_Header->m_BoardUnits ) )
1008 THROW_IO_ERROR( "Unknown board units" );
1009
1010 double baseScale( c_baseScales.at( m_brdDb.m_Header->m_BoardUnits ) );
1011
1012 m_scale = baseScale / m_brdDb.m_Header->m_UnitsDivisor;
1013}
1014
1015
1030{
1031public:
1042
1052 class COMPLEX_FIRST_FILL_TASK : public PRIORITY_THREAD_POOL_TASK<std::vector<FILL_INFO>>
1053 {
1054 public:
1055 COMPLEX_FIRST_FILL_TASK( bool aSimplify ) : m_simplify( aSimplify ) {}
1056
1057 private:
1058 int computePriorityKey( const FILL_INFO& a ) const override
1059 {
1060 return static_cast<int>( a.m_CombinedFill.TotalVertices() );
1061 }
1062
1063 size_t task( FILL_INFO& fillInfo ) override
1064 {
1065 SHAPE_POLY_SET finalFillPolys = fillInfo.m_Zone->GetBoardOutline();
1066
1067 finalFillPolys.ClearArcs();
1068 fillInfo.m_CombinedFill.ClearArcs();
1069
1070 // Intersect the zone outline with the combined fill that was assembled
1071 // from all the related objects.
1072 finalFillPolys.BooleanIntersection( fillInfo.m_CombinedFill );
1073 finalFillPolys.Fracture( m_simplify );
1074
1075 // This is already mutex-ed, so this is safe
1076 fillInfo.m_Zone->SetFilledPolysList( fillInfo.m_Layer, finalFillPolys );
1077 return 1;
1078 }
1079
1081 };
1082
1086 void ProcessPolygons( bool aSimplify )
1087 {
1088 PROF_TIMER timer( "Zone fill processing" );
1089
1090 COMPLEX_FIRST_FILL_TASK fillTask( aSimplify );
1091 fillTask.Execute( m_FillInfos );
1092
1093 wxLogTrace( traceAllegroPerf, wxT( " Intersected and fractured zone fills in %.3f ms" ), // format:allow
1094 timer.msecs() );
1095 }
1096
1097 void QueuePolygonForZone( ZONE& aZone, SHAPE_POLY_SET aFilledArea, PCB_LAYER_ID aLayer )
1098 {
1099 // Rule areas don't need filling
1100 if( aZone.GetIsRuleArea() )
1101 return;
1102
1103 m_FillInfos.emplace_back( &aZone, aLayer, std::move( aFilledArea ) );
1104 }
1105
1106private:
1107 std::vector<FILL_INFO> m_FillInfos;
1108};
1109
1110
1114
1115
1116static int clampForScale( double aValue )
1117{
1118 double result = std::round( aValue );
1119
1120 if( result > std::numeric_limits<int>::max() )
1121 return std::numeric_limits<int>::max();
1122
1123 if( result < std::numeric_limits<int>::min() )
1124 return std::numeric_limits<int>::min();
1125
1126 return static_cast<int>( result );
1127}
1128
1129
1131{
1132 return VECTOR2I{
1133 clampForScale( aVector.x * m_scale ),
1134 clampForScale( -aVector.y * m_scale ),
1135 };
1136}
1137
1138int BOARD_BUILDER::scale( int aValue ) const
1139{
1140 return clampForScale( aValue * m_scale );
1141}
1142
1143
1145{
1146 return VECTOR2I{
1147 clampForScale( std::abs( aSize.x ) * m_scale ),
1148 clampForScale( std::abs( aSize.y ) * m_scale ),
1149 };
1150}
1151
1152
1153static EDA_ANGLE fromMillidegrees( uint32_t aMilliDegrees )
1154{
1155 return EDA_ANGLE{ static_cast<double>( aMilliDegrees ) / 1000.0, DEGREES_T };
1156}
1157
1158
1159void BOARD_BUILDER::reportMissingBlock( uint32_t aKey, uint8_t aType ) const
1160{
1161 m_reporter.Report( wxString::Format( "Could not find expected block with key %#010x and type %#04x", aKey, aType ),
1163}
1164
1165
1166void BOARD_BUILDER::reportUnexpectedBlockType( uint8_t aGot, uint8_t aExpected, uint32_t aKey, size_t aOffset,
1167 const wxString& aName ) const
1168{
1169 wxString name = aName.IsEmpty() ? wxString( "Object" ) : aName;
1170 wxString withKey = ( aKey == 0 ) ? wxString( "" ) : wxString::Format( ", with key %#010x ", aKey );
1171 wxString withOffset = ( aOffset == 0 ) ? wxString( "" ) : wxString::Format( ", at offset %#zx ", aOffset );
1172
1173 wxString s = wxString::Format( "%s has unexpected type %#04x (expected %#04x)%s%s", name, aGot, aExpected, withKey,
1174 withOffset );
1175
1176 m_reporter.Report( s, RPT_SEVERITY_WARNING );
1177}
1178
1179
1180wxString BOARD_BUILDER::get0x30StringValue( uint32_t a0x30Key ) const
1181{
1183
1184 if( blk0x30 == nullptr )
1185 THROW_IO_ERROR( "Failed to get 0x30 for string lookup" );
1186
1188
1189 if( blk0x31 == nullptr )
1190 THROW_IO_ERROR( "Failed to get 0x31 for string lookup" );
1191
1192 return blk0x31->m_Value;
1193}
1194
1195
1197{
1198 TYPED_LL_WALKER<BLK_0x36_DEF_TABLE> x36Walker{ m_brdDb.m_Header->m_LL_0x36.m_Head,
1199 m_brdDb.m_Header->m_LL_0x36.m_Tail, m_brdDb };
1200
1201 bool encountered = false;
1202
1203 for( const BLK_0x36_DEF_TABLE& blk0x36 : x36Walker )
1204 {
1205 if( blk0x36.m_Code != 0x08 )
1206 continue;
1207
1208 if( encountered )
1209 {
1210 // This would be bad, because we won't get the indexes into the list right if there
1211 // it's made up of entries from more than one list of entries.
1212 m_reporter.Report( "Found more than one font definition lists in the 0x36 list.", RPT_SEVERITY_WARNING );
1213 break;
1214 }
1215
1216 for( const auto& item : blk0x36.m_Items )
1217 {
1218 const auto& fontDef = std::get<BLK_0x36_DEF_TABLE::FontDef_X08>( item );
1219 m_fontDefList.push_back( &fontDef );
1220 }
1221
1222 encountered = true;
1223 }
1224}
1225
1226
1228{
1229 wxLogTrace( traceAllegroBuilder, "Creating nets from Allegro data" );
1230
1231 // Incrementing netcode. We could also choose to, say, use the 0x1B key if we wanted
1232 int netCode = 1;
1233
1234 std::vector<BOARD_ITEM*> bulkAdded;
1235
1237 m_brdDb.m_Header->m_LL_0x1B_Nets,
1238 m_brdDb,
1240 };
1241
1242 for( const BLK_0x1B_NET& netBlk : netWalker )
1243 {
1244 wxString netName = m_brdDb.GetString( netBlk.m_NetName );
1245
1246 // Allegro allows unnamed nets. KiCad's NETINFO_LIST matches nets by name, and all
1247 // empty-named nets would collapse to the unconnected net (code 0). Generate a unique
1248 // name so each Allegro net gets its own KiCad net code.
1249 if( netName.IsEmpty() )
1250 netName = wxString::Format( wxS( "Net_%d" ), netCode );
1251
1252 const bool isNew = m_board.FindNet( netName ) == nullptr;
1253 NETINFO_ITEM* kiNetInfo = m_board.FindOrAddNet( netName, netCode, ADD_MODE::BULK_APPEND );
1254 netCode++;
1255
1256 m_netCache[netBlk.m_Key] = kiNetInfo;
1257
1258 if( isNew )
1259 bulkAdded.push_back( kiNetInfo );
1260 }
1261
1262 m_board.FinalizeBulkAdd( bulkAdded );
1263
1264 wxLogTrace( traceAllegroBuilder, "Added %zu nets", m_netCache.size() );
1265}
1266
1267
1268wxString BOARD_BUILDER::resolveConstraintSetNameFromField( uint32_t aFieldKey ) const
1269{
1270 const BLOCK_BASE* fieldBlock = m_brdDb.GetObjectByKey( aFieldKey );
1271
1272 if( !fieldBlock || fieldBlock->GetBlockType() != 0x03 )
1273 return wxEmptyString;
1274
1275 const BLK_0x03_FIELD& field = BlockDataAs<BLK_0x03_FIELD>( *fieldBlock );
1276 const std::string* str = std::get_if<std::string>( &field.m_Substruct );
1277
1278 if( !str )
1279 return wxEmptyString;
1280
1281 // Extract name from schematic cross-reference format: @lib.xxx(view):\NAME\.
1282 // Find the last colon-backslash separator in the raw std::string and extract from there.
1283 size_t sep = str->find( ":\\" );
1284
1285 if( sep == std::string::npos )
1286 return wxEmptyString;
1287
1288 std::string extracted = str->substr( sep + 2 );
1289
1290 if( !extracted.empty() && extracted.back() == '\\' )
1291 extracted.pop_back();
1292
1293 return wxString( extracted );
1294}
1295
1296
1298{
1299 wxLogTrace( traceAllegroBuilder, "Importing physical constraint sets from 0x1D blocks" );
1300
1301 BOARD_DESIGN_SETTINGS& bds = m_board.GetDesignSettings();
1302 std::shared_ptr<NET_SETTINGS> netSettings = bds.m_NetSettings;
1303
1304 bool isV172Plus = ( m_brdDb.m_FmtVer >= FMT_VER::V_172 );
1305
1306 struct CS_DEF
1307 {
1308 wxString name;
1309 int lineWidth = 0;
1310 int clearance = 0;
1311 int diffPairGap = 0;
1312 };
1313
1314 // Map from constraint set name to its definition
1315 std::map<wxString, CS_DEF> constraintSets;
1316
1317 // Also map string table keys to set names for net lookup
1318 std::map<uint32_t, wxString> keyToSetName;
1319
1320 int csIndex = 0;
1321 TYPED_LL_WALKER<BLK_0x1D_CONSTRAINT_SET> csWalker( m_brdDb.m_Header->m_LL_0x1D_0x1E_0x1F, m_brdDb );
1322
1323 for( const BLK_0x1D_CONSTRAINT_SET& csBlock : csWalker )
1324 {
1325 wxString setName;
1326 const wxString& resolved = m_brdDb.GetString( csBlock.m_NameStrKey );
1327
1328 if( !resolved.IsEmpty() )
1329 {
1330 setName = resolved;
1331 }
1332 else if( csBlock.m_FieldPtr != 0 )
1333 {
1334 // Some boards store the name in a 0x03 FIELD block as a schematic cross-reference
1335 setName = resolveConstraintSetNameFromField( csBlock.m_FieldPtr );
1336 }
1337
1338 // Pre-V172 boards store the name as an index into the 0x36 name table
1339 if( setName.IsEmpty() && !isV172Plus && ( csBlock.m_NameStrKey >> 24 ) == 0x03 )
1340 {
1341 const uint32_t index = csBlock.m_NameStrKey & 0x00FFFFFF;
1342
1343 TYPED_LL_WALKER<BLK_0x36_DEF_TABLE> nameTables( m_brdDb.m_Header->m_LL_0x36.m_Head,
1344 m_brdDb.m_Header->m_LL_0x36.m_Tail, m_brdDb );
1345
1346 for( const BLK_0x36_DEF_TABLE& table : nameTables )
1347 {
1348 if( table.m_Code != 0x03 || index >= table.m_Items.size() )
1349 continue;
1350
1351 const auto& item = std::get<BLK_0x36_DEF_TABLE::X03>( table.m_Items[index] );
1352
1353 if( item.m_Str16x.has_value() )
1354 setName = wxString( item.m_Str16x.value() );
1355
1356 break;
1357 }
1358 }
1359
1360 if( setName.IsEmpty() )
1361 setName = wxString::Format( wxS( "CS_%d" ), csIndex );
1362
1363 csIndex++;
1364
1365 if( csBlock.m_DataB.empty() )
1366 {
1367 wxLogTrace( traceAllegroBuilder, "Constraint set '%s' has no DataB records, skipping", setName );
1368 continue;
1369 }
1370
1371 // Parse first DataB record (first copper layer) as 14 x int32
1372 const auto& record = csBlock.m_DataB[0];
1373 int32_t fields[14];
1374 static_assert( sizeof( fields ) == std::tuple_size_v<std::decay_t<decltype( record )>> );
1375 memcpy( fields, record.data(), sizeof( fields ) );
1376
1377 CS_DEF def;
1378 def.name = setName;
1379
1380 if( isV172Plus )
1381 {
1382 def.lineWidth = scale( fields[1] );
1383 def.clearance = scale( fields[4] );
1384 }
1385 else
1386 {
1387 // Pre-V172: f[0] is preferred line width, f[1] is line spacing (used as clearance).
1388 // f[4] is sometimes also clearance when non-zero, but f[1] is the primary source.
1389 def.lineWidth = scale( fields[0] );
1390 def.clearance = scale( fields[1] );
1391 }
1392
1393 def.diffPairGap = scale( fields[7] );
1394
1395 constraintSets[setName] = def;
1396 keyToSetName[csBlock.m_NameStrKey] = setName;
1397
1398 wxLogTrace( traceAllegroBuilder,
1399 "Constraint set '%s': line_width=%d nm, clearance=%d nm, dp_gap=%d nm",
1400 setName, def.lineWidth, def.clearance, def.diffPairGap );
1401 }
1402
1403 if( constraintSets.empty() )
1404 {
1405 wxLogTrace( traceAllegroBuilder, "No physical constraint sets found" );
1406 return;
1407 }
1408
1409 // Create a netclass for each constraint set that has nonzero values
1410 for( const auto& [name, def] : constraintSets )
1411 {
1412 wxString ncName = name;
1413
1414 if( ncName.CmpNoCase( NETCLASS::Default ) == 0 )
1415 ncName = wxS( "Allegro_Default" );
1416
1417 if( netSettings->HasNetclass( ncName ) )
1418 continue;
1419
1420 std::shared_ptr<NETCLASS> nc = std::make_shared<NETCLASS>( ncName );
1421
1422 if( def.lineWidth > 0 )
1423 nc->SetTrackWidth( def.lineWidth );
1424
1425 if( def.clearance > 0 )
1426 nc->SetClearance( def.clearance );
1427
1428 if( def.diffPairGap > 0 )
1429 {
1430 nc->SetDiffPairGap( def.diffPairGap );
1431
1432 // Diff pair width is the same as track width for the pair's netclass
1433 if( def.lineWidth > 0 )
1434 nc->SetDiffPairWidth( def.lineWidth );
1435 }
1436
1437 netSettings->SetNetclass( ncName, nc );
1438
1439 wxLogTrace( traceAllegroBuilder, "Created netclass '%s' from constraint set '%s'", ncName, name );
1440 }
1441
1442 // Walk all NETs and assign them to constraint set netclasses via field 0x1a0
1443 wxString defaultSetName;
1444
1445 for( const auto& [name, def] : constraintSets )
1446 {
1447 if( name.CmpNoCase( wxS( "DEFAULT" ) ) == 0 )
1448 {
1449 defaultSetName = name;
1450 break;
1451 }
1452 }
1453
1454 TYPED_LL_WALKER<BLK_0x1B_NET> csNetWalker{ m_brdDb.m_Header->m_LL_0x1B_Nets, m_brdDb };
1455
1456 for( const BLK_0x1B_NET& netBlk : csNetWalker )
1457 {
1458 // Field 0x1a0 references the constraint set. It can be an integer (string table key
1459 // that matches 0x1D.m_NameStrKey) or a direct string (the constraint set name).
1460 auto resolveSetName = [&]( const std::optional<FIELD_VALUE>& aField ) -> wxString
1461 {
1462 if( !aField.has_value() )
1463 return wxEmptyString;
1464
1465 if( auto* intVal = std::get_if<uint32_t>( &aField.value() ) )
1466 {
1467 auto it = keyToSetName.find( *intVal );
1468 return it != keyToSetName.end() ? it->second : wxString();
1469 }
1470
1471 if( auto* strVal = std::get_if<wxString>( &aField.value() ) )
1472 return constraintSets.count( *strVal ) ? *strVal : wxString();
1473
1474 return wxEmptyString;
1475 };
1476
1477 wxString assignedSetName = resolveSetName( GetFirstFieldOfType( m_brdDb, netBlk.m_FieldsPtr, netBlk.m_Key,
1479
1480 // Differential pairs carry the set on their match group table instead of on the net
1481 if( assignedSetName.IsEmpty() )
1482 {
1483 if( const BLK_0x2C_TABLE* table = resolveMatchGroupTable( netBlk ) )
1484 {
1485 assignedSetName = resolveSetName( GetFirstFieldOfType( m_brdDb, table->m_Ptr2, table->m_Key,
1487 }
1488 }
1489
1490 // Nets without field 0x1a0 use the DEFAULT constraint set
1491 if( assignedSetName.IsEmpty() && !defaultSetName.IsEmpty() )
1492 assignedSetName = defaultSetName;
1493
1494 if( assignedSetName.IsEmpty() )
1495 continue;
1496
1497 wxString ncName = assignedSetName;
1498
1499 if( ncName.CmpNoCase( NETCLASS::Default ) == 0 )
1500 ncName = wxS( "Allegro_Default" );
1501
1502 if( !netSettings->HasNetclass( ncName ) )
1503 continue;
1504
1505 auto netIt = m_netCache.find( netBlk.m_Key );
1506
1507 if( netIt == m_netCache.end() )
1508 continue;
1509
1510 NETINFO_ITEM* kiNet = netIt->second;
1511 netSettings->SetNetclassPatternAssignment( kiNet->GetNetname(), ncName );
1512 kiNet->SetNetClass( netSettings->GetNetClassByName( ncName ) );
1513 }
1514
1515 wxLogTrace( traceAllegroBuilder, "Applied %zu physical constraint sets", constraintSets.size() );
1516}
1517
1518
1520{
1521 wxLogTrace( traceAllegroBuilder, "Applying per-net trace width constraints" );
1522
1523 BOARD_DESIGN_SETTINGS& bds = m_board.GetDesignSettings();
1524 std::shared_ptr<NET_SETTINGS> netSettings = bds.m_NetSettings;
1525
1526 // Group nets by their minimum trace width to create netclasses.
1527 // Allegro stores per-net min/max trace width in FIELD blocks attached to each NET.
1528 std::map<int, std::vector<uint32_t>> widthToNetKeys;
1529
1530 TYPED_LL_WALKER<BLK_0x1B_NET> widthNetWalker{ m_brdDb.m_Header->m_LL_0x1B_Nets, m_brdDb };
1531
1532 for( const BLK_0x1B_NET& netBlk : widthNetWalker )
1533 {
1534 std::optional<int> minWidth =
1535 GetFirstFieldOfTypeInt( m_brdDb, netBlk.m_FieldsPtr, netBlk.m_Key, FIELD_KEYS::MIN_LINE_WIDTH );
1536
1537 if( !minWidth.has_value() || minWidth.value() <= 0 )
1538 continue;
1539
1540 int widthNm = scale( minWidth.value() );
1541 widthToNetKeys[widthNm].push_back( netBlk.m_Key );
1542 }
1543
1544 if( widthToNetKeys.empty() )
1545 {
1546 wxLogTrace( traceAllegroBuilder, "No per-net trace width constraints found" );
1547 return;
1548 }
1549
1550 for( const auto& [widthNm, netKeys] : widthToNetKeys )
1551 {
1552 int widthMils = ( widthNm + 12700 ) / 25400;
1553 wxString ncName = wxString::Format( wxS( "W%dmil" ), widthMils );
1554
1555 if( netSettings->HasNetclass( ncName ) )
1556 continue;
1557
1558 std::shared_ptr<NETCLASS> nc = std::make_shared<NETCLASS>( ncName );
1559 nc->SetTrackWidth( widthNm );
1560 netSettings->SetNetclass( ncName, nc );
1561
1562 for( uint32_t netKey : netKeys )
1563 {
1564 auto it = m_netCache.find( netKey );
1565
1566 if( it == m_netCache.end() )
1567 continue;
1568
1569 NETINFO_ITEM* kiNet = it->second;
1570 netSettings->SetNetclassPatternAssignment( kiNet->GetNetname(), ncName );
1571 kiNet->SetNetClass( nc );
1572 }
1573
1574 wxLogTrace( traceAllegroBuilder, "Created netclass '%s' (track width %d nm) with %zu nets",
1575 ncName, widthNm, netKeys.size() );
1576 }
1577
1578 wxLogTrace( traceAllegroBuilder, "Applied trace width constraints from %zu unique width groups",
1579 widthToNetKeys.size() );
1580}
1581
1582
1584{
1585 if( aNet.m_MatchGroupPtr == 0 )
1586 return nullptr;
1587
1588 const BLOCK_BASE* block = m_brdDb.GetObjectByKey( aNet.m_MatchGroupPtr );
1589
1590 if( !block )
1591 return nullptr;
1592
1593 uint32_t tableKey = 0;
1594
1595 if( block->GetBlockType() == 0x26 )
1596 {
1597 // V172+ path: NET -> 0x26 -> m_GroupPtr -> 0x2C TABLE
1598 const auto& x26 = BlockDataAs<BLK_0x26_MATCH_GROUP>( *block );
1599 tableKey = x26.m_GroupPtr;
1600
1601 // Some boards have chained 0x26 blocks (m_GroupPtr -> another 0x26 -> 0x2C)
1602 if( tableKey != 0 )
1603 {
1604 const BLOCK_BASE* next = m_brdDb.GetObjectByKey( tableKey );
1605
1606 if( next && next->GetBlockType() == 0x26 )
1607 {
1608 const auto& x26b = BlockDataAs<BLK_0x26_MATCH_GROUP>( *next );
1609 tableKey = x26b.m_GroupPtr;
1610 }
1611 }
1612 }
1613 else if( block->GetBlockType() == 0x2C )
1614 {
1615 // Pre-V172 path: NET -> 0x2C TABLE directly
1616 tableKey = aNet.m_MatchGroupPtr;
1617 }
1618 else
1619 {
1620 return nullptr;
1621 }
1622
1623 if( tableKey == 0 )
1624 return nullptr;
1625
1626 // Verify the target is actually a 0x2C TABLE before calling expectBlockByKey to
1627 // avoid noisy warnings on boards with unexpected pointer chain configurations.
1628 const BLOCK_BASE* tableBlock = m_brdDb.GetObjectByKey( tableKey );
1629
1630 if( !tableBlock || tableBlock->GetBlockType() != 0x2C )
1631 return nullptr;
1632
1633 return expectBlockByKey<BLK_0x2C_TABLE>( tableKey );
1634}
1635
1636
1638{
1639 const BLK_0x2C_TABLE* tbl = resolveMatchGroupTable( aNet );
1640
1641 if( !tbl || tbl->m_StringPtr == 0 )
1642 return wxEmptyString;
1643
1644 const wxString& name = m_brdDb.GetString( tbl->m_StringPtr );
1645
1646 wxLogTrace( traceAllegroBuilder, "Resolving match group name for NET '%s': found table at key %#010x, subtype %#x, name '%s'",
1647 m_brdDb.GetString( aNet.m_NetName ), tbl->m_Key, tbl->m_SubType, name );
1648
1649 // A group made from a schematic path keeps Cadence's \name\ wrapper, which is not part of the name
1651}
1652
1653
1655{
1656 wxLogTrace( traceAllegroBuilder, "Applying match group / differential pair assignments" );
1657
1658 BOARD_DESIGN_SETTINGS& bds = m_board.GetDesignSettings();
1659 std::shared_ptr<NET_SETTINGS> netSettings = bds.m_NetSettings;
1660
1661 // Group NET keys by their match group name
1662 std::map<wxString, std::vector<uint32_t>> groupToNetKeys;
1663
1664 TYPED_LL_WALKER<BLK_0x1B_NET> netWalker{ m_brdDb.m_Header->m_LL_0x1B_Nets, m_brdDb };
1665
1666 for( const BLK_0x1B_NET& netBlk : netWalker )
1667 {
1668 wxString groupName = resolveMatchGroupName( netBlk );
1669
1670 if( groupName.empty() )
1671 continue;
1672
1673 groupToNetKeys[groupName].push_back( netBlk.m_Key );
1674 }
1675
1676 if( groupToNetKeys.empty() )
1677 {
1678 wxLogTrace( traceAllegroBuilder, "No match groups found" );
1679 return;
1680 }
1681
1682 int dpCount = 0;
1683 int mgCount = 0;
1684
1685 for( const auto& [groupName, netKeys] : groupToNetKeys )
1686 {
1687 // A diff pair has exactly 2 nets. We don't check P/N naming because Allegro doesn't
1688 // require any naming convention for paired nets.
1689 bool isDiffPair = ( netKeys.size() == 2 );
1690 wxString ncPrefix = isDiffPair ? wxS( "DP_" ) : wxS( "MG_" );
1691 wxString ncName = ncPrefix + groupName;
1692
1693 if( netSettings->HasNetclass( ncName ) )
1694 continue;
1695
1696 std::shared_ptr<NETCLASS> nc = std::make_shared<NETCLASS>( ncName );
1697
1698 // Inherit constraint set values from the first net's current netclass so that
1699 // clearance and track width from the underlying constraint set are not lost.
1700 for( uint32_t netKey : netKeys )
1701 {
1702 auto it = m_netCache.find( netKey );
1703
1704 if( it == m_netCache.end() )
1705 continue;
1706
1707 NETCLASS* existing = it->second->GetNetClass();
1708
1709 if( existing && existing->GetName() != NETCLASS::Default )
1710 {
1711 if( existing->HasClearance() )
1712 nc->SetClearance( existing->GetClearance() );
1713
1714 if( existing->HasTrackWidth() )
1715 nc->SetTrackWidth( existing->GetTrackWidth() );
1716
1717 if( existing->HasDiffPairGap() )
1718 nc->SetDiffPairGap( existing->GetDiffPairGap() );
1719
1720 if( existing->HasDiffPairWidth() )
1721 nc->SetDiffPairWidth( existing->GetDiffPairWidth() );
1722
1723 break;
1724 }
1725 }
1726
1727 netSettings->SetNetclass( ncName, nc );
1728
1729 for( uint32_t netKey : netKeys )
1730 {
1731 auto it = m_netCache.find( netKey );
1732
1733 if( it == m_netCache.end() )
1734 continue;
1735
1736 NETINFO_ITEM* kiNet = it->second;
1737 netSettings->SetNetclassPatternAssignment( kiNet->GetNetname(), ncName );
1738 kiNet->SetNetClass( nc );
1739 }
1740
1741 if( isDiffPair )
1742 dpCount++;
1743 else
1744 mgCount++;
1745
1746 wxLogTrace( traceAllegroBuilder, "%s group '%s' -> netclass '%s' with %zu nets",
1747 isDiffPair ? wxS( "Diff pair" ) : wxS( "Match" ),
1748 groupName, ncName, netKeys.size() );
1749 }
1750
1751 wxLogTrace( traceAllegroBuilder,
1752 "Applied match groups: %d diff pairs, %d match groups (%zu total groups)",
1753 dpCount, mgCount, groupToNetKeys.size() );
1754}
1755
1756
1770static std::unordered_set<LAYER_INFO> ScanForLayers( const BRD_DB& aDb )
1771{
1772 std::unordered_set<LAYER_INFO> layersFound;
1773
1774 const auto& addLayer =
1775 [&]( std::optional<LAYER_INFO>& info )
1776 {
1777 if( info.has_value() )
1778 layersFound.insert( std::move( info.value() ) );
1779 };
1780
1781 const auto& simpleWalker =
1782 [&]( const FILE_HEADER::LINKED_LIST& aLL )
1783 {
1784 LL_WALKER walker{ aLL, aDb };
1785
1786 for( const BLOCK_BASE* block : walker )
1787 {
1788 std::optional<LAYER_INFO> info = tryLayerFromBlock( *block );
1789 addLayer( info );
1790 }
1791 };
1792
1793 simpleWalker( aDb.m_Header->m_LL_Shapes );
1794 simpleWalker( aDb.m_Header->m_LL_0x24_0x28 );
1795 simpleWalker( aDb.m_Header->m_LL_0x14 );
1796
1797 return layersFound;
1798}
1799
1800
1802{
1803 wxLogTrace( traceAllegroBuilder, "Setting up layer mapping from Allegro to KiCad" );
1804
1805 const std::array<FILE_HEADER::LAYER_MAP_ENTRY, 25>& layerMap = m_brdDb.m_Header->m_LayerMap;
1806
1807 for( size_t i = 0; i < layerMap.size(); ++i )
1808 {
1809 const uint8_t classNum = static_cast<uint8_t>( i );
1810
1811 const uint32_t x2aKey = layerMap[i].m_LayerList0x2A;
1812
1813 if( x2aKey == 0 )
1814 continue;
1815
1817
1818 // Probably an error
1819 if( !layerList )
1820 continue;
1821
1822 m_layerMapper->ProcessLayerList( classNum, *layerList );
1823 }
1824
1825 std::unordered_set<LAYER_INFO> layersFound = ScanForLayers( m_brdDb );
1826
1827 wxLogTrace( traceAllegroBuilder, "Scanned %zu layers", layersFound.size() );
1828
1829 for( const LAYER_INFO& info : layersFound )
1830 {
1831 wxLogTrace( traceAllegroBuilder, " - %#02x:%#02x (%s)", info.m_Class, info.m_Subclass,
1833 }
1834
1835 // The outline is sometimes on OUTLINE and sometimes on DESIGN_OUTLINE, and sometimes
1836 // on both. In the first two cases, whichever it is goes to Edge.Cuts, but in the both case,
1837 // we send one to a User layer
1840
1841 if( layersFound.count( outlineInfo ) && layersFound.count( designOutlineInfo ) )
1842 {
1843 // Both layers found, remap DESIGN_OUTLINE to a user layer
1844 wxLogTrace( traceAllegroBuilder,
1845 "Both OUTLINE and DESIGN_OUTLINE layers found, remapping DESIGN_OUTLINE to a user layer" );
1846 m_layerMapper->MapCustomLayer( designOutlineInfo, layerInfoDisplayName( designOutlineInfo ) );
1847 }
1848
1849 m_layerMapper->FinalizeLayers();
1850}
1851
1852
1854{
1855 if( aIndex == 0 || aIndex > m_fontDefList.size() )
1856 {
1857 m_reporter.Report( wxString::Format( "Font def index %u requested, have %zu entries",
1858 aIndex,
1859 m_fontDefList.size() ),
1861 return nullptr;
1862 }
1863
1864 // The index appears to be 1-indexed (maybe 0 means something special?)
1865 aIndex -= 1;
1866
1867 return m_fontDefList[aIndex];
1868}
1869
1870
1871std::unique_ptr<PCB_SHAPE> BOARD_BUILDER::buildLineSegment( const BLK_0x15_16_17_SEGMENT& aSegment,
1872 const LAYER_INFO& aLayerInfo, PCB_LAYER_ID aLayer,
1873 BOARD_ITEM_CONTAINER& aParent )
1874{
1875 VECTOR2I start = scale( { aSegment.m_StartX, aSegment.m_StartY } );
1876 VECTOR2I end = scale( { aSegment.m_EndX, aSegment.m_EndY } );
1877 const int width = scale( aSegment.m_Width );
1878
1879 if( !m_layerMapper->IsLayerMapped( aLayer ) )
1880 {
1881 wxLogTrace( traceAllegroBuilder, "Unmapped Seg: %#04x %#04x %s, %s", aLayerInfo.m_Class, aLayerInfo.m_Subclass,
1882 start.Format(), end.Format() );
1883 }
1884
1885 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent, SHAPE_T::SEGMENT );
1886 shape->SetLayer( aLayer );
1887 shape->SetStart( start );
1888 shape->SetEnd( end );
1889
1890 {
1891 int adjustedWidth = width;
1892
1893 if( adjustedWidth <= 0 )
1894 adjustedWidth = m_board.GetDesignSettings().GetLineThickness( aLayer );
1895
1896 shape->SetWidth( adjustedWidth );
1897 }
1898
1899 return shape;
1900}
1901
1902
1903std::unique_ptr<PCB_SHAPE> BOARD_BUILDER::buildArc( const BLK_0x01_ARC& aArc, const LAYER_INFO& aLayerInfo,
1904 PCB_LAYER_ID aLayer, BOARD_ITEM_CONTAINER& aParent )
1905{
1906 VECTOR2I start{ aArc.m_StartX, aArc.m_StartY };
1907 VECTOR2I end{ aArc.m_EndX, aArc.m_EndY };
1908
1909 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent, SHAPE_T::ARC );
1910
1911 shape->SetLayer( aLayer );
1912
1913 if( !m_layerMapper->IsLayerMapped( aLayer ) )
1914 {
1915 wxLogTrace( traceAllegroBuilder, "Unmapped Arc: %#04x %#04x %s, %s", aLayerInfo.m_Class, aLayerInfo.m_Subclass,
1916 start.Format(), end.Format() );
1917 }
1918
1919 start = scale( start );
1920 end = scale( end );
1921
1922 VECTOR2I c = scale( KiROUND( VECTOR2D{ aArc.m_CenterX, aArc.m_CenterY } ) );
1923
1924 int radius = scale( KiROUND( aArc.m_Radius ) );
1925
1926 bool clockwise = ( aArc.m_SubType & 0x40 ) != 0;
1927
1928 {
1929 int arcWidth = scale( aArc.m_Width );
1930
1931 if( arcWidth <= 0 )
1932 arcWidth = m_board.GetDesignSettings().GetLineThickness( aLayer );
1933
1934 shape->SetWidth( arcWidth );
1935 }
1936
1937 if( start == end )
1938 {
1939 shape->SetShape( SHAPE_T::CIRCLE );
1940 shape->SetCenter( c );
1941 shape->SetRadius( radius );
1942 }
1943 else
1944 {
1945 shape->SetShape( SHAPE_T::ARC );
1946 EDA_ANGLE startangle( start - c );
1947 EDA_ANGLE endangle( end - c );
1948
1949 startangle.Normalize();
1950 endangle.Normalize();
1951
1952 EDA_ANGLE angle = endangle - startangle;
1953
1954 if( clockwise && angle < ANGLE_0 )
1955 angle += ANGLE_360;
1956 if( !clockwise && angle > ANGLE_0 )
1957 angle -= ANGLE_360;
1958
1959 if( start == end )
1960 angle = -ANGLE_360;
1961
1962 VECTOR2I mid = start;
1963 RotatePoint( mid, c, -angle / 2.0 );
1964
1965 // A near-straight arc has a centre outside the coordinate range, so it cannot be transformed.
1966 // The centre is measured before the arc is built since building it already rotates by it.
1967 const double centreDistance =
1968 ( CalcArcCenter( VECTOR2D( start ), VECTOR2D( mid ), VECTOR2D( end ) ) - VECTOR2D( start ) )
1969 .EuclideanNorm();
1970
1971 if( !std::isfinite( centreDistance ) || centreDistance > std::numeric_limits<int>::max() / 4 )
1972 {
1973 shape->SetShape( SHAPE_T::SEGMENT );
1974 shape->SetStart( start );
1975 shape->SetEnd( end );
1976 }
1977 else
1978 {
1979 shape->SetArcGeometry( start, mid, end );
1980 }
1981 }
1982
1983 return shape;
1984}
1985
1986
1987std::unique_ptr<PCB_TEXT> BOARD_BUILDER::buildPcbText( const BLK_0x30_STR_WRAPPER& aStrWrapper,
1988 BOARD_ITEM_CONTAINER& aParent )
1989{
1990 std::unique_ptr<PCB_TEXT> text = std::make_unique<PCB_TEXT>( &aParent );
1991
1992 PCB_LAYER_ID layer = getLayer( aStrWrapper.m_Layer );
1993 text->SetLayer( layer );
1994
1996
1997 if( !strGraphic )
1998 {
1999 m_reporter.Report( wxString::Format( "Failed to find string graphic (0x31) with key %#010x "
2000 "in string wrapper (0x30) with key %#010x",
2001 aStrWrapper.m_StrGraphicPtr, aStrWrapper.m_Key ),
2003 return nullptr;
2004 }
2005
2006 const BLK_0x30_STR_WRAPPER::TEXT_PROPERTIES* props = nullptr;
2007
2008 if( aStrWrapper.m_Font.has_value() )
2009 props = &aStrWrapper.m_Font.value();
2010
2011 if( !props && aStrWrapper.m_Font16x.has_value() )
2012 props = &aStrWrapper.m_Font16x.value();
2013
2014 if( !props )
2015 {
2016 m_reporter.Report( wxString::Format( "Expected one of the font properties fields in 0x30 object (key %#010x) "
2017 "to be set.",
2018 aStrWrapper.m_Key ),
2020 return nullptr;
2021 }
2022
2023 const BLK_0x36_DEF_TABLE::FontDef_X08* fontDef = getFontDef( props->m_Key );
2024
2025 if( !fontDef )
2026 return nullptr;
2027
2028 text->SetText( strGraphic->m_Value );
2029 text->SetTextWidth( scale( fontDef->m_CharWidth ) );
2030 text->SetTextHeight( scale( fontDef->m_CharHeight ) );
2031
2032 if( fontDef->m_StrokeWidth > 0 )
2033 text->SetTextThickness( scale( fontDef->m_StrokeWidth ) );
2034 else
2035 text->SetTextThickness( GetPenSizeForNormal( scale( fontDef->m_CharHeight ) ) );
2036
2037 const EDA_ANGLE textAngle = fromMillidegrees( aStrWrapper.m_Rotation );
2038 text->SetTextAngle( textAngle );
2039
2040 VECTOR2I textPos = scale( VECTOR2I{ aStrWrapper.m_CoordsX, aStrWrapper.m_CoordsY } );
2041
2042 // KiCad's stroke font has a different baseline than Allegro's, so apply a vertical offset to compensate.
2043 // The exact offset is a bit of guesswork based on visually matching Allegro and KiCad text, but the
2044 // stoke font itself isn't the same anyway, so we can't be 100% here.
2045 VECTOR2I textFontOffset = VECTOR2I{ 0, -( scale( fontDef->m_CharHeight ) * 45 ) / 100 };
2046 RotatePoint( textFontOffset, textAngle );
2047 text->SetPosition( textPos + textFontOffset );
2048
2051 {
2052 text->SetMirrored( true );
2053 }
2054
2055 switch( props->m_Alignment )
2056 {
2058 text->SetHorizJustify( GR_TEXT_H_ALIGN_LEFT );
2059 break;
2061 text->SetHorizJustify( GR_TEXT_H_ALIGN_CENTER );
2062 break;
2064 text->SetHorizJustify( GR_TEXT_H_ALIGN_RIGHT );
2065 break;
2066 default:
2067 break;
2068 }
2069
2070 return text;
2071}
2072
2073
2074std::vector<std::unique_ptr<BOARD_ITEM>> BOARD_BUILDER::buildDrillMarker( const BLK_0x0C_PIN_DEF& aPinDef,
2075 BOARD_ITEM_CONTAINER& aParent )
2076{
2078 std::vector<std::unique_ptr<PCB_SHAPE>> shapes;
2079
2080 const uint32_t markerShape = aPinDef.GetShape();
2081
2082 PCB_LAYER_ID layer = getLayer( aPinDef.m_Layer );
2083 const VECTOR2I center = scale( VECTOR2I{ aPinDef.m_Coords[0], aPinDef.m_Coords[1] } );
2084 const VECTOR2I size = scaleSize( VECTOR2I{ aPinDef.m_Size[0], aPinDef.m_Size[1] } );
2085
2086 const auto addLine =
2087 [&]( const SEG& aSeg )
2088 {
2089 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent, SHAPE_T::SEGMENT );
2090 shape->SetStart( aSeg.A );
2091 shape->SetEnd( aSeg.B );
2092 shapes.push_back( std::move( shape ) );
2093 };
2094
2095 const auto addPolyPts =
2096 [&]( const std::vector<VECTOR2I>& aPts )
2097 {
2098 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent, SHAPE_T::POLY );
2099 shape->SetPolyPoints( aPts );
2100 shapes.push_back( std::move( shape ) );
2101 };
2102
2103 switch( markerShape )
2104 {
2105 case MS::CIRCLE:
2106 {
2107 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent, SHAPE_T::CIRCLE );
2108 shape->SetCenter( center );
2109 shape->SetRadius( size.x / 2 );
2110 shapes.push_back( std::move( shape ) );
2111 break;
2112 }
2113 case MS::SQUARE:
2114 case MS::RECTANGLE:
2115 {
2116 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent, SHAPE_T::RECTANGLE );
2117 shape->SetStart( center - size / 2 );
2118 shape->SetEnd( center + size / 2 );
2119 shapes.push_back( std::move( shape ) );
2120 break;
2121 }
2122 case MS::CROSS:
2123 {
2124 std::unique_ptr<PCB_SHAPE> shape;
2125
2126 std::vector<SEG> segs = KIGEOM::MakeCrossSegments( center, size, ANGLE_0 );
2127
2128 for( const SEG& seg : segs )
2129 addLine( seg );
2130
2131 break;
2132 }
2133 case MS::OBLONG_X:
2134 case MS::OBLONG_Y:
2135 {
2136 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent, SHAPE_T::RECTANGLE );
2137 shape->SetStart( center - size / 2 );
2138 shape->SetEnd( center + size / 2 );
2139
2140 int minSize = std::min( size.x, size.y );
2141 shape->SetCornerRadius( minSize / 2 );
2142 shapes.push_back( std::move( shape ) );
2143 break;
2144 }
2145 case MS::TRIANGLE:
2146 {
2147 // This triangle is point-up
2148 // Size follows fabmaster - the circumscribed circle of the triangle
2149 std::vector<VECTOR2I> pts = KIGEOM::MakeRegularPolygonPoints( center, 3, size.x / 2, true, ANGLE_90 );
2150 addPolyPts( pts );
2151 break;
2152 }
2153 case MS::DIAMOND:
2154 {
2155 std::vector<VECTOR2I> pts = KIGEOM::MakeRegularPolygonPoints( center, 4, size.x / 2, true, ANGLE_90 );
2156 addPolyPts( pts );
2157 break;
2158 }
2159 case MS::PENTAGON:
2160 {
2161 // Not 100% sure which way this should point
2162 std::vector<VECTOR2I> pts = KIGEOM::MakeRegularPolygonPoints( center, 5, size.x / 2, true, ANGLE_90 );
2163 addPolyPts( pts );
2164 break;
2165 }
2166 case MS::HEXAGON_X:
2167 case MS::HEXAGON_Y:
2168 {
2169 EDA_ANGLE startAngle = ( markerShape == MS::HEXAGON_X ) ? ANGLE_0 : ANGLE_90;
2170 std::vector<VECTOR2I> pts = KIGEOM::MakeRegularPolygonPoints( center, 6, size.x / 2, true, startAngle );
2171 addPolyPts( pts );
2172 break;
2173 }
2174 case MS::OCTAGON:
2175 {
2176 EDA_ANGLE startAngle = FULL_CIRCLE / 16; // Start at 22.5 degrees to align flat sides with axes
2177 // Octagons are measured across flats
2178 std::vector<VECTOR2I> pts = KIGEOM::MakeRegularPolygonPoints( center, 8, size.x / 2, false, startAngle );
2179 addPolyPts( pts );
2180 break;
2181 }
2182 default:
2183 wxLogTrace( traceAllegroBuilder, "Unsupported drill marker shape type %#04x for pin definition with key %#010x",
2184 markerShape, aPinDef.m_Key );
2185 break;
2186 }
2187
2188 std::vector<std::unique_ptr<BOARD_ITEM>> items;
2189
2190 for( std::unique_ptr<PCB_SHAPE>& shape : shapes )
2191 {
2192 shape->SetLayer( layer );
2193 shape->SetWidth( 0 );
2194
2195 items.push_back( std::move( shape ) );
2196 }
2197
2198 return items;
2199}
2200
2201
2202std::vector<std::unique_ptr<BOARD_ITEM>> BOARD_BUILDER::buildGraphicItems( const BLOCK_BASE& aBlock,
2203 BOARD_ITEM_CONTAINER& aParent )
2204{
2205 std::vector<std::unique_ptr<BOARD_ITEM>> newItems;
2206
2207 switch( aBlock.GetBlockType() )
2208 {
2209 case 0x0c:
2210 {
2211 const auto& pinDef = BlockDataAs<BLK_0x0C_PIN_DEF>( aBlock );
2212 newItems = buildDrillMarker( pinDef, aParent );
2213 break;
2214 }
2215 case 0x0e:
2216 {
2217 const auto& rect = BlockDataAs<BLK_0x0E_RECT>( aBlock );
2218
2219 std::unique_ptr<PCB_SHAPE> shape = buildRect( rect, aParent );
2220 if( shape )
2221 newItems.push_back( std::move( shape ) );
2222 break;
2223 }
2224 case 0x14:
2225 {
2226 const auto& graphicContainer = BlockDataAs<BLK_0x14_GRAPHIC>( aBlock );
2227
2228 std::vector<std::unique_ptr<PCB_SHAPE>> shapes = buildShapes( graphicContainer, aParent );
2229
2230 for( std::unique_ptr<PCB_SHAPE>& shape : shapes )
2231 newItems.push_back( std::move( shape ) );
2232
2233 break;
2234 }
2235 case 0x24:
2236 {
2237 const auto& rect = BlockDataAs<BLK_0x24_RECT>( aBlock );
2238
2239 std::unique_ptr<PCB_SHAPE> shape = buildRect( rect, aParent );
2240
2241 if( shape )
2242 newItems.push_back( std::move( shape ) );
2243
2244 break;
2245 }
2246 case 0x28:
2247 {
2248 const auto& shapeData = BlockDataAs<BLK_0x28_SHAPE>( aBlock );
2249 std::unique_ptr<PCB_SHAPE> shape = buildPolygon( shapeData, aParent );
2250
2251 if( shape )
2252 newItems.push_back( std::move( shape ) );
2253
2254 break;
2255 }
2256 case 0x30:
2257 {
2258 const auto& strWrapper = BlockDataAs<BLK_0x30_STR_WRAPPER>( aBlock );
2259
2260 std::unique_ptr<BOARD_ITEM> newItem = buildPcbText( strWrapper, aParent );
2261
2262 if( newItem )
2263 newItems.push_back( std::move( newItem ) );
2264
2265 break;
2266 }
2267 default:
2268 wxLogTrace( traceAllegroBuilder, " Unhandled block type for buildItems: %#04x", aBlock.GetBlockType() );
2269 break;
2270 }
2271
2272 return newItems;
2273};
2274
2275
2277{
2278 return m_layerMapper->GetLayer( aLayerInfo );
2279}
2280
2281
2282// Only PCB_SHAPE carries a net among the types the filter handles, so no dynamic_cast on a path
2283// that runs once per graphic
2284static int graphicNetCode( const BOARD_ITEM& aItem )
2285{
2286 if( aItem.Type() == PCB_SHAPE_T )
2287 return static_cast<const PCB_SHAPE&>( aItem ).GetNetCode();
2288
2290}
2291
2292
2294{
2295 size_t seed = 0;
2296 hash_combine( seed, (int) aItem->Type(), (int) aItem->GetLayer(), graphicNetCode( *aItem ) );
2297
2298 if( aItem->Type() == PCB_SHAPE_T )
2299 {
2300 const PCB_SHAPE* shape = static_cast<const PCB_SHAPE*>( aItem );
2301
2302 hash_combine( seed, (int) shape->GetShape(), shape->GetStart().x, shape->GetStart().y,
2303 shape->GetEnd().x, shape->GetEnd().y, shape->GetWidth() );
2304 }
2305 else if( aItem->Type() == PCB_TEXT_T )
2306 {
2307 const PCB_TEXT* text = static_cast<const PCB_TEXT*>( aItem );
2308
2309 hash_combine( seed, text->GetPosition().x, text->GetPosition().y, text->GetText().ToStdString() );
2310 }
2311
2312 return seed;
2313}
2314
2315
2316bool BOARD_BUILDER::GRAPHIC_KEY_EQ::operator()( const BOARD_ITEM* aFirst, const BOARD_ITEM* aSecond ) const
2317{
2318 if( aFirst->Type() != aSecond->Type()
2319 || aFirst->GetLayer() != aSecond->GetLayer()
2320 || graphicNetCode( *aFirst ) != graphicNetCode( *aSecond ) )
2321 {
2322 return false;
2323 }
2324
2325 if( aFirst->Type() == PCB_SHAPE_T )
2326 return static_cast<const PCB_SHAPE*>( aFirst )->Compare( static_cast<const PCB_SHAPE*>( aSecond ) ) == 0;
2327
2328 if( aFirst->Type() == PCB_TEXT_T )
2329 return static_cast<const PCB_TEXT*>( aFirst )->Compare( static_cast<const PCB_TEXT*>( aSecond ) ) == 0;
2330
2331 return false;
2332}
2333
2334
2336{
2337 if( aItem->Type() != PCB_SHAPE_T && aItem->Type() != PCB_TEXT_T )
2338 return true;
2339
2340 return m_seen.insert( aItem ).second;
2341}
2342
2343
2344void BOARD_BUILDER::stampIds( BOARD_ITEM& aItem, uint32_t aKey, uint32_t& aSeq )
2345{
2346 // RFC 4122 name-based UUID, naming the item by the block it came from and its position
2347 // within that block
2348 aItem.SetUuidDirect( KIID::FromName( "allegro:" + std::to_string( aKey ) + ":" + std::to_string( aSeq++ ) ) );
2349
2350 // A group's children are board items in their own right, stamped where they are built.
2351 // Descending into them here would also re-stamp them in the order of the group's
2352 // pointer-keyed member set, which varies between runs
2353 if( aItem.Type() == PCB_GROUP_T )
2354 return;
2355
2356 aItem.RunOnChildren(
2357 [&]( BOARD_ITEM* aChild )
2358 {
2359 stampIds( *aChild, aKey, aSeq );
2360 },
2362}
2363
2364
2365std::vector<std::unique_ptr<PCB_SHAPE>> BOARD_BUILDER::buildShapes( const BLK_0x14_GRAPHIC& aGraphic,
2366 BOARD_ITEM_CONTAINER& aParent )
2367{
2368 std::vector<std::unique_ptr<PCB_SHAPE>> shapes;
2369
2370 PCB_LAYER_ID layer = getLayer( aGraphic.m_Layer );
2371
2372 // Within the graphics list, we can get various lines and arcs on PLACE_BOUND_TOP, which
2373 // aren't actually the courtyard, which is a polygon in the 0x28 list. So, if we see such items,
2374 // remap them now to a specific other layer
2375 if( layer == F_CrtYd )
2376 layer = m_layerMapper->GetPlaceBounds( true );
2377 else if( layer == B_CrtYd )
2378 layer = m_layerMapper->GetPlaceBounds( false );
2379
2380 // Lines of the anti-etch class remove copper on any layer, as lines on a plane layer do. The lines of a
2381 // footprint are in board coordinates too, so they join the same voids
2382 const bool isVoidLine = m_layerMapper->IsPlaneLayer( aGraphic.m_Layer )
2383 || ( aGraphic.m_Layer.m_Class == LAYER_INFO::CLASS::ANTI_ETCH && IsCopperLayer( layer ) );
2384
2385 const LL_WALKER segWalker{ aGraphic.m_SegmentPtr, aGraphic.m_Key, m_brdDb };
2386
2387 for( const BLOCK_BASE* segBlock : segWalker )
2388 {
2389 std::unique_ptr<PCB_SHAPE> shape;
2390
2391 switch( segBlock->GetBlockType() )
2392 {
2393 case 0x01:
2394 {
2395 const auto& arc = BlockDataAs<BLK_0x01_ARC>( *segBlock );
2396 shape = buildArc( arc, aGraphic.m_Layer, layer, aParent );
2397 break;
2398 }
2399 case 0x15:
2400 case 0x16:
2401 case 0x17:
2402 {
2403 const auto& seg = BlockDataAs<BLK_0x15_16_17_SEGMENT>( *segBlock );
2404 shape = buildLineSegment( seg, aGraphic.m_Layer, layer, aParent );
2405 break;
2406 }
2407 default:
2408 wxLogTrace( traceAllegroBuilder, " Unhandled block type in BLK_0x14_GRAPHIC: %#04x",
2409 segBlock->GetBlockType() );
2410 break;
2411 }
2412
2413 if( !shape )
2414 continue;
2415
2416 // Void lines on a copper layer are kept as clearance and not as copper
2417 if( isVoidLine )
2418 {
2419 shape->TransformShapeToPolygon( m_planeVoids[layer], layer, 0, ARC_HIGH_DEF, ERROR_INSIDE );
2420 continue;
2421 }
2422
2423 shapes.push_back( std::move( shape ) );
2424 }
2425
2426 return shapes;
2427}
2428
2429
2430std::unique_ptr<PCB_SHAPE> BOARD_BUILDER::buildRect( const BLK_0x24_RECT& aRect, BOARD_ITEM_CONTAINER& aParent )
2431{
2432 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent );
2433
2434 PCB_LAYER_ID layer = getLayer( aRect.m_Layer );
2435 shape->SetLayer( layer );
2436
2437 shape->SetShape( SHAPE_T::RECTANGLE );
2438
2439 const VECTOR2I cornerA = scale( VECTOR2I{ aRect.m_Coords[0], aRect.m_Coords[1] } );
2440 const VECTOR2I cornerB = scale( VECTOR2I{ aRect.m_Coords[2], aRect.m_Coords[3] } );
2441
2442 shape->SetStart( cornerA );
2443 shape->SetEnd( cornerB );
2444
2445 const EDA_ANGLE angle = fromMillidegrees( aRect.m_Rotation );
2446 shape->Rotate( cornerA, angle );
2447
2448 const int lineWidth = 0;
2449 shape->SetWidth( lineWidth );
2450
2451 return shape;
2452}
2453
2454
2455std::unique_ptr<PCB_SHAPE> BOARD_BUILDER::buildRect( const BLK_0x0E_RECT& aRect, BOARD_ITEM_CONTAINER& aParent )
2456{
2457 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent );
2458
2459 PCB_LAYER_ID layer = getLayer( aRect.m_Layer );
2460 shape->SetLayer( layer );
2461
2462 shape->SetShape( SHAPE_T::RECTANGLE );
2463
2464 const VECTOR2I cornerA = scale( VECTOR2I{ aRect.m_Coords[0], aRect.m_Coords[1] } );
2465 const VECTOR2I cornerB = scale( VECTOR2I{ aRect.m_Coords[2], aRect.m_Coords[3] } );
2466
2467 shape->SetStart( cornerA );
2468 shape->SetEnd( cornerB );
2469
2470 const EDA_ANGLE angle = fromMillidegrees( aRect.m_Rotation );
2471 shape->Rotate( cornerA, angle );
2472
2473 const int lineWidth = 0;
2474 shape->SetWidth( lineWidth );
2475
2476 return shape;
2477}
2478
2479
2480std::unique_ptr<PCB_SHAPE> BOARD_BUILDER::buildPolygon( const BLK_0x28_SHAPE& aPolygon, BOARD_ITEM_CONTAINER& aParent )
2481{
2482 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &aParent );
2483
2484 PCB_LAYER_ID layer = getLayer( aPolygon.m_Layer );
2485 shape->SetLayer( layer );
2486
2487 shape->SetShape( SHAPE_T::POLY );
2488
2489 SHAPE_LINE_CHAIN chain = buildOutline( aPolygon );
2490
2491 if( chain.PointCount() < 3 )
2492 {
2493 wxLogTrace( traceAllegroBuilder, "Polygon (0x28) with key %#010x has fewer than 3 points, skipping",
2494 aPolygon.m_Key );
2495 return nullptr;
2496 }
2497
2498 chain.SetClosed( true );
2499 shape->SetPolyShape( chain );
2500
2501 const int lineWidth = 0;
2502 shape->SetWidth( lineWidth );
2503
2504 return shape;
2505}
2506
2507
2508std::vector<std::unique_ptr<PCB_SHAPE>> BOARD_BUILDER::buildPolygonShapes( const BLK_0x28_SHAPE& aShapeData,
2509 BOARD_ITEM_CONTAINER& aParent )
2510{
2511 std::vector<std::unique_ptr<PCB_SHAPE>> shapes;
2512
2513 PCB_LAYER_ID layer = getLayer( aShapeData.m_Layer );
2514
2515 // Walk the segments in this shape and create PCB_SHAPE objects on Edge_Cuts
2516 const LL_WALKER segWalker{ aShapeData.m_FirstSegmentPtr, aShapeData.m_Key, m_brdDb };
2517
2518 for( const BLOCK_BASE* segBlock : segWalker )
2519 {
2520 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &m_board );
2521 shape->SetLayer( layer );
2522 shape->SetWidth( m_board.GetDesignSettings().GetLineThickness( layer ) );
2523
2524 switch( segBlock->GetBlockType() )
2525 {
2526 case 0x01:
2527 {
2528 const auto& arc = BlockDataAs<BLK_0x01_ARC>( *segBlock );
2529
2530 VECTOR2I start = scale( { arc.m_StartX, arc.m_StartY } );
2531 VECTOR2I end = scale( { arc.m_EndX, arc.m_EndY } );
2532 VECTOR2I c = scale( KiROUND( VECTOR2D{ arc.m_CenterX, arc.m_CenterY } ) );
2533
2534 int radius = scale( arc.m_Radius );
2535 if( start == end )
2536 {
2537 shape->SetShape( SHAPE_T::CIRCLE );
2538 shape->SetCenter( c );
2539 shape->SetRadius( radius );
2540 }
2541 else
2542 {
2543 shape->SetShape( SHAPE_T::ARC );
2544
2545 bool clockwise = ( arc.m_SubType & 0x40 ) != 0;
2546
2547 EDA_ANGLE startangle( start - c );
2548 EDA_ANGLE endangle( end - c );
2549
2550 startangle.Normalize();
2551 endangle.Normalize();
2552
2553 EDA_ANGLE angle = endangle - startangle;
2554
2555 if( clockwise && angle < ANGLE_0 )
2556 angle += ANGLE_360;
2557
2558 if( !clockwise && angle > ANGLE_0 )
2559 angle -= ANGLE_360;
2560
2561 VECTOR2I mid = start;
2562 RotatePoint( mid, c, -angle / 2.0 );
2563
2564 shape->SetArcGeometry( start, mid, end );
2565 }
2566 break;
2567 }
2568 case 0x15:
2569 case 0x16:
2570 case 0x17:
2571 {
2572 const auto& seg = BlockDataAs<BLK_0x15_16_17_SEGMENT>( *segBlock );
2573 VECTOR2I start = scale( { seg.m_StartX, seg.m_StartY } );
2574 VECTOR2I end = scale( { seg.m_EndX, seg.m_EndY } );
2575
2576 shape->SetShape( SHAPE_T::SEGMENT );
2577 shape->SetStart( start );
2578 shape->SetEnd( end );
2579 shape->SetWidth( m_board.GetDesignSettings().GetLineThickness( layer ) );
2580 break;
2581 }
2582 default:
2583 wxLogTrace( traceAllegroBuilder, " Unhandled segment type in outline: %#04x", segBlock->GetBlockType() );
2584 continue;
2585 }
2586
2587 shapes.push_back( std::move( shape ) );
2588 }
2589
2590 return shapes;
2591}
2592
2593
2595{
2596 uint32_t refKey = 0x00;
2597
2598 if( aFpInstance.m_InstRef.has_value() )
2599 refKey = aFpInstance.m_InstRef.value();
2600
2601 if( !refKey && aFpInstance.m_InstRef16x.has_value() )
2602 refKey = aFpInstance.m_InstRef16x.value();
2603
2604 // This can happen, for example for dimension "symbols".
2605 if( refKey == 0 )
2606 return nullptr;
2607
2609 return blk07;
2610}
2611
2612
2613std::vector<std::unique_ptr<BOARD_ITEM>> BOARD_BUILDER::buildPadItems( const BLK_0x1C_PADSTACK& aPadstack,
2614 FOOTPRINT& aFp, const wxString& aPadName,
2615 int aNetcode, bool aBackSide )
2616{
2617 // Not all Allegro PADSTACKS can be represented by a single KiCad pad. For example, the
2618 // paste and mask layers can have completely independent shapes in Allegro, but in KiCad that
2619 // would require a separate aperture pad.
2620 // Also if there are multiple drills, we will need to make a pad for each
2621 std::vector<std::unique_ptr<BOARD_ITEM>> padItems;
2622
2623 std::vector<std::unique_ptr<PADSTACK::COPPER_LAYER_PROPS>> copperLayers( aPadstack.GetLayerCount() );
2624
2625 // Thermal relief gap from antipad/pad size difference on the first layer that has both.
2626 std::optional<int> thermalGap;
2627
2628 const wxString& padStackName = m_brdDb.GetString( aPadstack.m_PadStr );
2629
2630 wxLogTrace( traceAllegroBuilder, "Building pad '%s' with %u layers", padStackName, aPadstack.GetLayerCount() );
2631
2632 // First, gather all the copper layers into a set of shape props, which we can then use to decide on the padstack mode
2633 for( size_t i = 0; i < aPadstack.GetLayerCount(); ++i )
2634 {
2635 const size_t layerBaseIndex = aPadstack.m_NumFixedCompEntries + i * aPadstack.m_NumCompsPerLayer;
2636 const ALLEGRO::PADSTACK_COMPONENT& padComp = aPadstack.m_Components[layerBaseIndex
2638 const ALLEGRO::PADSTACK_COMPONENT& antiPadComp = aPadstack.m_Components[layerBaseIndex
2640 const ALLEGRO::PADSTACK_COMPONENT& thermalComp = aPadstack.m_Components[layerBaseIndex
2642
2643 // If this is zero just skip entirely - I don't think we can usefully make pads with just thermal relief
2644 // Flag up if that happens.
2646 {
2647 if( antiPadComp.m_Type != PADSTACK_COMPONENT::TYPE_NULL )
2648 {
2649 m_reporter.Report( wxString::Format( "Padstack %s: Copper layer %zu has no pad component, but has "
2650 "antipad",
2651 padStackName,
2652 i ),
2654 }
2655 if( thermalComp.m_Type != PADSTACK_COMPONENT::TYPE_NULL )
2656 {
2657 m_reporter.Report( wxString::Format( "Copper layer %zu has no pad component, but has thermal relief",
2658 i ),
2660 }
2661 continue;
2662 }
2663
2664 auto& layerCuProps = copperLayers[i];
2665 wxLogTrace( traceAllegroBuilder, " Adding copper layer %zu with pad type %d", i, (int) padComp.m_Type );
2666 layerCuProps = std::make_unique<PADSTACK::COPPER_LAYER_PROPS>();
2667
2668 switch( padComp.m_Type )
2669 {
2671 layerCuProps->shape.shape = PAD_SHAPE::RECTANGLE;
2672 layerCuProps->shape.size = scaleSize( VECTOR2I{ padComp.m_W, padComp.m_H } );
2673 layerCuProps->shape.offset = scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } );
2674 break;
2676 layerCuProps->shape.shape = PAD_SHAPE::RECTANGLE;
2677 layerCuProps->shape.size = scaleSize( VECTOR2I{ padComp.m_W, padComp.m_W } );
2678 layerCuProps->shape.offset = scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } );
2679 break;
2681 layerCuProps->shape.shape = PAD_SHAPE::CIRCLE;
2682 layerCuProps->shape.size = scaleSize( VECTOR2I{ padComp.m_W, padComp.m_H } );
2683 layerCuProps->shape.offset = scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } );
2684 break;
2687 layerCuProps->shape.shape = PAD_SHAPE::OVAL;
2688 layerCuProps->shape.size = scaleSize( VECTOR2I{ padComp.m_W, padComp.m_H } );
2689 layerCuProps->shape.offset = scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } );
2690 break;
2692 {
2693 layerCuProps->shape.shape = PAD_SHAPE::ROUNDRECT;
2694 layerCuProps->shape.size = scaleSize( VECTOR2I{ padComp.m_W, padComp.m_H } );
2695 layerCuProps->shape.offset = scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } );
2696
2697 int minDim = std::min( std::abs( padComp.m_W ), std::abs( padComp.m_H ) );
2698
2699 if( padComp.m_Z1.has_value() && padComp.m_Z1.value() > 0 && minDim > 0 )
2700 layerCuProps->shape.round_rect_radius_ratio = padComp.m_Z1.value() / (double) minDim;
2701 else
2702 layerCuProps->shape.round_rect_radius_ratio = 0.25;
2703
2704 break;
2705 }
2707 {
2708 layerCuProps->shape.shape = PAD_SHAPE::CHAMFERED_RECT;
2709 layerCuProps->shape.size = scaleSize( VECTOR2I{ padComp.m_W, padComp.m_H } );
2710 layerCuProps->shape.offset = scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } );
2711
2712 int minDim = std::min( std::abs( padComp.m_W ), std::abs( padComp.m_H ) );
2713
2714 if( padComp.m_Z1.has_value() && padComp.m_Z1.value() > 0 && minDim > 0 )
2715 layerCuProps->shape.chamfered_rect_ratio = padComp.m_Z1.value() / (double) minDim;
2716 else
2717 layerCuProps->shape.chamfered_rect_ratio = 0.25;
2718
2719 layerCuProps->shape.chamfered_rect_positions = RECT_CHAMFER_ALL;
2720 break;
2721 }
2723 {
2724 // Approximate octagon as a round rectangle with ~29.3% corner radius
2725 // (tan(22.5°) ≈ 0.414, half of that as ratio ≈ 0.207, but visually 0.293 is closer)
2726 layerCuProps->shape.shape = PAD_SHAPE::CHAMFERED_RECT;
2727 layerCuProps->shape.size = scaleSize( VECTOR2I{ padComp.m_W, padComp.m_H } );
2728 layerCuProps->shape.offset = scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } );
2729 layerCuProps->shape.chamfered_rect_ratio = 1.0 - 1.0 / sqrt( 2.0 );
2730 layerCuProps->shape.chamfered_rect_positions = RECT_CHAMFER_ALL;
2731 break;
2732 }
2734 {
2735 // Custom shape defined by a 0x28 polygon. Walk the shape's segments and build
2736 // a polygon primitive for this pad.
2737 const BLK_0x28_SHAPE* shapeData = expectBlockByKey<BLK_0x28_SHAPE>( padComp.m_ShapePtr );
2738
2739 if( !shapeData )
2740 {
2741 wxLogTrace( traceAllegroBuilder, "Padstack %s: SHAPE_SYMBOL on layer %zu has no 0x28 shape at %#010x",
2742 padStackName, i, padComp.m_ShapePtr );
2743 break;
2744 }
2745
2747
2748 if( outline.PointCount() >= 3 )
2749 {
2750 outline.SetClosed( true );
2751
2752 // A custom pad ignores the shape offset, so it moves the outline instead
2753 outline.Move( scale( VECTOR2I{ padComp.m_OffsetX, padComp.m_OffsetY } ) );
2754
2755 layerCuProps->shape.shape = PAD_SHAPE::CUSTOM;
2756 layerCuProps->shape.anchor_shape = PAD_SHAPE::CIRCLE;
2757
2758 // Anchor size based on the shape's bounding box center
2759 BOX2I bbox = outline.BBox();
2760 int anchorSize = static_cast<int>(
2761 std::min( bbox.GetWidth(), bbox.GetHeight() ) / 4 );
2762
2763 if( anchorSize < 1 )
2764 anchorSize = 1;
2765
2766 layerCuProps->shape.size = VECTOR2I( anchorSize, anchorSize );
2767
2768 std::shared_ptr<PCB_SHAPE> poly = std::make_shared<PCB_SHAPE>( nullptr, SHAPE_T::POLY );
2769 poly->SetPolyShape( SHAPE_POLY_SET( outline ) );
2770 poly->SetFilled( true );
2771 poly->SetWidth( 0 );
2772 layerCuProps->custom_shapes.push_back( poly );
2773 }
2774 else
2775 {
2776 wxLogTrace( traceAllegroBuilder, "Padstack %s: SHAPE_SYMBOL on layer %zu produced only %d points",
2777 padStackName, i, outline.PointCount() );
2778 }
2779
2780 break;
2781 }
2783 {
2784 layerCuProps->shape.shape = PAD_SHAPE::CUSTOM;
2785 layerCuProps->shape.anchor_shape = PAD_SHAPE::CIRCLE;
2786
2787 const int w = std::max( padComp.m_W, 300 );
2788 const int h = std::max( padComp.m_H, 220 );
2789
2790 SHAPE_LINE_CHAIN outline;
2791 auto S = [&]( int x, int y )
2792 {
2793 return scale( VECTOR2I{ x, y } );
2794 };
2795
2796 // Regular pentagon with flat bottom edge
2797 outline.Append( S( 0, -h / 2 ) );
2798 outline.Append( S( w / 2, -h / 6 ) );
2799 outline.Append( S( w / 3, h / 2 ) );
2800 outline.Append( S( -w / 3, h / 2 ) );
2801 outline.Append( S( -w / 2, -h / 6 ) );
2802 outline.SetClosed( true );
2803 outline.Move( S( padComp.m_OffsetX, padComp.m_OffsetY ) );
2804
2805 BOX2I bbox = outline.BBox();
2806 int anchorSize = static_cast<int>(
2807 std::min( bbox.GetWidth(), bbox.GetHeight() ) / 7 );
2808
2809 if( anchorSize < 1 )
2810 anchorSize = 1;
2811
2812 layerCuProps->shape.size = VECTOR2I( anchorSize, anchorSize );
2813
2814 std::shared_ptr<PCB_SHAPE> poly = std::make_shared<PCB_SHAPE>( nullptr, SHAPE_T::POLY );
2815 poly->SetPolyShape( SHAPE_POLY_SET( outline ) );
2816 poly->SetFilled( true );
2817 poly->SetWidth( 0 );
2818 layerCuProps->custom_shapes.push_back( poly );
2819 break;
2820 }
2821 default:
2822 m_reporter.Report( wxString::Format( "Padstack %s: unhandled copper pad shape type %d on layer %zu",
2823 padStackName,
2824 static_cast<int>( padComp.m_Type ),
2825 i ),
2827 break;
2828 }
2829
2830 if( antiPadComp.m_Type != PADSTACK_COMPONENT::TYPE_NULL)
2831 {
2832 if( antiPadComp.m_Type != padComp.m_Type )
2833 {
2834 wxLogTrace( traceAllegroBuilder,
2835 "Padstack %s: copper layer %zu antipad shape %d differs from pad shape %d",
2836 padStackName, i, antiPadComp.m_Type, padComp.m_Type );
2837 }
2838
2839 int clearanceX = scale( ( antiPadComp.m_W - padComp.m_W ) / 2 );
2840 int clearanceY = scale( ( antiPadComp.m_H - padComp.m_H ) / 2 );
2841
2842 if( clearanceX && clearanceX != clearanceY )
2843 {
2844 wxLogTrace( traceAllegroBuilder, "Padstack %s: copper layer %zu unequal antipad clearance X=%d Y=%d",
2845 padStackName, i, clearanceX, clearanceY );
2846 }
2847
2848 if( antiPadComp.m_OffsetX != 0 || antiPadComp.m_OffsetY != 0 )
2849 {
2850 wxLogTrace( traceAllegroBuilder, "Padstack %s: copper layer %zu antipad offset %d, %d", padStackName, i,
2851 antiPadComp.m_OffsetX, antiPadComp.m_OffsetY );
2852 }
2853
2854 layerCuProps->clearance = clearanceX;
2855 }
2856
2857 if( thermalComp.m_Type != PADSTACK_COMPONENT::TYPE_NULL && !thermalGap.has_value() )
2858 {
2859 // The thermal gap is the clearance between the pad copper and the surrounding zone.
2860 // We derive it from the antipad-to-pad size difference.
2861 if( antiPadComp.m_Type != PADSTACK_COMPONENT::TYPE_NULL && padComp.m_W > 0 )
2862 {
2863 int gap = scale( ( antiPadComp.m_W - padComp.m_W ) / 2 );
2864
2865 if( gap > 0 )
2866 thermalGap = gap;
2867 }
2868
2869 wxLogTrace( traceAllegroBuilder, "Padstack %s: thermal relief type=%d, gap=%snm",
2870 padStackName,
2871 thermalComp.m_Type,
2872 thermalGap.has_value() ? wxString::Format( "%d", thermalGap.value() )
2873 : wxString( "N/A" ) );
2874 }
2875
2876 // Padstack-level keepouts (antipad relief geometry) are handled via the
2877 // antipad slot in copperLayers above. Board-level keepouts use BLK_0x34.
2878 }
2879
2880 // We have now constructed a list of copper props. We can determine the PADSTACK mode now and assign the shapes
2881 PADSTACK padStack( &aFp );
2882
2883 if( copperLayers.size() == 0 )
2884 {
2885 // SMD aperture PAD or something?
2886 }
2887 else
2888 {
2889 const auto layersEqual =
2890 [&](size_t aFrom, size_t aTo) -> bool
2891 {
2892 bool eq = true;
2893
2894 for( size_t i = aFrom + 1; i < aTo; ++i )
2895 {
2896 if( !copperLayers[i - 1] || !copperLayers[i] || *copperLayers[i - 1] != *copperLayers[i] )
2897 {
2898 eq = false;
2899 break;
2900 }
2901 }
2902 return eq;
2903 };
2904
2905 for(size_t i = 0; i < copperLayers.size(); ++i )
2906 wxLogTrace( traceAllegroBuilder, " Layer %zu: %s", i, copperLayers[i] ? "present" : "null" );
2907
2908 padStack.SetLayerSet( PAD::PTHMask() );
2909
2910 if( copperLayers.front() && copperLayers.back() && layersEqual( 0, copperLayers.size() ) )
2911 {
2912 wxLogTrace( traceAllegroBuilder, " Using NORMAL padstack mode (all layers identical)" );
2913 padStack.SetMode( PADSTACK::MODE::NORMAL );
2914 PADSTACK::COPPER_LAYER_PROPS& layerProps = padStack.CopperLayer( F_Cu );
2915 layerProps = *copperLayers.front();
2916 }
2917 else if( copperLayers.front() && copperLayers.back() && layersEqual( 1, copperLayers.size() - 1 ) )
2918 {
2919 wxLogTrace( traceAllegroBuilder, " Using FRONT_INNER_BACK padstack mode (inner layers identical)" );
2921 padStack.CopperLayer( F_Cu ) = *copperLayers.front();
2922 padStack.CopperLayer( B_Cu ) = *copperLayers.back();
2923
2924 // May be B_Cu if layers = 2, but that's OK
2925 if( copperLayers.size() > 2 && copperLayers[1] )
2926 padStack.CopperLayer( In1_Cu ) = *copperLayers[1];
2927 }
2928 else
2929 {
2930 wxLogTrace( traceAllegroBuilder, " Using CUSTOM padstack mode (layers differ)" );
2931 padStack.SetMode( PADSTACK::MODE::CUSTOM );
2932
2933 for( size_t i = 0; i < copperLayers.size(); ++i )
2934 {
2935 if( !copperLayers[i] )
2936 continue;
2937
2938 const int count = static_cast<int>( copperLayers.size() );
2939 PCB_LAYER_ID layer = nthCopperLayerId( static_cast<int>( i ), count );
2940
2941 // The flip mirrors around the rounded-up stackup, so start from where it lands on the right layer
2942 if( aBackSide && count % 2 != 0 )
2943 layer = m_board.FlipLayer( nthCopperLayerId( count - 1 - static_cast<int>( i ), count ) );
2944
2945 padStack.CopperLayer( layer ) = *copperLayers[i];
2946 }
2947 }
2948 }
2949
2950 // The drill/slot dimensions are extracted in priority order:
2951 //
2952 // 1. V172+ m_SlotAndUnknownArr[0] and [3] hold the true slot outline dimensions (X and Y).
2953 // For routed slots (round drill bit + routing path), m_DrillArr only has the bit diameter,
2954 // while m_SlotAndUnknownArr has the full slot envelope.
2955 //
2956 // 2. V172+ m_DrillArr[4] (width) and m_DrillArr[7] (height, 0 for round).
2957 // These match m_SlotAndUnknownArr for punched oblong drills but only have the bit
2958 // diameter for routed slots.
2959 //
2960 // 3. Pre-V172 m_Drill field (drill diameter, always round).
2961 int drillW = 0;
2962 int drillH = 0;
2963
2964 if( std::holds_alternative<BLK_0x1C_PADSTACK::HEADER_v16x>( aPadstack.m_Header ) )
2965 {
2966 const auto& hdr16x = std::get<BLK_0x1C_PADSTACK::HEADER_v16x>( aPadstack.m_Header );
2967
2968 if( hdr16x.m_SlotY > 0 )
2969 {
2970 drillW = scale( static_cast<int>( hdr16x.m_SlotX ) );
2971 drillH = scale( static_cast<int>( hdr16x.m_SlotY ) );
2972 }
2973 else
2974 {
2975 drillW = scale( static_cast<int>( aPadstack.GetDrillSize() ) );
2976 }
2977 }
2978 else
2979 {
2980 const auto& hdr17x = std::get<BLK_0x1C_PADSTACK::HEADER_v17x>( aPadstack.m_Header );
2981
2982 if( hdr17x.m_SlotY > 0 )
2983 {
2984 drillW = scale( static_cast<int>( hdr17x.m_SlotX ) );
2985 drillH = scale( static_cast<int>( hdr17x.m_SlotY ) );
2986 }
2987 else
2988 {
2989 drillW = scale( static_cast<int>( hdr17x.m_DrillSize ) );
2990 }
2991 }
2992
2993 if( drillH == 0 )
2994 drillH = drillW;
2995
2996 // Allegro stores slot dimensions as (primary, secondary) regardless of orientation,
2997 // not as (X, Y). Compare the first copper layer pad's aspect ratio to determine if
2998 // the drill needs to be rotated 90 degrees.
2999 if( drillW != drillH && aPadstack.GetLayerCount() > 0 )
3000 {
3001 size_t firstCopperIdx = aPadstack.m_NumFixedCompEntries;
3002 const ALLEGRO::PADSTACK_COMPONENT& firstPadComp =
3003 aPadstack.m_Components[firstCopperIdx + BLK_0x1C_PADSTACK::LAYER_COMP_SLOT::PAD];
3004
3005 bool padIsTaller = ( std::abs( firstPadComp.m_H ) > std::abs( firstPadComp.m_W ) );
3006 bool drillIsTaller = ( drillH > drillW );
3007
3008 if( padIsTaller != drillIsTaller )
3009 std::swap( drillW, drillH );
3010 }
3011
3012 bool isSmd = ( drillW == 0 ) || ( aPadstack.GetLayerCount() == 1 );
3013
3014 if( isSmd )
3015 {
3016 padStack.Drill().size = VECTOR2I( 0, 0 );
3017 }
3018 else
3019 {
3020 padStack.Drill().size = VECTOR2I( drillW, drillH );
3021
3022 if( drillW != drillH )
3023 padStack.Drill().shape = PAD_DRILL_SHAPE::OBLONG;
3024 else
3025 padStack.Drill().shape = PAD_DRILL_SHAPE::CIRCLE;
3026 }
3027
3028 // A hole with no copper still needs a pad size, and KiCad takes the drill as that size
3029 if( !isSmd && !aPadstack.IsPlated() )
3030 {
3031 for( PCB_LAYER_ID layer : padStack.UniqueLayers() )
3032 {
3033 PADSTACK::COPPER_LAYER_PROPS& props = padStack.CopperLayer( layer );
3034
3035 if( props.shape.size.x <= 0 || props.shape.size.y <= 0 )
3036 {
3037 props.shape.shape = drillW == drillH ? PAD_SHAPE::CIRCLE : PAD_SHAPE::OVAL;
3038 props.shape.size = VECTOR2I( drillW, drillH );
3039 }
3040 }
3041 }
3042
3043 // A pad with no copper and no hole has no size, which KiCad cannot save
3044 if( isSmd && std::none_of( copperLayers.begin(), copperLayers.end(),
3045 []( const auto& aProps ) { return aProps != nullptr; } ) )
3046 {
3047 wxLogTrace( traceAllegroBuilder, "Padstack %s has no copper and no drill, skipping pad '%s'", padStackName,
3048 aPadName );
3049 return padItems;
3050 }
3051
3052 std::unique_ptr<PAD> pad = std::make_unique<PAD>( &aFp );
3053 pad->SetPadstack( padStack );
3054 pad->SetNumber( aPadName );
3055 pad->SetNetCode( aNetcode );
3056
3057 if( isSmd )
3058 {
3059 pad->SetAttribute( PAD_ATTRIB::SMD );
3060
3061 // A one-layer padstack starts on the layer of its pad, the bottom for the far fingers of an edge connector
3062 const int etchCount = m_layerMapper->GetEtchLayerCount();
3063 PCB_LAYER_ID padLayer = F_Cu;
3064
3065 if( aPadstack.GetLayerCount() == 1 && aPadstack.m_StartLayer < etchCount )
3066 {
3067 // The start layer is in board order, and the footprint flip still to come mirrors it
3068 const int boardIndex = aBackSide ? etchCount - 1 - aPadstack.m_StartLayer : aPadstack.m_StartLayer;
3070 static_cast<uint8_t>( boardIndex ) } );
3071
3072 if( IsCopperLayer( boardLayer ) )
3073 padLayer = aBackSide ? m_board.FlipLayer( boardLayer ) : boardLayer;
3074 }
3075
3076 if( padLayer == F_Cu )
3077 pad->SetLayerSet( PAD::SMDMask() );
3078 else if( padLayer == B_Cu && m_brdDb.m_FmtVer < FMT_VER::V_172 )
3079 pad->SetLayerSet( LSET( { B_Cu, B_Mask } ) ); // no 16.x bottom paste slot is known
3080 else if( padLayer == B_Cu )
3081 pad->SetLayerSet( LSET( { B_Cu, B_Paste, B_Mask } ) );
3082 else
3083 pad->SetLayerSet( LSET( { padLayer } ) );
3084 }
3085 else if( aPadstack.IsPlated() )
3086 {
3087 pad->SetAttribute( PAD_ATTRIB::PTH );
3088 pad->SetLayerSet( PAD::PTHMask() );
3089 }
3090 else
3091 {
3092 pad->SetAttribute( PAD_ATTRIB::NPTH );
3093 pad->SetLayerSet( PAD::UnplatedHoleMask() );
3094 }
3095
3096 if( thermalGap.has_value() )
3097 pad->SetThermalGap( thermalGap.value() );
3098
3099 // Now, for each technical layer, we see if we can include it into the existing padstack, or if we need to add
3100 // it as a standalone pad
3101 for( size_t i = 0; i < aPadstack.m_NumFixedCompEntries; ++i )
3102 {
3103 const ALLEGRO::PADSTACK_COMPONENT& psComp = aPadstack.m_Components[i];
3104
3105 // Knock off known layers that are clearly null
3107 {
3108 if( m_brdDb.m_FmtVer < FMT_VER::V_172 )
3109 {
3111 pad->SetLayerSet( pad->GetLayerSet().reset( F_Mask ) );
3113 pad->SetLayerSet( pad->GetLayerSet().reset( B_Mask ) );
3115 pad->SetLayerSet( pad->GetLayerSet().reset( F_Paste ) );
3116 }
3117 else
3118 {
3120 pad->SetLayerSet( pad->GetLayerSet().reset( F_Mask ) );
3122 pad->SetLayerSet( pad->GetLayerSet().reset( B_Mask ) );
3124 pad->SetLayerSet( pad->GetLayerSet().reset( F_Paste ) );
3126 pad->SetLayerSet( pad->GetLayerSet().reset( B_Paste ) );
3127 }
3128
3129 continue;
3130 }
3131
3132 // All fixed slots are technical layers (solder mask, paste mask, film mask,
3133 // assembly variant, etc). Custom mask expansion extraction is not yet implemented;
3134 // KiCad's default pad-matches-mask behavior applies.
3135 wxLogTrace( traceAllegroBuilder, "Fixed padstack slot %zu: type=%d, W=%d, H=%d",
3136 i, static_cast<int>( psComp.m_Type ), psComp.m_W, psComp.m_H );
3137 }
3138
3139 padItems.push_back( std::move( pad ) );
3140
3141 return padItems;
3142}
3143
3144
3145static std::optional<double> modelUnitToMm( const wxString& aUnits )
3146{
3147 if( aUnits == wxS( "MM" ) )
3148 return 1.0;
3149 else if( aUnits == wxS( "CM" ) )
3150 return 10.0;
3151 else if( aUnits == wxS( "MICRONS" ) )
3152 return 0.001;
3153 else if( aUnits == wxS( "MILS" ) )
3154 return 0.0254;
3155 else if( aUnits == wxS( "INCH" ) )
3156 return 25.4;
3157
3158 return std::nullopt;
3159}
3160
3161
3162// Allegro holds the model assignment on the package definition as two comma separated
3163// properties, the file name plus cache metadata and the placement in the symbol frame
3164static std::optional<FP_3DMODEL> build3DModel( const BRD_DB& aDb, const BLK_0x2B_FOOTPRINT_DEF& aFpDef )
3165{
3166 std::optional<FIELD_VALUE> fileField =
3168
3169 const wxString* fileValue = fileField.has_value() ? std::get_if<wxString>( &fileField.value() ) : nullptr;
3170
3171 if( !fileValue )
3172 return std::nullopt;
3173
3174 wxString fileName = fileValue->BeforeFirst( ',' ).Trim( true ).Trim( false );
3175
3176 if( fileName.IsEmpty() )
3177 return std::nullopt;
3178
3180 model.m_Filename = fileName;
3181
3182 std::optional<FIELD_VALUE> placementField =
3184
3185 const wxString* placementValue =
3186 placementField.has_value() ? std::get_if<wxString>( &placementField.value() ) : nullptr;
3187
3188 if( !placementValue )
3189 return model;
3190
3191 wxArrayString tokens = wxSplit( *placementValue, ',', '\0' );
3192
3193 if( tokens.size() < 7 )
3194 {
3195 wxLogTrace( traceAllegroBuilder, " Ignoring malformed 3D placement '%s'", *placementValue );
3196 return model;
3197 }
3198
3199 const std::optional<double> toMm = modelUnitToMm( tokens[0].Trim( true ).Trim( false ).Upper() );
3200
3201 if( !toMm.has_value() )
3202 {
3203 wxLogTrace( traceAllegroBuilder, " Unknown 3D placement units '%s'", tokens[0] );
3204 return model;
3205 }
3206
3207 std::array<double, 6> placement{};
3208
3209 for( size_t i = 0; i < placement.size(); ++i )
3210 {
3211 if( !tokens[i + 1].Trim( true ).Trim( false ).ToCDouble( &placement[i] ) )
3212 {
3213 wxLogTrace( traceAllegroBuilder, " Ignoring malformed 3D placement '%s'", *placementValue );
3214 return model;
3215 }
3216 }
3217
3218 // Allegro and the KiCad 3D scene share a Z-up, Y-up frame local to the symbol, but KiCad
3219 // stores the negation of the rotation its renderers apply
3220 model.m_Offset = VECTOR3D( placement[0] * *toMm, placement[1] * *toMm, placement[2] * *toMm );
3221 model.m_Rotation = VECTOR3D( -placement[3], -placement[4], -placement[5] );
3222
3223 return model;
3224}
3225
3226
3228 const BLK_0x30_STR_WRAPPER& aStrWrapper, bool& aValueFieldSet )
3229{
3230 std::unique_ptr<PCB_TEXT> text = buildPcbText( aStrWrapper, aFp );
3231
3232 if( !text )
3233 return;
3234
3235 const uint8_t textClass = aStrWrapper.m_Layer.m_Class;
3236 const uint8_t textSubclass = aStrWrapper.m_Layer.m_Subclass;
3237
3238 bool isSilk = ( textSubclass == LAYER_INFO::SUBCLASS::SILKSCREEN_TOP
3239 || textSubclass == LAYER_INFO::SUBCLASS::SILKSCREEN_BOTTOM );
3240 bool isAssembly = ( textSubclass == LAYER_INFO::SUBCLASS::ASSEMBLY_TOP
3241 || textSubclass == LAYER_INFO::SUBCLASS::ASSEMBLY_BOTTOM );
3242
3243 if( textClass == LAYER_INFO::CLASS::REF_DES && isSilk )
3244 {
3245 // Visible silkscreen refdes updates the built-in REFERENCE field.
3246 PCB_FIELD* const refDes = aFp.GetField( FIELD_T::REFERENCE );
3247
3248 // KiCad netlisting requires non-digit + digit annotation.
3249 if( !text->GetText().IsEmpty() && !wxIsalpha( text->GetText()[0] ) )
3250 text->SetText( wxString( "UNK" ) + text->GetText() );
3251
3252 *refDes = PCB_FIELD( *text, FIELD_T::REFERENCE );
3253 refDes->SetTextAngle( text->GetTextAngle() ); // Set to absolute orientation
3254 }
3255 else if( textClass == LAYER_INFO::CLASS::REF_DES && isAssembly )
3256 {
3257 // Assembly refdes becomes a text item with the magic ${REFERENCE}
3258 // if it's an un-referenced refdes (e.g. in an unplaced footprint)
3259 if( text->GetText().Contains( wxS( "*" ) ) )
3260 text->SetText( wxS( "${REFERENCE}" ) );
3261
3262 aFp.Add( text.release() );
3263 }
3264 else if( textClass == LAYER_INFO::CLASS::COMPONENT_VALUE && isAssembly )
3265 {
3266 if( !aValueFieldSet )
3267 {
3268 // First COMPONENT_VALUE on assembly updates the built-in VALUE field
3269 PCB_FIELD* valField = aFp.GetField( FIELD_T::VALUE );
3270 *valField = PCB_FIELD( *text, FIELD_T::VALUE );
3271 valField->SetTextAngle( text->GetTextAngle() ); // Set to absolute orientation
3272 valField->SetVisible( false );
3273 aValueFieldSet = true;
3274 }
3275 else
3276 {
3277 PCB_FIELD* field = new PCB_FIELD( *text, FIELD_T::USER, wxS( "Component Value" ) );
3278 field->SetVisible( false );
3279 aFp.Add( field, ADD_MODE::APPEND );
3280 }
3281 }
3282 else if( textClass == LAYER_INFO::CLASS::DEVICE_TYPE )
3283 {
3284 PCB_FIELD* field = new PCB_FIELD( *text, FIELD_T::USER, wxS( "Device Type" ) );
3285 field->SetVisible( !isAssembly );
3286 aFp.Add( field, ADD_MODE::APPEND );
3287 }
3288 else if( textClass == LAYER_INFO::CLASS::TOLERANCE )
3289 {
3290 PCB_FIELD* field = new PCB_FIELD( *text, FIELD_T::USER, wxS( "Tolerance" ) );
3291 field->SetVisible( isSilk );
3292 aFp.Add( field, ADD_MODE::APPEND );
3293 }
3294 else if( textClass == LAYER_INFO::CLASS::USER_PART_NUMBER )
3295 {
3296 PCB_FIELD* field = new PCB_FIELD( *text, FIELD_T::USER, wxS( "User Part Number" ) );
3297 field->SetVisible( isSilk );
3298 aFp.Add( field, ADD_MODE::APPEND );
3299 }
3300 else if( textClass == LAYER_INFO::CLASS::COMPONENT_VALUE && isSilk )
3301 {
3302 PCB_FIELD* field = new PCB_FIELD( *text, FIELD_T::USER, wxS( "Component Value" ) );
3303 field->SetVisible( true );
3304 aFp.Add( field, ADD_MODE::APPEND );
3305 }
3306 else if( aGraphics.IsFirst( text.get() ) )
3307 {
3308 aFp.Add( text.release() );
3309 }
3310}
3311
3312
3313std::unique_ptr<FOOTPRINT> BOARD_BUILDER::buildFootprint( const BLK_0x2D_FOOTPRINT_INST& aFpInstance )
3314{
3315 std::unique_ptr<FOOTPRINT> fp = std::make_unique<FOOTPRINT>( &m_board );
3316
3317 const BLK_0x07_COMPONENT_INST* fpInstData = getFpInstRef( aFpInstance );
3318
3319 const bool backSide = ( aFpInstance.m_Layer != 0 );
3320
3321 wxLogTrace( traceAllegroBuilder, "Building footprint from 0x2D block key %#010x", aFpInstance.m_Key );
3322
3323 wxString refDesStr;
3324 if( fpInstData )
3325 {
3326 refDesStr = m_brdDb.GetString( fpInstData->m_RefDesStrPtr );
3327
3328 if( refDesStr.IsEmpty() )
3329 {
3330 // Does this happen even when there's an 0x07 block?
3331 m_reporter.Report( wxString::Format( "Empty ref des for 0x2D key %#010x", aFpInstance.m_Key ),
3333 }
3334 }
3335
3336 // We may update the PCB_FIELD layer if it's specified explicitly (e.g. with font size and so on),
3337 // but if not, set the refdes at least, but make it invisible
3338 fp->SetReference( refDesStr );
3339 fp->GetField( FIELD_T::REFERENCE )->SetVisible( false );
3340
3341 // Symbols without a reference (dimensions, marks) have no schematic counterpart
3342 if( refDesStr.IsEmpty() )
3344
3345 wxLogTrace( traceAllegroBuilder, " Footprint reference: '%s'", refDesStr );
3346
3347 const VECTOR2I fpPos = scale( VECTOR2I{ aFpInstance.m_CoordX, aFpInstance.m_CoordY } );
3348 fp->SetPosition( fpPos );
3349
3350 // Coincidence filters. Pad geometry is placed before the footprint is flipped and rotated
3351 // and everything else after, so it is filtered in its own space first and folded into the
3352 // shared filter once the transform has been applied
3353 GRAPHIC_DEDUP padDedup;
3354 GRAPHIC_DEDUP fpGraphics;
3355
3356 // Find the pads.
3357 // Pads are in non-flipped local footprint's coordinate system
3358 TYPED_LL_WALKER<BLK_0x32_PLACED_PAD> padWalker{ aFpInstance.m_FirstPadPtr, aFpInstance.m_Key, m_brdDb,
3360 for( const BLK_0x32_PLACED_PAD& placedPadInfo : padWalker )
3361 {
3362 const BLK_0x04_NET_ASSIGNMENT* netAssignment =
3363 expectBlockByKey<BLK_0x04_NET_ASSIGNMENT>( placedPadInfo.m_NetPtr );
3364 const BLK_0x0D_PAD* padInfo = expectBlockByKey<BLK_0x0D_PAD>( placedPadInfo.m_PadPtr );
3365
3366 if( !padInfo )
3367 continue;
3368
3370
3371 if( !padStack )
3372 continue;
3373
3374 int netCode = NETINFO_LIST::UNCONNECTED;
3375
3376 if( netAssignment )
3377 {
3378 auto netIt = m_netCache.find( netAssignment->m_Net );
3379
3380 if( netIt != m_netCache.end() )
3381 netCode = netIt->second->GetNetCode();
3382 }
3383
3384 const wxString padName = m_brdDb.GetString( padInfo->m_NameStrId );
3385
3386 // 0x0D coordinates and rotation are in the footprint's local (unrotatesinced) space.
3387 // Use SetFPRelativePosition/Orientation to let KiCad handle the transform to
3388 // board-absolute coordinates (rotating by FP orientation and adding FP position).
3389 VECTOR2I padLocalPos = scale( VECTOR2I{ padInfo->m_CoordsX, padInfo->m_CoordsY } );
3390 EDA_ANGLE padLocalRot = fromMillidegrees( padInfo->m_Rotation );
3391
3392 std::vector<std::unique_ptr<BOARD_ITEM>> padItems = buildPadItems( *padStack, *fp, padName, netCode, backSide );
3393
3394 for( std::unique_ptr<BOARD_ITEM>& item : padItems )
3395 {
3396 if( item->Type() == PCB_PAD_T )
3397 {
3398 PAD* pad = static_cast<PAD*>( item.get() );
3399 pad->SetFPRelativeOrientation( padLocalRot );
3400 }
3401
3402 item->SetFPRelativePosition( padLocalPos );
3403
3404 if( padDedup.IsFirst( item.get() ) )
3405 fp->Add( item.release() );
3406 }
3407 }
3408
3409 {
3410 EDA_ANGLE rotation = fromMillidegrees( aFpInstance.m_Rotation );
3411
3412 if( backSide )
3413 fp->Flip( fpPos, FLIP_DIRECTION::LEFT_RIGHT );
3414
3415 fp->Rotate( fpPos, rotation );
3416 }
3417
3418 // Pad geometry has landed in the same space as everything that follows, so record it and
3419 // let the graphics coming next be filtered against it too
3420 for( BOARD_ITEM* placed : fp->GraphicalItems() )
3421 fpGraphics.IsFirst( placed );
3422
3423 // Graphics, text, and areas are stored in Allegro as board-absolute geometry
3424 // on their final layers. Pads were already placed in local footprint space and
3425 // the footprint Flip/Rotate above put them into board space, so these items
3426 // can be added as-is.
3427 TYPED_LL_WALKER<BLK_0x14_GRAPHIC> graphicsWalker{ aFpInstance.m_GraphicPtr, aFpInstance.m_Key, m_brdDb,
3429 graphicsWalker.SetMismatchReporter(
3430 [this]( uint8_t aType, const BLOCK_BASE& )
3431 {
3432 m_reporter.Report( wxString::Format( "Unexpected type in graphics list: %#04x", aType ),
3434 } );
3435
3436 for( const BLK_0x14_GRAPHIC& graphics : graphicsWalker )
3437 {
3438 std::vector<std::unique_ptr<PCB_SHAPE>> shapes = buildShapes( graphics, *fp );
3439
3440 for( std::unique_ptr<PCB_SHAPE>& shape : shapes )
3441 {
3442 if( fpGraphics.IsFirst( shape.get() ) )
3443 fp->Add( shape.release() );
3444 }
3445 }
3446
3447 bool valueFieldSet = false;
3448
3449 TYPED_LL_WALKER<BLK_0x30_STR_WRAPPER> textWalker{ aFpInstance.m_TextPtr, aFpInstance.m_Key, m_brdDb,
3451
3452 for( const BLK_0x30_STR_WRAPPER& strWrapper : textWalker )
3453 addFootprintText( *fp, fpGraphics, strWrapper, valueFieldSet );
3454
3455 // Assembly drawing
3456 LL_WALKER assemblyWalker{ aFpInstance.m_AssemblyPtr, aFpInstance.m_Key, m_brdDb };
3457
3458 for( const BLOCK_BASE* assemblyBlock : assemblyWalker )
3459 {
3460 std::vector<std::unique_ptr<BOARD_ITEM>> shapes = buildGraphicItems( *assemblyBlock, *fp );
3461
3462 for( std::unique_ptr<BOARD_ITEM>& item : shapes )
3463 {
3464 if( fpGraphics.IsFirst( item.get() ) )
3465 fp->Add( item.release() );
3466 }
3467 }
3468
3469 // Areas (courtyards, etc)
3470 LL_WALKER areaWalker{ aFpInstance.m_AreasPtr, aFpInstance.m_Key, m_brdDb };
3471
3472 // Probably don't need this as we can't have filled zone, but it's cheap
3473 ZONE_FILL_HANDLER zoneFillHandler;
3474
3475 for( const BLOCK_BASE* areaBlock : areaWalker )
3476 {
3477 std::optional<LAYER_INFO> layerInfo = tryLayerFromBlock( *areaBlock );
3478
3479 if( layerInfo.has_value() && layerIsZone( *layerInfo ) )
3480 {
3481 // Zone within a footprint - we can handle keepouts at least
3482 std::unique_ptr<ZONE> zone = buildZone( *areaBlock, {}, zoneFillHandler, *fp );
3483
3484 if( zone )
3485 fp->Add( zone.release() );
3486 }
3487 else
3488 {
3489 std::vector<std::unique_ptr<BOARD_ITEM>> shapes = buildGraphicItems( *areaBlock, *fp );
3490
3491 for( std::unique_ptr<BOARD_ITEM>& item : shapes )
3492 {
3493 // If we find shapes in the areas list, they are (presumably) filled.
3494 // Maybe there's a flag to look at rather than just assuming this?
3495 if( item->Type() == PCB_SHAPE_T )
3496 {
3497 PCB_SHAPE& shape = static_cast<PCB_SHAPE&>( *item );
3498
3499 // But in KiCad, courtyards are usually not filled even if they come in as "areas"
3500 if( shape.GetLayer() != F_CrtYd && shape.GetLayer() != B_CrtYd )
3501 shape.SetFilled( true );
3502 }
3503
3504 if( fpGraphics.IsFirst( item.get() ) )
3505 fp->Add( item.release() );
3506 }
3507 }
3508 }
3509
3510 // A net tie part has exactly two pads. Anything larger that stacks nets is more likely a source error
3511 if( fp->Pads().size() != 2 )
3512 return fp;
3513
3514 // Pads of different nets stacked on one point are a net tie, which KiCad only accepts when declared
3515 std::vector<std::set<wxString>> tieGroups;
3516
3517 for( PAD* padA : fp->Pads() )
3518 {
3519 for( PAD* padB : fp->Pads() )
3520 {
3521 if( padA->GetNetCode() <= 0 || padB->GetNetCode() <= 0 || padA->GetNetCode() == padB->GetNetCode()
3522 || padA->GetPosition() != padB->GetPosition() )
3523 {
3524 continue;
3525 }
3526
3527 bool overlaps = false;
3528
3529 for( PCB_LAYER_ID layer : LSET( padA->GetLayerSet() & padB->GetLayerSet() & LSET::AllCuMask() ).Seq() )
3530 {
3531 if( padA->GetEffectiveShape( layer )->Collide( padB->GetEffectiveShape( layer ).get() ) )
3532 {
3533 overlaps = true;
3534 break;
3535 }
3536 }
3537
3538 if( !overlaps )
3539 continue;
3540
3541 std::set<wxString> merged{ padA->GetNumber(), padB->GetNumber() };
3542
3543 for( auto it = tieGroups.begin(); it != tieGroups.end(); )
3544 {
3545 if( it->count( padA->GetNumber() ) || it->count( padB->GetNumber() ) )
3546 {
3547 merged.insert( it->begin(), it->end() );
3548 it = tieGroups.erase( it );
3549 }
3550 else
3551 {
3552 ++it;
3553 }
3554 }
3555
3556 tieGroups.push_back( std::move( merged ) );
3557 }
3558 }
3559
3560 for( const std::set<wxString>& group : tieGroups )
3561 {
3562 wxString numbers;
3563
3564 for( const wxString& number : group )
3565 {
3566 wxString escaped = number;
3567
3568 escaped.Replace( wxS( "\\" ), wxS( "\\\\" ) );
3569 escaped.Replace( wxS( "," ), wxS( "\\," ) );
3570
3571 if( !numbers.IsEmpty() )
3572 numbers += wxS( "," );
3573
3574 numbers += escaped;
3575 }
3576
3577 fp->AddNetTiePadGroup( numbers );
3578
3579 m_reporter.Report( wxString::Format( _( "Footprint %s has stacked pads on different nets and is imported as a "
3580 "net tie" ),
3581 refDesStr ),
3583 }
3584
3585 return fp;
3586}
3587
3588std::vector<std::unique_ptr<BOARD_ITEM>> BOARD_BUILDER::buildTrack( const BLK_0x05_TRACK& aTrackBlock, int aNetCode )
3589{
3590 std::vector<std::unique_ptr<BOARD_ITEM>> items;
3591
3592 // Anti-etch tracks are thermal relief patterns generated by Allegro.
3593 // These are handled by pad-level thermal relief properties instead.
3594 if( aTrackBlock.m_Layer.m_Class == LAYER_INFO::CLASS::ANTI_ETCH )
3595 {
3596 wxLogTrace( traceAllegroBuilder, "Skipping ANTI_ETCH track (class=%#04x, subclass=%#04x)",
3597 aTrackBlock.m_Layer.m_Class, aTrackBlock.m_Layer.m_Subclass );
3598 return items;
3599 }
3600
3601 const PCB_LAYER_ID layer = getLayer( aTrackBlock.m_Layer );
3602
3603 LL_WALKER segWalker{ aTrackBlock.m_FirstSegPtr, aTrackBlock.m_Key, m_brdDb };
3604
3605 for( const BLOCK_BASE* block : segWalker )
3606 {
3607 const uint8_t segType = block->GetBlockType();
3608
3609 switch( segType )
3610 {
3611 case 0x15:
3612 case 0x16:
3613 case 0x17:
3614 {
3616
3617 VECTOR2I start{ segInfo.m_StartX, segInfo.m_StartY };
3618 VECTOR2I end{ segInfo.m_EndX, segInfo.m_EndY };
3619 int width = static_cast<int>( segInfo.m_Width );
3620
3621 std::unique_ptr<PCB_TRACK> seg = std::make_unique<PCB_TRACK>( &m_board );
3622
3623 seg->SetNetCode( aNetCode );
3624 seg->SetLayer( layer );
3625
3626 seg->SetStart( scale( start ) );
3627 seg->SetEnd( scale( end ) );
3628 seg->SetWidth( scale( width ) );
3629
3630 items.push_back( std::move( seg ) );
3631 break;
3632 }
3633 case 0x01:
3634 {
3635 const BLK_0x01_ARC& arcInfo = BlockDataAs<BLK_0x01_ARC>( *block );
3636
3637 VECTOR2I start = scale( { arcInfo.m_StartX, arcInfo.m_StartY } );
3638 VECTOR2I end = scale( { arcInfo.m_EndX, arcInfo.m_EndY } );
3639 VECTOR2I c = scale( KiROUND( VECTOR2D{ arcInfo.m_CenterX, arcInfo.m_CenterY } ) );
3640 int width = scale( static_cast<int>( arcInfo.m_Width ) );
3641
3642 bool clockwise = ( arcInfo.m_SubType & 0x40 ) != 0;
3643
3644 EDA_ANGLE startAngle( start - c );
3645 EDA_ANGLE endAngle( end - c );
3646 startAngle.Normalize();
3647 endAngle.Normalize();
3648
3649 EDA_ANGLE angle = endAngle - startAngle;
3650
3651 if( clockwise && angle < ANGLE_0 )
3652 angle += ANGLE_360;
3653
3654 if( !clockwise && angle > ANGLE_0 )
3655 angle -= ANGLE_360;
3656
3657 VECTOR2I mid = start;
3658 RotatePoint( mid, c, -angle / 2.0 );
3659
3660 std::unique_ptr<PCB_ARC> arc = std::make_unique<PCB_ARC>( &m_board );
3661
3662 arc->SetNetCode( aNetCode );
3663 arc->SetLayer( layer );
3664
3665 arc->SetStart( start );
3666 arc->SetMid( mid );
3667 arc->SetEnd( end );
3668 arc->SetWidth( width );
3669
3670 items.push_back( std::move( arc ) );
3671 break;
3672 }
3673 default:
3674 wxLogTrace( traceAllegroBuilder, "Unhandled segment type in track: %#04x", segType );
3675 break;
3676 }
3677 }
3678 return items;
3679}
3680
3681
3682std::unique_ptr<BOARD_ITEM> BOARD_BUILDER::buildVia( const BLK_0x33_VIA& aViaData, int aNetCode )
3683{
3684 VECTOR2I viaPos{ aViaData.m_CoordsX, aViaData.m_CoordsY };
3685
3686 const BLK_0x1C_PADSTACK* viaPadstack = expectBlockByKey<BLK_0x1C_PADSTACK>( aViaData.m_Padstack );
3687
3688 if( !viaPadstack )
3689 return nullptr;
3690
3691 std::unique_ptr<PCB_VIA> via = std::make_unique<PCB_VIA>( &m_board );
3692 via->SetPosition( scale( viaPos ) );
3693 via->SetNetCode( aNetCode );
3694
3695 // The via size comes from the first copper layer's pad component.
3696 int viaWidth = 0;
3697
3698 if( viaPadstack->GetLayerCount() > 0 )
3699 {
3700 const ALLEGRO::PADSTACK_COMPONENT& padComp =
3702
3703 if( padComp.m_Type != PADSTACK_COMPONENT::TYPE_NULL )
3704 viaWidth = scale( padComp.m_W );
3705 }
3706
3707 const int totalCu = m_layerMapper->GetEtchLayerCount();
3708
3709 int startLayer = viaPadstack->m_StartLayer;
3710 int layerCount = viaPadstack->GetLayerCount();
3711 int endLayer = startLayer + layerCount - 1;
3712
3713 if( layerCount > 1 && layerCount < totalCu )
3714 {
3715 // Set the type before the layer pair: SanitizeLayers() snaps a THROUGH via back to
3716 // F_Cu/B_Cu and would discard the span. Reaching an outer layer makes it BLIND, else BURIED.
3717 const bool touchesOuter = ( startLayer == 0 ) || ( endLayer == totalCu - 1 );
3718
3719 via->SetViaType( touchesOuter ? VIATYPE::BLIND : VIATYPE::BURIED );
3720 via->SetLayerPair( nthCopperLayerId( startLayer, totalCu ), nthCopperLayerId( endLayer, totalCu ) );
3721 }
3722 else
3723 {
3724 via->SetViaType( VIATYPE::THROUGH );
3725 via->SetTopLayer( F_Cu );
3726 via->SetBottomLayer( B_Cu );
3727 }
3728
3729 int viaDrill = scale( viaPadstack->GetDrillSize() );
3730
3731 if( viaDrill == 0 )
3732 {
3733 viaDrill = viaWidth / 2;
3734 const wxString& padstackName = m_brdDb.GetString( viaPadstack->m_PadStr );
3735 wxLogTrace( traceAllegroBuilder, "Via at (%d, %d): no drill in padstack '%s' key %#010x, using fallback %d",
3736 aViaData.m_CoordsX, aViaData.m_CoordsY, padstackName, viaPadstack->m_Key, viaDrill );
3737 }
3738
3739 if( viaWidth <= 0 )
3740 {
3741 const wxString& padstackName = m_brdDb.GetString( viaPadstack->m_PadStr );
3742 wxLogTrace( traceAllegroBuilder, "Via at (%d, %d) in padstack '%s' key %#010x has no valid pad component, "
3743 "using drill-based fallback (%d * 2)",
3744 aViaData.m_CoordsX, aViaData.m_CoordsY, padstackName, viaPadstack->m_Key, viaDrill );
3745 viaWidth = viaDrill * 2;
3746 }
3747
3748 via->SetWidth( F_Cu, viaWidth );
3749 via->SetDrill( viaDrill );
3750
3751 return via;
3752}
3753
3754
3756{
3757 wxLogTrace( traceAllegroBuilder, "Creating tracks, vias, and other routed items" );
3758
3759 std::vector<BOARD_ITEM*> newItems;
3760
3761 // We need to walk this list again - we could do this all in createNets, but this seems tidier.
3762 TYPED_LL_WALKER<BLK_0x1B_NET> netWalker{ m_brdDb.m_Header->m_LL_0x1B_Nets, m_brdDb, MISMATCH_POLICY::REPORT };
3763 netWalker.SetMismatchReporter(
3764 [this]( uint8_t aType, const BLOCK_BASE& aBlock )
3765 {
3767 } );
3768
3769 for( const BLK_0x1B_NET& net : netWalker )
3770 {
3771 auto netIt = m_netCache.find( net.m_Key );
3772
3773 if( netIt == m_netCache.end() )
3774 continue;
3775
3776 const int netCode = netIt->second->GetNetCode();
3777
3778 TYPED_LL_WALKER<BLK_0x04_NET_ASSIGNMENT> assignmentWalker{ net.m_Assignment, net.m_Key, m_brdDb,
3780 assignmentWalker.SetMismatchReporter(
3781 [this]( uint8_t aType, const BLOCK_BASE& aBlock )
3782 {
3783 reportUnexpectedBlockType( aType, 0x04, 0, aBlock.GetOffset(), "Net assignment" );
3784 } );
3785
3786 for( const BLK_0x04_NET_ASSIGNMENT& assign : assignmentWalker )
3787 {
3788 // Walk the 0x05/0x32/... list
3789 LL_WALKER connWalker{ assign.m_ConnItem, assign.m_Key, m_brdDb };
3790
3791 for( const BLOCK_BASE* connItemBlock : connWalker )
3792 {
3793 const uint8_t connType = connItemBlock->GetBlockType();
3794
3795 // One connected item can be multiple KiCad objects, e.g.
3796 // 0x05 track -> list of segments/arcs
3797 std::vector<std::unique_ptr<BOARD_ITEM>> newItemList;
3798
3799 switch( connType )
3800 {
3801 // Track
3802 case 0x05:
3803 {
3804 const BLK_0x05_TRACK& trackData = BlockDataAs<BLK_0x05_TRACK>( *connItemBlock );
3805 newItemList = buildTrack( trackData, netCode );
3806 break;
3807 }
3808 case 0x33:
3809 {
3810 const BLK_0x33_VIA& viaData = BlockDataAs<BLK_0x33_VIA>( *connItemBlock );
3811
3812 // A via whose padstack is missing has nothing to place
3813 if( std::unique_ptr<BOARD_ITEM> via = buildVia( viaData, netCode ) )
3814 newItemList.push_back( std::move( via ) );
3815
3816 break;
3817 }
3818 case 0x32:
3819 {
3820 // This is a pad in a footprint - we don't need to handle this here, as we do all the footprint
3821 // pads, connected or not, in the footprint step.
3822 break;
3823 }
3824 case 0x28:
3825 {
3826 // 0x28 shapes on the net chain are computed copper fills.
3827 // Collect them for teardrop and polygon import.
3828 const BLK_0x28_SHAPE& fillShape = BlockDataAs<BLK_0x28_SHAPE>( *connItemBlock );
3829
3830 PCB_LAYER_ID fillLayer = getLayer( fillShape.m_Layer );
3831
3832 if( fillLayer != UNDEFINED_LAYER )
3833 m_zoneFillShapes[fillShape.m_Key] = { &fillShape, netCode, fillLayer };
3834
3835 break;
3836 }
3837 case 0x2E:
3838 default:
3839 wxLogTrace( traceAllegroBuilder, " Unhandled connected item code: %#04x", (int) connType );
3840 }
3841
3842 uint32_t idSeq = 0;
3843
3844 for( std::unique_ptr<BOARD_ITEM>& newItem : newItemList )
3845 {
3846 stampIds( *newItem, connItemBlock->GetKey(), idSeq );
3847 newItems.push_back( newItem.get() );
3848 m_board.Add( newItem.release(), ADD_MODE::BULK_APPEND, true );
3849 }
3850 }
3851 }
3852 }
3853
3854 m_board.FinalizeBulkAdd( newItems );
3855
3856 wxLogTrace( traceAllegroBuilder, "Finished creating %zu track/via items", newItems.size() );
3857}
3858
3859
3861{
3862 wxLogTrace( traceAllegroBuilder, "Creating shapes" );
3863
3864 // Walk through LL_0x24_0x28 which contains rectangles (0x24) and shapes (0x28)
3865 const LL_WALKER shapeWalker( m_brdDb.m_Header->m_LL_0x24_0x28, m_brdDb );
3866 int blockCount = 0;
3867
3868 std::vector<std::unique_ptr<BOARD_ITEM>> newItems;
3869
3870 for( const BLOCK_BASE* block : shapeWalker )
3871 {
3872 blockCount++;
3873
3874 switch( block->GetBlockType() )
3875 {
3876 case 0x24:
3877 {
3878 const BLK_0x24_RECT& rectData = BlockDataAs<BLK_0x24_RECT>( *block );
3879
3880 // These are zones, we don't handle them here
3881 if( layerIsZone( rectData.m_Layer ) )
3882 continue;
3883
3884 std::unique_ptr<PCB_SHAPE> rectShape = buildRect( rectData, m_board );
3885 stampIds( *rectShape, rectData.m_Key );
3886 newItems.push_back( std::move( rectShape ) );
3887 break;
3888 }
3889 case 0x28:
3890 {
3891 const BLK_0x28_SHAPE& shapeData = BlockDataAs<BLK_0x28_SHAPE>( *block );
3892
3893 // These are zones, we don't handle them here
3894 if( layerIsZone( shapeData.m_Layer ) )
3895 continue;
3896
3897 std::vector<std::unique_ptr<PCB_SHAPE>> shapeItems = buildPolygonShapes( shapeData, m_board );
3898 uint32_t idSeq = 0;
3899
3900 for( std::unique_ptr<PCB_SHAPE>& shapeItem : shapeItems )
3901 {
3902 stampIds( *shapeItem, shapeData.m_Key, idSeq );
3903 newItems.push_back( std::move( shapeItem ) );
3904 }
3905
3906 break;
3907 }
3908 default:
3909 wxLogTrace( traceAllegroBuilder, " Unhandled block type in outline walker: %#04x", block->GetBlockType() );
3910 break;
3911 }
3912 }
3913
3914 wxLogTrace( traceAllegroBuilder, " Found %d shape blocks", blockCount, newItems.size() );
3915 blockCount = 0;
3916
3917 LL_WALKER outline2Walker( m_brdDb.m_Header->m_LL_Shapes, m_brdDb );
3918
3919 for( const BLOCK_BASE* block : outline2Walker )
3920 {
3921 blockCount++;
3922
3923 switch( block->GetBlockType() )
3924 {
3925 case 0x0E:
3926 {
3927 const BLK_0x0E_RECT& rectData = BlockDataAs<BLK_0x0E_RECT>( *block );
3928
3929 if( layerIsZone( rectData.m_Layer ) )
3930 continue;
3931
3932 std::unique_ptr<PCB_SHAPE> rectShape = buildRect( rectData, m_board );
3933 stampIds( *rectShape, rectData.m_Key );
3934 newItems.push_back( std::move( rectShape ) );
3935 break;
3936 }
3937 case 0x24:
3938 {
3939 const BLK_0x24_RECT& rectData = BlockDataAs<BLK_0x24_RECT>( *block );
3940
3941 if( layerIsZone( rectData.m_Layer ) )
3942 continue;
3943
3944 std::unique_ptr<PCB_SHAPE> rectShape = buildRect( rectData, m_board );
3945 stampIds( *rectShape, rectData.m_Key );
3946 newItems.push_back( std::move( rectShape ) );
3947 break;
3948 }
3949 case 0x28:
3950 {
3951 const BLK_0x28_SHAPE& shapeData = BlockDataAs<BLK_0x28_SHAPE>( *block );
3952
3953 if( layerIsZone( shapeData.m_Layer ) )
3954 continue;
3955
3956 std::vector<std::unique_ptr<PCB_SHAPE>> shapeItems = buildPolygonShapes( shapeData, m_board );
3957 uint32_t idSeq = 0;
3958
3959 for( std::unique_ptr<PCB_SHAPE>& shapeItem : shapeItems )
3960 {
3961 stampIds( *shapeItem, shapeData.m_Key, idSeq );
3962 newItems.push_back( std::move( shapeItem ) );
3963 }
3964 break;
3965 }
3966 default:
3967 wxLogTrace( traceAllegroBuilder, " Unhandled block type in outline walker: %#04x", block->GetBlockType() );
3968 break;
3969 }
3970 }
3971
3972 wxLogTrace( traceAllegroBuilder, " Found %d outline items in m_LL_Shapes", blockCount );
3973 blockCount = 0;
3974
3975 TYPED_LL_WALKER<BLK_0x14_GRAPHIC> graphicContainerWalker( m_brdDb.m_Header->m_LL_0x14, m_brdDb,
3977
3978 for( const BLK_0x14_GRAPHIC& graphicContainer : graphicContainerWalker )
3979 {
3980 blockCount++;
3981
3982 if( layerIsZone( graphicContainer.m_Layer ) )
3983 continue;
3984
3985 std::vector<std::unique_ptr<PCB_SHAPE>> graphicItems = buildShapes( graphicContainer, m_board );
3986 uint32_t idSeq = 0;
3987
3988 for( std::unique_ptr<PCB_SHAPE>& item : graphicItems )
3989 {
3990 stampIds( *item, graphicContainer.m_Key, idSeq );
3991 newItems.push_back( std::move( item ) );
3992 }
3993 }
3994
3995 wxLogTrace( traceAllegroBuilder, " Found %d graphic container items", blockCount );
3996
3997 std::vector<BOARD_ITEM*> addedItems;
3998 int dropped = 0;
3999
4000 for( std::unique_ptr<BOARD_ITEM>& item : newItems )
4001 {
4002 if( !m_boardGraphics.IsFirst( item.get() ) )
4003 {
4004 dropped++;
4005 continue;
4006 }
4007
4008 addedItems.push_back( item.get() );
4009 m_board.Add( item.release(), ADD_MODE::BULK_APPEND, true );
4010 }
4011
4012 m_board.FinalizeBulkAdd( addedItems );
4013
4014 if( dropped > 0 )
4015 wxLogTrace( traceAllegroBuilder, "Dropped %d coincident board graphics", dropped );
4016
4017 wxLogTrace( traceAllegroBuilder, "Created %zu board shapes", addedItems.size() );
4018}
4019
4020
4021SHAPE_LINE_CHAIN BOARD_BUILDER::buildSegmentChain( uint32_t aStartKey, const TRANSFORM_TRS& aXform ) const
4022{
4023 const bool cacheable = aXform.IsIdentity();
4024
4025 if( cacheable )
4026 {
4027 auto cacheIt = m_segChainCache.find( aStartKey );
4028
4029 if( cacheIt != m_segChainCache.end() )
4030 return cacheIt->second;
4031 }
4032
4033 SHAPE_LINE_CHAIN localOutline;
4034 SHAPE_LINE_CHAIN& outline = cacheable ? m_segChainCache[aStartKey] : localOutline;
4035 uint32_t currentKey = aStartKey;
4036
4037 // Safety limit to prevent infinite loops on corrupt data
4038 static constexpr int MAX_CHAIN_LENGTH = 50000;
4039 int visited = 0;
4040
4041 while( currentKey != 0 && visited < MAX_CHAIN_LENGTH )
4042 {
4043 const BLOCK_BASE* block = m_brdDb.GetObjectByKey( currentKey );
4044
4045 if( !block )
4046 break;
4047
4048 visited++;
4049
4050 switch( block->GetBlockType() )
4051 {
4052 case 0x01:
4053 {
4054 const auto& arc = BlockDataAs<BLK_0x01_ARC>( *block );
4055 VECTOR2I start = scale( { arc.m_StartX, arc.m_StartY } );
4056 VECTOR2I end = scale( { arc.m_EndX, arc.m_EndY } );
4057 VECTOR2I center = scale( KiROUND( VECTOR2D{ arc.m_CenterX, arc.m_CenterY } ) );
4058
4059 if( start == end )
4060 {
4061 center = aXform.InverseApply( center );
4062 start = aXform.InverseApply( start );
4063
4064 SHAPE_ARC shapeArc( center, start, ANGLE_360 );
4065 outline.Append( shapeArc );
4066 }
4067 else
4068 {
4069 bool clockwise = ( arc.m_SubType & 0x40 ) != 0;
4070
4071 EDA_ANGLE startAngle( start - center );
4072 EDA_ANGLE endAngle( end - center );
4073 startAngle.Normalize();
4074 endAngle.Normalize();
4075
4076 EDA_ANGLE arcAngle = endAngle - startAngle;
4077
4078 if( clockwise && arcAngle < ANGLE_0 )
4079 arcAngle += ANGLE_360;
4080
4081 if( !clockwise && arcAngle > ANGLE_0 )
4082 arcAngle -= ANGLE_360;
4083
4084 VECTOR2I mid = start;
4085 RotatePoint( mid, center, -arcAngle / 2.0 );
4086
4087 start = aXform.InverseApply( start );
4088 mid = aXform.InverseApply( mid );
4089 end = aXform.InverseApply( end );
4090
4091 SHAPE_ARC shapeArc( start, mid, end, 0 );
4092 outline.Append( shapeArc );
4093 }
4094
4095 currentKey = arc.m_Next;
4096 break;
4097 }
4098 case 0x15:
4099 case 0x16:
4100 case 0x17:
4101 {
4102 const auto& seg = BlockDataAs<BLK_0x15_16_17_SEGMENT>( *block );
4103 VECTOR2I start = aXform.InverseApply( scale( { seg.m_StartX, seg.m_StartY } ) );
4104
4105 if( outline.PointCount() == 0 || outline.CLastPoint() != start )
4106 outline.Append( start );
4107
4108 VECTOR2I end = aXform.InverseApply( scale( { seg.m_EndX, seg.m_EndY } ) );
4109 outline.Append( end );
4110 currentKey = seg.m_Next;
4111 break;
4112 }
4113 default:
4114 currentKey = 0;
4115 break;
4116 }
4117 }
4118
4119 return outline;
4120}
4121
4122
4124{
4125 SHAPE_LINE_CHAIN outline;
4126
4127 VECTOR2I topLeft = scale( VECTOR2I{ aRect.m_Coords[0], aRect.m_Coords[1] } );
4128 VECTOR2I botRight = scale( VECTOR2I{ aRect.m_Coords[2], aRect.m_Coords[3] } );
4129 VECTOR2I topRight{ botRight.x, topLeft.y };
4130 VECTOR2I botLeft{ topLeft.x, botRight.y };
4131
4132 outline.Append( topLeft );
4133 outline.Append( topRight );
4134 outline.Append( botRight );
4135 outline.Append( botLeft );
4136
4137 const EDA_ANGLE angle = fromMillidegrees( aRect.m_Rotation );
4138 outline.Rotate( angle, topLeft );
4139
4140 for( int i = 0; i < outline.PointCount(); i++ )
4141 outline.SetPoint( i, aXform.InverseApply( outline.CPoint( i ) ) );
4142
4143 return outline;
4144}
4145
4146
4148{
4149 SHAPE_LINE_CHAIN outline;
4150
4151 VECTOR2I topLeft = scale( VECTOR2I{ aRect.m_Coords[0], aRect.m_Coords[1] } );
4152 VECTOR2I botRight = scale( VECTOR2I{ aRect.m_Coords[2], aRect.m_Coords[3] } );
4153 VECTOR2I topRight{ botRight.x, topLeft.y };
4154 VECTOR2I botLeft{ topLeft.x, botRight.y };
4155
4156 outline.Append( topLeft );
4157 outline.Append( topRight );
4158 outline.Append( botRight );
4159 outline.Append( botLeft );
4160
4161 const EDA_ANGLE angle = fromMillidegrees( aRect.m_Rotation );
4162 outline.Rotate( angle, topLeft );
4163
4164 for( int i = 0; i < outline.PointCount(); i++ )
4165 outline.SetPoint( i, aXform.InverseApply( outline.CPoint( i ) ) );
4166
4167 return outline;
4168}
4169
4170
4172{
4173 return buildSegmentChain( aShape.m_FirstSegmentPtr, aXform );
4174}
4175
4176
4178{
4179 SHAPE_POLY_SET polySet;
4180 SHAPE_LINE_CHAIN outline = buildSegmentChain( aShape.m_FirstSegmentPtr, aXform );
4181
4182 if( outline.PointCount() < 3 )
4183 {
4184 wxLogTrace( traceAllegroBuilder, " Not enough points for polygon (%d)", outline.PointCount() );
4185 return polySet;
4186 }
4187
4188 outline.SetClosed( true );
4189 polySet.AddOutline( outline );
4190
4191 // Walk 0x34 KEEPOUT chain from m_Ptr4 for holes
4192 uint32_t holeKey = aShape.m_FirstKeepoutPtr;
4193
4194 while( holeKey != 0 )
4195 {
4196 const BLOCK_BASE* holeBlock = m_brdDb.GetObjectByKey( holeKey );
4197
4198 if( !holeBlock || holeBlock->GetBlockType() != 0x34 )
4199 break;
4200
4201 const auto& keepout = BlockDataAs<BLK_0x34_KEEPOUT>( *holeBlock );
4202
4203 SHAPE_LINE_CHAIN holeOutline = buildSegmentChain( keepout.m_FirstSegmentPtr, aXform );
4204
4205 if( holeOutline.PointCount() >= 3 )
4206 {
4207 holeOutline.SetClosed( true );
4208 polySet.AddHole( holeOutline );
4209 }
4210
4211 holeKey = keepout.m_Next;
4212 }
4213
4214 return polySet;
4215}
4216
4217
4219 const TRANSFORM_TRS& aXform ) const
4220{
4221 SHAPE_POLY_SET polySet;
4222
4223 switch( aBlock.GetBlockType() )
4224 {
4225 case 0x0E:
4226 {
4227 const auto& rectData = BlockDataAs<BLK_0x0E_RECT>( aBlock );
4228
4229 SHAPE_LINE_CHAIN chain( buildOutline( rectData, aXform ) );
4230 chain.SetClosed( true );
4231
4232 polySet = SHAPE_POLY_SET( chain );
4233 break;
4234 }
4235 case 0x14:
4236 {
4237 const auto& graphicContainer = BlockDataAs<BLK_0x14_GRAPHIC>( aBlock );
4238
4239 SHAPE_LINE_CHAIN chain = buildSegmentChain( graphicContainer.m_SegmentPtr, aXform );
4240 chain.SetClosed( true );
4241
4242 polySet = SHAPE_POLY_SET( chain );
4243 break;
4244 }
4245 case 0x24:
4246 {
4247 const auto& rectData = BlockDataAs<BLK_0x24_RECT>( aBlock );
4248
4249 SHAPE_LINE_CHAIN chain( buildOutline( rectData, aXform ) );
4250 chain.SetClosed( true );
4251
4252 polySet = SHAPE_POLY_SET( chain );
4253 break;
4254 }
4255 case 0x28:
4256 {
4257 const auto& shapeData = BlockDataAs<BLK_0x28_SHAPE>( aBlock );
4258 polySet = shapeToPolySet( shapeData, aXform );
4259 break;
4260 }
4261 default:
4262 wxLogTrace( traceAllegroBuilder, " Unhandled block type in tryBuildZoneShape: %#04x", aBlock.GetBlockType() );
4263 }
4264
4265 return polySet;
4266}
4267
4268
4269std::unique_ptr<ZONE> BOARD_BUILDER::buildZone( const BLOCK_BASE& aBoundaryBlock,
4270 const std::vector<const BLOCK_BASE*>& aRelatedBlocks,
4271 ZONE_FILL_HANDLER& aZoneFillHandler, BOARD_ITEM_CONTAINER& aParent )
4272{
4273 int netCode = NETINFO_LIST::UNCONNECTED;
4274 const LAYER_INFO layerInfo = expectLayerFromBlock( aBoundaryBlock );
4275
4276 bool isCopperZone = ( layerInfo.m_Class == LAYER_INFO::CLASS::ETCH
4277 || layerInfo.m_Class == LAYER_INFO::CLASS::BOUNDARY );
4278
4280
4281 if( isCopperZone )
4282 {
4283 // BOUNDARY shares the ETCH layer list, so resolve subclass via ETCH class
4284 if( layerInfo.m_Class == LAYER_INFO::CLASS::BOUNDARY )
4285 {
4286 LAYER_INFO etchLayer{};
4287 etchLayer.m_Class = LAYER_INFO::CLASS::ETCH;
4288 etchLayer.m_Subclass = layerInfo.m_Subclass;
4289 layer = getLayer( etchLayer );
4290 }
4291 else
4292 {
4293 layer = getLayer( layerInfo );
4294 }
4295 }
4296 else
4297 {
4298 layer = F_Cu;
4299 }
4300
4301 if( isCopperZone && layer == UNDEFINED_LAYER )
4302 {
4303 wxLogTrace( traceAllegroBuilder, " Skipping shape on layer %#02x:%#02x - unmapped copper layer",
4304 layerInfo.m_Class, layerInfo.m_Subclass );
4305 return nullptr;
4306 }
4307
4308 // Allegro area geometry is board-absolute. Footprint zones store local outlines,
4309 // so undo the parent footprint transform when one is present.
4310 TRANSFORM_TRS xform;
4311
4312 if( FOOTPRINT* fp = dynamic_cast<FOOTPRINT*>( &aParent ) )
4313 xform = fp->GetTransform();
4314
4315 SHAPE_POLY_SET zoneShape = tryBuildZoneShape( aBoundaryBlock, xform );
4316
4317 if( zoneShape.OutlineCount() != 1 )
4318 {
4319 wxLogTrace( traceAllegroBuilder, " Skipping zone with type %#04x, key %#010x - failed to build outline",
4320 aBoundaryBlock.GetBlockType(), aBoundaryBlock.GetKey() );
4321 return nullptr;
4322 }
4323
4324 std::unique_ptr<ZONE> zone = std::make_unique<ZONE>( &aParent );
4325 zone->SetHatchStyle( ZONE_BORDER_DISPLAY_STYLE::NO_HATCH );
4326
4327 if( isCopperZone )
4328 {
4329 zone->SetLayer( layer );
4330 zone->SetFillMode( ZONE_FILL_MODE::POLYGONS );
4331 }
4332 else
4333 {
4334 LSET layerSet = m_layerMapper->GetRuleAreaLayers( layerInfo );
4335
4336 bool isRouteKeepout = ( layerInfo.m_Class == LAYER_INFO::CLASS::ROUTE_KEEPOUT );
4337 bool isViaKeepout = ( layerInfo.m_Class == LAYER_INFO::CLASS::VIA_KEEPOUT );
4338 bool isPackageKeepout = ( layerInfo.m_Class == LAYER_INFO::CLASS::PACKAGE_KEEPOUT );
4339 bool isRouteKeepin = ( layerInfo.m_Class == LAYER_INFO::CLASS::ROUTE_KEEPIN );
4340 bool isPackageKeepin = ( layerInfo.m_Class == LAYER_INFO::CLASS::PACKAGE_KEEPIN );
4341
4342 zone->SetIsRuleArea( true );
4343 zone->SetLayerSet( layerSet );
4344 zone->SetDoNotAllowTracks( isRouteKeepout );
4345 zone->SetDoNotAllowVias( isViaKeepout );
4346 zone->SetDoNotAllowZoneFills( isRouteKeepout || isViaKeepout );
4347 zone->SetDoNotAllowPads( false );
4348 zone->SetDoNotAllowFootprints( isPackageKeepout );
4349
4350 // Zones don't have native keepin functions, so we leave a note for the user here
4351 // Later, we could consider adding a custom DRC rule for this (or KiCad could add native keepin
4352 // zone support)
4353 if( isRouteKeepin )
4354 zone->SetZoneName( "Route Keepin" );
4355 else if( isPackageKeepin )
4356 zone->SetZoneName( "Package Keepin" );
4357 }
4358
4359 SHAPE_POLY_SET combinedFill;
4360
4361 for( const BLOCK_BASE* block : aRelatedBlocks )
4362 {
4363 if( !block )
4364 continue;
4365
4366 switch( block->GetBlockType() )
4367 {
4368 case 0x1B:
4369 {
4370 const auto it = m_netCache.find( block->GetKey() );
4371
4372 if( it != m_netCache.end() )
4373 {
4374 wxLogTrace( traceAllegroBuilder, " Resolved BOUNDARY %#010x -> net '%s' (code %d)",
4375 aBoundaryBlock.GetKey(), it->second->GetNetname(), it->second->GetNetCode() );
4376
4377 netCode = it->second->GetNetCode();
4378 }
4379 else
4380 {
4381 m_reporter.Report( wxString::Format( "Could not find net key %#010x in cache for BOUNDARY %#010x",
4382 block->GetKey(), aBoundaryBlock.GetKey() ),
4384 }
4385 break;
4386 }
4387 case 0x28:
4388 {
4389 const BLK_0x28_SHAPE& shapeData = BlockDataAs<BLK_0x28_SHAPE>( *block );
4390
4391 SHAPE_POLY_SET fillPolySet = shapeToPolySet( shapeData, xform );
4392 combinedFill.Append( fillPolySet );
4393 m_usedZoneFillShapes.emplace( block->GetKey() );
4394 break;
4395 }
4396 default: break;
4397 }
4398 }
4399
4400 // Set net code AFTER layer assignment. SetNetCode checks IsOnCopperLayer() and
4401 // forces net=0 if the zone isn't on a copper layer yet.
4402 zone->SetNetCode( netCode );
4403
4404 for( const SHAPE_LINE_CHAIN& chain : zoneShape.CPolygon( 0 ) )
4405 zone->AddPolygon( chain );
4406
4407 // Add zone fills
4408 if( isCopperZone && !combinedFill.IsEmpty() )
4409 {
4410 // We don't do this here, though it feels like we should. We collect the
4411 // information for batch processing later on (which is conceptually
4412 // easier to parallelise compared to this function). But there is room
4413 // for improvement by threading more of this work: shapeToPolySet
4414 // accounts for about 40% of the remaining single-threaded time in the
4415 // building process.
4416
4417 // combinedFill.ClearArcs();
4418 // zoneOutline.ClearArcs();
4419 // combinedFill.BooleanIntersection( zoneOutline );
4420 // zone->SetFilledPolysList( layer, combinedFill );
4421
4422 zone->SetIsFilled( true );
4423 zone->SetNeedRefill( false );
4424
4425 // Poke these relevant context in here for batch processing later on
4426 aZoneFillHandler.QueuePolygonForZone( *zone, std::move( combinedFill ), layer );
4427 }
4428
4429 return zone;
4430}
4431
4432
4433std::vector<const BLOCK_BASE*> BOARD_BUILDER::getShapeRelatedBlocks( const BLK_0x28_SHAPE& aShape ) const
4434{
4435 // Follow pointer chain: BOUNDARY.TablePtr -> 0x2C TABLE -> Ptr1 -> 0x37 -> m_Ptrs
4436 std::vector<const BLOCK_BASE*> ret;
4437 uint32_t tableKey = aShape.GetTablePtr();
4438
4439 if( tableKey == 0 )
4440 return ret;
4441
4442 const BLK_0x2C_TABLE* tbl = expectBlockByKey<BLK_0x2C_TABLE>( tableKey );
4443
4444 if( !tbl )
4445 return ret;
4446
4448
4449 if( !ptrArray || ptrArray->m_Count == 0 )
4450 return ret;
4451
4452 const size_t count = std::min<size_t>( ptrArray->m_Count, ptrArray->m_Ptrs.size() );
4453 ret.resize( count );
4454
4455 for( size_t i = 0; i < count; i++ )
4456 ret[i] = m_brdDb.GetObjectByKey( ptrArray->m_Ptrs[i] );
4457
4458 return ret;
4459}
4460
4461
4463{
4464 TYPED_LL_WALKER<BLK_0x30_STR_WRAPPER> textWalker( m_brdDb.m_Header->m_LL_0x03_0x30, m_brdDb );
4465 int textCount = 0;
4466
4467 for( const BLK_0x30_STR_WRAPPER& strWrapper : textWalker )
4468 {
4469 std::unique_ptr<PCB_TEXT> text = buildPcbText( strWrapper, m_board );
4470
4471 if( !text )
4472 continue;
4473
4474 // If the text is referenced from a group, it's not board-level text,
4475 // and we'll pick up up while iterating the group elsewhere.
4476 if( strWrapper.GetGroupPtr() != 0 )
4477 {
4478 // In a group
4479 continue;
4480 }
4481
4482 wxLogTrace( traceAllegroBuilder, " Board text '%s' on layer %s at (%d, %d)", text->GetText(),
4483 m_board.GetLayerName( text->GetLayer() ), text->GetPosition().x, text->GetPosition().y );
4484
4485 if( !m_boardGraphics.IsFirst( text.get() ) )
4486 continue;
4487
4488 stampIds( *text, strWrapper.m_Key );
4489 m_board.Add( text.release(), ADD_MODE::APPEND );
4490 textCount++;
4491 }
4492
4493 wxLogTrace( traceAllegroBuilder, "Created %d board-level text objects", textCount );
4494}
4495
4496
4497template <std::derived_from<BOARD_ITEM> T>
4498void BulkAddToBoard( BOARD& aBoard, std::vector<std::unique_ptr<T>>&& aItems )
4499{
4500 std::vector<BOARD_ITEM*> rawPointers;
4501 rawPointers.reserve( aItems.size() );
4502
4503 for( std::unique_ptr<T>& item : aItems )
4504 {
4505 rawPointers.push_back( item.get() );
4506 aBoard.Add( item.release(), ADD_MODE::BULK_APPEND, true );
4507 }
4508
4509 aBoard.FinalizeBulkAdd( rawPointers );
4510}
4511
4512
4514{
4515 wxLogTrace( traceAllegroBuilder, "Creating zones from m_LL_Shapes and m_LL_0x24_0x28" );
4516
4517 std::vector<std::unique_ptr<ZONE>> newZones;
4518 std::vector<std::unique_ptr<ZONE>> keepoutZones;
4519
4520 ZONE_FILL_HANDLER zoneFillHandler;
4521
4522 // Walk m_LL_Shapes to find BOUNDARY shapes (zone outlines).
4523 // BOUNDARY shapes use class 0x15 with copper layer subclass indices.
4524 const LL_WALKER shapeWalker( m_brdDb.m_Header->m_LL_Shapes, m_brdDb );
4525
4526 for( const BLOCK_BASE* block : shapeWalker )
4527 {
4528 std::unique_ptr<ZONE> zone;
4529 LAYER_INFO layerInfo{};
4530
4531 switch( block->GetBlockType() )
4532 {
4533 case 0x0e:
4534 {
4535 const BLK_0x0E_RECT& rectData = BlockDataAs<BLK_0x0E_RECT>( *block );
4536
4537 if( !layerIsZone( rectData.m_Layer ) )
4538 continue;
4539
4540 zone = buildZone( *block, {}, zoneFillHandler, m_board );
4541 layerInfo = rectData.m_Layer;
4542 break;
4543 }
4544 case 0x24:
4545 {
4546 const BLK_0x24_RECT& rectData = BlockDataAs<BLK_0x24_RECT>( *block );
4547
4548 if( !layerIsZone( rectData.m_Layer ) )
4549 continue;
4550
4551 zone = buildZone( *block, {}, zoneFillHandler, m_board );
4552 layerInfo = rectData.m_Layer;
4553 break;
4554 }
4555 case 0x28:
4556 {
4557 const BLK_0x28_SHAPE& shapeData = BlockDataAs<BLK_0x28_SHAPE>( *block );
4558
4559 if( !layerIsZone( shapeData.m_Layer ) )
4560 continue;
4561
4562 zone = buildZone( *block, getShapeRelatedBlocks( shapeData ), zoneFillHandler, m_board );
4563 layerInfo = shapeData.m_Layer;
4564 break;
4565 }
4566 default:
4567 {
4568 wxLogTrace( traceAllegroBuilder, "Unhandled block type in zone shape walker: %#04x, key: %#010x",
4569 block->GetBlockType(), block->GetKey() );
4570 break;
4571 }
4572 }
4573
4574 if( zone )
4575 {
4576 wxLogTrace( traceAllegroBuilder, " Zone %#010x net=%d layer=%s class=%#04x:%#04x", block->GetKey(),
4577 zone->GetNetCode(), m_board.GetLayerName( zone->GetFirstLayer() ), layerInfo.m_Class,
4578 layerInfo.m_Subclass );
4579
4580 stampIds( *zone, block->GetKey() );
4581 newZones.push_back( std::move( zone ) );
4582 }
4583 }
4584
4585 // Walk m_LL_0x24_0x28 for keepout/in shapes
4586 const LL_WALKER keepoutWalker( m_brdDb.m_Header->m_LL_0x24_0x28, m_brdDb );
4587
4588 for( const BLOCK_BASE* block : keepoutWalker )
4589 {
4590 std::unique_ptr<ZONE> zone;
4591
4592 switch( block->GetBlockType() )
4593 {
4594 case 0x24:
4595 {
4596 const BLK_0x24_RECT& rectData = BlockDataAs<BLK_0x24_RECT>( *block );
4597
4598 if( !layerIsZone( rectData.m_Layer ) )
4599 continue;
4600
4601 wxLogTrace( traceAllegroBuilder, " Processing %s rect %#010x", layerInfoDisplayName( rectData.m_Layer ),
4602 rectData.m_Key );
4603
4604 zone = buildZone( *block, {}, zoneFillHandler, m_board );
4605 break;
4606 }
4607 case 0x28:
4608 {
4609 const BLK_0x28_SHAPE& shapeData = BlockDataAs<BLK_0x28_SHAPE>( *block );
4610
4611 if( !layerIsZone( shapeData.m_Layer ) )
4612 continue;
4613
4614 wxLogTrace( traceAllegroBuilder, " Processing %s shape %#010x", layerInfoDisplayName( shapeData.m_Layer ),
4615 shapeData.m_Key );
4616
4617 zone = buildZone( *block, {}, zoneFillHandler, m_board );
4618 break;
4619 }
4620 default:
4621 break;
4622 }
4623
4624 if( zone )
4625 {
4626 stampIds( *zone, block->GetKey() );
4627 newZones.push_back( std::move( zone ) );
4628 }
4629 }
4630
4631 // Deal with all the collected zone fill polygons now, all at once
4632 zoneFillHandler.ProcessPolygons( true );
4633
4634 int originalCount = newZones.size();
4635
4636 // Merge zones with identical polygons and same net into multi-layer zones.
4637 // Allegro often defines the same zone outline on multiple copper layers (e.g.
4638 // a ground pour spanning all layers). KiCad represents this as a single zone
4639 // with multiple fill layers.
4640 //
4641 // Rule areas (keepouts) can also merge.
4642 std::vector<std::unique_ptr<ZONE>> mergedZones = MergeZonesWithSameOutline( std::move( newZones ) );
4643 int mergedCount = mergedZones.size();
4644
4645 int keepoutCount = 0;
4646 int boundaryCount = 0;
4647
4648 for( const std::unique_ptr<ZONE>& zone : mergedZones )
4649 {
4650 if( zone->GetIsRuleArea() )
4651 keepoutCount++;
4652 else
4653 boundaryCount++;
4654 }
4655
4656 BulkAddToBoard( m_board, std::move( mergedZones ) );
4657
4658 wxLogTrace( traceAllegroBuilder, "Created %d zone outlines and %d keepout areas (%d merged away), ", boundaryCount,
4659 keepoutCount, originalCount - mergedCount );
4660}
4661
4662
4664{
4665 for( auto& [layer, voids] : m_planeVoids )
4666 {
4667 voids.Simplify();
4668
4669 if( voids.IsEmpty() )
4670 continue;
4671
4672 // A zone saves only its first polygon, so every separate void gets an area of its own
4673 for( const SHAPE_POLY_SET::POLYGON& polygon : voids.CPolygons() )
4674 {
4675 std::unique_ptr<ZONE> area = std::make_unique<ZONE>( &m_board );
4676
4677 area->SetIsRuleArea( true );
4678 area->SetLayerSet( LSET( { layer } ) );
4679 area->SetDoNotAllowZoneFills( true );
4680 area->SetDoNotAllowTracks( false );
4681 area->SetDoNotAllowVias( false );
4682 area->SetDoNotAllowPads( false );
4683 area->SetDoNotAllowFootprints( false );
4684 area->SetZoneName( wxS( "Plane void" ) );
4685 area->SetHatchStyle( ZONE_BORDER_DISPLAY_STYLE::NO_HATCH );
4686 *area->Outline() = SHAPE_POLY_SET( polygon );
4687
4688 m_board.Add( area.release() );
4689 }
4690 }
4691
4692 m_planeVoids.clear();
4693}
4694
4695
4697{
4698 wxLogTrace( traceAllegroBuilder, "Creating tables from m_LL_0x2C" );
4699
4700 TYPED_LL_WALKER<BLK_0x2C_TABLE> tableWalker( m_brdDb.m_Header->m_LL_0x2C, m_brdDb );
4701 for( const BLK_0x2C_TABLE& tableData : tableWalker )
4702 {
4703 if( tableData.m_SubType != BLK_0x2C_TABLE::SUBTYPE::SUBTYPE_GRAPHICAL_GROUP )
4704 {
4705 // 0x2c tables can have lots of subtypes. Only 0x110 seems useful to iterate in this way for now.
4706 continue;
4707 }
4708
4709 const wxString& tableName = m_brdDb.GetString( tableData.m_StringPtr );
4710
4711 std::vector<std::unique_ptr<BOARD_ITEM>> newItems;
4712
4713 LL_WALKER keyTableWalker{ tableData.m_Ptr1, tableData.m_Key, m_brdDb };
4714
4715 for( const BLOCK_BASE* keyTable : keyTableWalker )
4716 {
4717 wxLogTrace( traceAllegroBuilder, " Table '%s' (key %#010x, table block key %#010x)", tableName,
4718 tableData.m_Key, tableData.m_Ptr1 );
4719
4720 if( !keyTable )
4721 {
4722 wxLogTrace( traceAllegroBuilder, " Key table pointer %#010x is invalid", tableData.m_Ptr1 );
4723 continue;
4724 }
4725
4726 switch( keyTable->GetBlockType() )
4727 {
4728 case 0x37:
4729 {
4730 const BLK_0x37_PTR_ARRAY& ptrArray = BlockDataAs<BLK_0x37_PTR_ARRAY>( *keyTable );
4731
4732 uint32_t count = std::min( ptrArray.m_Count, static_cast<uint32_t>( ptrArray.m_Ptrs.size() ) );
4733
4734 wxLogTrace( traceAllegroBuilder, " Pointer array with %zu entries", static_cast<size_t>( count ) );
4735
4736 for( uint32_t ptrIndex = 0; ptrIndex < count; ptrIndex++ )
4737 {
4738 uint32_t ptrKey = ptrArray.m_Ptrs[ptrIndex];
4739
4740 if( ptrKey == 0 )
4741 continue;
4742
4743 const BLOCK_BASE* entryBlock = m_brdDb.GetObjectByKey( ptrKey );
4744
4745 if( !entryBlock )
4746 {
4747 wxLogTrace( traceAllegroBuilder, " Entry pointer %#010x is invalid", ptrKey );
4748 continue;
4749 }
4750
4751 for( std::unique_ptr<BOARD_ITEM>& newItem : buildGraphicItems( *entryBlock, m_board ) )
4752 {
4753 if( m_boardGraphics.IsFirst( newItem.get() ) )
4754 newItems.push_back( std::move( newItem ) );
4755 }
4756 }
4757
4758 break;
4759 }
4760 case 0x3c:
4761 {
4762 const BLK_0x3C_KEY_LIST& keyList = BlockDataAs<BLK_0x3C_KEY_LIST>( *keyTable );
4763
4764 wxLogTrace( traceAllegroBuilder, " Key list with %zu entries",
4765 static_cast<size_t>( keyList.m_NumEntries ) );
4766 break;
4767 }
4768 default:
4769 {
4770 wxLogTrace( traceAllegroBuilder, " Table has unhandled key table type %#04x",
4771 keyTable->GetBlockType() );
4772 break;
4773 }
4774 }
4775 }
4776
4777 if( newItems.size() > 0 )
4778 {
4779 wxLogTrace( traceAllegroBuilder, " Creating group '%s' with %zu items", tableName, newItems.size() );
4780
4781 std::unique_ptr<PCB_GROUP> group = std::make_unique<PCB_GROUP>( &m_board );
4782 group->SetName( tableName );
4783
4784 uint32_t idSeq = 0;
4785
4786 for( const std::unique_ptr<BOARD_ITEM>& item : newItems )
4787 {
4788 stampIds( *item, tableData.m_Key, idSeq );
4789 group->AddItem( item.get() );
4790 }
4791
4792 stampIds( *group, tableData.m_Key, idSeq );
4793 newItems.push_back( std::move( group ) );
4794
4795 BulkAddToBoard( m_board, std::move( newItems ) );
4796 }
4797 }
4798}
4799
4800
4802{
4803 if( m_zoneFillShapes.empty() )
4804 return;
4805
4806 PROF_TIMER fillTimer;
4807
4808 wxLogTrace( traceAllegroBuilder, "Applying zone fill polygons from %zu collected fills",
4809 m_zoneFillShapes.size() );
4810
4811
4812 // Unmatched ETCH shapes are either standalone copper polygons or dynamic copper
4813 // (teardrops/fillets). On V172+ boards, m_Unknown2 bit 12 (0x1000) marks auto-generated
4814 // dynamic copper that maps to KiCad teardrop zones. Shapes without this flag are genuine
4815 // standalone copper imported as filled PCB_SHAPE.
4816 int copperShapeCount = 0;
4817 int teardropCount = 0;
4818
4819 for( const auto& [fillKey, fill] : m_zoneFillShapes )
4820 {
4821 if( m_usedZoneFillShapes.contains( fillKey ) )
4822 continue;
4823
4824 SHAPE_POLY_SET polySet = shapeToPolySet( *fill.shape );
4825 polySet.Simplify();
4826
4827 uint32_t idSeq = 0;
4828
4829 for( const SHAPE_POLY_SET::POLYGON& poly : polySet.CPolygons() )
4830 {
4831 SHAPE_POLY_SET fractured( poly );
4832 fractured.ClearArcs();
4833 fractured.Fracture( /* aSimplify */ false );
4834
4835 const bool isDynCopperShape = ( fill.shape->m_Unknown2.value_or( 0 ) & 0x1000 ) != 0;
4836
4837 if( isDynCopperShape )
4838 {
4839 std::unique_ptr<ZONE> zone = std::make_unique<ZONE>( &m_board );
4840
4841 zone->SetTeardropAreaType( TEARDROP_TYPE::TD_VIAPAD );
4842 zone->SetLayer( fill.layer );
4843 zone->SetNetCode( fill.netCode );
4844 zone->SetLocalClearance( 0 );
4845 zone->SetPadConnection( ZONE_CONNECTION::FULL );
4846 zone->SetIslandRemovalMode( ISLAND_REMOVAL_MODE::NEVER );
4847 zone->SetHatchStyle( ZONE_BORDER_DISPLAY_STYLE::INVISIBLE_BORDER );
4848
4849 for( const SHAPE_LINE_CHAIN& chain : poly )
4850 zone->AddPolygon( chain );
4851
4852 zone->SetFilledPolysList( fill.layer, fractured );
4853 zone->SetIsFilled( true );
4854 zone->SetNeedRefill( false );
4855 zone->CalculateFilledArea();
4856
4857 stampIds( *zone, fillKey, idSeq );
4858 m_board.Add( zone.release(), ADD_MODE::APPEND );
4859 teardropCount++;
4860 }
4861 else if( m_layerMapper->IsPlaneLayer( fill.shape->m_Layer ) )
4862 {
4863 // A negative plane has no clearance around other nets in its shape, so the copper has
4864 // to be a zone that KiCad fills
4865 std::unique_ptr<ZONE> zone = std::make_unique<ZONE>( &m_board );
4866
4867 zone->SetLayer( fill.layer );
4868 zone->SetNetCode( fill.netCode );
4869 zone->SetHatchStyle( ZONE_BORDER_DISPLAY_STYLE::NO_HATCH );
4870 zone->SetFillMode( ZONE_FILL_MODE::POLYGONS );
4871 zone->SetLocalClearance( 0 );
4872 zone->SetMinThickness( 0 );
4873 zone->Outline()->AddPolygon( poly );
4874 zone->SetNeedRefill( true );
4875
4876 stampIds( *zone, fillKey, idSeq );
4877 m_board.Add( zone.release(), ADD_MODE::APPEND );
4878 copperShapeCount++;
4879 }
4880 else
4881 {
4882 std::unique_ptr<PCB_SHAPE> shape = std::make_unique<PCB_SHAPE>( &m_board, SHAPE_T::POLY );
4883 shape->SetPolyShape( fractured );
4884 shape->SetFilled( true );
4885 shape->SetLayer( fill.layer );
4886 shape->SetNetCode( fill.netCode );
4887 shape->SetStroke( STROKE_PARAMS( 0, LINE_STYLE::SOLID ) );
4888
4889 if( !m_boardGraphics.IsFirst( shape.get() ) )
4890 continue;
4891
4892 stampIds( *shape, fillKey, idSeq );
4893 m_board.Add( shape.release(), ADD_MODE::APPEND );
4894 copperShapeCount++;
4895 }
4896 }
4897 }
4898
4899 wxLogTrace( traceAllegroPerf, wxT( " applyZoneFills unmatched loop: %.3f ms (%d shapes, %d teardrops)" ), //format:allow
4900 fillTimer.msecs( true ), copperShapeCount, teardropCount );
4901}
4902
4903
4905{
4906 std::unordered_map<int, std::vector<ZONE*>> teardropsByNet;
4907
4908 for( ZONE* zone : m_board.Zones() )
4909 {
4910 if( zone->IsTeardropArea() )
4911 teardropsByNet[zone->GetNetCode()].push_back( zone );
4912 }
4913
4914 if( teardropsByNet.empty() )
4915 return;
4916
4917 int padCount = 0;
4918 int viaCount = 0;
4919
4920 for( FOOTPRINT* fp : m_board.Footprints() )
4921 {
4922 for( PAD* pad : fp->Pads() )
4923 {
4924 auto it = teardropsByNet.find( pad->GetNetCode() );
4925
4926 if( it == teardropsByNet.end() )
4927 continue;
4928
4929 for( ZONE* tdZone : it->second )
4930 {
4931 if( !pad->IsOnLayer( tdZone->GetLayer() ) )
4932 continue;
4933
4934 if( tdZone->Outline()->Contains( pad->GetPosition() ) )
4935 {
4936 pad->SetTeardropsEnabled( true );
4937 padCount++;
4938 break;
4939 }
4940 }
4941 }
4942 }
4943
4944 for( PCB_TRACK* track : m_board.Tracks() )
4945 {
4946 if( track->Type() != PCB_VIA_T )
4947 continue;
4948
4949 PCB_VIA* via = static_cast<PCB_VIA*>( track );
4950 auto it = teardropsByNet.find( via->GetNetCode() );
4951
4952 if( it == teardropsByNet.end() )
4953 continue;
4954
4955 for( ZONE* tdZone : it->second )
4956 {
4957 if( !via->IsOnLayer( tdZone->GetLayer() ) )
4958 continue;
4959
4960 if( tdZone->Outline()->Contains( via->GetPosition() ) )
4961 {
4962 via->SetTeardropsEnabled( true );
4963 viaCount++;
4964 break;
4965 }
4966 }
4967 }
4968
4969 wxLogTrace( traceAllegroBuilder, "Enabled teardrops on %d pads and %d vias", padCount, viaCount );
4970}
4971
4972
4974{
4975 wxLogTrace( traceAllegroBuilder, "Starting BuildBoard() - Phase 2 of Allegro import" );
4976 wxLogTrace( traceAllegroBuilder, " Format version: %d (V172+ = %s)", static_cast<int>( m_brdDb.m_FmtVer ),
4977 ( m_brdDb.m_FmtVer >= FMT_VER::V_172 ) ? "yes" : "no" );
4978 wxLogTrace( traceAllegroBuilder, " Allegro version string: %.60s", m_brdDb.m_Header->m_AllegroVersion.data() );
4979
4980 if( m_progressReporter )
4981 {
4982 m_progressReporter->AddPhases( 4 );
4983 m_progressReporter->AdvancePhase( _( "Constructing caches" ) );
4984 m_progressReporter->KeepRefreshing();
4985 }
4986
4987 PROF_TIMER buildTimer;
4988
4989 wxLogTrace( traceAllegroBuilder, "Caching font definitions and setting up layers" );
4990 cacheFontDefs();
4991 wxLogTrace( traceAllegroPerf, wxT( " cacheFontDefs: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
4992
4993 setupLayers();
4994 wxLogTrace( traceAllegroPerf, wxT( " setupLayers: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
4995
4996 if( m_progressReporter )
4997 {
4998 m_progressReporter->AdvancePhase( _( "Creating nets" ) );
4999 m_progressReporter->KeepRefreshing();
5000 }
5001
5002 createNets();
5003 wxLogTrace( traceAllegroPerf, wxT( " createNets: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5004
5005 if( m_progressReporter )
5006 {
5007 m_progressReporter->AdvancePhase( _( "Creating tracks" ) );
5008 m_progressReporter->KeepRefreshing();
5009 }
5010
5011 createTracks();
5012 wxLogTrace( traceAllegroPerf, wxT( " createTracks: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5013
5014 if( m_progressReporter )
5015 m_progressReporter->KeepRefreshing();
5016
5018 wxLogTrace( traceAllegroPerf, wxT( " createBoardShapes: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5019
5021 wxLogTrace( traceAllegroPerf, wxT( " createBoardText: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5022
5023 createZones();
5024 wxLogTrace( traceAllegroPerf, wxT( " createZones: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5025
5026 createTables();
5027 wxLogTrace( traceAllegroPerf, wxT( " createTables: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5028
5029 if( m_progressReporter )
5030 m_progressReporter->KeepRefreshing();
5031
5033 wxLogTrace( traceAllegroPerf, wxT( " applyZoneFills: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5034
5036 wxLogTrace( traceAllegroPerf, wxT( " applyConstraintSets: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5037
5039 wxLogTrace( traceAllegroPerf, wxT( " applyNetConstraints: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5040
5042 wxLogTrace( traceAllegroPerf, wxT( " applyMatchGroups: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5043
5044 if( m_progressReporter )
5045 {
5046 m_progressReporter->AdvancePhase( _( "Converting footprints" ) );
5047 m_progressReporter->KeepRefreshing();
5048 }
5049
5050 TYPED_LL_WALKER<BLK_0x2B_FOOTPRINT_DEF> fpWalker( m_brdDb.m_Header->m_LL_0x2B, m_brdDb );
5051 std::vector<BOARD_ITEM*> bulkAddedItems;
5052
5053 THROTTLE refreshThrottle( std::chrono::milliseconds( 100 ) );
5054
5055 for( const BLK_0x2B_FOOTPRINT_DEF& fpBlock : fpWalker )
5056 {
5057 TYPED_LL_WALKER<BLK_0x2D_FOOTPRINT_INST> instWalker( fpBlock.m_FirstInstPtr, fpBlock.m_Key, m_brdDb,
5059 instWalker.SetMismatchReporter(
5060 [this, &fpBlock]( uint8_t aType, const BLOCK_BASE& )
5061 {
5062 m_reporter.Report( wxString::Format( "Unexpected object of type %#04x found in footprint %#010x",
5063 aType,
5064 fpBlock.m_Key ),
5066 } );
5067
5068 const std::optional<FP_3DMODEL> model3D = build3DModel( m_brdDb, fpBlock );
5069
5070 LIB_ID fpId;
5071 fpId.SetLibItemName( LIB_ID::FixIllegalChars( m_brdDb.GetString( fpBlock.m_FpStrRef ).utf8_string(), false ) );
5072
5073 for( const BLK_0x2D_FOOTPRINT_INST& inst : instWalker )
5074 {
5075 std::unique_ptr<FOOTPRINT> fp = buildFootprint( inst );
5076
5077 if( fp )
5078 {
5079 fp->SetFPID( fpId );
5080
5081 if( model3D.has_value() )
5082 fp->Models().push_back( *model3D );
5083
5084 stampIds( *fp, inst.m_Key );
5085 bulkAddedItems.push_back( fp.get() );
5086 m_board.Add( fp.release(), ADD_MODE::BULK_APPEND, true );
5087 }
5088 else
5089 {
5090 m_reporter.Report( wxString::Format( "Failed to construct footprint for 0x2D key %#010x", inst.m_Key ),
5092 }
5093
5094 if( m_progressReporter && refreshThrottle.Ready() )
5095 m_progressReporter->KeepRefreshing();
5096 }
5097 }
5098
5099 wxLogTrace( traceAllegroPerf, wxT( " convertFootprints (%zu footprints): %.3f ms" ), //format:allow
5100 bulkAddedItems.size(), buildTimer.msecs( true ) );
5101
5102 if( !bulkAddedItems.empty() )
5103 m_board.FinalizeBulkAdd( bulkAddedItems );
5104
5105 wxLogTrace( traceAllegroPerf, wxT( " FinalizeBulkAdd: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5106 wxLogTrace( traceAllegroBuilder, "Converted %zu footprints", bulkAddedItems.size() );
5107
5108 // the footprints have added their voids by now
5110
5112 wxLogTrace( traceAllegroPerf, wxT( " enablePadTeardrops: %.3f ms" ), buildTimer.msecs( true ) ); //format:allow
5113 wxLogTrace( traceAllegroPerf, wxT( " Phase 2 total: %.3f ms" ), buildTimer.msecs() ); //format:allow
5114
5115 wxLogTrace( traceAllegroBuilder, "Board construction completed successfully" );
5116 return true;
5117}
int index
const char * name
static std::unordered_set< LAYER_INFO > ScanForLayers(const BRD_DB &aDb)
Look through some lists for a list of layers used.
static std::optional< LAYER_INFO > tryLayerFromBlock(const BLOCK_BASE &aBlock)
Some blocks report layer info - if they do, return it else std::nullopt.
static PCB_LAYER_ID nthCopperLayerId(int aIndex, int aTotal)
Map a 0-based copper index (0 = F_Cu, aTotal-1 = B_Cu) to a KiCad copper layer.
static wxString layerInfoDisplayName(const LAYER_INFO &aLayerInfo)
Build a unique display name for a LAYER_INFO entry from the static maps above, suitable for presentat...
static bool layerIsZone(const LAYER_INFO &aLayerInfo)
Some layers map to KiCad rule areas (zones) - for example a package keepout on ALL maps to a rule are...
static EDA_ANGLE fromMillidegrees(uint32_t aMilliDegrees)
#define BLK_FIELD(BLK_T, FIELD)
static std::optional< FP_3DMODEL > build3DModel(const BRD_DB &aDb, const BLK_0x2B_FOOTPRINT_DEF &aFpDef)
static const std::unordered_map< LAYER_INFO, PCB_LAYER_ID > s_LayerKiMap
Map of the pre-set class:subclass pairs to standard layers.
static const std::unordered_map< LAYER_INFO, wxString > s_OptionalFixedMappings
Names for custom KiCad layers that correspond to pre-defined Allegro layers.
void BulkAddToBoard(BOARD &aBoard, std::vector< std::unique_ptr< T > > &&aItems)
static uint32_t PadGetNextInFootprint(const BLOCK_BASE &aBlock)
"Get Next" function for the pad list in a footprint's 0x32 list.
LAYER_INFO expectLayerFromBlock(const BLOCK_BASE &aBlock)
Get a layer from a block that has layer info.
static int graphicNetCode(const BOARD_ITEM &aItem)
static int clampForScale(double aValue)
static std::optional< double > modelUnitToMm(const wxString &aUnits)
static constexpr uint32_t LAYER_PROP_PLANE
Layer list property bit of a negative plane layer.
Utility functions that operate over BRD_DBs and BLOCKs.
@ ERROR_INSIDE
constexpr int ARC_HIGH_DEF
Definition base_units.h:144
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
The base class for all blocks in the main body of an Allegro file.
uint32_t GetKey() const
uint8_t GetBlockType() const
This is the actual type code as read from the file.
Rejects graphics that repeat one already accepted into the same container.
bool IsFirst(const BOARD_ITEM *aItem)
True when this graphic has not been seen before, and records it.
std::unordered_set< const BOARD_ITEM *, GRAPHIC_KEY_HASH, GRAPHIC_KEY_EQ > m_seen
VECTOR2I scale(const VECTOR2I &aVector) const
const BLK_0x2C_TABLE * resolveMatchGroupTable(const BLK_0x1B_NET &aNet) const
Follow a net's match group pointer to its 0x2C TABLE.
wxString resolveMatchGroupName(const BLK_0x1B_NET &aNet) const
Follow m_MatchGroupPtr through the 0x26/0x2C pointer chain to get the match group name for a NET.
LAYER_MAPPING_HANDLER m_layerMappingHandler
PROGRESS_REPORTER * m_progressReporter
std::map< PCB_LAYER_ID, SHAPE_POLY_SET > m_planeVoids
void reportUnexpectedBlockType(uint8_t aGot, uint8_t aExpected, uint32_t aKey=0, size_t aOffset=0, const wxString &aName=wxEmptyString) const
const BLK_0x07_COMPONENT_INST * getFpInstRef(const BLK_0x2D_FOOTPRINT_INST &aFpInstance) const
Look up 0x07 FP instance data (0x07) for a given 0x2D FP instance.
SHAPE_POLY_SET tryBuildZoneShape(const BLOCK_BASE &aBlock, const TRANSFORM_TRS &aXform=TRANSFORM_TRS()) const
Try to build a zone shape for the given block, with holes.
std::vector< const BLOCK_BASE * > getShapeRelatedBlocks(const BLK_0x28_SHAPE &aShape) const
Get blocks that are related to the BOUNDARY shape, i.e.
VECTOR2I scaleSize(const VECTOR2I &aSize) const
PCB_LAYER_ID getLayer(const LAYER_INFO &aLayerInfo) const
std::unordered_map< uint32_t, SHAPE_LINE_CHAIN > m_segChainCache
std::vector< std::unique_ptr< PCB_SHAPE > > buildShapes(const BLK_0x14_GRAPHIC &aGraphicList, BOARD_ITEM_CONTAINER &aParent)
Build the shapes from an 0x14 shape list.
static void stampIds(BOARD_ITEM &aItem, uint32_t aKey, uint32_t &aSeq)
Give aItem and its children ids derived from the Allegro block they came from.
GRAPHIC_DEDUP m_boardGraphics
Coincidence filter for everything added straight to the board, which is one container.
BOARD_BUILDER(const BRD_DB &aBrdDb, BOARD &aBoard, REPORTER &aReporter, PROGRESS_REPORTER *aProgressReporter, const LAYER_MAPPING_HANDLER &aLayerMappingHandler)
std::unique_ptr< LAYER_MAPPER > m_layerMapper
const T * expectBlockByKey(uint32_t aKey) const
Get a block by its key, and check that it is of the expected type.
std::vector< std::unique_ptr< BOARD_ITEM > > buildDrillMarker(const BLK_0x0C_PIN_DEF &aPinDef, BOARD_ITEM_CONTAINER &aParent)
Build a drill marker from a 0x0C PIN_DEF block.
std::unique_ptr< PCB_SHAPE > buildRect(const BLK_0x24_RECT &aRect, BOARD_ITEM_CONTAINER &aParent)
Build a rectangular shape from a 0x24 RECT block.
std::vector< std::unique_ptr< PCB_SHAPE > > buildPolygonShapes(const BLK_0x28_SHAPE &aShape, BOARD_ITEM_CONTAINER &aParent)
Build graphics from an 0x28 SHAPE, with separate items per segment/arc.
SHAPE_POLY_SET shapeToPolySet(const BLK_0x28_SHAPE &aShape, const TRANSFORM_TRS &aXform=TRANSFORM_TRS()) const
std::unique_ptr< PCB_SHAPE > buildArc(const BLK_0x01_ARC &aArc, const LAYER_INFO &aLayerInfo, PCB_LAYER_ID aLayer, BOARD_ITEM_CONTAINER &aParent)
std::unique_ptr< PCB_TEXT > buildPcbText(const BLK_0x30_STR_WRAPPER &aStrWrapper, BOARD_ITEM_CONTAINER &aParent)
void addFootprintText(FOOTPRINT &aFp, GRAPHIC_DEDUP &aGraphics, const BLK_0x30_STR_WRAPPER &aStrWrapper, bool &aValueFieldSet)
Add a 0x30 text object to a footprint, either as one of the built-in fields or as a graphic,...
std::unique_ptr< FOOTPRINT > buildFootprint(const BLK_0x2D_FOOTPRINT_INST &aFpInstance)
std::vector< std::unique_ptr< BOARD_ITEM > > buildPadItems(const BLK_0x1C_PADSTACK &aPadstack, FOOTPRINT &aFp, const wxString &aPadName, int aNetcode, bool aBackSide)
Construct "pad" items for a given 0x1C PADSTACK block.
void reportMissingBlock(uint32_t aKey, uint8_t aType) const
std::unordered_map< uint32_t, NETINFO_ITEM * > m_netCache
std::unique_ptr< PCB_SHAPE > buildLineSegment(const BLK_0x15_16_17_SEGMENT &aSegment, const LAYER_INFO &aLayerInfo, PCB_LAYER_ID aLayer, BOARD_ITEM_CONTAINER &aParent)
Build a single line segment.
std::vector< std::unique_ptr< BOARD_ITEM > > buildTrack(const BLK_0x05_TRACK &aBlock, int aNetcode)
std::vector< const BLK_0x36_DEF_TABLE::FontDef_X08 * > m_fontDefList
std::unordered_map< uint32_t, ZoneFillEntry > m_zoneFillShapes
wxString get0x30StringValue(uint32_t a0x30Key) const
Get just the string value from a 0x31 STRING WRAPPER -> 0x30 STRING GRAPHIC pair.
const BLK_0x36_DEF_TABLE::FontDef_X08 * getFontDef(unsigned aIndex) const
Get the font definition for a given index in a 0x30, etc.
std::vector< std::unique_ptr< BOARD_ITEM > > buildGraphicItems(const BLOCK_BASE &aBlock, BOARD_ITEM_CONTAINER &aParent)
Build a list of graphic items, e.g.
std::unique_ptr< BOARD_ITEM > buildVia(const BLK_0x33_VIA &aBlock, int aNetcode)
std::unique_ptr< PCB_SHAPE > buildPolygon(const BLK_0x28_SHAPE &aShape, BOARD_ITEM_CONTAINER &aParent)
Build a graphic polygon from a 0x28 SHAPE block.
wxString resolveConstraintSetNameFromField(uint32_t aFieldKey) const
Extract constraint set name from a 0x03 FIELD block pointer.
std::unordered_set< uint32_t > m_usedZoneFillShapes
SHAPE_LINE_CHAIN buildOutline(const BLK_0x0E_RECT &aRect, const TRANSFORM_TRS &aXform=TRANSFORM_TRS()) const
SHAPE_LINE_CHAIN buildSegmentChain(uint32_t aStartKey, const TRANSFORM_TRS &aXform=TRANSFORM_TRS()) const
Walk a geometry chain (0x01 arcs and 0x15-17 segments) starting from the given key,...
std::unique_ptr< ZONE > buildZone(const BLOCK_BASE &aBoundaryBlock, const std::vector< const BLOCK_BASE * > &aRelatedBlocks, ZONE_FILL_HANDLER &aZoneFillHandler, BOARD_ITEM_CONTAINER &aParent)
Build a ZONE from an 0x0E, 0x24 or 0x28 block.
An Allegro board database representing the contents of a .brd (and presumably .dra) file.
Definition allegro_db.h:42
std::unique_ptr< FILE_HEADER > m_Header
Definition allegro_db.h:85
Class to handle the mapping for Allegro CLASS/SUBCLASS idiom to KiCad layers.
PCB_LAYER_ID GetPlaceBounds(bool aTop)
Allegro puts more graphics than just the polygon on PBT/B, but we don't want to always make a static ...
int GetEtchLayerCount() const
Return whether this layer ID is something we mapped to, or the catch-all unmapped layer.
void FinalizeLayers()
Called after all the custom layers are loaded.
void ProcessLayerList(uint8_t aClass, const BLK_0x2A_LAYER_LIST &aList)
LAYER_MAPPER(const BRD_DB &aRawBoard, BOARD &aBoard, const LAYER_MAPPING_HANDLER &aLayerMappingHandler)
PCB_LAYER_ID addUserLayer(const wxString &aName)
std::unordered_map< LAYER_INFO, wxString > m_customLayerDialogNames
Names used in the layer mapping dialog for custom (non-ETCH, non-static) layers.
static PCB_LAYER_ID getNthUserLayer(int aNum)
std::unordered_map< const BLK_0x2A_LAYER_LIST *, std::vector< CUSTOM_LAYER > > m_Lists
PCB_LAYER_ID mapCustomLayerByName(const wxString &aLayerName)
Create or find a mapped layer with a given name, but not specifically bound to a specific class:subcl...
LSET GetRuleAreaLayers(const LAYER_INFO &aLayerInfo)
std::unordered_map< LAYER_INFO, PCB_LAYER_ID > m_staticLayerOverrides
Overrides for the static s_LayerKiMap entries, populated by the layer mapping handler.
std::unordered_map< wxString, PCB_LAYER_ID > m_MappedOptionalLayers
This is a map of optional, Allegro layers that we have mapped to KiCad layers with given names.
PCB_LAYER_ID GetLayer(const LAYER_INFO &aLayerInfo)
bool IsOutlineLayer(const LAYER_INFO &aLayerInfo) const
Resolve the subclass name for a given class:subclass pair using the per-class custom layer list.
bool IsLayerMapped(PCB_LAYER_ID aLayerId) const
std::unordered_map< LAYER_INFO, int > m_unknownLayers
A record of what we failed to map.
std::unordered_map< uint8_t, std::vector< CUSTOM_LAYER > * > m_ClassCustomLayerLists
bool IsPlaneLayer(const LAYER_INFO &aLayerInfo) const
Plane layers are drawn as negatives, so a line on one is a void and not copper.
static PCB_LAYER_ID getNthCopperLayer(int aNum, int aTotal)
std::unordered_map< LAYER_INFO, PCB_LAYER_ID > m_customLayerToKiMap
The main map from CLASS:SUBCLASS custom mappings to KiCadLayers.
PCB_LAYER_ID MapCustomLayer(const LAYER_INFO &aLayerInfo, const wxString &aLayerName)
Record a specific class:subclass layer as mapping to some KiCad user layer, with a given name.
const LAYER_MAPPING_HANDLER & m_layerMappingHandler
Range-for-compatible walker over a linked list of BLOCK_BASE objects in a BRD_DB.
Range-for-compatible walker that yields only typed data from a linked list.
void SetMismatchReporter(MISMATCH_REPORTER aReporter)
Priority task dispatcher for zone fills - we want to do the biggest ones first.
Filled zones have their own outline and the fill itself comes from a bunch of "related" spaces.
void ProcessPolygons(bool aSimplify)
Process the polygons in a thread pool for more fans, more faster.
void QueuePolygonForZone(ZONE &aZone, SHAPE_POLY_SET aFilledArea, PCB_LAYER_ID aLayer)
Container for design settings for a BOARD object.
std::shared_ptr< NET_SETTINGS > m_NetSettings
Abstract interface for BOARD_ITEMs capable of storing other items inside.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
void SetUuidDirect(const KIID &aUuid)
Raw UUID assignment.
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
virtual void RunOnChildren(const std::function< void(BOARD_ITEM *)> &aFunction, RECURSE_MODE aMode) const
Invoke a function on all children.
Definition board_item.h:279
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Removes an item from the container.
Definition board.cpp:1548
void FinalizeBulkAdd(std::vector< BOARD_ITEM * > &aNewItems)
Must be used if Add() is used using a BULK_x ADD_MODE to generate a change event for listeners.
Definition board.cpp:1686
constexpr size_type GetWidth() const
Definition box2.h:217
constexpr size_type GetHeight() const
Definition box2.h:218
EDA_ANGLE Normalize()
Definition eda_angle.h:228
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
SHAPE_T GetShape() const
Definition eda_shape.h:178
virtual void SetFilled(bool aFlag)
Definition eda_shape.h:145
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:334
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:284
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
PCB_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this footprint.
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Adds an item to the container.
static KIID FromName(const std::string &aName)
Return a KIID derived from a name, the same name always gives the same KIID.
Definition kiid.cpp:237
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int SetLibItemName(const UTF8 &aLibItemName)
Override the library item name portion of the LIB_ID to aLibItemName.
Definition lib_id.cpp:124
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:205
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
static const LSET & AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
Definition lset.cpp:604
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
static const LSET & AllLayersMask()
Definition lset.cpp:637
A collection of nets and the parameters used to route or test these nets.
Definition netclass.h:44
static const char Default[]
the name of the default NETCLASS
Definition netclass.h:46
int GetDiffPairGap() const
Definition netclass.h:198
bool HasDiffPairWidth() const
Definition netclass.h:189
const wxString GetName() const
Gets the name of this (maybe aggregate) netclass in a format for internal usage or for export to exte...
Definition netclass.cpp:382
bool HasTrackWidth() const
Definition netclass.h:149
int GetDiffPairWidth() const
Definition netclass.h:190
bool HasDiffPairGap() const
Definition netclass.h:197
int GetTrackWidth() const
Definition netclass.h:150
int GetClearance() const
Definition netclass.h:142
bool HasClearance() const
Definition netclass.h:141
Handle the data for a net.
Definition netinfo.h:50
const wxString & GetNetname() const
Definition netinfo.h:110
void SetNetClass(const std::shared_ptr< NETCLASS > &aNetClass)
static const int UNCONNECTED
Constant that holds the "unconnected net" number (typically 0) all items "connected" to this net are ...
Definition netinfo.h:281
A PADSTACK defines the characteristics of a single or multi-layer pad, in the IPC sense of the word.
Definition padstack.h:161
void SetMode(MODE aMode)
COPPER_LAYER_PROPS & CopperLayer(PCB_LAYER_ID aLayer)
DRILL_PROPS & Drill()
Definition padstack.h:363
std::vector< PCB_LAYER_ID > UniqueLayers() const
@ NORMAL
Shape is the same on all layers.
Definition padstack.h:175
@ CUSTOM
Shapes can be defined on arbitrary layers.
Definition padstack.h:177
@ FRONT_INNER_BACK
Up to three shapes can be defined (F_Cu, inner copper layers, B_Cu)
Definition padstack.h:176
void SetLayerSet(const LSET &aSet)
Definition padstack.h:338
Definition pad.h:61
static LSET PTHMask()
layer set for a through hole pad
Definition pad.cpp:620
static LSET UnplatedHoleMask()
layer set for a mechanical unplated through hole pad
Definition pad.cpp:641
static LSET SMDMask()
layer set for a SMD pad on Front layer
Definition pad.cpp:627
int GetWidth() const override
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition pcb_shape.h:70
void SetTextAngle(const EDA_ANGLE &aAngle) override
Definition pcb_text.cpp:574
size_t Execute(ContainerT &aItems)
Call this to execute the task on all items in aItems, using the thread pool and dispatching the tasks...
A small class to help profiling.
Definition profile.h:46
double msecs(bool aSinceLast=false)
Definition profile.h:148
A progress reporter interface for use in multi-threaded environments.
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
Definition seg.h:38
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
void Move(const VECTOR2I &aVector) override
void SetPoint(int aIndex, const VECTOR2I &aPos)
Move a point to a specific location.
void SetClosed(bool aClosed)
Mark the line chain as closed (i.e.
int PointCount() const
Return the number of points (vertices) in this line chain.
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
void Rotate(const EDA_ANGLE &aAngle, const VECTOR2I &aCenter={ 0, 0 }) override
Rotate all vertices by a given angle.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
const VECTOR2I & CLastPoint() const
Return the last point in the line chain.
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
Represent a set of closed polygons.
void ClearArcs()
Removes all arc references from all the outlines and holes in the polyset.
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index.
bool IsEmpty() const
Return true if the set is empty (no polygons at all)
int TotalVertices() const
Return total number of vertices stored in the set.
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
void Simplify()
Simplify the polyset (merges overlapping polys, eliminates degeneracy/self-intersections)
std::vector< SHAPE_LINE_CHAIN > POLYGON
represents a single polygon outline with holes.
int AddHole(const SHAPE_LINE_CHAIN &aHole, int aOutline=-1)
Adds a new hole to the given outline (default: last) and returns its index.
void BooleanIntersection(const SHAPE_POLY_SET &b)
Perform boolean polyset intersection.
int OutlineCount() const
Return the number of outlines in the set.
void Fracture(bool aSimplify=true)
Convert a set of polygons with holes to a single outline with "slits"/"fractures" connecting the oute...
bool Contains(const VECTOR2I &aP, int aSubpolyIndex=-1, int aAccuracy=0, bool aUseBBoxCaches=false) const
Return true if a given subpolygon contains the point aP.
const POLYGON & CPolygon(int aIndex) const
const std::vector< POLYGON > & CPolygons() const
Simple container to manage line stroke parameters.
Rate-limiter that fires at most once per interval.
Definition throttle.h:31
bool Ready()
Definition throttle.h:44
VECTOR2I InverseApply(const VECTOR2I &aPoint) const
bool IsIdentity() const
const std::string Format() const
Return the vector formatted as a string.
Definition vector2d.h:444
Handle a list of polygons defining a copper zone.
Definition zone.h:70
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:834
virtual PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition zone.cpp:610
SHAPE_POLY_SET * Outline()
Definition zone.h:421
void SetFilledPolysList(PCB_LAYER_ID aLayer, const SHAPE_POLY_SET &aPolysList)
Set the list of filled polygons.
Definition zone.h:748
SHAPE_POLY_SET GetBoardOutline() const
Definition zone.cpp:953
static wxString displayName(const DATABASE_LIB_TABLE &aTable)
const int minSize
Push and Shove router track width and via size dialog.
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
@ DEGREES_T
Definition eda_angle.h:30
static constexpr EDA_ANGLE FULL_CIRCLE
Definition eda_angle.h:470
static constexpr EDA_ANGLE ANGLE_360
Definition eda_angle.h:478
@ NO_RECURSE
Definition eda_item.h:52
@ SEGMENT
Definition eda_shape.h:57
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
@ FP_EXCLUDE_FROM_POS_FILES
Definition footprint.h:88
@ FP_BOARD_ONLY
Definition footprint.h:90
@ FP_EXCLUDE_FROM_BOM
Definition footprint.h:89
int GetPenSizeForNormal(int aTextSize)
Definition gr_text.cpp:58
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
static const wxChar *const traceAllegroBuilder
Flag to enable debug output of Allegro board construction.
static constexpr void hash_combine(std::size_t &seed)
This is a dummy function to take the final case of hash_combine below.
Definition hash.h:28
@ S
Solder (HASL/SMOBC)
wxString LayerName(int aLayer)
Returns the default display name for a given layer.
Definition layer_id.cpp:31
#define MAX_USER_DEFINED_LAYERS
Definition layer_ids.h:173
bool IsUserLayer(PCB_LAYER_ID aLayerId)
Test whether a layer is a non copper and a non tech layer.
Definition layer_ids.h:826
bool IsCopperLayer(int aLayerId)
Test whether a layer is a copper layer.
Definition layer_ids.h:744
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_CrtYd
Definition layer_ids.h:112
@ Edge_Cuts
Definition layer_ids.h:108
@ F_Paste
Definition layer_ids.h:100
@ Cmts_User
Definition layer_ids.h:104
@ B_Mask
Definition layer_ids.h:94
@ B_Cu
Definition layer_ids.h:61
@ F_Mask
Definition layer_ids.h:93
@ B_Paste
Definition layer_ids.h:101
@ F_Fab
Definition layer_ids.h:115
@ F_SilkS
Definition layer_ids.h:96
@ B_CrtYd
Definition layer_ids.h:111
@ UNDEFINED_LAYER
Definition layer_ids.h:57
@ In1_Cu
Definition layer_ids.h:62
@ User_1
Definition layer_ids.h:120
@ B_SilkS
Definition layer_ids.h:97
@ F_Cu
Definition layer_ids.h:60
@ B_Fab
Definition layer_ids.h:114
PCB_LAYER_ID ToLAYER_ID(int aLayer)
Definition lset.cpp:750
@ LEFT_RIGHT
Flip left to right (around the Y axis)
Definition mirror.h:27
@ THROW
THROW_IO_ERROR on mismatch.
@ LOG_TRACE
wxLogTrace the mismatch and skip
@ REPORT
invoke a user-supplied callback, then skip
std::optional< FIELD_VALUE > GetFirstFieldOfType(const BRD_DB &aDb, uint32_t aFieldsPtr, uint32_t aEndKey, uint16_t aFieldCode)
Look up the first 0x03 FIELD value of a given type in a linked field chain.
std::optional< int > GetFirstFieldOfTypeInt(const BRD_DB &aDb, uint32_t aFieldsPtr, uint32_t aEndKey, uint16_t aFieldCode)
Convenience wrapper around GetFirstFieldOfType() for integer-valued fields.
wxString DecodeEscapedIdentifiers(const wxString &aName)
Remove the backslash wrapper Cadence puts around an identifier that holds special characters.
@ MODEL_3D_PLACEMENT
3D model units, XYZ offset and XYZ rotation
@ MODEL_3D_FILE
3D model file name, size, mtime and display colour
@ PHYS_CONSTRAINT_SET
Physical Constraint Set assignment.
const BLK_T & BlockDataAs(const BLOCK_BASE &aBlock)
Cast a BLOCK_BASE to a typed BLOCK<T> and return the data.
std::vector< VECTOR2I > MakeRegularPolygonPoints(const VECTOR2I &aCenter, size_t aN, const VECTOR2I &aPt0)
Get the corners of a regular polygon from the centre, one point and the number of sides.
std::vector< SEG > MakeCrossSegments(const VECTOR2I &aCenter, const VECTOR2I &aSize, EDA_ANGLE aAngle)
Create the two segments for a cross.
STL namespace.
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
@ NPTH
like PAD_PTH, but not plated mechanical use only, no connection allowed
Definition padstack.h:104
@ SMD
Smd pad, appears on the solder paste layer (default)
Definition padstack.h:100
@ PTH
Plated through hole pad.
Definition padstack.h:99
@ CHAMFERED_RECT
Definition padstack.h:61
@ ROUNDRECT
Definition padstack.h:58
@ RECTANGLE
Definition padstack.h:55
Class to handle a set of BOARD_ITEMs.
static const wxChar *const traceAllegroPerf
std::function< std::map< wxString, PCB_LAYER_ID >(const std::vector< INPUT_LAYER_DESC > &)> LAYER_MAPPING_HANDLER
Pointer to a function that takes a map of source and KiCad layers and returns a re-mapped version.
CITER next(CITER it)
Definition ptree.cpp:120
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
Utility functions for working with shapes.
const int scale
Arc segment used in tracks, zone outlines, and shape boundaries.
uint8_t m_SubType
Bit 6 (0x40) = clockwise direction.
Field/property references with variable-typed substructs.
std::variant< uint32_t, std::array< uint32_t, 2 >, std::string, SUB_0x6C, SUB_0x70_0x74, SUB_0xF6 > m_Substruct
Net assignment linking a net (0x1B) to its member objects.
Track segment container.
Component instance reference data.
Pin definition with shape type, drill character, coordinates, and size.
std::array< int32_t, 2 > m_Size
std::array< int32_t, 2 > m_Coords
Pad geometry and placement in board-absolute coordinates.
uint32_t m_Rotation
Board-absolute millidegrees. Subtract footprint rotation for FP-local orientation.
int32_t m_CoordsX
Board coordinates. Use SetFPRelativePosition() for KiCad FP-local space.
int32_t m_CoordsY
Board coordinates. Use SetFPRelativePosition() for KiCad FP-local space.
uint32_t m_Rotation
Rotation in millidegrees.
std::array< int32_t, 4 > m_Coords
Graphics container holding a chain of line segments and arcs.
0x15 , 0x16, 0x17 are segments:
0x1B objects are nets.
static constexpr uint8_t BLOCK_TYPE_CODE
uint32_t m_MatchGroupPtr
Diff pair / match group pointer (0x26 or 0x2C)
Padstack definition containing drill dimensions and a table of per-layer pad/antipad/thermal componen...
size_t m_NumFixedCompEntries
How many of the entries are fixed roles (after this is n*layers)
std::vector< PADSTACK_COMPONENT > m_Components
Collection of components that make up the padstack.
Physical constraint sets containing trace width, clearance, and routing rules.
Rectangle defined by four coordinates.
uint32_t m_Rotation
Rotation in millidegrees.
std::array< int32_t, 4 > m_Coords
Polygon shape defined by a linked list of segments starting at m_FirstSegmentPtr (0x15/0x16/0x17 line...
Represents a list of layers.
COND_GE< FMT_VER::V_165, std::vector< REF_ENTRY > > m_RefEntries
COND_LT< FMT_VER::V_165, std::vector< NONREF_ENTRY > > m_NonRefEntries
Footprint definition (template) shared by multiple placed instances.
uint32_t m_FieldsPtr
Pointer to first 0x03 FIELD object or null.
Lookup table used for named associations.
@ SUBTYPE_GRAPHICAL_GROUP
Used for drill charts and x-section charts.
Placed footprint instance on the board.
uint32_t m_Rotation
Millidegrees (divide by 1000 for degrees)
COND_LT< FMT_VER::V_172, uint32_t > m_InstRef16x
COND_GE< FMT_VER::V_172, uint32_t > m_InstRef
Text object with position, rotation, layer, font properties, and alignment.
COND_GE< FMT_VER::V_172, TEXT_PROPERTIES > m_Font
COND_LT< FMT_VER::V_172, TEXT_PROPERTIES > m_Font16x
String graphic content holding the actual text value and its display layer category.
Placed pad instance linking a pad definition (0x0D via m_PadPtr) to its parent footprint (m_ParentFp)...
Via instance with board position, padstack reference (m_Padstack for drill/annular ring definitions),...
Heterogeneous definition table containing font metrics (FontDef_X08), layer name definitions (X03),...
std::vector< uint32_t > m_Ptrs
bool operator()(const BOARD_ITEM *aFirst, const BOARD_ITEM *aSecond) const
size_t operator()(const BOARD_ITEM *aItem) const
This is apparently some kind of linked list that chains though subsets objects in the file.
Represents the information found in a single entry of a layer list.
Substruct in a padstack object.
COND_GE< FMT_VER::V_172, int32_t > m_Z1
uint32_t m_ShapePtr
Seems to point to various things:
This is all the info needed to do the fill of one layer of one zone.
SHAPE_POLY_SET m_CombinedFill
The wider filled area we will chop a piece out of for this layer of this zone.
Describes an imported layer and how it could be mapped to KiCad Layers.
PCB_LAYER_ID AutoMapLayer
Best guess as to what the equivalent KiCad layer might be.
bool Required
Should we require the layer to be assigned?
LSET PermittedLayers
KiCad layers that the imported layer can be mapped onto.
wxString Name
Imported layer name as displayed in original application.
The features of a padstack that can vary between copper layers All parameters are optional; leaving t...
Definition padstack.h:234
VECTOR2I size
Drill diameter (x == y) or slot dimensions (x != y)
Definition padstack.h:278
PAD_DRILL_SHAPE shape
Definition padstack.h:279
VECTOR2I size
Size of the shape, or of the anchor pad for custom shape pads.
Definition padstack.h:195
PAD_SHAPE shape
Shape of the pad.
Definition padstack.h:193
size_t operator()(const LAYER_INFO &aLayerInfo) const noexcept
@ USER
The field ID hasn't been set yet; field is invalid.
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
const std::string table
KIBIS_MODEL * model
VECTOR2I center
const SHAPE_LINE_CHAIN chain
int radius
VECTOR2I end
int clearance
wxString result
Test unit parsing edge cases and error handling.
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition trigo.cpp:227
const VECTOR2I CalcArcCenter(const VECTOR2I &aStart, const VECTOR2I &aMid, const VECTOR2I &aEnd)
Determine the center of an arc or circle given three points on its circumference.
Definition trigo.cpp:540
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition typeinfo.h:103
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:79
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
VECTOR3< double > VECTOR3D
Definition vector3.h:230
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)
static PIECE polygon(std::vector< VIA_CROSS_SECTION_GEOMETRY::POINT > aPoints, bool aMixed=false)
std::vector< std::unique_ptr< ZONE > > MergeZonesWithSameOutline(std::vector< std::unique_ptr< ZONE > > &&aZones)
Merges zones with identical outlines and nets on different layers into single multi-layer zones.
@ FULL
pads are covered by copper
Definition zones.h:47