KiCad PCB EDA Suite
Loading...
Searching...
No Matches
footprint.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2017 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 2015 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
6 * Copyright (C) 2015 Wayne Stambaugh <[email protected]>
7 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23#include "footprint.h"
24
25#include <magic_enum.hpp>
26
27#include <algorithm>
28#include <cmath>
29#include <unordered_set>
30#include <utility> // std::as_const
31
32#include <wx/log.h>
33#include <wx/debug.h>
34#include <wx/tokenzr.h>
35
36#include <bitmaps.h>
37#include <board.h>
39#include <collectors.h>
41#include <confirm.h>
46#include <core/kicad_algo.h>
48#include <embedded_files.h>
49#include <font/font.h>
50#include <font/outline_font.h>
54#include <i18n_utility.h>
55#include <lset.h>
56#include <macros.h>
57#include <pad.h>
58#include <pcb_dimension.h>
59#include <pcb_edit_frame.h>
60#include <pcb_field.h>
61#include <pcb_group.h>
63#include <pcb_marker.h>
64#include <pcb_point.h>
65#include <pcb_3d_body.h>
66#include <pcb_reference_image.h>
67#include <pcb_textbox.h>
68#include <pcb_track.h>
69#include <pcb_barcode.h>
70#include <name_validation.h>
71#include <refdes_utils.h>
72#include <string_utils.h>
73#include <view/view.h>
74#include <zone.h>
75
76#include <google/protobuf/any.pb.h>
77#include <api/board/board_types.pb.h>
78#include <api/api_enums.h>
79#include <api/api_utils.h>
80#include <api/api_pcb_utils.h>
81#include <properties/property.h>
83
84
86{
87public:
88 PCB_FOOTPRINT_FIELD_PROPERTY( const wxString& aName ) :
89 PROPERTY_BASE( aName ),
90 m_name( aName )
91 {
92 SetGroup( _HKI( "Fields" ) );
93 }
94
95 size_t OwnerHash() const override { return TYPE_HASH( FOOTPRINT ); }
96 size_t BaseHash() const override { return TYPE_HASH( FOOTPRINT ); }
97 size_t TypeHash() const override { return TYPE_HASH( wxString ); }
98
99 void setter( void* obj, wxAny& v ) override
100 {
101 wxString value;
102
103 if( !v.GetAs( &value ) )
104 return;
105
106 FOOTPRINT* footprint = reinterpret_cast<FOOTPRINT*>( obj );
107 PCB_FIELD* field = footprint->GetField( m_name );
108
109 wxString variantName;
110
111 if( footprint->GetBoard() )
112 variantName = footprint->GetBoard()->GetCurrentVariant();
113
114 if( !variantName.IsEmpty() )
115 {
116 FOOTPRINT_VARIANT* variant = footprint->AddVariant( variantName );
117
118 if( variant )
119 variant->SetFieldValue( m_name, value );
120 }
121 else if( !field )
122 {
123 PCB_FIELD* newField = new PCB_FIELD( footprint, FIELD_T::USER, m_name );
124 newField->SetText( value );
125 footprint->Add( newField );
126 }
127 else
128 {
129 field->SetText( value );
130 }
131 }
132
133 wxAny getter( const void* obj ) const override
134 {
135 const FOOTPRINT* footprint = reinterpret_cast<const FOOTPRINT*>( obj );
136 PCB_FIELD* field = footprint->GetField( m_name );
137
138 if( !field )
139 return wxAny();
140
141 wxString variantName;
142
143 if( footprint->GetBoard() )
144 variantName = footprint->GetBoard()->GetCurrentVariant();
145
146 wxString text;
147
148 if( !variantName.IsEmpty() )
149 text = footprint->GetFieldValueForVariant( variantName, m_name );
150 else
151 text = field->GetText();
152
153 return wxAny( text );
154 }
155
156private:
157 wxString m_name;
158};
159
160
161// Net-tie groups are comma-separated with backslash escapes and free whitespace, so compare and
162// serialize the parsed pad numbers rather than the raw text
163static std::vector<wxString> parseNetTiePadGroup( const wxString& aGroup )
164{
165 std::vector<wxString> padNumbers;
166 wxString pad;
167 bool esc = false;
168
169 auto addPad =
170 [&]()
171 {
172 pad.Trim( true ).Trim( false );
173
174 if( !pad.IsEmpty() )
175 padNumbers.push_back( pad );
176
177 pad.Clear();
178 };
179
180 for( wxUniChar ch : aGroup )
181 {
182 if( esc )
183 {
184 esc = false;
185 pad.Append( ch );
186 }
187 else if( ch == '\\' )
188 {
189 esc = true;
190 }
191 else if( ch == ',' )
192 {
193 addPad();
194 }
195 else
196 {
197 pad.Append( ch );
198 }
199 }
200
201 addPad();
202 return padNumbers;
203}
204
205
208 m_attributes( 0 ),
216 m_lastEditTime( 0 ),
217 m_arflag( 0 ),
218 m_link( 0 ),
219 m_initial_comments( nullptr ),
221{
222 m_layer = F_Cu;
223 m_embedFonts = false;
224
225 auto addField =
226 [this]( FIELD_T id, PCB_LAYER_ID layer, bool visible )
227 {
228 PCB_FIELD* field = new PCB_FIELD( this, id );
229 field->SetLayer( layer );
230 field->SetVisible( visible );
231 m_fields.push_back( field );
232 };
233
234 addField( FIELD_T::REFERENCE, F_SilkS, true );
235 addField( FIELD_T::VALUE, F_Fab, true );
236 addField( FIELD_T::DATASHEET, F_Fab, false );
237 addField( FIELD_T::DESCRIPTION, F_Fab, false );
238
239 m_3D_Drawings.clear();
240}
241
242
243FOOTPRINT::FOOTPRINT( const FOOTPRINT& aFootprint ) :
244 BOARD_ITEM_CONTAINER( aFootprint ),
245 EMBEDDED_FILES( aFootprint ),
247{
248 m_transform = aFootprint.m_transform;
249 m_flipped = aFootprint.m_flipped;
250 m_fpid = aFootprint.m_fpid;
251 m_attributes = aFootprint.m_attributes;
252 m_fpStatus = aFootprint.m_fpStatus;
254
255 m_geometry_cache.reset();
256
259 m_unitInfo = aFootprint.m_unitInfo;
263
265 m_clearance = aFootprint.m_clearance;
269
270 m_stackupLayers = aFootprint.m_stackupLayers;
271 m_stackupMode = aFootprint.m_stackupMode;
272
274 m_keywords = aFootprint.m_keywords;
275 m_path = aFootprint.m_path;
276 m_sheetname = aFootprint.m_sheetname;
277 m_sheetfile = aFootprint.m_sheetfile;
278 m_filters = aFootprint.m_filters;
279 m_lastEditTime = aFootprint.m_lastEditTime;
280 m_arflag = 0;
281 m_link = aFootprint.m_link;
282 m_privateLayers = aFootprint.m_privateLayers;
283
284 m_3D_Drawings = aFootprint.m_3D_Drawings;
285 m_height = aFootprint.m_height;
286
287 for( PCB_3D_BODY* body : aFootprint.m_bodies )
288 Add( static_cast<PCB_3D_BODY*>( body->Clone() ), ADD_MODE::APPEND );
289
290 m_initial_comments = aFootprint.m_initial_comments ? new wxArrayString( *aFootprint.m_initial_comments )
291 : nullptr;
292
293 m_embedFonts = aFootprint.m_embedFonts;
294 m_variants = aFootprint.m_variants;
295
296 m_componentClassCacheProxy->SetStaticComponentClass(
298
299 std::map<EDA_ITEM*, EDA_ITEM*> ptrMap;
300
301 // Copy fields
302 for( PCB_FIELD* field : aFootprint.m_fields )
303 {
304 if( field->IsMandatory() )
305 {
306 PCB_FIELD* existingField = GetField( field->GetId() );
307 ptrMap[field] = existingField;
308 *existingField = *field;
309
310 // Assignment retains the constructor-generated KIID because m_Uuid is const
311 existingField->SetUuidDirect( field->m_Uuid );
312 existingField->SetParent( this );
313 }
314 else
315 {
316 PCB_FIELD* newField = static_cast<PCB_FIELD*>( field->Clone() );
317 ptrMap[field] = newField;
318 Add( newField );
319 }
320 }
321
322 // Copy pads
323 for( PAD* pad : aFootprint.Pads() )
324 {
325 PAD* newPad = static_cast<PAD*>( pad->Clone() );
326 ptrMap[ pad ] = newPad;
327 Add( newPad, ADD_MODE::APPEND ); // Append to ensure indexes are identical
328 }
329
330 // Copy zones
331 for( ZONE* zone : aFootprint.Zones() )
332 {
333 ZONE* newZone = static_cast<ZONE*>( zone->Clone() );
334 ptrMap[ zone ] = newZone;
335 Add( newZone, ADD_MODE::APPEND ); // Append to ensure indexes are identical
336
337 // Ensure the net info is OK and especially uses the net info list
338 // living in the current board
339 // Needed when copying a fp from fp editor that has its own board
340 // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
341 newZone->SetNetCode( -1 );
342 }
343
344 // Copy drawings
345 for( BOARD_ITEM* item : aFootprint.GraphicalItems() )
346 {
347 BOARD_ITEM* newItem = static_cast<BOARD_ITEM*>( item->Clone() );
348 ptrMap[ item ] = newItem;
349 Add( newItem, ADD_MODE::APPEND ); // Append to ensure indexes are identical
350 }
351
352 // Copy groups
353 for( PCB_GROUP* group : aFootprint.Groups() )
354 {
355 PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( group->Clone() );
356 ptrMap[ group ] = newGroup;
357 Add( newGroup, ADD_MODE::APPEND ); // Append to ensure indexes are identical
358 }
359
360 // Copy constraints. Clone preserves the uuid, so each constraint's KIID members still
361 // resolve to the matching cloned items.
362 for( PCB_CONSTRAINT* constraint : aFootprint.Constraints() )
363 Add( static_cast<PCB_CONSTRAINT*>( constraint->Clone() ), ADD_MODE::APPEND );
364
365 for( PCB_POINT* point : aFootprint.Points() )
366 {
367 PCB_POINT* newPoint = static_cast<PCB_POINT*>( point->Clone() );
368 ptrMap[ point ] = newPoint;
369 Add( newPoint, ADD_MODE::APPEND ); // Append to ensure indexes are identical
370 }
371
372 // Rebuild groups
373 for( PCB_GROUP* group : aFootprint.Groups() )
374 {
375 PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( ptrMap[ group ] );
376
377 newGroup->GetItems().clear();
378
379 for( EDA_ITEM* member : group->GetItems() )
380 {
381 if( ptrMap.count( member ) )
382 newGroup->AddItem( ptrMap[ member ] );
383 }
384 }
385
386 // Embedded files are inherited via the EMBEDDED_FILES copy constructor invoked in the
387 // member initializer list above; the underlying file payloads are reference-counted so
388 // cloning a footprint is cheap even when it carries large embedded models or fonts.
389}
390
391
393 BOARD_ITEM_CONTAINER( aFootprint ),
395{
396 *this = std::move( aFootprint );
397}
398
399
401{
402 // Clean up the owned elements
403 delete m_initial_comments;
404
405 for( PCB_FIELD* f : m_fields )
406 delete f;
407
408 m_fields.clear();
409
410 for( PAD* p : m_pads )
411 delete p;
412
413 m_pads.clear();
414
415 for( ZONE* zone : m_zones )
416 delete zone;
417
418 m_zones.clear();
419
420 for( PCB_GROUP* group : m_groups )
421 delete group;
422
423 m_groups.clear();
424
425 for( PCB_CONSTRAINT* constraint : m_constraints )
426 delete constraint;
427
428 m_constraints.clear();
429
430 for( PCB_POINT* point : m_points )
431 delete point;
432
433 m_points.clear();
434
435 for( BOARD_ITEM* d : m_drawings )
436 delete d;
437
438 m_drawings.clear();
439
440 for( PCB_3D_BODY* body : m_bodies )
441 delete body;
442}
443
444std::vector<PROPERTY_BASE*> FOOTPRINT::GetDynamicProperties() const
445{
446 std::vector<PROPERTY_BASE*> props;
447 const BOARD* board = GetBoard();
448 bool isFPedit = board && board->IsFootprintHolder();
449
450 auto getOrCreate =
451 [&]( const wxString& aName )
452 {
453 auto it = m_fieldPropsStorageCache.find( aName );
454
455 if( it == m_fieldPropsStorageCache.end() )
456 {
457 auto prop = std::make_unique<PCB_FOOTPRINT_FIELD_PROPERTY>( aName );
458 it = m_fieldPropsStorageCache.emplace( aName, std::move( prop ) ).first;
459 }
460
461 return it->second.get();
462 };
463
464 for( PCB_FIELD* field : GetFields() )
465 {
466 if( !field->IsMandatory() )
467 continue;
468
469 if( !isFPedit && field->IsPrivate() )
470 continue;
471
472 const wxString& name = field->GetUntranslatedName();
473
474 if( PROPERTY_MANAGER::Instance().GetProperty( TYPE_HASH( FOOTPRINT ), name ) )
475 continue;
476
477 props.push_back( getOrCreate( name ) );
478 }
479
480 std::vector<PCB_FIELD*> userFields;
481
482 for( PCB_FIELD* field : GetFields() )
483 {
484 if( field->IsMandatory() || ( !isFPedit && field->IsPrivate() ) )
485 continue;
486
487 userFields.push_back( field );
488 }
489
490 std::ranges::sort( userFields,
491 []( const PCB_FIELD* a, const PCB_FIELD* b )
492 {
493 return a->GetUntranslatedName().CmpNoCase( b->GetUntranslatedName() ) < 0;
494 } );
495
496 for( PCB_FIELD* field : userFields )
497 {
498 const wxString& name = field->GetUntranslatedName();
499 props.push_back( getOrCreate( name ) );
500 }
501
503 props.push_back( prop );
504
505 return props;
506}
507
508
509void FOOTPRINT::Serialize( google::protobuf::Any &aContainer ) const
510{
511 using namespace kiapi::board;
512 types::FootprintInstance footprint;
513
514 footprint.mutable_id()->set_value( m_Uuid.AsStdString() );
515 footprint.mutable_position()->set_x_nm( GetPosition().x );
516 footprint.mutable_position()->set_y_nm( GetPosition().y );
517 footprint.mutable_orientation()->set_value_degrees( GetOrientationDegrees() );
518 footprint.set_layer( ToProtoEnum<PCB_LAYER_ID, types::BoardLayer>( GetLayer() ) );
519 footprint.set_locked( IsLocked() ? kiapi::common::types::LockedState::LS_LOCKED
520 : kiapi::common::types::LockedState::LS_UNLOCKED );
521
522 if( const BOARD* board = GetBoard() )
523 footprint.mutable_parent()->set_value( board->m_Uuid.AsStdString() );
524
525 GetField( FIELD_T::REFERENCE )->Serialize( *footprint.mutable_reference_field() );
526 GetField( FIELD_T::VALUE )->Serialize( *footprint.mutable_value_field() );
527 GetField( FIELD_T::DATASHEET )->Serialize( *footprint.mutable_datasheet_field() );
528 GetField( FIELD_T::DESCRIPTION )->Serialize( *footprint.mutable_description_field() );
529
530 types::FootprintAttributes* attrs = footprint.mutable_attributes();
531
532 attrs->set_not_in_schematic( IsBoardOnly() );
533 attrs->set_exclude_from_position_files( IsExcludedFromPosFiles() );
534 attrs->set_exclude_from_bill_of_materials( IsExcludedFromBOM() );
535 attrs->set_exclude_from_simulation( IsExcludedFromSim() );
536 attrs->set_exempt_from_courtyard_requirement( AllowMissingCourtyard() );
537 attrs->set_do_not_populate( IsDNP() );
538 attrs->set_allow_soldermask_bridges( AllowSolderMaskBridges() );
539
541 attrs->set_mounting_style( types::FootprintMountingStyle::FMS_THROUGH_HOLE );
542 else if( m_attributes & FP_SMD )
543 attrs->set_mounting_style( types::FootprintMountingStyle::FMS_SMD );
544 else
545 attrs->set_mounting_style( types::FootprintMountingStyle::FMS_UNSPECIFIED );
546
547 SerializeDefinition( footprint.mutable_definition() );
548
549 types::FootprintDesignRuleOverrides* overrides = footprint.mutable_overrides();
550
551 if( GetLocalClearance().has_value() )
552 overrides->mutable_copper_clearance()->set_value_nm( *GetLocalClearance() );
553
554 if( GetLocalSolderMaskMargin().has_value() )
555 overrides->mutable_solder_mask()->mutable_solder_mask_margin()->set_value_nm( *GetLocalSolderMaskMargin() );
556
557 if( GetLocalSolderPasteMargin().has_value() )
558 overrides->mutable_solder_paste()->mutable_solder_paste_margin()->set_value_nm( *GetLocalSolderPasteMargin() );
559
560 if( GetLocalSolderPasteMarginRatio().has_value() )
561 overrides->mutable_solder_paste()->mutable_solder_paste_margin_ratio()->set_value( *GetLocalSolderPasteMarginRatio() );
562
563 overrides->set_zone_connection(
565
566 kiapi::common::PackSheetPath( *footprint.mutable_symbol_path(), m_path );
567
568 footprint.set_symbol_sheet_name( m_sheetname.ToUTF8() );
569 footprint.set_symbol_sheet_filename( m_sheetfile.ToUTF8() );
570 footprint.set_symbol_footprint_filters( m_filters.ToUTF8() );
571
572 kiapi::board::PackEmbeddedFiles( *footprint.mutable_embedded_files(), *this );
573
574 kiapi::common::PackCustomProperties( footprint.mutable_custom_properties(), *this );
575
576 for( const auto& [variantName, variant] : m_variants )
577 {
578 types::FootprintVariant* variantMsg = footprint.add_variants();
579 variantMsg->set_name( variantName.ToUTF8() );
580 variantMsg->set_do_not_populate( variant.GetDNP() );
581 variantMsg->set_exclude_from_bill_of_materials( variant.GetExcludedFromBOM() );
582 variantMsg->set_exclude_from_position_files( variant.GetExcludedFromPosFiles() );
583 variantMsg->set_exclude_from_simulation( variant.GetExcludedFromSim() );
584
585 for( const auto& [fieldName, fieldValue] : variant.GetFields() )
586 {
587 variantMsg->mutable_fields()->insert( { std::string( fieldName.ToUTF8() ),
588 std::string( fieldValue.ToUTF8() ) } );
589 }
590 }
591
592 for( const FP_UNIT_INFO& unit : m_unitInfo )
593 {
594 types::FootprintUnitInfo* unitMsg = footprint.add_symbol_units();
595 unitMsg->set_name( unit.m_unitName.ToUTF8() );
596
597 for( const wxString& pinNumber : unit.m_pins )
598 unitMsg->add_pin_numbers( pinNumber.ToUTF8() );
599 }
600
601 if( !aContainer.PackFrom( footprint ) )
602 wxFAIL_MSG( wxT( "Failed to pack FOOTPRINT" ) );
603}
604
605
606void FOOTPRINT::SerializeDefinition( kiapi::board::types::Footprint* aOutput ) const
607{
608 using namespace kiapi::board;
609
610 kiapi::common::PackLibId( aOutput->mutable_id(), GetFPID() );
611 // anchor?
612 aOutput->mutable_attributes()->set_description( GetLibDescription().ToUTF8() );
613 aOutput->mutable_attributes()->set_keywords( GetKeywords().ToUTF8() );
614
615 // TODO: serialize library mandatory fields
616
617 for( const wxString& group : GetNetTiePadGroups() )
618 {
619 types::NetTieDefinition* netTie = aOutput->add_net_ties();
620
621 for( const wxString& padNumber : parseNetTiePadGroup( group ) )
622 netTie->add_pad_number( padNumber.ToUTF8() );
623 }
624
625 for( PCB_LAYER_ID layer : GetPrivateLayers().Seq() )
626 aOutput->add_private_layers( ToProtoEnum<PCB_LAYER_ID, types::BoardLayer>( layer ) );
627
628 types::JumperSettings* jumpers = aOutput->mutable_jumpers();
629 jumpers->set_duplicate_names_are_jumpered( GetDuplicatePadNumbersAreJumpers() );
630
631 for( const JUMPER_GROUP& group : JumperPadGroups().GetAll() )
632 {
633 types::JumperGroup* jumperGroup = jumpers->add_groups();
634
635 for( const wxString& padName : group.GetNames() )
636 jumperGroup->add_pad_names( padName.ToUTF8() );
637 }
638
639 if( GetHeight() > 0 )
640 kiapi::common::PackDistance( *aOutput->mutable_height(), GetHeight() );
641
642 for( const PCB_FIELD* item : m_fields )
643 {
644 if( item->IsMandatory() )
645 continue;
646
647 google::protobuf::Any* itemMsg = aOutput->add_items();
648 item->Serialize( *itemMsg );
649 }
650
651 for( const PAD* item : Pads() )
652 {
653 google::protobuf::Any* itemMsg = aOutput->add_items();
654 item->Serialize( *itemMsg );
655 }
656
657 for( const BOARD_ITEM* item : GraphicalItems() )
658 {
659 google::protobuf::Any* itemMsg = aOutput->add_items();
660 item->Serialize( *itemMsg );
661 }
662
663 for( const PCB_POINT* item : Points() )
664 {
665 google::protobuf::Any* itemMsg = aOutput->add_items();
666 item->Serialize( *itemMsg );
667 }
668
669 for( const ZONE* item : Zones() )
670 {
671 google::protobuf::Any* itemMsg = aOutput->add_items();
672 item->Serialize( *itemMsg );
673 }
674
675 for( const PCB_3D_BODY* body : Bodies() )
676 {
677 if( body->GetExtruded()->m_height > 0 )
678 {
679 google::protobuf::Any* itemMsg = aOutput->add_items();
680 body->Serialize( *itemMsg );
681 }
682 }
683
684 for( const FP_3DMODEL& model : Models() )
685 {
686 google::protobuf::Any* itemMsg = aOutput->add_items();
687 types::Footprint3DModel modelMsg;
688 modelMsg.set_filename( model.m_Filename.ToUTF8() );
689 kiapi::common::PackVector3D( *modelMsg.mutable_scale(), model.m_Scale );
690 kiapi::common::PackVector3D( *modelMsg.mutable_rotation(), model.m_Rotation );
691 kiapi::common::PackVector3D( *modelMsg.mutable_offset(), model.m_Offset );
692 modelMsg.set_visible( model.m_Show );
693 modelMsg.set_opacity( model.m_Opacity );
694
695 if( !itemMsg->PackFrom( modelMsg ) )
696 wxFAIL_MSG( wxT( "Failed to pack FP_3DMODEL" ) );
697 }
698}
699
700
701bool FOOTPRINT::DeserializeDefinition( const kiapi::board::types::Footprint& aInput )
702{
703 using namespace kiapi::board;
704
705 SetFPID( kiapi::common::UnpackLibId( aInput.id() ) );
706 // TODO: how should anchor be handled?
707 SetLibDescription( aInput.attributes().description() );
708 SetKeywords( aInput.attributes().keywords() );
709
710 // TODO: deserialize library mandatory fields
711
712 m_netTiePadGroups.clear();
713
714 for( const types::NetTieDefinition& netTieMsg : aInput.net_ties() )
715 {
716 wxString group;
717
718 for( const std::string& pad : netTieMsg.pad_number() )
719 {
720 wxString escaped = wxString::FromUTF8( pad );
721
722 escaped.Replace( wxS( "\\" ), wxS( "\\\\" ) );
723 escaped.Replace( wxS( "," ), wxS( "\\," ) );
724
725 if( !group.IsEmpty() )
726 group += wxS( ", " );
727
728 group += escaped;
729 }
730
732 }
733
734 SetDuplicatePadNumbersAreJumpers( aInput.jumpers().duplicate_names_are_jumpered() );
735
736 JUMPER_GROUP_SET& jumperGroups = JumperPadGroups();
737 jumperGroups.Clear();
738
739 for( const types::JumperGroup& groupMsg : aInput.jumpers().groups() )
740 {
741 std::set<wxString> padNames;
742
743 for( const std::string& padName : groupMsg.pad_names() )
744 padNames.insert( wxString::FromUTF8( padName ) );
745
746 jumperGroups.Add( std::move( padNames ) );
747 }
748
749 LSET privateLayers;
750
751 for( int layerMsg : aInput.private_layers() )
752 {
753 auto layer = FromProtoEnum<PCB_LAYER_ID, types::BoardLayer>( static_cast<types::BoardLayer>( layerMsg ) );
754
755 if( layer > UNDEFINED_LAYER )
756 privateLayers.set( layer );
757 }
758
759 SetPrivateLayers( privateLayers );
760
761 if( int height = kiapi::common::UnpackDistance( aInput.height() ); height > 0 )
762 SetHeight( height );
763
764 // Footprint items
765 for( PCB_FIELD* field : m_fields )
766 {
767 if( !field->IsMandatory() )
768 Remove( field );
769 }
770
771 // If this footprint is on a board, uncache all items before clearing
772 if( BOARD* board = GetBoard() )
773 board->UncacheChildrenById( *this );
774
775 Pads().clear();
776 GraphicalItems().clear();
777 Zones().clear();
778 Groups().clear();
779 Constraints().clear();
780 Models().clear();
781 Points().clear();
782
783 while( !m_bodies.empty() )
784 Remove( m_bodies.back() );
785
786 for( const google::protobuf::Any& itemMsg : aInput.items() )
787 {
788 std::optional<KICAD_T> type = kiapi::common::TypeNameFromAny( itemMsg );
789
790 if( !type )
791 {
792 // Bit of a hack here, but eventually 3D models should be promoted to a first-class
793 // object, at which point they can get their own serialization
794 if( itemMsg.type_url() == "type.googleapis.com/kiapi.board.types.Footprint3DModel" )
795 {
796 types::Footprint3DModel modelMsg;
797
798 if( !itemMsg.UnpackTo( &modelMsg ) )
799 continue;
800
802
803 model.m_Filename = wxString::FromUTF8( modelMsg.filename() );
804 model.m_Show = modelMsg.visible();
805 model.m_Opacity = modelMsg.opacity();
806 model.m_Scale = kiapi::common::UnpackVector3D( modelMsg.scale() );
807 model.m_Rotation = kiapi::common::UnpackVector3D( modelMsg.rotation() );
808 model.m_Offset = kiapi::common::UnpackVector3D( modelMsg.offset() );
809
810 Models().push_back( std::move( model ) );
811 }
812 else
813 {
814 wxLogTrace( traceApi, wxString::Format( wxS( "Attempting to unpack unknown type %s "
815 "from footprint message, skipping" ),
816 itemMsg.type_url() ) );
817 }
818
819 continue;
820 }
821
822 std::unique_ptr<BOARD_ITEM> item = CreateItemForType( *type, this );
823
824 if( item && item->Deserialize( itemMsg ) )
825 Add( item.release(), ADD_MODE::APPEND );
826 }
827
828 return true;
829}
830
831
832bool FOOTPRINT::Deserialize( const google::protobuf::Any &aContainer )
833{
834 using namespace kiapi::board;
835 types::FootprintInstance footprint;
836
837 if( !aContainer.UnpackTo( &footprint ) )
838 return false;
839
840 SetUuidDirect( KIID( footprint.id().value() ) );
841 SetPosition( VECTOR2I( footprint.position().x_nm(), footprint.position().y_nm() ) );
842 SetOrientationDegrees( footprint.orientation().value_degrees() );
844 SetLocked( footprint.locked() == kiapi::common::types::LockedState::LS_LOCKED );
845
846 google::protobuf::Any buf;
847 types::Field mandatoryField;
848
849 if( footprint.has_reference_field() )
850 {
851 mandatoryField = footprint.reference_field();
852 mandatoryField.mutable_id()->set_id( (int) FIELD_T::REFERENCE );
853
854 if( !buf.PackFrom( mandatoryField ) )
855 wxFAIL_MSG( wxT( "Failed to pack footprint reference field" ) );
856
858 }
859
860 if( footprint.has_value_field() )
861 {
862 mandatoryField = footprint.value_field();
863 mandatoryField.mutable_id()->set_id( (int) FIELD_T::VALUE );
864
865 if( !buf.PackFrom( mandatoryField ) )
866 wxFAIL_MSG( wxT( "Failed to pack footpring value field" ) );
867
869 }
870
871 if( footprint.has_datasheet_field() )
872 {
873 mandatoryField = footprint.datasheet_field();
874 mandatoryField.mutable_id()->set_id( (int) FIELD_T::DATASHEET );
875
876 if( !buf.PackFrom( mandatoryField ) )
877 wxFAIL_MSG( wxT( "Failed to pack footprint datasheet field" ) );
878
880 }
881
882 if( footprint.has_description_field() )
883 {
884 mandatoryField = footprint.description_field();
885 mandatoryField.mutable_id()->set_id( (int) FIELD_T::DESCRIPTION );
886
887 if( !buf.PackFrom( mandatoryField ) )
888 wxFAIL_MSG( wxT( "Failed to pack footprint description field" ) );
889
891 }
892
893 m_attributes = 0;
894
895 switch( footprint.attributes().mounting_style() )
896 {
897 case types::FootprintMountingStyle::FMS_THROUGH_HOLE:
899 break;
900
901 case types::FootprintMountingStyle::FMS_SMD:
903 break;
904
905 default:
906 break;
907 }
908
909 SetBoardOnly( footprint.attributes().not_in_schematic() );
910 SetExcludedFromBOM( footprint.attributes().exclude_from_bill_of_materials() );
911 SetExcludedFromSim( footprint.attributes().exclude_from_simulation() );
912 SetExcludedFromPosFiles( footprint.attributes().exclude_from_position_files() );
913 SetAllowMissingCourtyard( footprint.attributes().exempt_from_courtyard_requirement() );
914 SetDNP( footprint.attributes().do_not_populate() );
915 SetAllowSolderMaskBridges( footprint.attributes().allow_soldermask_bridges() );
916
917 // Definition
918 DeserializeDefinition( footprint.definition() );
919
920 const types::FootprintDesignRuleOverrides& overrides = footprint.overrides();
921
922 if( overrides.has_copper_clearance() )
923 SetLocalClearance( overrides.copper_clearance().value_nm() );
924 else
925 SetLocalClearance( std::nullopt );
926
927 if( overrides.has_solder_mask() && overrides.solder_mask().has_solder_mask_margin() )
928 SetLocalSolderMaskMargin( overrides.solder_mask().solder_mask_margin().value_nm() );
929 else
930 SetLocalSolderMaskMargin( std::nullopt );
931
932 if( overrides.has_solder_paste() )
933 {
934 const types::SolderPasteOverrides& pasteSettings = overrides.solder_paste();
935
936 if( pasteSettings.has_solder_paste_margin() )
937 SetLocalSolderPasteMargin( pasteSettings.solder_paste_margin().value_nm() );
938 else
939 SetLocalSolderPasteMargin( std::nullopt );
940
941 if( pasteSettings.has_solder_paste_margin_ratio() )
942 SetLocalSolderPasteMarginRatio( pasteSettings.solder_paste_margin_ratio().value() );
943 else
944 SetLocalSolderPasteMarginRatio( std::nullopt );
945 }
946
947 SetLocalZoneConnection( FromProtoEnum<ZONE_CONNECTION>( overrides.zone_connection() ) );
948
949 m_path = kiapi::common::UnpackSheetPath( footprint.symbol_path() );
950 m_sheetname = wxString::FromUTF8( footprint.symbol_sheet_name() );
951 m_sheetfile = wxString::FromUTF8( footprint.symbol_sheet_filename() );
952 m_filters = wxString::FromUTF8( footprint.symbol_footprint_filters() );
953
954 kiapi::common::UnpackCustomProperties( footprint.custom_properties(), *this );
955
956 if( !kiapi::board::UnpackEmbeddedFiles( *this, footprint.embedded_files() ) )
957 return false;
958
959 m_variants.clear();
960
961 for( const types::FootprintVariant& variantMsg : footprint.variants() )
962 {
963 wxString variantName = wxString::FromUTF8( variantMsg.name() );
964
965 if( variantName.IsEmpty() || variantName.CmpNoCase( GetDefaultVariantName() ) == 0 )
966 continue;
967
968 FOOTPRINT_VARIANT& variant = m_variants[variantName];
969 variant.SetName( variantName );
970 variant.SetDNP( variantMsg.do_not_populate() );
971 variant.SetExcludedFromBOM( variantMsg.exclude_from_bill_of_materials() );
972 variant.SetExcludedFromPosFiles( variantMsg.exclude_from_position_files() );
973 variant.SetExcludedFromSim( variantMsg.exclude_from_simulation() );
974
975 for( const auto& [fieldName, fieldValue] : variantMsg.fields() )
976 variant.SetFieldValue( wxString::FromUTF8( fieldName ), wxString::FromUTF8( fieldValue ) );
977 }
978
979 m_unitInfo.clear();
980
981 for( const types::FootprintUnitInfo& unitMsg : footprint.symbol_units() )
982 {
983 FP_UNIT_INFO unit;
984 unit.m_unitName = wxString::FromUTF8( unitMsg.name() );
985
986 for( const std::string& pinNumber : unitMsg.pin_numbers() )
987 unit.m_pins.emplace_back( wxString::FromUTF8( pinNumber ) );
988
989 m_unitInfo.push_back( std::move( unit ) );
990 }
991
992 return true;
993}
994
995
997{
998 for( PCB_FIELD* field : m_fields )
999 {
1000 if( field->GetId() == aFieldType )
1001 return field;
1002 }
1003
1004 PCB_FIELD* field = new PCB_FIELD( this, aFieldType );
1005 m_fields.push_back( field );
1006
1007 return field;
1008}
1009
1010
1011const PCB_FIELD* FOOTPRINT::GetField( FIELD_T aFieldType ) const
1012{
1013 for( const PCB_FIELD* field : m_fields )
1014 {
1015 if( field->GetId() == aFieldType )
1016 return field;
1017 }
1018
1019 return nullptr;
1020}
1021
1022
1023bool FOOTPRINT::HasField( const wxString& aFieldName ) const
1024{
1025 return GetField( aFieldName ) != nullptr;
1026}
1027
1028
1029PCB_FIELD* FOOTPRINT::GetField( const wxString& aFieldName ) const
1030{
1031 for( PCB_FIELD* field : m_fields )
1032 {
1033 if( field->GetName() == aFieldName )
1034 return field;
1035 }
1036
1037 return nullptr;
1038}
1039
1040
1041void FOOTPRINT::GetFields( std::vector<PCB_FIELD*>& aVector, bool aVisibleOnly ) const
1042{
1043 aVector.clear();
1044
1045 for( PCB_FIELD* field : m_fields )
1046 {
1047 if( aVisibleOnly )
1048 {
1049 if( !field->IsVisible() || field->GetText().IsEmpty() )
1050 continue;
1051 }
1052
1053 aVector.push_back( field );
1054 }
1055
1056 std::sort( aVector.begin(), aVector.end(),
1057 []( PCB_FIELD* lhs, PCB_FIELD* rhs )
1058 {
1059 return lhs->GetOrdinal() < rhs->GetOrdinal();
1060 } );
1061}
1062
1063
1064void FOOTPRINT::UpdateFields( const std::vector<PCB_FIELD>& aFields, std::vector<PCB_FIELD*>& aAdded,
1065 std::vector<PCB_FIELD*>& aDetached )
1066{
1067 std::deque<PCB_FIELD*> updatedFieldSet;
1068 std::vector<wxString> assignedFields;
1069
1070 auto assignOrAdd =
1071 [&]( PCB_FIELD* existingField, const PCB_FIELD& sourceField )
1072 {
1073 if( existingField )
1074 {
1075 *existingField = sourceField;
1076 existingField->ClearEditFlags();
1077 existingField->SetParent( this );
1078 updatedFieldSet.push_back( existingField );
1079 assignedFields.push_back( sourceField.GetName() );
1080 }
1081 else
1082 {
1083 PCB_FIELD* destField = sourceField.CloneField();
1084 aAdded.push_back( destField );
1085 updatedFieldSet.push_back( destField );
1086 }
1087 };
1088
1089 for( const PCB_FIELD& field : aFields )
1090 {
1091 // The const overload returns nullptr for a missing mandatory field instead of quietly creating one
1092 if( field.IsMandatory() )
1093 assignOrAdd( const_cast<PCB_FIELD*>( std::as_const( *this ).GetField( field.GetId() ) ), field );
1094 else
1095 assignOrAdd( GetField( field.GetName() ), field );
1096 }
1097
1098 for( PCB_FIELD* field : m_fields )
1099 {
1100 if( !field->IsMandatory() && !alg::contains( assignedFields, field->GetName() ) )
1101 aDetached.push_back( field );
1102 }
1103
1104 // Add() and Remove() carry the board's item-by-id cache and the geometry caches with them
1105 for( PCB_FIELD* field : aDetached )
1106 Remove( field );
1107
1108 for( PCB_FIELD* field : aAdded )
1109 Add( field );
1110
1111 // Add() appends, so restore the order the caller asked for
1112 m_fields = std::move( updatedFieldSet );
1113
1115}
1116
1117
1119{
1120 int ordinal = 42; // Arbitrarily larger than any mandatory FIELD_T id
1121
1122 for( const PCB_FIELD* field : m_fields )
1123 ordinal = std::max( ordinal, field->GetOrdinal() + 1 );
1124
1125 return ordinal;
1126}
1127
1128
1129void FOOTPRINT::ApplyDefaultSettings( const BOARD& board, bool aStyleFields, bool aStyleText,
1130 bool aStyleShapes, bool aStyleDimensions, bool aStyleBarcodes )
1131{
1132 if( aStyleFields )
1133 {
1134 for( PCB_FIELD* field : m_fields )
1135 field->StyleFromSettings( board.GetDesignSettings(), true );
1136 }
1137
1138 for( BOARD_ITEM* item : m_drawings )
1139 {
1140 switch( item->Type() )
1141 {
1142 case PCB_TEXT_T:
1143 case PCB_TEXTBOX_T:
1144 if( aStyleText )
1145 item->StyleFromSettings( board.GetDesignSettings(), true );
1146
1147 break;
1148
1149 case PCB_SHAPE_T:
1150 if( aStyleShapes && !item->IsOnCopperLayer() )
1151 item->StyleFromSettings( board.GetDesignSettings(), true );
1152
1153 break;
1154
1155 case PCB_DIM_ALIGNED_T:
1156 case PCB_DIM_LEADER_T:
1157 case PCB_DIM_CENTER_T:
1158 case PCB_DIM_RADIAL_T:
1160 if( aStyleDimensions )
1161 item->StyleFromSettings( board.GetDesignSettings(), true );
1162
1163 break;
1164
1165 case PCB_BARCODE_T:
1166 if( aStyleBarcodes )
1167 item->StyleFromSettings( board.GetDesignSettings(), true );
1168
1169 break;
1170
1171 default:
1172 break;
1173 }
1174 }
1175}
1176
1177
1179{
1180 // replace null UUIDs if any by a valid uuid
1181 std::vector< BOARD_ITEM* > item_list;
1182
1183 for( PCB_FIELD* field : m_fields )
1184 item_list.push_back( field );
1185
1186 for( PAD* pad : m_pads )
1187 item_list.push_back( pad );
1188
1189 for( BOARD_ITEM* gr_item : m_drawings )
1190 item_list.push_back( gr_item );
1191
1192 // Note: one cannot fix null UUIDs inside the group, but it should not happen
1193 // because null uuids can be found in old footprints, therefore without group
1194 for( PCB_GROUP* group : m_groups )
1195 item_list.push_back( group );
1196
1197 // Probably not needed, because old fp do not have zones. But just in case.
1198 for( ZONE* zone : m_zones )
1199 item_list.push_back( zone );
1200
1201 // Ditto
1202 for( PCB_POINT* point : m_points )
1203 item_list.push_back( point );
1204
1205 bool changed = false;
1206
1207 for( BOARD_ITEM* item : item_list )
1208 {
1209 if( item->m_Uuid == niluuid )
1210 {
1211 item->ResetUuidDirect();
1212 changed = true;
1213 }
1214 }
1215
1216 return changed;
1217}
1218
1219
1221{
1222 BOARD_ITEM::operator=( aOther );
1223
1224 m_courtyard_cache.reset();
1225 m_geometry_cache.reset();
1226
1227 m_fpid = aOther.m_fpid;
1228 m_attributes = aOther.m_attributes;
1229 m_fpStatus = aOther.m_fpStatus;
1230 m_transform = aOther.m_transform;
1231 m_flipped = aOther.m_flipped;
1232 m_lastEditTime = aOther.m_lastEditTime;
1233 m_link = aOther.m_link;
1234 m_path = aOther.m_path;
1235 m_variants = std::move( aOther.m_variants );
1236
1237 m_clearance = aOther.m_clearance;
1238 m_solderMaskMargin = aOther.m_solderMaskMargin;
1239 m_solderPasteMargin = aOther.m_solderPasteMargin;
1240 m_solderPasteMarginRatio = aOther.m_solderPasteMarginRatio;
1241 m_zoneConnection = aOther.m_zoneConnection;
1242 m_netTiePadGroups = aOther.m_netTiePadGroups;
1243 m_duplicatePadNumbersAreJumpers = aOther.m_duplicatePadNumbersAreJumpers;
1244 m_jumperPadGroups = aOther.m_jumperPadGroups;
1245 m_unitInfo = aOther.m_unitInfo;
1246
1247 // If this footprint is on a board, uncache all items before deleting them
1248 if( BOARD* board = GetBoard() )
1249 board->UncacheChildrenById( *this );
1250
1251 // Move the fields
1252 for( PCB_FIELD* field : m_fields )
1253 delete field;
1254
1255 m_fields.clear();
1256
1257 for( PCB_FIELD* field : aOther.m_fields )
1258 Add( field );
1259
1260 aOther.m_fields.clear();
1261
1262 // Move the pads
1263 for( PAD* pad : m_pads )
1264 delete pad;
1265
1266 m_pads.clear();
1267
1268 for( PAD* pad : aOther.Pads() )
1269 Add( pad );
1270
1271 aOther.Pads().clear();
1272
1273 // Move the zones
1274 for( ZONE* zone : m_zones )
1275 delete zone;
1276
1277 m_zones.clear();
1278
1279 for( ZONE* item : aOther.Zones() )
1280 {
1281 Add( item );
1282
1283 // Ensure the net info is OK and especially uses the net info list
1284 // living in the current board
1285 // Needed when copying a fp from fp editor that has its own board
1286 // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
1287 item->SetNetCode( -1 );
1288 }
1289
1290 aOther.Zones().clear();
1291
1292 // Move the drawings
1293 for( BOARD_ITEM* item : m_drawings )
1294 delete item;
1295
1296 m_drawings.clear();
1297
1298 for( BOARD_ITEM* item : aOther.GraphicalItems() )
1299 Add( item );
1300
1301 aOther.GraphicalItems().clear();
1302
1303 // Move the groups
1304 for( PCB_GROUP* group : m_groups )
1305 delete group;
1306
1307 m_groups.clear();
1308
1309 for( PCB_GROUP* group : aOther.Groups() )
1310 Add( group );
1311
1312 aOther.Groups().clear();
1313
1314 // Move the constraints
1315 for( PCB_CONSTRAINT* constraint : m_constraints )
1316 delete constraint;
1317
1318 m_constraints.clear();
1319
1320 for( PCB_CONSTRAINT* constraint : aOther.Constraints() )
1321 Add( constraint );
1322
1323 aOther.Constraints().clear();
1324
1325 // Move the points
1326 for( PCB_POINT* point : m_points )
1327 delete point;
1328
1329 m_points.clear();
1330
1331 for( PCB_POINT* point : aOther.Points() )
1332 Add( point );
1333
1334 aOther.Points().clear();
1335
1336 EMBEDDED_FILES::operator=( std::move( aOther ) );
1337
1338 // Copy auxiliary data
1339 m_3D_Drawings = aOther.m_3D_Drawings;
1340 m_height = aOther.m_height;
1341 m_libDescription = aOther.m_libDescription;
1342 m_keywords = aOther.m_keywords;
1343 m_privateLayers = aOther.m_privateLayers;
1344
1345 m_initial_comments = aOther.m_initial_comments;
1346
1347 m_componentClassCacheProxy->SetStaticComponentClass(
1348 aOther.m_componentClassCacheProxy->GetStaticComponentClass() );
1349
1350 // Clear the other item's containers since this is a move
1351
1352 for( PCB_3D_BODY* body : m_bodies )
1353 delete body;
1354
1355 m_bodies.clear();
1356
1357 for( PCB_3D_BODY* body : aOther.m_bodies )
1358 Add( body );
1359
1360 aOther.m_bodies.clear();
1361 aOther.m_fields.clear();
1362 aOther.Pads().clear();
1363 aOther.Zones().clear();
1364 aOther.GraphicalItems().clear();
1365 aOther.m_initial_comments = nullptr;
1366
1367 return *this;
1368}
1369
1370
1372{
1373 BOARD_ITEM::operator=( aOther );
1374
1375 m_courtyard_cache.reset();
1376 m_geometry_cache.reset();
1377
1378 m_fpid = aOther.m_fpid;
1379 m_attributes = aOther.m_attributes;
1380 m_fpStatus = aOther.m_fpStatus;
1381 m_transform = aOther.m_transform;
1382 m_flipped = aOther.m_flipped;
1384 m_link = aOther.m_link;
1385 m_path = aOther.m_path;
1386
1387 m_clearance = aOther.m_clearance;
1395 m_unitInfo = aOther.m_unitInfo;
1396 m_variants = aOther.m_variants;
1397
1398 // If this footprint is on a board, uncache all items before deleting them
1399 if( BOARD* board = GetBoard() )
1400 board->UncacheChildrenById( *this );
1401
1402 std::map<EDA_ITEM*, EDA_ITEM*> ptrMap;
1403
1404 // Copy fields
1405 for( PCB_FIELD* field : m_fields )
1406 delete field;
1407
1408 m_fields.clear();
1409
1410 for( PCB_FIELD* field : aOther.m_fields )
1411 {
1412 PCB_FIELD* newField = new PCB_FIELD( *field );
1413 ptrMap[field] = newField;
1414 Add( newField );
1415 }
1416
1417 // Copy pads
1418 for( PAD* pad : m_pads )
1419 delete pad;
1420
1421 m_pads.clear();
1422
1423 for( PAD* pad : aOther.Pads() )
1424 {
1425 PAD* newPad = new PAD( *pad );
1426 ptrMap[ pad ] = newPad;
1427 Add( newPad );
1428 }
1429
1430 // Copy zones
1431 for( ZONE* zone : m_zones )
1432 delete zone;
1433
1434 m_zones.clear();
1435
1436 for( ZONE* zone : aOther.Zones() )
1437 {
1438 ZONE* newZone = static_cast<ZONE*>( zone->Clone() );
1439 ptrMap[ zone ] = newZone;
1440 Add( newZone );
1441
1442 // Ensure the net info is OK and especially uses the net info list
1443 // living in the current board
1444 // Needed when copying a fp from fp editor that has its own board
1445 // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
1446 newZone->SetNetCode( -1 );
1447 }
1448
1449 // Copy drawings
1450 for( BOARD_ITEM* item : m_drawings )
1451 delete item;
1452
1453 m_drawings.clear();
1454
1455 for( BOARD_ITEM* item : aOther.GraphicalItems() )
1456 {
1457 BOARD_ITEM* newItem = static_cast<BOARD_ITEM*>( item->Clone() );
1458 ptrMap[ item ] = newItem;
1459 Add( newItem );
1460 }
1461
1462 // Copy groups
1463 for( PCB_GROUP* group : m_groups )
1464 delete group;
1465
1466 m_groups.clear();
1467
1468 for( PCB_GROUP* group : aOther.Groups() )
1469 {
1470 PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( group->Clone() );
1471 newGroup->GetItems().clear();
1472
1473 for( EDA_ITEM* member : group->GetItems() )
1474 newGroup->AddItem( ptrMap[ member ] );
1475
1476 Add( newGroup );
1477 }
1478
1479 // Copy constraints. Members reference items by KIID, which Clone preserves, so the
1480 // copies still point at the matching cloned items by uuid (resolved on next use).
1481 for( PCB_CONSTRAINT* constraint : m_constraints )
1482 delete constraint;
1483
1484 m_constraints.clear();
1485
1486 for( PCB_CONSTRAINT* constraint : aOther.Constraints() )
1487 Add( static_cast<PCB_CONSTRAINT*>( constraint->Clone() ) );
1488
1489 // Copy points
1490 for( PCB_POINT* point : m_points )
1491 delete point;
1492
1493 m_points.clear();
1494
1495 for( PCB_POINT* point : aOther.Points() )
1496 {
1497 BOARD_ITEM* newItem = static_cast<BOARD_ITEM*>( point->Clone() );
1498 ptrMap[ point ] = newItem;
1499 Add( newItem );
1500 }
1501
1502 // Copy auxiliary data
1504 m_height = aOther.m_height;
1505
1506 // Clear the other item's containers since this is a move
1507
1508 for( PCB_3D_BODY* body : m_bodies )
1509 delete body;
1510
1511 m_bodies.clear();
1512
1513 for( PCB_3D_BODY* body : aOther.m_bodies )
1514 Add( static_cast<PCB_3D_BODY*>( body->Clone() ), ADD_MODE::APPEND );
1515
1517 m_keywords = aOther.m_keywords;
1519
1521 new wxArrayString( *aOther.m_initial_comments ) : nullptr;
1522
1523 m_componentClassCacheProxy->SetStaticComponentClass(
1525
1526 EMBEDDED_FILES::operator=( aOther );
1527
1528 return *this;
1529}
1530
1531
1532void FOOTPRINT::CopyFrom( const BOARD_ITEM* aOther )
1533{
1534 wxCHECK( aOther && aOther->Type() == PCB_FOOTPRINT_T, /* void */ );
1535 *this = *static_cast<const FOOTPRINT*>( aOther );
1536
1537 for( PAD* pad : m_pads )
1538 pad->SetDirty();
1539}
1540
1541
1543{
1544 {
1545 std::lock_guard<std::mutex> lock( m_geometry_cache_mutex );
1546 m_geometry_cache.reset();
1547 }
1548
1549 std::lock_guard<std::mutex> lock( m_courtyard_cache_mutex );
1550 m_courtyard_cache.reset();
1551}
1552
1553
1555{
1556 return HasFlag( COURTYARD_CONFLICT );
1557}
1558
1559
1560bool FOOTPRINT::IsWithinSchematicSheet( const KIID_PATH& aSheetPath ) const
1561{
1562 if( aSheetPath.empty() )
1563 return false;
1564
1565 // m_path is written by the netlist, which omits the root sheet the way PathAsString() does
1566 return m_path.size() >= aSheetPath.size() - 1
1567 && std::equal( aSheetPath.begin() + 1, aSheetPath.end(), m_path.begin() );
1568}
1569
1570
1571void FOOTPRINT::GetContextualTextVars( wxArrayString* aVars ) const
1572{
1573 aVars->push_back( wxT( "REFERENCE" ) );
1574 aVars->push_back( wxT( "VALUE" ) );
1575 aVars->push_back( wxT( "LAYER" ) );
1576 aVars->push_back( wxT( "FOOTPRINT_LIBRARY" ) );
1577 aVars->push_back( wxT( "FOOTPRINT_NAME" ) );
1578 aVars->push_back( wxT( "SHORT_NET_NAME(<pad_number>)" ) );
1579 aVars->push_back( wxT( "NET_NAME(<pad_number>)" ) );
1580 aVars->push_back( wxT( "NET_CLASS(<pad_number>)" ) );
1581 aVars->push_back( wxT( "PIN_NAME(<pad_number>)" ) );
1582 aVars->push_back( wxT( "EXCLUDE_FROM_BOM" ) );
1583 aVars->push_back( wxT( "EXCLUDE_FROM_BOARD" ) );
1584 aVars->push_back( wxT( "EXCLUDE_FROM_SIM" ) );
1585 aVars->push_back( wxT( "EXCLUDE_FROM_POS_FILES" ) );
1586 aVars->push_back( wxT( "DNP" ) );
1587}
1588
1589
1590bool FOOTPRINT::ResolveTextVar( wxString* token, int aDepth ) const
1591{
1592 wxString variant;
1593
1594 if( GetBoard() )
1595 variant = GetBoard()->GetCurrentVariant();
1596
1597 return ResolveTextVar( token, variant, aDepth );
1598}
1599
1600
1601bool FOOTPRINT::ResolveTextVar( wxString* token, const wxString& aVariantName, int aDepth ) const
1602{
1603 if( GetBoard() && GetBoard()->GetBoardUse() == BOARD_USE::FPHOLDER )
1604 return false;
1605
1606 wxString variant = aVariantName;
1607
1608 if( token->IsSameAs( wxT( "REFERENCE" ) ) )
1609 {
1610 if( const PCB_FIELD* reference = GetField( FIELD_T::REFERENCE ) )
1611 *token = reference->GetShownText( variant, INTERNAL, aDepth + 1 );
1612 else
1613 token->Clear();
1614
1615 return true;
1616 }
1617 else if( token->IsSameAs( wxT( "VALUE" ) ) )
1618 {
1619 if( const PCB_FIELD* value = GetField( FIELD_T::VALUE ) )
1620 *token = value->GetShownText( variant, INTERNAL, aDepth + 1 );
1621 else
1622 token->Clear();
1623
1624 return true;
1625 }
1626 else if( token->IsSameAs( wxT( "LAYER" ) ) )
1627 {
1628 *token = GetLayerName();
1629 return true;
1630 }
1631 else if( token->IsSameAs( wxT( "FOOTPRINT_LIBRARY" ) ) )
1632 {
1633 *token = m_fpid.GetUniStringLibNickname();
1634 return true;
1635 }
1636 else if( token->IsSameAs( wxT( "FOOTPRINT_NAME" ) ) )
1637 {
1638 *token = m_fpid.GetUniStringLibItemName();
1639 return true;
1640 }
1641 else if( token->StartsWith( wxT( "SHORT_NET_NAME(" ) )
1642 || token->StartsWith( wxT( "NET_NAME(" ) )
1643 || token->StartsWith( wxT( "NET_CLASS(" ) )
1644 || token->StartsWith( wxT( "PIN_NAME(" ) ) )
1645 {
1646 wxString padNumber = token->AfterFirst( '(' );
1647 padNumber = padNumber.BeforeLast( ')' );
1648
1649 for( PAD* pad : Pads() )
1650 {
1651 if( pad->GetNumber() == padNumber )
1652 {
1653 if( token->StartsWith( wxT( "SHORT_NET_NAME" ) ) )
1654 *token = pad->GetShortNetname();
1655 else if( token->StartsWith( wxT( "NET_NAME" ) ) )
1656 *token = pad->GetNetname();
1657 else if( token->StartsWith( wxT( "NET_CLASS" ) ) )
1658 *token = pad->GetNetClassName();
1659 else
1660 *token = pad->GetPinFunction();
1661
1662 return true;
1663 }
1664 }
1665 }
1666 else if( token->IsSameAs( wxT( "EXCLUDE_FROM_BOM" ) ) )
1667 {
1668 *token = wxEmptyString;
1669
1670 if( GetExcludedFromBOMForVariant( variant ) )
1671 *token = wxS( "Excluded from BOM" );
1672
1673 return true;
1674 }
1675 else if( token->IsSameAs( wxT( "EXCLUDE_FROM_POS_FILES" ) ) )
1676 {
1677 *token = wxEmptyString;
1678
1679 if( GetExcludedFromPosFilesForVariant( variant ) )
1680 *token = wxS( "Excluded from position files" );
1681
1682 return true;
1683 }
1684 else if( token->IsSameAs( wxT( "EXCLUDE_FROM_BOARD" ) ) )
1685 {
1686 // Footprints are never excluded from board by definition
1687 *token = wxEmptyString;
1688 return true;
1689 }
1690 else if( token->IsSameAs( wxT( "EXCLUDE_FROM_SIM" ) ) )
1691 {
1692 *token = wxEmptyString;
1693
1694 if( GetExcludedFromSimForVariant( variant ) )
1695 *token = wxS( "Excluded from simulation" );
1696
1697 return true;
1698 }
1699 else if( token->IsSameAs( wxT( "DNP" ) ) )
1700 {
1701 *token = wxEmptyString;
1702
1703 if( GetDNPForVariant( variant ) )
1704 *token = wxS( "DNP" );
1705
1706 return true;
1707 }
1708 else if( PCB_FIELD* field = GetField( *token ) )
1709 {
1710 *token = field->GetShownText( variant, INTERNAL, aDepth + 1 );
1711 return true;
1712 }
1713 // The great property resolver: ${PROPERTY.My_Property}
1714 else if( token->StartsWith( wxS( "PROPERTY." ) ) )
1715 {
1716 // Get the second half, convert _ to ' '
1717 wxString propertyName = token->AfterFirst( '.' );
1718 propertyName.Replace( wxS( "_" ), wxS( " " ) );
1719
1720 // Check if the property manager knows this property
1722 PROPERTY_BASE* property = propMgr.GetProperty( this, propertyName );
1723
1724 if( !property || property->IsHiddenFromPropertiesManager() )
1725 return false;
1726
1727 if( !propMgr.IsAvailableFor( TYPE_HASH( *this ), property, const_cast<FOOTPRINT*>( this ) ) )
1728 return false;
1729
1730 KICAD_DIFF::DIFF_VALUE value = KICAD_DIFF::WxAnyToDiffValue( Get( property ), property );
1731
1733 return false;
1734
1735 *token = value.ToDisplayString( EDA_UNITS::MM, pcbIUScale );
1736 return true;
1737 }
1738
1739 if( GetBoard() && GetBoard()->ResolveTextVar( token, aVariantName, aDepth + 1 ) )
1740 return true;
1741
1742 return false;
1743}
1744
1745
1746// ============================================================================
1747// Variant Support Implementation
1748// ============================================================================
1749
1750const FOOTPRINT_VARIANT* FOOTPRINT::GetVariant( const wxString& aVariantName ) const
1751{
1752 auto it = m_variants.find( aVariantName );
1753
1754 return it != m_variants.end() ? &it->second : nullptr;
1755}
1756
1757
1758FOOTPRINT_VARIANT* FOOTPRINT::GetVariant( const wxString& aVariantName )
1759{
1760 auto it = m_variants.find( aVariantName );
1761
1762 return it != m_variants.end() ? &it->second : nullptr;
1763}
1764
1765
1767{
1768 if( aVariant.GetName().IsEmpty()
1769 || aVariant.GetName().CmpNoCase( GetDefaultVariantName() ) == 0 )
1770 {
1771 return;
1772 }
1773
1774 auto it = m_variants.find( aVariant.GetName() );
1775
1776 if( it != m_variants.end() )
1777 {
1778 FOOTPRINT_VARIANT updated = aVariant;
1779 updated.SetName( it->first );
1780 it->second = std::move( updated );
1781 return;
1782 }
1783
1784 m_variants.emplace( aVariant.GetName(), aVariant );
1785}
1786
1787
1788FOOTPRINT_VARIANT* FOOTPRINT::AddVariant( const wxString& aVariantName )
1789{
1790 if( aVariantName.IsEmpty()
1791 || aVariantName.CmpNoCase( GetDefaultVariantName() ) == 0 )
1792 {
1793 wxASSERT_MSG( false, wxT( "Variant name cannot be empty or default." ) );
1794 return nullptr;
1795 }
1796
1797 auto it = m_variants.find( aVariantName );
1798
1799 if( it != m_variants.end() )
1800 return &it->second;
1801
1802 FOOTPRINT_VARIANT variant( aVariantName );
1803 variant.SetDNP( IsDNP() );
1807
1808 auto inserted = m_variants.emplace( aVariantName, std::move( variant ) );
1809 return &inserted.first->second;
1810}
1811
1812
1813void FOOTPRINT::DeleteVariant( const wxString& aVariantName )
1814{
1815 m_variants.erase( aVariantName );
1816}
1817
1818
1819void FOOTPRINT::RenameVariant( const wxString& aOldName, const wxString& aNewName )
1820{
1821 if( aNewName.IsEmpty()
1822 || aNewName.CmpNoCase( GetDefaultVariantName() ) == 0 )
1823 {
1824 return;
1825 }
1826
1827 auto it = m_variants.find( aOldName );
1828
1829 if( it == m_variants.end() )
1830 return;
1831
1832 auto existingIt = m_variants.find( aNewName );
1833
1834 if( existingIt != m_variants.end() && existingIt != it )
1835 return;
1836
1837 if( it->first == aNewName )
1838 return;
1839
1840 FOOTPRINT_VARIANT variant = it->second;
1841 variant.SetName( aNewName );
1842 m_variants.erase( it );
1843 m_variants.emplace( aNewName, std::move( variant ) );
1844}
1845
1846
1847bool FOOTPRINT::HasVariant( const wxString& aVariantName ) const
1848{
1849 return m_variants.find( aVariantName ) != m_variants.end();
1850}
1851
1852
1853bool FOOTPRINT::GetDNPForVariant( const wxString& aVariantName ) const
1854{
1855 // Empty variant name means default
1856 if( aVariantName.IsEmpty() || aVariantName.CmpNoCase( GetDefaultVariantName() ) == 0 )
1857 return IsDNP();
1858
1859 const FOOTPRINT_VARIANT* variant = GetVariant( aVariantName );
1860
1861 if( variant )
1862 return variant->GetDNP();
1863
1864 // Fall back to default if variant doesn't exist
1865 return IsDNP();
1866}
1867
1868
1869bool FOOTPRINT::GetExcludedFromBOMForVariant( const wxString& aVariantName ) const
1870{
1871 // Empty variant name means default
1872 if( aVariantName.IsEmpty() || aVariantName.CmpNoCase( GetDefaultVariantName() ) == 0 )
1873 return IsExcludedFromBOM();
1874
1875 const FOOTPRINT_VARIANT* variant = GetVariant( aVariantName );
1876
1877 if( variant )
1878 return variant->GetExcludedFromBOM();
1879
1880 // Fall back to default if variant doesn't exist
1881 return IsExcludedFromBOM();
1882}
1883
1884
1885bool FOOTPRINT::GetExcludedFromSimForVariant( const wxString& aVariantName ) const
1886{
1887 // Empty variant name means default
1888 if( aVariantName.IsEmpty() || aVariantName.CmpNoCase( GetDefaultVariantName() ) == 0 )
1889 return IsExcludedFromSim();
1890
1891 const FOOTPRINT_VARIANT* variant = GetVariant( aVariantName );
1892
1893 if( variant )
1894 return variant->GetExcludedFromSim();
1895
1896 // Fall back to default if variant doesn't exist
1897 return IsExcludedFromSim();
1898}
1899
1900
1901bool FOOTPRINT::GetExcludedFromPosFilesForVariant( const wxString& aVariantName ) const
1902{
1903 // Empty variant name means default
1904 if( aVariantName.IsEmpty() || aVariantName.CmpNoCase( GetDefaultVariantName() ) == 0 )
1905 return IsExcludedFromPosFiles();
1906
1907 const FOOTPRINT_VARIANT* variant = GetVariant( aVariantName );
1908
1909 if( variant )
1910 return variant->GetExcludedFromPosFiles();
1911
1912 // Fall back to default if variant doesn't exist
1913 return IsExcludedFromPosFiles();
1914}
1915
1916
1917wxString FOOTPRINT::GetFieldValueForVariant( const wxString& aVariantName, const wxString& aFieldName ) const
1918{
1919 // Check variant-specific override first
1920 if( !aVariantName.IsEmpty() && aVariantName.CmpNoCase( GetDefaultVariantName() ) != 0 )
1921 {
1922 const FOOTPRINT_VARIANT* variant = GetVariant( aVariantName );
1923
1924 if( variant && variant->HasFieldValue( aFieldName ) )
1925 return variant->GetFieldValue( aFieldName );
1926 }
1927
1928 // Fall back to default field value
1929 if( const PCB_FIELD* field = GetField( aFieldName ) )
1930 return field->GetText();
1931
1932 return wxString();
1933}
1934
1935
1937{
1938 // Force the ORPHANED dummy net info on every BOARD_CONNECTED_ITEM descendant so that
1939 // operations which read through m_netinfo (e.g. library serialization) cannot chase a
1940 // dangling pointer when this footprint has been detached from its original parent board.
1941 // ORPHANED dummy net does not depend on a board.
1943 []( BOARD_ITEM* aItem )
1944 {
1945 if( BOARD_CONNECTED_ITEM* bci = dynamic_cast<BOARD_CONNECTED_ITEM*>( aItem ) )
1946 bci->SetNetCode( NETINFO_LIST::ORPHANED, /* aNoAssert */ true );
1947 },
1949}
1950
1951
1952void FOOTPRINT::Add( BOARD_ITEM* aBoardItem, ADD_MODE aMode, bool aSkipConnectivity )
1953{
1954 switch( aBoardItem->Type() )
1955 {
1956 case PCB_FIELD_T:
1957 m_fields.push_back( static_cast<PCB_FIELD*>( aBoardItem ) );
1958 break;
1959
1960 case PCB_BARCODE_T:
1961 case PCB_TEXT_T:
1962 case PCB_DIM_ALIGNED_T:
1963 case PCB_DIM_LEADER_T:
1964 case PCB_DIM_CENTER_T:
1965 case PCB_DIM_RADIAL_T:
1967 case PCB_SHAPE_T:
1968 case PCB_TEXTBOX_T:
1969 case PCB_TABLE_T:
1971 if( aMode == ADD_MODE::APPEND )
1972 m_drawings.push_back( aBoardItem );
1973 else
1974 m_drawings.push_front( aBoardItem );
1975
1976 break;
1977
1978 case PCB_PAD_T:
1979 if( aMode == ADD_MODE::APPEND )
1980 m_pads.push_back( static_cast<PAD*>( aBoardItem ) );
1981 else
1982 m_pads.push_front( static_cast<PAD*>( aBoardItem ) );
1983
1984 break;
1985
1986 case PCB_ZONE_T:
1987 if( aMode == ADD_MODE::APPEND )
1988 m_zones.push_back( static_cast<ZONE*>( aBoardItem ) );
1989 else
1990 m_zones.insert( m_zones.begin(), static_cast<ZONE*>( aBoardItem ) );
1991
1992 break;
1993
1994 case PCB_GROUP_T:
1995 if( aMode == ADD_MODE::APPEND )
1996 m_groups.push_back( static_cast<PCB_GROUP*>( aBoardItem ) );
1997 else
1998 m_groups.insert( m_groups.begin(), static_cast<PCB_GROUP*>( aBoardItem ) );
1999
2000 break;
2001
2002 case PCB_CONSTRAINT_T:
2003 if( aMode == ADD_MODE::APPEND )
2004 m_constraints.push_back( static_cast<PCB_CONSTRAINT*>( aBoardItem ) );
2005 else
2006 m_constraints.insert( m_constraints.begin(), static_cast<PCB_CONSTRAINT*>( aBoardItem ) );
2007
2008 break;
2009
2010 case PCB_MARKER_T:
2011 wxFAIL_MSG( wxT( "FOOTPRINT::Add(): Markers go at the board level, even in the footprint editor" ) );
2012 return;
2013
2014 case PCB_FOOTPRINT_T:
2015 wxFAIL_MSG( wxT( "FOOTPRINT::Add(): Nested footprints not supported" ) );
2016 return;
2017
2018 case PCB_POINT_T:
2019 if( aMode == ADD_MODE::APPEND )
2020 m_points.push_back( static_cast<PCB_POINT*>( aBoardItem ) );
2021 else
2022 m_points.insert( m_points.begin(), static_cast<PCB_POINT*>( aBoardItem ) );
2023
2024 break;
2025
2026 case PCB_3D_BODY_T:
2027 if( aMode == ADD_MODE::APPEND )
2028 m_bodies.push_back( static_cast<PCB_3D_BODY*>( aBoardItem ) );
2029 else
2030 m_bodies.push_front( static_cast<PCB_3D_BODY*>( aBoardItem ) );
2031
2032 break;
2033
2034 default:
2035 wxFAIL_MSG( wxString::Format( wxT( "FOOTPRINT::Add(): BOARD_ITEM type (%d) not handled" ),
2036 aBoardItem->Type() ) );
2037
2038 return;
2039 }
2040
2041 aBoardItem->ClearEditFlags();
2042 aBoardItem->SetParent( this );
2043
2044 // If this footprint is on a board, update the board's item-by-id cache
2045 // Skip caching for copy-constructed footprints (inherited board ptr but not a real member).
2046 if( BOARD* board = GetBoard(); board && board->IsItemIndexedById( this ) )
2047 {
2048 board->CacheItemSubtreeById( *aBoardItem );
2049
2050 // A pad arriving here never passes through BOARD::Add, so this is the only chance to
2051 // invalidate the drill caches
2052 board->noteDrillModelChange( aBoardItem );
2053 }
2054
2056}
2057
2058
2059void FOOTPRINT::Remove( BOARD_ITEM* aBoardItem, REMOVE_MODE aMode )
2060{
2061 switch( aBoardItem->Type() )
2062 {
2063 case PCB_FIELD_T:
2064 for( auto it = m_fields.begin(); it != m_fields.end(); ++it )
2065 {
2066 if( *it == aBoardItem )
2067 {
2068 const wxString fieldName = ( *it )->GetUntranslatedName();
2069
2070 m_fields.erase( it );
2071
2072 for( auto& [variantName, footprintVariant] : m_variants )
2073 footprintVariant.RemoveFieldValue( fieldName );
2074
2075 break;
2076 }
2077 }
2078
2079 break;
2080
2081 case PCB_BARCODE_T:
2082 case PCB_TEXT_T:
2083 case PCB_DIM_ALIGNED_T:
2084 case PCB_DIM_CENTER_T:
2086 case PCB_DIM_RADIAL_T:
2087 case PCB_DIM_LEADER_T:
2088 case PCB_SHAPE_T:
2089 case PCB_TEXTBOX_T:
2090 case PCB_TABLE_T:
2092 for( auto it = m_drawings.begin(); it != m_drawings.end(); ++it )
2093 {
2094 if( *it == aBoardItem )
2095 {
2096 m_drawings.erase( it );
2097 break;
2098 }
2099 }
2100
2101 break;
2102
2103 case PCB_PAD_T:
2104 for( auto it = m_pads.begin(); it != m_pads.end(); ++it )
2105 {
2106 if( *it == static_cast<PAD*>( aBoardItem ) )
2107 {
2108 m_pads.erase( it );
2109 break;
2110 }
2111 }
2112
2113 break;
2114
2115 case PCB_ZONE_T:
2116 for( auto it = m_zones.begin(); it != m_zones.end(); ++it )
2117 {
2118 if( *it == static_cast<ZONE*>( aBoardItem ) )
2119 {
2120 m_zones.erase( it );
2121 break;
2122 }
2123 }
2124
2125 break;
2126
2127 case PCB_CONSTRAINT_T:
2128 for( auto it = m_constraints.begin(); it != m_constraints.end(); ++it )
2129 {
2130 if( *it == static_cast<PCB_CONSTRAINT*>( aBoardItem ) )
2131 {
2132 m_constraints.erase( it );
2133 break;
2134 }
2135 }
2136
2137 break;
2138
2139 case PCB_GROUP_T:
2140 for( auto it = m_groups.begin(); it != m_groups.end(); ++it )
2141 {
2142 if( *it == static_cast<PCB_GROUP*>( aBoardItem ) )
2143 {
2144 m_groups.erase( it );
2145 break;
2146 }
2147 }
2148
2149 break;
2150
2151 case PCB_MARKER_T:
2152 wxFAIL_MSG( wxT( "FOOTPRINT::Remove(): Markers go at the board level, even in the footprint editor" ) );
2153 break;
2154
2155 case PCB_FOOTPRINT_T:
2156 wxFAIL_MSG( wxT( "FOOTPRINT::Remove(): Nested footprints not supported" ) );
2157 break;
2158
2159 case PCB_POINT_T:
2160 for( auto it = m_points.begin(); it != m_points.end(); ++it )
2161 {
2162 if( *it == static_cast<PCB_POINT*>( aBoardItem ) )
2163 {
2164 m_points.erase( it );
2165 break;
2166 }
2167 }
2168
2169 break;
2170
2171 case PCB_3D_BODY_T:
2172 std::erase( m_bodies, static_cast<PCB_3D_BODY*>( aBoardItem ) );
2173 break;
2174
2175 default:
2176 wxFAIL_MSG( wxString::Format( wxT( "FOOTPRINT::Remove() needs work: BOARD_ITEM type (%d) not handled" ),
2177 aBoardItem->Type() ) );
2178 }
2179
2180 // If this footprint is on a board, update the board's item-by-id cache
2181 if( BOARD* board = GetBoard() )
2182 {
2183 if( board->IsItemIndexedById( this ) )
2184 {
2185 board->UncacheItemSubtreeById( *aBoardItem );
2186 board->noteDrillModelChange( aBoardItem );
2187 }
2188
2189 board->IncrementTimeStamp();
2190 }
2191
2192 aBoardItem->SetFlags( STRUCT_DELETED );
2193
2195}
2196
2197
2198double FOOTPRINT::GetArea( int aPadding ) const
2199{
2200 BOX2I bbox = GetBoundingBox( false );
2201
2202 double w = std::abs( static_cast<double>( bbox.GetWidth() ) ) + aPadding;
2203 double h = std::abs( static_cast<double>( bbox.GetHeight() ) ) + aPadding;
2204 return w * h;
2205}
2206
2207
2209{
2210 int smd_count = 0;
2211 int tht_count = 0;
2212
2213 for( PAD* pad : m_pads )
2214 {
2215 switch( pad->GetProperty() )
2216 {
2219 continue;
2220
2221 case PAD_PROP::HEATSINK:
2224 continue;
2225
2226 case PAD_PROP::NONE:
2227 case PAD_PROP::BGA:
2229 case PAD_PROP::PRESSFIT:
2230 break;
2231 }
2232
2233 switch( pad->GetAttribute() )
2234 {
2235 case PAD_ATTRIB::PTH:
2236 tht_count++;
2237 break;
2238
2239 case PAD_ATTRIB::SMD:
2240 if( pad->IsOnCopperLayer() )
2241 smd_count++;
2242
2243 break;
2244
2246 case PAD_ATTRIB::CONN:
2247 case PAD_ATTRIB::NPTH:
2248 break;
2249 }
2250 }
2251
2252 // Footprints with plated through-hole pads should usually be marked through hole even if they
2253 // also have SMD because they might not be auto-placed. Exceptions to this might be shielded
2254 if( tht_count > 0 )
2255 return FP_THROUGH_HOLE;
2256
2257 if( smd_count > 0 )
2258 return FP_SMD;
2259
2260 return 0;
2261}
2262
2263
2265{
2267 return _( "SMD" );
2268
2270 return _( "Through hole" );
2271
2272 return _( "Unspecified" );
2273}
2274
2275
2286
2287
2289{
2291
2292 if( aMountingStyle == FOOTPRINT_TYPE::THROUGH_HOLE )
2294 else if( aMountingStyle == FOOTPRINT_TYPE::SMD )
2296}
2297
2298
2299std::vector<SEARCH_TERM>& FOOTPRINT::GetSearchTerms()
2300{
2301 m_searchTerms.clear();
2302 m_searchTerms.reserve( 6 );
2303
2304 m_searchTerms.emplace_back( SEARCH_TERM( GetLibNickname(), 4 ) );
2305 m_searchTerms.emplace_back( SEARCH_TERM( GetName(), 8, true ) );
2306 m_searchTerms.emplace_back( SEARCH_TERM( GetLIB_ID().Format(), 16, true ) );
2307
2308 wxStringTokenizer keywordTokenizer( GetKeywords(), wxS( " \t\r\n" ), wxTOKEN_STRTOK );
2309
2310 while( keywordTokenizer.HasMoreTokens() )
2311 m_searchTerms.emplace_back( SEARCH_TERM( keywordTokenizer.GetNextToken(), 4 ) );
2312
2313 m_searchTerms.emplace_back( SEARCH_TERM( GetKeywords(), 1 ) );
2314 m_searchTerms.emplace_back( SEARCH_TERM( GetLibDescription(), 1 ) );
2315
2316 return m_searchTerms;
2317}
2318
2319
2321{
2322 BOX2I bbox;
2323
2324 // We want the bounding box of the footprint pads at rot 0, not flipped
2325 // Create such a image:
2326 FOOTPRINT dummy( *this );
2327
2328 dummy.SetPosition( VECTOR2I( 0, 0 ) );
2329 dummy.SetOrientation( ANGLE_0 );
2330
2331 if( dummy.IsFlipped() )
2332 dummy.Flip( VECTOR2I( 0, 0 ), FLIP_DIRECTION::TOP_BOTTOM );
2333
2334 for( PAD* pad : dummy.Pads() )
2335 bbox.Merge( pad->GetBoundingBox() );
2336
2337 return bbox;
2338}
2339
2340
2342{
2343 for( BOARD_ITEM* item : m_drawings )
2344 {
2345 if( m_privateLayers.test( item->GetLayer() ) )
2346 continue;
2347
2348 if( item->Type() != PCB_FIELD_T && item->Type() != PCB_TEXT_T )
2349 return false;
2350 }
2351
2352 return true;
2353}
2354
2355
2357{
2358 return GetBoundingBox( true );
2359}
2360
2361
2362const BOX2I FOOTPRINT::GetBoundingBox( bool aIncludeText ) const
2363{
2364 const BOARD* board = GetBoard();
2365
2366 if( board )
2367 {
2368 std::lock_guard<std::mutex> lock( m_geometry_cache_mutex );
2369
2370 if( !m_geometry_cache )
2371 m_geometry_cache = std::make_unique<FOOTPRINT_GEOMETRY_CACHE_DATA>();
2372
2373 if( aIncludeText )
2374 {
2375 if( m_geometry_cache->bounding_box_timestamp >= board->GetTimeStamp() )
2376 return m_geometry_cache->bounding_box;
2377 }
2378 else
2379 {
2380 if( m_geometry_cache->text_excluded_bbox_timestamp >= board->GetTimeStamp() )
2381 return m_geometry_cache->text_excluded_bbox;
2382 }
2383 }
2384
2385 std::vector<PCB_TEXT*> texts;
2386 bool isFPEdit = board && board->IsFootprintHolder();
2387
2388 BOX2I bbox( m_transform.GetTranslate() );
2389 bbox.Inflate( pcbIUScale.mmToIU( 0.25 ) ); // Give a min size to the bbox
2390
2391 // Calculate the footprint side
2392 PCB_LAYER_ID footprintSide = GetSide();
2393
2394 for( BOARD_ITEM* item : m_drawings )
2395 {
2396 if( IsValidLayer( item->GetLayer() ) && m_privateLayers.test( item->GetLayer() ) && !isFPEdit )
2397 continue;
2398
2399 // We want the bitmap bounding box just in the footprint editor
2400 // so it will start with the correct initial zoom
2401 if( item->Type() == PCB_REFERENCE_IMAGE_T && !isFPEdit )
2402 continue;
2403
2404 // Handle text separately
2405 if( item->Type() == PCB_TEXT_T )
2406 {
2407 texts.push_back( static_cast<PCB_TEXT*>( item ) );
2408 continue;
2409 }
2410
2411 // If we're not including text then drop annotations as well -- unless, of course, it's
2412 // an unsided footprint -- in which case it's likely to be nothing *but* annotations.
2413 if( !aIncludeText && footprintSide != UNDEFINED_LAYER )
2414 {
2415 if( BaseType( item->Type() ) == PCB_DIMENSION_T )
2416 continue;
2417
2418 if( item->GetLayer() == Cmts_User || item->GetLayer() == Dwgs_User
2419 || item->GetLayer() == Eco1_User || item->GetLayer() == Eco2_User )
2420 {
2421 continue;
2422 }
2423 }
2424
2425 bbox.Merge( item->GetBoundingBox() );
2426 }
2427
2428 for( PCB_FIELD* field : m_fields )
2429 {
2430 // Reference and value get their own processing
2431 if( field->IsReference() || field->IsValue() )
2432 continue;
2433
2434 texts.push_back( field );
2435 }
2436
2437 for( PAD* pad : m_pads )
2438 bbox.Merge( pad->GetBoundingBox() );
2439
2440 for( ZONE* zone : m_zones )
2441 bbox.Merge( zone->GetBoundingBox() );
2442
2443 for( PCB_POINT* point : m_points )
2444 bbox.Merge( point->GetBoundingBox() );
2445
2446 bool noDrawItems = ( m_drawings.empty() && m_pads.empty() && m_zones.empty() );
2447
2448 // Groups do not contribute to the rect, only their members
2449 if( aIncludeText || noDrawItems )
2450 {
2451 // Only PCB_TEXT and PCB_FIELD items are independently selectable; PCB_TEXTBOX items go
2452 // in with other graphic items above.
2453 for( PCB_TEXT* text : texts )
2454 {
2455 if( !isFPEdit && m_privateLayers.test( text->GetLayer() ) )
2456 continue;
2457
2458 if( text->Type() == PCB_FIELD_T && !text->IsVisible() )
2459 continue;
2460
2461 bbox.Merge( text->GetBoundingBox() );
2462 }
2463
2464 // A footprint is constructed with its mandatory fields, but they can be removed again
2465 // through the editing dialogs or the scripting API, and the const accessors return
2466 // nullptr rather than recreating them.
2467 const PCB_FIELD* value = GetField( FIELD_T::VALUE );
2468 const PCB_FIELD* reference = GetField( FIELD_T::REFERENCE );
2469
2470 // This can be further optimized when aIncludeInvisibleText is true, but currently
2471 // leaving this as is until it's determined there is a noticeable speed hit.
2472 bool valueLayerIsVisible = true;
2473 bool refLayerIsVisible = true;
2474
2475 if( board )
2476 {
2477 // The first "&&" conditional handles the user turning layers off as well as layers
2478 // not being present in the current PCB stackup. Values, references, and all
2479 // footprint text can also be turned off via the GAL meta-layers, so the 2nd and
2480 // 3rd "&&" conditionals handle that.
2481 if( value )
2482 {
2483 valueLayerIsVisible = board->IsLayerVisible( value->GetLayer() )
2484 && board->IsElementVisible( LAYER_FP_VALUES )
2485 && board->IsElementVisible( LAYER_FP_TEXT );
2486 }
2487
2488 if( reference )
2489 {
2490 refLayerIsVisible = board->IsLayerVisible( reference->GetLayer() )
2491 && board->IsElementVisible( LAYER_FP_REFERENCES )
2492 && board->IsElementVisible( LAYER_FP_TEXT );
2493 }
2494 }
2495
2496
2497 if( value && ( ( value->IsVisible() && valueLayerIsVisible ) || noDrawItems ) )
2498 bbox.Merge( value->GetBoundingBox() );
2499
2500 if( reference && ( ( reference->IsVisible() && refLayerIsVisible ) || noDrawItems ) )
2501 bbox.Merge( reference->GetBoundingBox() );
2502 }
2503
2504 if( board )
2505 {
2506 std::lock_guard<std::mutex> lock( m_geometry_cache_mutex );
2507
2508 if( !m_geometry_cache )
2509 m_geometry_cache = std::make_unique<FOOTPRINT_GEOMETRY_CACHE_DATA>();
2510
2511 if( aIncludeText || noDrawItems )
2512 {
2513 m_geometry_cache->bounding_box_timestamp = board->GetTimeStamp();
2514 m_geometry_cache->bounding_box = bbox;
2515 }
2516 else
2517 {
2518 m_geometry_cache->text_excluded_bbox_timestamp = board->GetTimeStamp();
2519 m_geometry_cache->text_excluded_bbox = bbox;
2520 }
2521 }
2522
2523 return bbox;
2524}
2525
2526
2527const BOX2I FOOTPRINT::GetLayerBoundingBox( const LSET& aLayers ) const
2528{
2529 std::vector<PCB_TEXT*> texts;
2530 const BOARD* board = GetBoard();
2531 bool isFPEdit = board && board->IsFootprintHolder();
2532
2533 // Start with an uninitialized bounding box
2534 BOX2I bbox;
2535
2536 for( BOARD_ITEM* item : m_drawings )
2537 {
2538 if( IsValidLayer( item->GetLayer() ) && m_privateLayers.test( item->GetLayer() ) && !isFPEdit )
2539 continue;
2540
2541 if( ( aLayers & item->GetLayerSet() ).none() )
2542 continue;
2543
2544 // We want the bitmap bounding box just in the footprint editor
2545 // so it will start with the correct initial zoom
2546 if( item->Type() == PCB_REFERENCE_IMAGE_T && !isFPEdit )
2547 continue;
2548
2549 bbox.Merge( item->GetBoundingBox() );
2550 }
2551
2552 for( PAD* pad : m_pads )
2553 {
2554 if( ( aLayers & pad->GetLayerSet() ).none() )
2555 continue;
2556
2557 bbox.Merge( pad->GetBoundingBox() );
2558 }
2559
2560 for( ZONE* zone : m_zones )
2561 {
2562 if( ( aLayers & zone->GetLayerSet() ).none() )
2563 continue;
2564
2565 bbox.Merge( zone->GetBoundingBox() );
2566 }
2567
2568 for( PCB_POINT* point : m_points )
2569 {
2570 if( m_privateLayers.test( point->GetLayer() ) && !isFPEdit )
2571 continue;
2572
2573 if( ( aLayers & point->GetLayerSet() ).none() )
2574 continue;
2575
2576 bbox.Merge( point->GetBoundingBox() );
2577 }
2578
2579 return bbox;
2580}
2581
2582
2584{
2585 const BOARD* board = GetBoard();
2586 bool isFPEdit = board && board->IsFootprintHolder();
2587
2588 if( board )
2589 {
2590 std::lock_guard<std::mutex> lock( m_geometry_cache_mutex );
2591
2592 if( m_geometry_cache && m_geometry_cache->hull_timestamp >= board->GetTimeStamp() )
2593 return m_geometry_cache->hull;
2594 }
2595
2596 SHAPE_POLY_SET rawPolys;
2597
2598 for( BOARD_ITEM* item : m_drawings )
2599 {
2600 if( !isFPEdit && m_privateLayers.test( item->GetLayer() ) )
2601 continue;
2602
2603 if( item->Type() != PCB_FIELD_T && item->Type() != PCB_REFERENCE_IMAGE_T )
2604 item->TransformShapeToPolygon( rawPolys, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
2605
2606 // We intentionally exclude footprint fields from the bounding hull.
2607 }
2608
2609 for( PAD* pad : m_pads )
2610 {
2611 pad->Padstack().ForEachUniqueLayer(
2612 [&]( PCB_LAYER_ID aLayer )
2613 {
2614 pad->TransformShapeToPolygon( rawPolys, aLayer, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
2615 } );
2616
2617 // In case hole is larger than pad
2618 pad->TransformHoleToPolygon( rawPolys, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
2619 }
2620
2621 for( ZONE* zone : m_zones )
2622 {
2623 for( PCB_LAYER_ID layer : zone->GetLayerSet() )
2624 {
2625 const SHAPE_POLY_SET& layerPoly = *zone->GetFilledPolysList( layer );
2626
2627 for( int ii = 0; ii < layerPoly.OutlineCount(); ii++ )
2628 {
2629 const SHAPE_LINE_CHAIN& poly = layerPoly.COutline( ii );
2630 rawPolys.AddOutline( poly );
2631 }
2632 }
2633 }
2634
2635 // If there are some graphic items, build the actual hull.
2636 // However if no items, create a minimal polygon (can happen if a footprint
2637 // is created with no item: it contains only 2 texts.
2638 if( rawPolys.OutlineCount() == 0 || rawPolys.FullPointCount() < 3 )
2639 {
2640 // generate a small dummy rectangular outline around the anchor
2641 const int halfsize = pcbIUScale.mmToIU( 1.0 );
2642
2643 rawPolys.NewOutline();
2644
2645 // add a square:
2646 rawPolys.Append( GetPosition().x - halfsize, GetPosition().y - halfsize );
2647 rawPolys.Append( GetPosition().x + halfsize, GetPosition().y - halfsize );
2648 rawPolys.Append( GetPosition().x + halfsize, GetPosition().y + halfsize );
2649 rawPolys.Append( GetPosition().x - halfsize, GetPosition().y + halfsize );
2650 }
2651
2652 std::vector<VECTOR2I> convex_hull;
2653 BuildConvexHull( convex_hull, rawPolys );
2654
2655 {
2656 std::lock_guard<std::mutex> lock( m_geometry_cache_mutex );
2657
2658 if( !m_geometry_cache )
2659 m_geometry_cache = std::make_unique<FOOTPRINT_GEOMETRY_CACHE_DATA>();
2660
2661 m_geometry_cache->hull.RemoveAllContours();
2662 m_geometry_cache->hull.NewOutline();
2663
2664 for( const VECTOR2I& pt : convex_hull )
2665 m_geometry_cache->hull.Append( pt );
2666
2667 if( board )
2668 m_geometry_cache->hull_timestamp = board->GetTimeStamp();
2669
2670 return m_geometry_cache->hull;
2671 }
2672}
2673
2674
2676{
2677 const BOARD* board = GetBoard();
2678 bool isFPEdit = board && board->IsFootprintHolder();
2679
2680 SHAPE_POLY_SET rawPolys;
2681 SHAPE_POLY_SET hull;
2682
2683 for( BOARD_ITEM* item : m_drawings )
2684 {
2685 if( !isFPEdit && m_privateLayers.test( item->GetLayer() ) )
2686 continue;
2687
2688 if( item->IsOnLayer( aLayer ) )
2689 {
2690 if( item->Type() != PCB_FIELD_T && item->Type() != PCB_REFERENCE_IMAGE_T )
2691 item->TransformShapeToPolygon( rawPolys, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
2692
2693 // We intentionally exclude footprint fields from the bounding hull.
2694 }
2695 }
2696
2697 for( PAD* pad : m_pads )
2698 {
2699 if( pad->IsOnLayer( aLayer ) )
2700 pad->TransformShapeToPolygon( rawPolys, aLayer, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
2701 }
2702
2703 for( ZONE* zone : m_zones )
2704 {
2705 if( zone->GetIsRuleArea() )
2706 continue;
2707
2708 if( zone->IsOnLayer( aLayer ) )
2709 {
2710 const std::shared_ptr<SHAPE_POLY_SET>& layerPoly = zone->GetFilledPolysList( aLayer );
2711
2712 for( int ii = 0; ii < layerPoly->OutlineCount(); ii++ )
2713 rawPolys.AddOutline( layerPoly->COutline( ii ) );
2714 }
2715 }
2716
2717 std::vector<VECTOR2I> convex_hull;
2718 BuildConvexHull( convex_hull, rawPolys );
2719
2720 hull.NewOutline();
2721
2722 for( const VECTOR2I& pt : convex_hull )
2723 hull.Append( pt );
2724
2725 return hull;
2726}
2727
2728
2729void FOOTPRINT::GetMsgPanelInfo( EDA_DRAW_FRAME* aFrame, std::vector<MSG_PANEL_ITEM>& aList )
2730{
2731 wxString msg, msg2;
2732 wxString variant;
2733
2734 if( BOARD* board = GetBoard() )
2735 variant = board->GetCurrentVariant();
2736
2737 // Don't use GetShownText(); we want to see the variable references here
2738 aList.emplace_back( UnescapeString( Reference().GetText() ),
2740 UNTRANSLATED ) ) ) );
2741
2742 if( aFrame->IsType( FRAME_FOOTPRINT_VIEWER )
2743 || aFrame->IsType( FRAME_FOOTPRINT_CHOOSER )
2744 || aFrame->IsType( FRAME_FOOTPRINT_EDITOR ) )
2745 {
2746 aList.emplace_back( _( "Library" ), GetFPID().GetLibNickname().wx_str() );
2747
2748 aList.emplace_back( _( "Footprint Name" ), GetFPID().GetLibItemName().wx_str() );
2749
2750 aList.emplace_back( _( "Pads" ), wxString::Format( wxT( "%u" ), GetNumberedPadCount() ) );
2751
2752 aList.emplace_back( wxString::Format( _( "Doc: %s" ), GetLibDescription() ),
2753 wxString::Format( _( "Keywords: %s" ), GetKeywords() ) );
2754
2755 return;
2756 }
2757
2758 // aFrame is the board editor:
2759
2760 switch( GetSide() )
2761 {
2762 case F_Cu: aList.emplace_back( _( "Board Side" ), _( "Front" ) ); break;
2763 case B_Cu: aList.emplace_back( _( "Board Side" ), _( "Back (Flipped)" ) ); break;
2764 default: /* unsided: user-layers only, etc. */ break;
2765 }
2766
2767 aList.emplace_back( _( "Rotation" ), wxString::Format( wxT( "%.4g" ), GetOrientation().AsDegrees() ) );
2768
2769 auto addToken = []( wxString* aStr, const wxString& aAttr )
2770 {
2771 if( !aStr->IsEmpty() )
2772 *aStr += wxT( ", " );
2773
2774 *aStr += aAttr;
2775 };
2776
2777 wxString status;
2778 wxString attrs;
2779
2780 if( IsLocked() )
2781 addToken( &status, _( "Locked" ) );
2782
2783 if( IsPlaced() )
2784 addToken( &status, _( "autoplaced" ) );
2785
2786 if( IsBoardOnly() )
2787 addToken( &attrs, _( "not in schematic" ) );
2788
2789 if( GetExcludedFromPosFilesForVariant( variant ) )
2790 addToken( &attrs, _( "exclude from pos files" ) );
2791
2792 if( GetExcludedFromBOMForVariant( variant ) )
2793 addToken( &attrs, _( "exclude from BOM" ) );
2794
2795 if( GetExcludedFromSimForVariant( variant ) )
2796 addToken( &attrs, _( "exclude from simulation" ) );
2797
2798 if( GetDNPForVariant( variant ) )
2799 addToken( &attrs, _( "DNP" ) );
2800
2801 aList.emplace_back( _( "Status: " ) + status, _( "Attributes:" ) + wxS( " " ) + attrs );
2802
2803 if( !m_componentClassCacheProxy->GetComponentClass()->IsEmpty() )
2804 {
2805 aList.emplace_back( _( "Component Class" ),
2806 m_componentClassCacheProxy->GetComponentClass()->GetHumanReadableName() );
2807 }
2808
2809 msg.Printf( _( "Footprint: %s" ), m_fpid.GetUniStringLibId() );
2810 msg2.Printf( _( "3D-Shape: %s" ), m_3D_Drawings.empty() ? _( "<none>" ) : m_3D_Drawings.front().m_Filename );
2811 aList.emplace_back( msg, msg2 );
2812
2813 msg.Printf( _( "Doc: %s" ), m_libDescription );
2814 msg2.Printf( _( "Keywords: %s" ), m_keywords );
2815 aList.emplace_back( msg, msg2 );
2816}
2817
2818
2820{
2821 if( const BOARD* board = GetBoard() )
2822 {
2823 if( board->IsFootprintHolder() )
2824 return UNDEFINED_LAYER;
2825 }
2826
2827 // Test pads first; they're the most likely to return a quick answer.
2828 for( PAD* pad : m_pads )
2829 {
2830 if( ( LSET::SideSpecificMask() & pad->GetLayerSet() ).any() )
2831 return GetLayer();
2832 }
2833
2834 for( BOARD_ITEM* item : m_drawings )
2835 {
2836 if( IsValidLayer( item->GetLayer() ) && LSET::SideSpecificMask().test( item->GetLayer() ) )
2837 return GetLayer();
2838 }
2839
2840 for( ZONE* zone : m_zones )
2841 {
2842 if( ( LSET::SideSpecificMask() & zone->GetLayerSet() ).any() )
2843 return GetLayer();
2844 }
2845
2846 return UNDEFINED_LAYER;
2847}
2848
2849
2851{
2852 auto isOnLayer =
2853 [aLayer]( const BOARD_ITEM* aItem )
2854 {
2855 return aItem->IsOnLayer( aLayer );
2856 };
2857
2858 return std::ranges::any_of( m_pads, isOnLayer )
2859 || std::ranges::any_of( m_zones, isOnLayer )
2860 || std::ranges::any_of( m_fields, isOnLayer )
2861 || std::ranges::any_of( m_drawings, isOnLayer );
2862}
2863
2864
2865bool FOOTPRINT::HitTestOnLayer( const VECTOR2I& aPosition, PCB_LAYER_ID aLayer, int aAccuracy ) const
2866{
2867 for( PAD* pad : m_pads )
2868 {
2869 if( pad->IsOnLayer( aLayer ) && pad->HitTest( aPosition, aAccuracy ) )
2870 return true;
2871 }
2872
2873 for( ZONE* zone : m_zones )
2874 {
2875 if( zone->IsOnLayer( aLayer ) && zone->HitTest( aPosition, aAccuracy ) )
2876 return true;
2877 }
2878
2879 for( BOARD_ITEM* item : m_drawings )
2880 {
2881 if( item->Type() != PCB_TEXT_T && item->IsOnLayer( aLayer )
2882 && item->HitTest( aPosition, aAccuracy ) )
2883 {
2884 return true;
2885 }
2886 }
2887
2888 return false;
2889}
2890
2891
2892bool FOOTPRINT::HitTestOnLayer( const BOX2I& aRect, bool aContained, PCB_LAYER_ID aLayer, int aAccuracy ) const
2893{
2894 std::vector<BOARD_ITEM*> items;
2895
2896 for( PAD* pad : m_pads )
2897 {
2898 if( pad->IsOnLayer( aLayer ) )
2899 items.push_back( pad );
2900 }
2901
2902 for( ZONE* zone : m_zones )
2903 {
2904 if( zone->IsOnLayer( aLayer ) )
2905 items.push_back( zone );
2906 }
2907
2908 for( BOARD_ITEM* item : m_drawings )
2909 {
2910 if( item->Type() != PCB_TEXT_T && item->IsOnLayer( aLayer ) )
2911 items.push_back( item );
2912 }
2913
2914 // If we require the elements to be contained in the rect and any of them are not,
2915 // we can return false;
2916 // Conversely, if we just require any of the elements to have a hit, we can return true
2917 // when the first one is found.
2918 for( BOARD_ITEM* item : items )
2919 {
2920 if( !aContained && item->HitTest( aRect, aContained, aAccuracy ) )
2921 return true;
2922 else if( aContained && !item->HitTest( aRect, aContained, aAccuracy ) )
2923 return false;
2924 }
2925
2926 // If we didn't exit in the loop, that means that we did not return false for aContained or
2927 // we did not return true for !aContained. So we can just return the bool with a test of
2928 // whether there were any elements or not.
2929 return !items.empty() && aContained;
2930}
2931
2932
2933bool FOOTPRINT::HitTest( const VECTOR2I& aPosition, int aAccuracy ) const
2934{
2935 BOX2I rect = GetBoundingBox( false );
2936 return rect.Inflate( aAccuracy ).Contains( aPosition );
2937}
2938
2939
2940bool FOOTPRINT::HitTestAccurate( const VECTOR2I& aPosition, int aAccuracy ) const
2941{
2942 return GetBoundingHull().Collide( aPosition, aAccuracy );
2943}
2944
2945
2946bool FOOTPRINT::HitTest( const BOX2I& aRect, bool aContained, int aAccuracy ) const
2947{
2948 BOX2I arect = aRect;
2949 arect.Inflate( aAccuracy );
2950
2951 if( aContained )
2952 {
2953 return arect.Contains( GetBoundingBox( false ) );
2954 }
2955 else
2956 {
2957 // If the rect does not intersect the bounding box, skip any tests
2958 if( !arect.Intersects( GetBoundingBox( false ) ) )
2959 return false;
2960
2961 // If there are no pads, zones, or drawings, allow intersection with text
2962 if( m_pads.empty() && m_zones.empty() && m_drawings.empty() )
2963 return GetBoundingBox( true ).Intersects( arect );
2964
2965 // Determine if any elements in the FOOTPRINT intersect the rect
2966 for( PAD* pad : m_pads )
2967 {
2968 if( pad->HitTest( arect, false, 0 ) )
2969 return true;
2970 }
2971
2972 for( ZONE* zone : m_zones )
2973 {
2974 if( zone->HitTest( arect, false, 0 ) )
2975 return true;
2976 }
2977
2978 for( PCB_POINT* point : m_points )
2979 {
2980 if( point->HitTest( arect, false, 0 ) )
2981 return true;
2982 }
2983
2984 // PCB fields are selectable on their own, so they don't get tested
2985
2986 for( BOARD_ITEM* item : m_drawings )
2987 {
2988 // Text items are selectable on their own, and are therefore excluded from this
2989 // test. TextBox items are NOT selectable on their own, and so MUST be included
2990 // here. Bitmaps aren't selectable since they aren't displayed.
2991 if( item->Type() != PCB_TEXT_T && item->HitTest( arect, false, 0 ) )
2992 return true;
2993 }
2994
2995 // Groups are not hit-tested; only their members
2996
2997 // No items were hit
2998 return false;
2999 }
3000}
3001
3002
3003bool FOOTPRINT::HitTest( const SHAPE_LINE_CHAIN& aPoly, bool aContained ) const
3004{
3005 using std::ranges::all_of;
3006 using std::ranges::any_of;
3007
3008 // If there are no pads, zones, or drawings, test footprint text instead.
3009 if( m_pads.empty() && m_zones.empty() && m_drawings.empty() )
3010 return KIGEOM::BoxHitTest( aPoly, GetBoundingBox( true ), aContained );
3011
3012 auto hitTest =
3013 [&]( const auto* aItem )
3014 {
3015 return aItem && aItem->HitTest( aPoly, aContained );
3016 };
3017
3018 // Filter out text items from the drawings, since they are selectable on their own,
3019 // and we don't want to select the whole footprint when text is hit. TextBox items are NOT
3020 // selectable on their own, so they are not excluded here.
3021 auto drawings = m_drawings | std::views::filter( []( const auto* aItem )
3022 {
3023 return aItem && aItem->Type() != PCB_TEXT_T;
3024 } );
3025
3026 // Test pads, zones and drawings with text excluded. PCB fields are also selectable
3027 // on their own, so they don't get tested. Groups are not hit-tested, only their members.
3028 // Bitmaps aren't selectable since they aren't displayed.
3029 if( aContained )
3030 {
3031 // All items must be contained in the selection poly.
3032 return all_of( drawings, hitTest )
3033 && all_of( m_pads, hitTest )
3034 && all_of( m_zones, hitTest );
3035 }
3036 else
3037 {
3038 // Any item intersecting the selection poly is sufficient.
3039 return any_of( drawings, hitTest )
3040 || any_of( m_pads, hitTest )
3041 || any_of( m_zones, hitTest );
3042 }
3043}
3044
3045
3046PAD* FOOTPRINT::FindPadByNumber( const wxString& aPadNumber, PAD* aSearchAfterMe ) const
3047{
3048 bool can_select = aSearchAfterMe ? false : true;
3049
3050 for( PAD* pad : m_pads )
3051 {
3052 if( !can_select && pad == aSearchAfterMe )
3053 {
3054 can_select = true;
3055 continue;
3056 }
3057
3058 if( can_select && pad->GetNumber() == aPadNumber )
3059 return pad;
3060 }
3061
3062 return nullptr;
3063}
3064
3065
3066PAD* FOOTPRINT::FindPadByUuid( const KIID& aUuid ) const
3067{
3068 for( PAD* pad : m_pads )
3069 {
3070 if( pad->m_Uuid == aUuid )
3071 return pad;
3072 }
3073
3074 return nullptr;
3075}
3076
3077
3078PAD* FOOTPRINT::GetPad( const VECTOR2I& aPosition, const LSET& aLayerMask )
3079{
3080 for( PAD* pad : m_pads )
3081 {
3082 // ... and on the correct layer.
3083 if( !( pad->GetLayerSet() & aLayerMask ).any() )
3084 continue;
3085
3086 if( pad->HitTest( aPosition ) )
3087 return pad;
3088 }
3089
3090 return nullptr;
3091}
3092
3093
3094std::vector<const PAD*> FOOTPRINT::GetPads( const wxString& aPadNumber, const PAD* aIgnore ) const
3095{
3096 std::vector<const PAD*> retv;
3097
3098 for( const PAD* pad : m_pads )
3099 {
3100 if( ( aIgnore && aIgnore == pad ) || ( pad->GetNumber() != aPadNumber ) )
3101 continue;
3102
3103 retv.push_back( pad );
3104 }
3105
3106 return retv;
3107}
3108
3109
3111{
3112 return m_pads.size();
3113}
3114
3115
3116std::set<wxString> FOOTPRINT::GetUniquePadNumbers() const
3117{
3118 std::set<wxString> usedNumbers;
3119
3120 // Create a set of used pad numbers
3121 for( PAD* pad : m_pads )
3122 {
3123 // Skip pads not on copper layers (used to build complex
3124 // solder paste shapes for instance)
3125 if( ( pad->GetLayerSet() & LSET::AllCuMask() ).none() )
3126 continue;
3127
3128 // Skip pads with no name, because they are usually "mechanical"
3129 // pads, not "electrical" pads
3130 if( pad->GetNumber().IsEmpty() )
3131 continue;
3132
3133 usedNumbers.insert( pad->GetNumber() );
3134 }
3135
3136 return usedNumbers;
3137}
3138
3139
3141{
3142 // A pad number is "electrical" (i.e. maps to a schematic pin) when it is either:
3143 //
3144 // - purely numeric: "1", "42"
3145 //
3146 // - BGA / alphanumeric style: up to two leading letters followed by digits, e.g.
3147 // "A1", "B12", "AA3", "AB10"
3148 //
3149 // - ganged alphanumeric: two strings matching the above alphanumeric style
3150 // separated by an underscore, as used on the outside
3151 // ganged pins of a USB-C connector, e.g.
3152 // "A1_B12", "A12_B1"
3153 // these pads count as two each, as they will match
3154 // two schematic pins
3155 //
3156 // Mounting-pad designators such as "MP" do not end in a digit typically and are
3157 // intentionally excluded.
3158 auto isElectricalPadNumber =
3159 []( const wxString& num ) -> bool
3160 {
3161 if( num.IsEmpty() )
3162 return false;
3163
3164 // Walk past an optional alphabetic prefix of at most two characters.
3165 size_t i = 0;
3166 while( i < num.size() && wxIsalpha( num[i] ) )
3167 ++i;
3168
3169 // Prefix must be 0–2 letters; anything longer is not a pin number.
3170 if( i > 2 )
3171 return false;
3172
3173 // The remainder must be non-empty and consist entirely of digits.
3174 if( i == num.size() )
3175 return false; // no digits at all (e.g. "MP", "GND")
3176
3177 for( size_t j = i; j < num.size(); ++j )
3178 {
3179 if( !wxIsdigit( num[j] ) )
3180 return false;
3181 }
3182
3183 return true;
3184 };
3185
3186 std::set<wxString> counted;
3187
3188 for( const PAD* pad : m_pads )
3189 {
3190 // Must be on at least one copper layer.
3191 if( ( pad->GetLayerSet() & LSET::AllCuMask() ).none() )
3192 continue;
3193
3194 // Skip NPTH (mechanical holes).
3195 if( pad->GetAttribute() == PAD_ATTRIB::NPTH )
3196 continue;
3197
3198 const wxString& num = pad->GetNumber();
3199
3200 if( isElectricalPadNumber( num ) )
3201 {
3202 counted.insert( num );
3203 }
3204 else if( num.Contains( '_' ) )
3205 {
3206 wxString first, second;
3207 first = num.BeforeFirst( '_', &second );
3208
3209 if( isElectricalPadNumber( first ) && isElectricalPadNumber( second ) )
3210 {
3211 counted.insert( first );
3212 counted.insert( second );
3213 }
3214 }
3215 }
3216
3217 return static_cast<unsigned>( counted.size() );
3218}
3219
3220
3222{
3223 if( nullptr == a3DModel )
3224 return;
3225
3226 if( !a3DModel->m_Filename.empty() )
3227 m_3D_Drawings.push_back( *a3DModel );
3228}
3229
3230
3232{
3233 if( PCB_3D_BODY* body = GetBody() )
3234 return *body;
3235
3236 PCB_3D_BODY* body = new PCB_3D_BODY( this );
3237 Add( body, ADD_MODE::APPEND );
3238 return *body;
3239}
3240
3241
3243{
3244 while( !m_bodies.empty() )
3245 Remove( m_bodies.back() );
3246}
3247
3248bool FOOTPRINT::Matches( const EDA_SEARCH_DATA& aSearchData, void* aAuxData ) const
3249{
3250 if( aSearchData.searchMetadata )
3251 {
3252 if( EDA_ITEM::Matches( GetFPIDAsString(), aSearchData ) )
3253 return true;
3254
3255 if( EDA_ITEM::Matches( GetLibDescription(), aSearchData ) )
3256 return true;
3257
3258 if( EDA_ITEM::Matches( GetKeywords(), aSearchData ) )
3259 return true;
3260 }
3261
3262 return false;
3263}
3264
3265
3266// see footprint.h
3267INSPECT_RESULT FOOTPRINT::Visit( INSPECTOR inspector, void* testData,
3268 const std::vector<KICAD_T>& aScanTypes )
3269{
3270#if 0 && defined(DEBUG)
3271 std::cout << GetClass().mb_str() << ' ';
3272#endif
3273
3274 bool drawingsScanned = false;
3275
3276 for( KICAD_T scanType : aScanTypes )
3277 {
3278 switch( scanType )
3279 {
3280 case PCB_FOOTPRINT_T:
3281 if( inspector( this, testData ) == INSPECT_RESULT::QUIT )
3282 return INSPECT_RESULT::QUIT;
3283
3284 break;
3285
3286 case PCB_PAD_T:
3287 if( IterateForward<PAD*>( m_pads, inspector, testData, { scanType } ) == INSPECT_RESULT::QUIT )
3288 return INSPECT_RESULT::QUIT;
3289
3290 break;
3291
3292 case PCB_ZONE_T:
3293 if( IterateForward<ZONE*>( m_zones, inspector, testData, { scanType } ) == INSPECT_RESULT::QUIT )
3294 return INSPECT_RESULT::QUIT;
3295
3296 break;
3297
3298 case PCB_FIELD_T:
3299 if( IterateForward<PCB_FIELD*>( m_fields, inspector, testData, { scanType } ) == INSPECT_RESULT::QUIT )
3300 return INSPECT_RESULT::QUIT;
3301
3302 break;
3303
3304 case PCB_TEXT_T:
3305 case PCB_DIM_ALIGNED_T:
3306 case PCB_DIM_LEADER_T:
3307 case PCB_DIM_CENTER_T:
3308 case PCB_DIM_RADIAL_T:
3310 case PCB_SHAPE_T:
3311 case PCB_BARCODE_T:
3312 case PCB_TEXTBOX_T:
3313 case PCB_TABLE_T:
3314 case PCB_TABLECELL_T:
3315 if( !drawingsScanned )
3316 {
3317 if( IterateForward<BOARD_ITEM*>( m_drawings, inspector, testData, aScanTypes ) == INSPECT_RESULT::QUIT )
3318 return INSPECT_RESULT::QUIT;
3319
3320 drawingsScanned = true;
3321 }
3322
3323 break;
3324
3325 case PCB_GROUP_T:
3326 if( IterateForward<PCB_GROUP*>( m_groups, inspector, testData, { scanType } ) == INSPECT_RESULT::QUIT )
3327 return INSPECT_RESULT::QUIT;
3328
3329 break;
3330
3331 case PCB_CONSTRAINT_T:
3332 if( IterateForward<PCB_CONSTRAINT*>( m_constraints, inspector, testData, { scanType } )
3334 {
3335 return INSPECT_RESULT::QUIT;
3336 }
3337
3338 break;
3339
3340 case PCB_POINT_T:
3341 if( IterateForward<PCB_POINT*>( m_points, inspector, testData, { scanType } ) == INSPECT_RESULT::QUIT )
3342 return INSPECT_RESULT::QUIT;
3343
3344 break;
3345
3346 case PCB_3D_BODY_T:
3347 if( IterateForward<PCB_3D_BODY*>( m_bodies, inspector, testData, { scanType } )
3349 {
3350 return INSPECT_RESULT::QUIT;
3351 }
3352
3353 break;
3354
3355 default:
3356 break;
3357 }
3358 }
3359
3361}
3362
3363
3364wxString FOOTPRINT::GetItemDescription( UNITS_PROVIDER* aUnitsProvider, bool aFull ) const
3365{
3366 wxString reference = GetReference();
3367
3368 if( reference.IsEmpty() )
3369 reference = _( "<no reference designator>" );
3370
3371 return wxString::Format( _( "Footprint %s" ), reference );
3372}
3373
3374
3375wxString FOOTPRINT::DisambiguateItemDescription( UNITS_PROVIDER* aUnitsProvider, bool aFull ) const
3376{
3377 return wxString::Format( wxT( "%s (%s)" ),
3378 GetItemDescription( aUnitsProvider, aFull ),
3379 GetFPIDAsString() );
3380}
3381
3382
3384{
3385 return BITMAPS::module;
3386}
3387
3388
3390{
3391 return new FOOTPRINT( *this );
3392}
3393
3394
3395void FOOTPRINT::RunOnChildren( const std::function<void( BOARD_ITEM* )>& aFunction, RECURSE_MODE aMode ) const
3396{
3397 try
3398 {
3399 for( PCB_FIELD* field : m_fields )
3400 aFunction( field );
3401
3402 for( PAD* pad : m_pads )
3403 aFunction( pad );
3404
3405 for( ZONE* zone : m_zones )
3406 aFunction( zone );
3407
3408 for( PCB_GROUP* group : m_groups )
3409 aFunction( group );
3410
3411 for( PCB_3D_BODY* body : m_bodies )
3412 aFunction( body );
3413
3414 for( PCB_CONSTRAINT* constraint : m_constraints )
3415 aFunction( constraint );
3416
3417 for( PCB_POINT* point : m_points )
3418 aFunction( point );
3419
3420 for( BOARD_ITEM* drawing : m_drawings )
3421 {
3422 aFunction( drawing );
3423
3424 if( aMode == RECURSE_MODE::RECURSE )
3425 drawing->RunOnChildren( aFunction, RECURSE_MODE::RECURSE );
3426 }
3427 }
3428 catch( std::bad_function_call& )
3429 {
3430 wxFAIL_MSG( wxT( "Error running FOOTPRINT::RunOnChildren" ) );
3431 }
3432}
3433
3434
3435std::vector<int> FOOTPRINT::ViewGetLayers() const
3436{
3437 std::vector<int> layers;
3438
3439 layers.reserve( 6 );
3440 layers.push_back( LAYER_ANCHOR );
3441
3442 switch( m_layer )
3443 {
3444 default:
3445 wxASSERT_MSG( false, wxT( "Illegal layer" ) ); // do you really have footprints placed
3446 // on other layers?
3448
3449 case F_Cu:
3450 layers.push_back( LAYER_FOOTPRINTS_FR );
3451 break;
3452
3453 case B_Cu:
3454 layers.push_back( LAYER_FOOTPRINTS_BK );
3455 break;
3456 }
3457
3458 layers.push_back( LAYER_CONFLICTS_SHADOW );
3459
3460 // If there are no pads, and only drawings on a silkscreen layer, then report the silkscreen
3461 // layer as well so that the component can be edited with the silkscreen layer
3462 bool f_silk = false, b_silk = false, non_silk = false;
3463
3464 for( BOARD_ITEM* item : m_drawings )
3465 {
3466 if( item->GetLayer() == F_SilkS )
3467 f_silk = true;
3468 else if( item->GetLayer() == B_SilkS )
3469 b_silk = true;
3470 else
3471 non_silk = true;
3472 }
3473
3474 if( ( f_silk || b_silk ) && !non_silk && m_pads.empty() )
3475 {
3476 if( f_silk )
3477 layers.push_back( F_SilkS );
3478
3479 if( b_silk )
3480 layers.push_back( B_SilkS );
3481 }
3482
3483 return layers;
3484}
3485
3486
3487double FOOTPRINT::ViewGetLOD( int aLayer, const KIGFX::VIEW* aView ) const
3488{
3489 if( aLayer == LAYER_CONFLICTS_SHADOW )
3490 {
3491 // The painter draws nothing here for a footprint that is not in conflict
3492 if( !IsConflicting() )
3493 return LOD_HIDE;
3494
3495 // The locked shadow shape is shown only if the footprint itself is visible
3496 if( ( m_layer == F_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_FR ) )
3497 return LOD_SHOW;
3498
3499 if( ( m_layer == B_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_BK ) )
3500 return LOD_SHOW;
3501
3502 return LOD_HIDE;
3503 }
3504
3505 // Only show anchors if the layer the footprint is on is visible
3506 if( aLayer == LAYER_ANCHOR && !aView->IsLayerVisible( m_layer ) )
3507 return LOD_HIDE;
3508
3509 int layer = ( m_layer == F_Cu ) ? LAYER_FOOTPRINTS_FR :
3511
3512 // Currently this is only pertinent for the anchor layer; everything else is drawn from the
3513 // children.
3514 // The "good" value is experimentally chosen.
3515 constexpr double MINIMAL_ZOOM_LEVEL_FOR_VISIBILITY = 1.5;
3516
3517 if( aView->IsLayerVisible( layer ) )
3518 return MINIMAL_ZOOM_LEVEL_FOR_VISIBILITY;
3519
3520 return LOD_HIDE;
3521}
3522
3523
3525{
3526 BOX2I area = GetBoundingBox( true );
3527
3528 // Inflate in case clearance lines are drawn around pads, etc.
3529 if( const BOARD* board = GetBoard() )
3530 {
3531 int biggest_clearance = board->GetMaxClearanceValue();
3532 area.Inflate( biggest_clearance );
3533 }
3534
3535 return area;
3536}
3537
3538
3539bool FOOTPRINT::IsLibNameValid( const wxString & aName )
3540{
3541 const wxChar * invalids = StringLibNameInvalidChars( false );
3542
3543 if( aName.find_first_of( invalids ) != std::string::npos )
3544 return false;
3545
3546 return true;
3547}
3548
3549
3550const wxChar* FOOTPRINT::StringLibNameInvalidChars( bool aUserReadable )
3551{
3552 // Filename rules are a superset of LIB_ID rules; the machine-readable list is the shared
3553 // source of truth, while the human-readable spelling stays local.
3554 static const wxString invalidChars = GetLibFilenameForbiddenChars();
3555 static const wxChar invalidCharsReadable[] = wxT("% $ < > 'tab' 'return' 'line feed' \\ \" / :");
3556
3557 if( aUserReadable )
3558 return invalidCharsReadable;
3559 else
3560 return invalidChars.wc_str();
3561}
3562
3563
3564void FOOTPRINT::Move( const VECTOR2I& aMoveVector )
3565{
3566 if( aMoveVector.x == 0 && aMoveVector.y == 0 )
3567 return;
3568
3569 VECTOR2I newpos = m_transform.GetTranslate() + aMoveVector;
3570 SetPosition( newpos );
3571}
3572
3573
3574void FOOTPRINT::Rotate( const VECTOR2I& aRotCentre, const EDA_ANGLE& aAngle )
3575{
3576 if( aAngle == ANGLE_0 )
3577 return;
3578
3580 EDA_ANGLE newOrientation = orientation + aAngle;
3581 VECTOR2I newpos = m_transform.GetTranslate();
3582 RotatePoint( newpos, aRotCentre, aAngle );
3583 SetPosition( newpos );
3584 SetOrientation( newOrientation );
3585
3586 for( PCB_FIELD* field : m_fields )
3587 field->KeepUpright();
3588
3589 for( BOARD_ITEM* item : m_drawings )
3590 {
3591 if( item->Type() == PCB_TEXT_T )
3592 static_cast<PCB_TEXT*>( item )->KeepUpright();
3593 }
3594}
3595
3596
3598{
3599 wxASSERT( aLayer == F_Cu || aLayer == B_Cu );
3600
3601 if( aLayer != GetLayer() )
3603}
3604
3605
3606void FOOTPRINT::Flip( const VECTOR2I& aCentre, FLIP_DIRECTION aFlipDirection )
3607{
3608 // Move footprint to its final position:
3609 VECTOR2I finalPos = m_transform.GetTranslate();
3610
3611 // Now Flip the footprint.
3612 // Flipping a footprint is a specific transform: it is not mirrored like a text.
3613 // We have to change the side, and ensure the footprint rotation is modified according to the
3614 // transform, because this parameter is used in pick and place files, and when updating the
3615 // footprint from library.
3616 // When flipped around the X axis (Y coordinates changed) orientation is negated
3617 // When flipped around the Y axis (X coordinates changed) orientation is 180 - old orient.
3618 // Because it is specific to a footprint, we flip around the X axis, and after rotate 180 deg
3619
3620 MIRROR( finalPos.y, aCentre.y );
3621
3622 SetPosition( finalPos );
3623
3624 // Flip layer
3626
3627 const VECTOR2I pos = m_transform.GetTranslate();
3628
3629 // Children mirror their lib-frame state directly so the result does not
3630 // depend on the parent rotation at the time of the call. The parent
3631 // rotation is negated once at the end.
3632 for( PCB_FIELD* field : m_fields )
3633 field->Flip( pos, FLIP_DIRECTION::TOP_BOTTOM );
3634
3635 for( PAD* pad : m_pads )
3636 pad->Flip( pos, FLIP_DIRECTION::TOP_BOTTOM );
3637
3638 for( ZONE* zone : m_zones )
3639 zone->Flip( pos, FLIP_DIRECTION::TOP_BOTTOM );
3640
3641 for( BOARD_ITEM* item : m_drawings )
3642 item->Flip( pos, FLIP_DIRECTION::TOP_BOTTOM );
3643
3644 // Points move but don't flip layer
3645 for( PCB_POINT* point : m_points )
3646 point->Flip( pos, FLIP_DIRECTION::TOP_BOTTOM );
3647
3648 EDA_ANGLE newOrientation = -m_transform.GetRotate();
3649 newOrientation.Normalize180();
3650 m_transform.SetRotate( newOrientation );
3651
3652 // Refresh derived caches now that the final rotation is in place.
3653 for( PCB_FIELD* field : m_fields )
3654 field->OnFootprintTransformed();
3655
3656 for( PAD* pad : m_pads )
3657 pad->OnFootprintTransformed();
3658
3659 for( ZONE* zone : m_zones )
3660 zone->OnFootprintTransformed();
3661
3662 for( BOARD_ITEM* item : m_drawings )
3663 {
3664 if( item->Type() == PCB_TEXT_T || item->Type() == PCB_SHAPE_T || item->Type() == PCB_TEXTBOX_T
3665 || item->Type() == PCB_BARCODE_T || item->Type() == PCB_TABLE_T
3666 || BaseType( item->Type() ) == PCB_DIMENSION_T )
3667 {
3668 item->OnFootprintTransformed();
3669 }
3670 }
3671
3672 for( PCB_POINT* point : m_points )
3673 point->OnFootprintTransformed();
3674
3675 // Swap the courtyard sides, then mirror in the same way as everything else.
3676 if( m_courtyard_cache )
3677 {
3678 std::swap( m_courtyard_cache->back, m_courtyard_cache->front );
3679 m_courtyard_cache->back.Mirror( pos, FLIP_DIRECTION::TOP_BOTTOM );
3680 m_courtyard_cache->back_hash = m_courtyard_cache->back.GetHash();
3681
3682 m_courtyard_cache->front.Mirror( pos, FLIP_DIRECTION::TOP_BOTTOM );
3683 m_courtyard_cache->front_hash = m_courtyard_cache->front.GetHash();
3684 }
3685
3686 for( PCB_3D_BODY* body : m_bodies )
3687 body->Flip( pos, aFlipDirection );
3688
3689 if( m_geometry_cache )
3690 m_geometry_cache->hull.Mirror( pos, FLIP_DIRECTION::TOP_BOTTOM );
3691
3692 // Now rotate 180 deg if required
3693 if( aFlipDirection == FLIP_DIRECTION::LEFT_RIGHT )
3694 Rotate( aCentre, ANGLE_180 );
3695
3696 if( m_geometry_cache )
3697 m_geometry_cache->text_excluded_bbox_timestamp = 0;
3698
3699 m_flipped = ( GetLayer() == B_Cu );
3700}
3701
3702
3704{
3705 BOARD_ITEM::SetLayer( aLayer );
3706 m_flipped = ( aLayer == B_Cu );
3707}
3708
3709
3710void FOOTPRINT::SetTransformScale( double aScaleX, double aScaleY )
3711{
3712 // Reject zero, negative, and non-finite scales: they produce a degenerate transform.
3713 if( !std::isfinite( aScaleX ) || !std::isfinite( aScaleY ) || aScaleX <= 0.0 || aScaleY <= 0.0 )
3714 return;
3715
3716 const double oldSx = m_transform.GetScaleX();
3717 const double oldSy = m_transform.GetScaleY();
3718 const double ratioX = aScaleX / oldSx;
3719 const double ratioY = aScaleY / oldSy;
3720 const double linearFactor = ( aScaleX + aScaleY ) / ( oldSx + oldSy );
3721
3722 m_transform.SetScale( aScaleX, aScaleY );
3723
3724 const VECTOR2I anchor = m_transform.GetTranslate();
3725 const EDA_ANGLE parentRotate = m_transform.GetRotate();
3726
3727 for( PAD* pad : m_pads )
3728 pad->OnFootprintRescaled( ratioX, ratioY, linearFactor, anchor, parentRotate );
3729
3730 for( PCB_FIELD* field : m_fields )
3731 field->OnFootprintRescaled( ratioX, ratioY, linearFactor, anchor, parentRotate );
3732
3733 for( BOARD_ITEM* item : m_drawings )
3734 item->OnFootprintRescaled( ratioX, ratioY, linearFactor, anchor, parentRotate );
3735
3736 for( ZONE* zone : m_zones )
3737 zone->OnFootprintRescaled( ratioX, ratioY, linearFactor, anchor, parentRotate );
3738
3739 for( PCB_POINT* point : m_points )
3740 point->OnFootprintTransformed();
3741
3742 if( m_geometry_cache )
3743 {
3744 m_geometry_cache->bounding_box_timestamp = 0;
3745 m_geometry_cache->text_excluded_bbox_timestamp = 0;
3746 }
3747
3748 m_courtyard_cache.reset();
3749}
3750
3751
3752void FOOTPRINT::RescaleAroundPoint( const VECTOR2I& aCenter, double aSx, double aSy )
3753{
3754 TRANSFORM_TRS rescaled = m_transform.RescaleAround( aCenter, aSx, aSy );
3755
3756 SetPosition( rescaled.GetTranslate() );
3757 SetTransformScale( rescaled.GetScaleX(), rescaled.GetScaleY() );
3758}
3759
3760
3762{
3763 VECTOR2I delta = aPos - m_transform.GetTranslate();
3764
3765 m_transform.SetTranslate( aPos );
3766
3767 for( PCB_FIELD* field : m_fields )
3768 field->OnFootprintTransformed();
3769
3770 for( PAD* pad : m_pads )
3771 pad->OnFootprintTransformed();
3772
3773 for( ZONE* zone : m_zones )
3774 zone->OnFootprintTransformed();
3775
3776 for( PCB_POINT* point : m_points )
3777 point->OnFootprintTransformed();
3778
3779 for( BOARD_ITEM* item : m_drawings )
3780 {
3781 if( item->Type() == PCB_TEXT_T || item->Type() == PCB_SHAPE_T || item->Type() == PCB_TEXTBOX_T
3782 || item->Type() == PCB_BARCODE_T || item->Type() == PCB_TABLE_T
3783 || BaseType( item->Type() ) == PCB_DIMENSION_T )
3784 {
3785 item->OnFootprintTransformed();
3786 }
3787 else
3788 {
3789 item->Move( delta );
3790 }
3791 }
3792
3793 if( m_geometry_cache )
3794 {
3795 m_geometry_cache->bounding_box.Move( delta );
3796 m_geometry_cache->text_excluded_bbox.Move( delta );
3797 m_geometry_cache->hull.Move( delta );
3798 }
3799
3800 // The geometry work has been conserved by using Move(). But the hashes
3801 // need to be updated, otherwise the cached polygons will still be rebuild.
3802 if( m_courtyard_cache )
3803 {
3804 m_courtyard_cache->back.Move( delta );
3805 m_courtyard_cache->back_hash = m_courtyard_cache->back.GetHash();
3806 m_courtyard_cache->front.Move( delta );
3807 m_courtyard_cache->front_hash = m_courtyard_cache->front.GetHash();
3808 }
3809}
3810
3811
3812void FOOTPRINT::MoveAnchorPosition( const VECTOR2I& aMoveVector )
3813{
3814 /*
3815 * Move the reference point of the footprint
3816 * the footprints elements (pads, outlines, edges .. ) are moved
3817 * but:
3818 * - the footprint position is not modified.
3819 * - the relative (local) coordinates of these items are modified
3820 * - Draw coordinates are updated
3821 */
3822
3823 // Update (move) the relative coordinates relative to the new anchor point.
3824 VECTOR2I moveVector = aMoveVector;
3825 RotatePoint( moveVector, -GetOrientation() );
3826
3827 // Update field local coordinates
3828 for( PCB_FIELD* field : m_fields )
3829 field->Move( moveVector );
3830
3831 // Update the pad local coordinates.
3832 for( PAD* pad : m_pads )
3833 pad->Move( moveVector );
3834
3835 // Update the draw element coordinates.
3836 for( BOARD_ITEM* item : GraphicalItems() )
3837 item->Move( moveVector );
3838
3839 // Update the keepout zones
3840 for( ZONE* zone : Zones() )
3841 zone->Move( moveVector );
3842
3843 // Update the point local coordinates.
3844 for( PCB_POINT* point : m_points )
3845 point->Move( moveVector );
3846
3847 // Update the 3D models
3848 for( FP_3DMODEL& model : Models() )
3849 {
3850 model.m_Offset.x += pcbIUScale.IUTomm( moveVector.x );
3851 model.m_Offset.y -= pcbIUScale.IUTomm( moveVector.y );
3852 }
3853
3854 if( m_geometry_cache )
3855 {
3856 m_geometry_cache->bounding_box.Move( moveVector );
3857 m_geometry_cache->text_excluded_bbox.Move( moveVector );
3858 m_geometry_cache->hull.Move( moveVector );
3859 }
3860
3861 // The geometry work have been conserved by using Move(). But the hashes
3862 // need to be updated, otherwise the cached polygons will still be rebuild.
3863 if( m_courtyard_cache )
3864 {
3865 m_courtyard_cache->back.Move( moveVector );
3866 m_courtyard_cache->back_hash = m_courtyard_cache->back.GetHash();
3867 m_courtyard_cache->front.Move( moveVector );
3868 m_courtyard_cache->front_hash = m_courtyard_cache->front.GetHash();
3869 }
3870}
3871
3872
3873void FOOTPRINT::SetOrientation( const EDA_ANGLE& aNewAngle )
3874{
3875 EDA_ANGLE angleChange = aNewAngle - m_transform.GetRotate(); // change in rotation
3876
3877 EDA_ANGLE newAngle = aNewAngle;
3878 newAngle.Normalize180();
3879 m_transform.SetRotate( newAngle );
3880
3881 const VECTOR2I rotationCenter = GetPosition();
3882
3883 for( PCB_FIELD* field : m_fields )
3884 field->OnFootprintTransformed();
3885
3886 for( PAD* pad : m_pads )
3887 pad->OnFootprintTransformed();
3888
3889 for( ZONE* zone : m_zones )
3890 zone->OnFootprintTransformed();
3891
3892 for( PCB_POINT* point : m_points )
3893 point->OnFootprintTransformed();
3894
3895 for( BOARD_ITEM* item : m_drawings )
3896 {
3897 if( item->Type() == PCB_TEXT_T || item->Type() == PCB_SHAPE_T || item->Type() == PCB_TEXTBOX_T
3898 || item->Type() == PCB_BARCODE_T || item->Type() == PCB_TABLE_T
3899 || BaseType( item->Type() ) == PCB_DIMENSION_T )
3900 {
3901 item->OnFootprintTransformed();
3902 }
3903 else
3904 {
3905 item->Rotate( rotationCenter, angleChange );
3906 }
3907 }
3908
3909 if( m_geometry_cache )
3910 m_geometry_cache->text_excluded_bbox_timestamp = 0;
3911
3912 if( m_courtyard_cache )
3913 {
3914 m_courtyard_cache->front.Rotate( angleChange, rotationCenter );
3915 m_courtyard_cache->front_hash = m_courtyard_cache->front.GetHash();
3916
3917 m_courtyard_cache->back.Rotate( angleChange, rotationCenter );
3918 m_courtyard_cache->back_hash = m_courtyard_cache->back.GetHash();
3919 }
3920
3921 if( m_geometry_cache )
3922 m_geometry_cache->hull.Rotate( angleChange, rotationCenter );
3923}
3924
3925
3926BOARD_ITEM* FOOTPRINT::Duplicate( bool addToParentGroup, BOARD_COMMIT* aCommit ) const
3927{
3928 FOOTPRINT* dupe = static_cast<FOOTPRINT*>( BOARD_ITEM::Duplicate( addToParentGroup, aCommit ) );
3929
3930 // Clones keep child UUIDs so cloned constraints still resolve to them
3931 // Map old ids to new before reset else constraints below strand
3932 std::map<KIID, KIID> idMap;
3933
3934 dupe->RunOnChildren(
3935 [&]( BOARD_ITEM* child )
3936 {
3937 KIID oldId = child->m_Uuid;
3938 child->ResetUuidDirect();
3939 idMap[oldId] = child->m_Uuid;
3940 },
3942
3943 for( PCB_CONSTRAINT* constraint : dupe->Constraints() )
3944 constraint->RemapKIIDs( idMap );
3945
3946 return dupe;
3947}
3948
3949
3950BOARD_ITEM* FOOTPRINT::DuplicateItem( bool addToParentGroup, BOARD_COMMIT* aCommit,
3951 const BOARD_ITEM* aItem, bool addToFootprint )
3952{
3953 BOARD_ITEM* new_item = nullptr;
3954
3955 switch( aItem->Type() )
3956 {
3957 case PCB_PAD_T:
3958 {
3959 PAD* new_pad = new PAD( *static_cast<const PAD*>( aItem ) );
3960 new_pad->ResetUuidDirect();
3961
3962 if( addToFootprint )
3963 m_pads.push_back( new_pad );
3964
3965 new_item = new_pad;
3966 break;
3967 }
3968
3969 case PCB_ZONE_T:
3970 {
3971 ZONE* new_zone = new ZONE( *static_cast<const ZONE*>( aItem ) );
3972 new_zone->ResetUuidDirect();
3973
3974 if( addToFootprint )
3975 m_zones.push_back( new_zone );
3976
3977 new_item = new_zone;
3978 break;
3979 }
3980
3981 case PCB_POINT_T:
3982 {
3983 PCB_POINT* new_point = new PCB_POINT( *static_cast<const PCB_POINT*>( aItem ) );
3984 new_point->ResetUuidDirect();
3985
3986 if( addToFootprint )
3987 m_points.push_back( new_point );
3988
3989 new_item = new_point;
3990 break;
3991 }
3992
3993 case PCB_FIELD_T:
3994 {
3995 PCB_FIELD* new_field = new PCB_FIELD( *static_cast<const PCB_FIELD*>( aItem ) );
3996 new_field->ResetUuidDirect();
3997
3998 switch( static_cast<const PCB_FIELD*>( aItem )->GetId() )
3999 {
4000 case FIELD_T::REFERENCE: new_field->SetText( wxT( "${REFERENCE}" ) ); break;
4001 case FIELD_T::VALUE: new_field->SetText( wxT( "${VALUE}" ) ); break;
4002 case FIELD_T::DATASHEET: new_field->SetText( wxT( "${DATASHEET}" ) ); break;
4003 default: break;
4004 }
4005
4006 if( addToFootprint )
4007 Add( new_field );
4008
4009 new_item = new_field;
4010 break;
4011 }
4012
4013 case PCB_TEXT_T:
4014 {
4015 PCB_TEXT* new_text = new PCB_TEXT( *static_cast<const PCB_TEXT*>( aItem ) );
4016 new_text->ResetUuidDirect();
4017
4018 if( addToFootprint )
4019 Add( new_text );
4020
4021 new_item = new_text;
4022 break;
4023 }
4024
4025 case PCB_SHAPE_T:
4026 {
4027 PCB_SHAPE* new_shape = new PCB_SHAPE( *static_cast<const PCB_SHAPE*>( aItem ) );
4028 new_shape->ResetUuidDirect();
4029
4030 if( addToFootprint )
4031 Add( new_shape );
4032
4033 new_item = new_shape;
4034 break;
4035 }
4036
4037 case PCB_BARCODE_T:
4038 {
4039 PCB_BARCODE* new_barcode = new PCB_BARCODE( *static_cast<const PCB_BARCODE*>( aItem ) );
4040 new_barcode->ResetUuidDirect();
4041
4042 if( addToFootprint )
4043 Add( new_barcode );
4044
4045 new_item = new_barcode;
4046 break;
4047 }
4048
4050 {
4051 PCB_REFERENCE_IMAGE* new_image = new PCB_REFERENCE_IMAGE( *static_cast<const PCB_REFERENCE_IMAGE*>( aItem ) );
4052 new_image->ResetUuidDirect();
4053
4054 if( addToFootprint )
4055 Add( new_image );
4056
4057 new_item = new_image;
4058 break;
4059 }
4060
4061 case PCB_TEXTBOX_T:
4062 {
4063 PCB_TEXTBOX* new_textbox = new PCB_TEXTBOX( *static_cast<const PCB_TEXTBOX*>( aItem ) );
4064 new_textbox->ResetUuidDirect();
4065
4066 if( addToFootprint )
4067 Add( new_textbox );
4068
4069 new_item = new_textbox;
4070 break;
4071 }
4072
4073 case PCB_DIM_ALIGNED_T:
4074 case PCB_DIM_LEADER_T:
4075 case PCB_DIM_CENTER_T:
4076 case PCB_DIM_RADIAL_T:
4078 {
4079 PCB_DIMENSION_BASE* dimension = static_cast<PCB_DIMENSION_BASE*>( aItem->Duplicate( addToParentGroup,
4080 aCommit ) );
4081
4082 if( addToFootprint )
4083 Add( dimension );
4084
4085 new_item = dimension;
4086 break;
4087 }
4088
4089 case PCB_TABLE_T:
4090 {
4091 new_item = aItem->Duplicate( addToParentGroup, aCommit );
4092
4093 if( addToFootprint )
4094 Add( new_item );
4095
4096 break;
4097 }
4098
4099 case PCB_GROUP_T:
4100 {
4101 PCB_GROUP* group = static_cast<const PCB_GROUP*>( aItem )->DeepDuplicate( addToParentGroup, aCommit );
4102
4103 if( addToFootprint )
4104 {
4105 group->RunOnChildren(
4106 [&]( BOARD_ITEM* aCurrItem )
4107 {
4108 Add( aCurrItem );
4109 },
4111
4112 Add( group );
4113 }
4114
4115 new_item = group;
4116 break;
4117 }
4118
4119 case PCB_FOOTPRINT_T:
4120 // Ignore the footprint itself
4121 break;
4122
4123 default:
4124 // Un-handled item for duplication
4125 wxFAIL_MSG( wxT( "Duplication not supported for items of class " ) + aItem->GetClass() );
4126 break;
4127 }
4128
4129 return new_item;
4130}
4131
4132
4133wxString FOOTPRINT::GetNextPadNumber( const wxString& aLastPadNumber ) const
4134{
4135 std::set<wxString> usedNumbers;
4136
4137 // Create a set of used pad numbers
4138 for( PAD* pad : m_pads )
4139 usedNumbers.insert( pad->GetNumber() );
4140
4141 // Pad numbers aren't technically reference designators, but the formatting is close enough
4142 // for these to give us what we need.
4143 wxString prefix = UTIL::GetRefDesPrefix( aLastPadNumber );
4144 int num = GetTrailingInt( aLastPadNumber );
4145
4146 while( usedNumbers.count( wxString::Format( wxT( "%s%d" ), prefix, num ) ) )
4147 num++;
4148
4149 return wxString::Format( wxT( "%s%d" ), prefix, num );
4150}
4151
4152
4154{
4155 // Auto-position reference and value
4156 BOX2I bbox = GetBoundingBox( false );
4157 bbox.Inflate( pcbIUScale.mmToIU( 0.2 ) ); // Gap between graphics and text
4158
4159 if( Reference().GetPosition() == VECTOR2I( 0, 0 ) )
4160 {
4164
4165 Reference().SetX( bbox.GetCenter().x );
4166 Reference().SetY( bbox.GetTop() - Reference().GetTextSize().y / 2 );
4167 }
4168
4169 if( Value().GetPosition() == VECTOR2I( 0, 0 ) )
4170 {
4174
4175 Value().SetX( bbox.GetCenter().x );
4176 Value().SetY( bbox.GetBottom() + Value().GetTextSize().y / 2 );
4177 }
4178}
4179
4180
4182{
4183 const wxString& refdes = GetReference();
4184
4185 SetReference( wxString::Format( wxT( "%s%i" ),
4186 UTIL::GetRefDesPrefix( refdes ),
4187 GetTrailingInt( refdes ) + aDelta ) );
4188}
4189
4190
4191double FOOTPRINT::GetCoverageArea( int aTextMargin ) const
4192{
4194 return polygonArea( hull );
4195}
4196
4197
4198double FOOTPRINT::CoverageRatio( const GENERAL_COLLECTOR& aCollector ) const
4199{
4200 int textMargin = aCollector.GetGuide()->Accuracy();
4201
4202 SHAPE_POLY_SET footprintRegion( GetBoundingHull() );
4203 SHAPE_POLY_SET coveredRegion;
4204
4206
4207 TransformFPShapesToPolySet( coveredRegion, UNDEFINED_LAYER, textMargin, ARC_LOW_DEF,
4209 true, /* include text */
4210 false, /* include shapes */
4211 false /* include private items */ );
4212
4213 for( int i = 0; i < aCollector.GetCount(); ++i )
4214 {
4215 const BOARD_ITEM* item = aCollector[i];
4216
4217 switch( item->Type() )
4218 {
4219 case PCB_FIELD_T:
4220 case PCB_TEXT_T:
4221 case PCB_TEXTBOX_T:
4222 case PCB_SHAPE_T:
4223 case PCB_BARCODE_T:
4224 case PCB_TRACE_T:
4225 case PCB_ARC_T:
4226 case PCB_VIA_T:
4227 if( item->GetParent() != this )
4228 {
4229 item->TransformShapeToPolygon( coveredRegion, UNDEFINED_LAYER, 0, ARC_LOW_DEF,
4230 ERROR_OUTSIDE );
4231 }
4232 break;
4233
4234 case PCB_FOOTPRINT_T:
4235 if( item != this )
4236 {
4237 const FOOTPRINT* footprint = static_cast<const FOOTPRINT*>( item );
4238 coveredRegion.AddOutline( footprint->GetBoundingHull().Outline( 0 ) );
4239 }
4240 break;
4241
4242 default:
4243 break;
4244 }
4245 }
4246
4247 coveredRegion.BooleanIntersection( footprintRegion );
4248
4249 double footprintRegionArea = polygonArea( footprintRegion );
4250 double uncoveredRegionArea = footprintRegionArea - polygonArea( coveredRegion );
4251 double coveredArea = footprintRegionArea - uncoveredRegionArea;
4252
4253 // Avoid div-by-zero (this will result in the disambiguate dialog)
4254 if( footprintRegionArea == 0 )
4255 return 1.0;
4256
4257 double ratio = coveredArea / footprintRegionArea;
4258
4259 // Test for negative ratio (should not occur).
4260 // better to be conservative (this will result in the disambiguate dialog)
4261 if( ratio < 0.0 )
4262 return 1.0;
4263
4264 return std::min( ratio, 1.0 );
4265}
4266
4267
4268std::shared_ptr<SHAPE> FOOTPRINT::GetEffectiveShape( PCB_LAYER_ID aLayer, FLASHING aFlash,
4269 DRC_CONSTRAINT_T aUsage ) const
4270{
4271 std::shared_ptr<SHAPE_COMPOUND> shape = std::make_shared<SHAPE_COMPOUND>();
4272
4273 // There are several possible interpretations here:
4274 // 1) the bounding box (without or without invisible items)
4275 // 2) just the pads and "edges" (ie: non-text graphic items)
4276 // 3) the courtyard
4277
4278 // We'll go with (2) for now, unless the caller is clearly looking for (3)
4279
4280 if( aLayer == F_CrtYd || aLayer == B_CrtYd )
4281 {
4282 const SHAPE_POLY_SET& courtyard = GetCourtyard( aLayer );
4283
4284 if( courtyard.OutlineCount() == 0 ) // malformed/empty polygon
4285 return shape;
4286
4287 shape->AddShape( new SHAPE_SIMPLE( courtyard.COutline( 0 ) ) );
4288 }
4289 else
4290 {
4291 for( PAD* pad : Pads() )
4292 shape->AddShape( pad->GetEffectiveShape( aLayer, aFlash, aUsage )->Clone() );
4293
4294 for( BOARD_ITEM* item : GraphicalItems() )
4295 {
4296 if( item->Type() == PCB_SHAPE_T )
4297 shape->AddShape( item->GetEffectiveShape( aLayer, aFlash, aUsage )->Clone() );
4298 else if( item->Type() == PCB_BARCODE_T )
4299 shape->AddShape( item->GetEffectiveShape( aLayer, aFlash, aUsage )->Clone() );
4300 }
4301 }
4302
4303 return shape;
4304}
4305
4306
4308{
4309 std::lock_guard<std::mutex> lock( m_courtyard_cache_mutex );
4310
4312 || m_courtyard_cache->front_hash != m_courtyard_cache->front.GetHash()
4313 || m_courtyard_cache->back_hash != m_courtyard_cache->back.GetHash() )
4314 {
4315 const_cast<FOOTPRINT*>(this)->BuildCourtyardCaches();
4316 }
4317
4318 return GetCachedCourtyard( aLayer );
4319}
4320
4321
4323{
4324 if( !m_courtyard_cache )
4325 m_courtyard_cache = std::make_unique<FOOTPRINT_COURTYARD_CACHE_DATA>();
4326
4327 if( IsBackLayer( aLayer ) )
4328 return m_courtyard_cache->back;
4329 else
4330 return m_courtyard_cache->front;
4331}
4332
4333
4335{
4336 if( !m_courtyard_cache )
4337 m_courtyard_cache = std::make_unique<FOOTPRINT_COURTYARD_CACHE_DATA>();
4338
4339 m_courtyard_cache->front.RemoveAllContours();
4340 m_courtyard_cache->back.RemoveAllContours();
4342
4343 // Build the courtyard area from graphic items on the courtyard.
4344 // Only PCB_SHAPE_T have meaning, graphic texts are ignored.
4345 // Collect items:
4346 std::vector<PCB_SHAPE*> list_front;
4347 std::vector<PCB_SHAPE*> list_back;
4348 std::map<int, int> front_width_histogram;
4349 std::map<int, int> back_width_histogram;
4350
4351 for( BOARD_ITEM* item : GraphicalItems() )
4352 {
4353 if( item->GetLayer() == B_CrtYd && item->Type() == PCB_SHAPE_T )
4354 {
4355 PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
4356 list_back.push_back( shape );
4357 back_width_histogram[ shape->GetStroke().GetWidth() ]++;
4358 }
4359
4360 if( item->GetLayer() == F_CrtYd && item->Type() == PCB_SHAPE_T )
4361 {
4362 PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
4363 list_front.push_back( shape );
4364 front_width_histogram[ shape->GetStroke().GetWidth() ]++;
4365 }
4366 }
4367
4368 if( !list_front.size() && !list_back.size() )
4369 return;
4370
4371 int maxError = pcbIUScale.mmToIU( 0.005 ); // max error for polygonization
4372 int chainingEpsilon = pcbIUScale.mmToIU( 0.02 ); // max dist from one endPt to next startPt
4373
4374 if( ConvertOutlineToPolygon( list_front, m_courtyard_cache->front, maxError, chainingEpsilon,
4375 true, aErrorHandler ) )
4376 {
4377 int width = 0;
4378
4379 // Touching courtyards, or courtyards -at- the clearance distance are legal.
4380 // Use maxError here because that is the allowed deviation when transforming arcs/circles to
4381 // polygons.
4382 m_courtyard_cache->front.Inflate( -maxError, CORNER_STRATEGY::CHAMFER_ACUTE_CORNERS, maxError );
4383
4384 m_courtyard_cache->front.CacheTriangulation();
4385 auto max = std::max_element( front_width_histogram.begin(), front_width_histogram.end(),
4386 []( const std::pair<int, int>& a, const std::pair<int, int>& b )
4387 {
4388 return a.second < b.second;
4389 } );
4390
4391 if( max != front_width_histogram.end() )
4392 width = max->first;
4393
4394 if( width == 0 )
4395 width = pcbIUScale.mmToIU( DEFAULT_COURTYARD_WIDTH );
4396
4397 if( m_courtyard_cache->front.OutlineCount() > 0 )
4398 m_courtyard_cache->front.Outline( 0 ).SetWidth( width );
4399 }
4400 else
4401 {
4403 }
4404
4405 if( ConvertOutlineToPolygon( list_back, m_courtyard_cache->back, maxError, chainingEpsilon, true,
4406 aErrorHandler ) )
4407 {
4408 int width = 0;
4409
4410 // Touching courtyards, or courtyards -at- the clearance distance are legal.
4411 m_courtyard_cache->back.Inflate( -maxError, CORNER_STRATEGY::CHAMFER_ACUTE_CORNERS, maxError );
4412
4413 m_courtyard_cache->back.CacheTriangulation();
4414 auto max = std::max_element( back_width_histogram.begin(), back_width_histogram.end(),
4415 []( const std::pair<int, int>& a, const std::pair<int, int>& b )
4416 {
4417 return a.second < b.second;
4418 } );
4419
4420 if( max != back_width_histogram.end() )
4421 width = max->first;
4422
4423 if( width == 0 )
4424 width = pcbIUScale.mmToIU( DEFAULT_COURTYARD_WIDTH );
4425
4426 if( m_courtyard_cache->back.OutlineCount() > 0 )
4427 m_courtyard_cache->back.Outline( 0 ).SetWidth( width );
4428 }
4429 else
4430 {
4432 }
4433
4434 m_courtyard_cache->front_hash = m_courtyard_cache->front.GetHash();
4435 m_courtyard_cache->back_hash = m_courtyard_cache->back.GetHash();
4436}
4437
4438
4440{
4441 m_netTieCache.clear();
4442 std::map<wxString, int> map = MapPadNumbersToNetTieGroups();
4443 std::map<PCB_LAYER_ID, std::vector<PCB_SHAPE*>> layer_shapes;
4444 BOARD* board = GetBoard();
4445
4446 std::for_each( m_drawings.begin(), m_drawings.end(),
4447 [&]( BOARD_ITEM* item )
4448 {
4449 if( item->Type() != PCB_SHAPE_T )
4450 return;
4451
4452 for( PCB_LAYER_ID layer : item->GetLayerSet() )
4453 {
4454 if( !IsCopperLayer( layer ) )
4455 continue;
4456
4457 if( board && !board->GetEnabledLayers().Contains( layer ) )
4458 continue;
4459
4460 layer_shapes[layer].push_back( static_cast<PCB_SHAPE*>( item ) );
4461 }
4462 } );
4463
4464 for( size_t ii = 0; ii < m_pads.size(); ++ii )
4465 {
4466 PAD* pad = m_pads[ ii ];
4467 bool has_nettie = false;
4468
4469 auto it = map.find( pad->GetNumber() );
4470
4471 if( it == map.end() || it->second < 0 )
4472 continue;
4473
4474 for( size_t jj = 0; jj < m_pads.size(); ++jj )
4475 {
4476 if( jj == ii )
4477 continue;
4478
4479 PAD* other = m_pads[ jj ];
4480
4481 auto it2 = map.find( other->GetNumber() );
4482
4483 if( it2 == map.end() || it2->second < 0 )
4484 continue;
4485
4486 if( it2->second == it->second )
4487 {
4488 m_netTieCache[pad].insert( pad->GetNetCode() );
4489 m_netTieCache[pad].insert( other->GetNetCode() );
4490 m_netTieCache[other].insert( other->GetNetCode() );
4491 m_netTieCache[other].insert( pad->GetNetCode() );
4492 has_nettie = true;
4493 }
4494 }
4495
4496 if( !has_nettie )
4497 continue;
4498
4499 for( auto& [ layer, shapes ] : layer_shapes )
4500 {
4501 auto pad_shape = pad->GetEffectiveShape( layer );
4502
4503 for( auto other_shape : shapes )
4504 {
4505 auto shape = other_shape->GetEffectiveShape( layer );
4506
4507 if( pad_shape->Collide( shape.get() ) )
4508 {
4509 std::set<int>& nettie = m_netTieCache[pad];
4510 m_netTieCache[other_shape].insert( nettie.begin(), nettie.end() );
4511 }
4512 }
4513 }
4514 }
4515}
4516
4517
4518std::map<wxString, int> FOOTPRINT::MapPadNumbersToNetTieGroups() const
4519{
4520 std::map<wxString, int> padNumberToGroupIdxMap;
4521
4522 for( const PAD* pad : m_pads )
4523 padNumberToGroupIdxMap[ pad->GetNumber() ] = -1;
4524
4525 for( int ii = 0; ii < (int) m_netTiePadGroups.size(); ++ii )
4526 {
4527 for( const wxString& padNumber : parseNetTiePadGroup( m_netTiePadGroups[ii] ) )
4528 padNumberToGroupIdxMap[padNumber] = ii;
4529 }
4530
4531 return padNumberToGroupIdxMap;
4532}
4533
4534
4535std::vector<PAD*> FOOTPRINT::GetNetTiePads( PAD* aPad ) const
4536{
4537 // First build a map from pad numbers to allowed-shorting-group indexes. This ends up being
4538 // something like O(3n), but it still beats O(n^2) for large numbers of pads.
4539
4540 std::map<wxString, int> padToNetTieGroupMap = MapPadNumbersToNetTieGroups();
4541 int groupIdx = padToNetTieGroupMap[ aPad->GetNumber() ];
4542 std::vector<PAD*> otherPads;
4543
4544 if( groupIdx >= 0 )
4545 {
4546 for( PAD* pad : m_pads )
4547 {
4548 if( padToNetTieGroupMap[ pad->GetNumber() ] == groupIdx )
4549 otherPads.push_back( pad );
4550 }
4551 }
4552
4553 return otherPads;
4554}
4555
4556
4558{
4559 wxASSERT( aImage->Type() == PCB_FOOTPRINT_T );
4560
4561 FOOTPRINT* image = static_cast<FOOTPRINT*>( aImage );
4562
4563 std::swap( *this, *image );
4564
4566 [&]( BOARD_ITEM* child )
4567 {
4568 child->SetParent( this );
4569 },
4571
4572 image->RunOnChildren(
4573 [&]( BOARD_ITEM* child )
4574 {
4575 child->SetParent( image );
4576 },
4578}
4579
4580
4582{
4583 for( PAD* pad : Pads() )
4584 {
4585 if( pad->GetAttribute() == PAD_ATTRIB::PTH || pad->GetAttribute() == PAD_ATTRIB::NPTH )
4586 {
4587 return true;
4588 }
4589 }
4590
4591 return false;
4592}
4593
4594
4595bool FOOTPRINT::operator==( const BOARD_ITEM& aOther ) const
4596{
4597 if( aOther.Type() != PCB_FOOTPRINT_T )
4598 return false;
4599
4600 const FOOTPRINT& other = static_cast<const FOOTPRINT&>( aOther );
4601
4602 return *this == other;
4603}
4604
4605
4606bool FOOTPRINT::operator==( const FOOTPRINT& aOther ) const
4607{
4608 auto equalItems =
4609 []( const auto* aLeft, const auto* aRight )
4610 {
4611 return *aLeft == *aRight;
4612 };
4613
4614 if( !std::ranges::equal( m_pads, aOther.m_pads, equalItems ) )
4615 return false;
4616
4617 if( !std::ranges::equal( m_drawings, aOther.m_drawings, equalItems ) )
4618 return false;
4619
4620 if( !std::ranges::equal( m_zones, aOther.m_zones, equalItems ) )
4621 return false;
4622
4623 if( !std::ranges::equal( m_groups, aOther.m_groups, equalItems ) )
4624 return false;
4625
4626 if( !std::ranges::equal( m_netTiePadGroups, aOther.m_netTiePadGroups,
4627 []( const wxString& aLeft, const wxString& aRight )
4628 {
4629 return parseNetTiePadGroup( aLeft ) == parseNetTiePadGroup( aRight );
4630 } ) )
4631 {
4632 return false;
4633 }
4634
4635 if( m_jumperPadGroups != aOther.m_jumperPadGroups )
4636 return false;
4637
4638 if( m_points.size() != aOther.m_points.size() )
4639 return false;
4640
4641 if( !std::ranges::equal( m_bodies, aOther.m_bodies, equalItems ) )
4642 return false;
4643
4644 if( m_height != aOther.m_height )
4645 return false;
4646
4647 // Compare fields in ordinally-sorted order
4648 std::vector<PCB_FIELD*> fields, otherFields;
4649
4650 GetFields( fields, false );
4651 aOther.GetFields( otherFields, false );
4652
4653 if( fields.size() != otherFields.size() )
4654 return false;
4655
4656 for( size_t ii = 0; ii < fields.size(); ++ii )
4657 {
4658 if( fields[ii] )
4659 {
4660 if( !( *fields[ii] == *otherFields[ii] ) )
4661 return false;
4662 }
4663 }
4664
4665 return true;
4666}
4667
4668
4669double FOOTPRINT::Similarity( const BOARD_ITEM& aOther ) const
4670{
4671 if( aOther.Type() != PCB_FOOTPRINT_T )
4672 return 0.0;
4673
4674 const FOOTPRINT& other = static_cast<const FOOTPRINT&>( aOther );
4675
4676 double similarity = 1.0;
4677
4678 for( const PAD* pad : m_pads)
4679 {
4680 const PAD* otherPad = other.FindPadByNumber( pad->GetNumber() );
4681
4682 if( !otherPad )
4683 continue;
4684
4685 similarity *= pad->Similarity( *otherPad );
4686 }
4687
4688 return similarity;
4689}
4690
4691
4695static constexpr std::optional<bool> cmp_points_opt( const VECTOR2I& aPtA, const VECTOR2I& aPtB )
4696{
4697 if( aPtA.x != aPtB.x )
4698 return aPtA.x < aPtB.x;
4699
4700 if( aPtA.y != aPtB.y )
4701 return aPtA.y < aPtB.y;
4702
4703 return std::nullopt;
4704}
4705
4706
4707bool FOOTPRINT::cmp_drawings::operator()( const BOARD_ITEM* itemA, const BOARD_ITEM* itemB ) const
4708{
4709 if( itemA->Type() != itemB->Type() )
4710 return itemA->Type() < itemB->Type();
4711
4712 if( itemA->GetLayer() != itemB->GetLayer() )
4713 return itemA->GetLayer() < itemB->GetLayer();
4714
4715 switch( itemA->Type() )
4716 {
4717 case PCB_SHAPE_T:
4718 {
4719 const PCB_SHAPE* dwgA = static_cast<const PCB_SHAPE*>( itemA );
4720 const PCB_SHAPE* dwgB = static_cast<const PCB_SHAPE*>( itemB );
4721
4722 if( dwgA->GetShape() != dwgB->GetShape() )
4723 return dwgA->GetShape() < dwgB->GetShape();
4724
4725 if( dwgA->GetShape() != SHAPE_T::POLY )
4726 {
4727 if( std::optional<bool> cmp = cmp_points_opt( dwgA->GetLibraryStart(), dwgB->GetLibraryStart() ) )
4728 return *cmp;
4729
4730 if( std::optional<bool> cmp = cmp_points_opt( dwgA->GetLibraryEnd(), dwgB->GetLibraryEnd() ) )
4731 return *cmp;
4732 }
4733
4734 if( dwgA->GetShape() == SHAPE_T::ARC )
4735 {
4736 if( std::optional<bool> cmp = cmp_points_opt( dwgA->GetLibraryArcMid(), dwgB->GetLibraryArcMid() ) )
4737 return *cmp;
4738 }
4739 else if( dwgA->GetShape() == SHAPE_T::BEZIER )
4740 {
4741 if( std::optional<bool> cmp = cmp_points_opt( dwgA->GetLibraryBezierC1(), dwgB->GetLibraryBezierC1() ) )
4742 return *cmp;
4743
4744 if( std::optional<bool> cmp = cmp_points_opt( dwgA->GetLibraryBezierC2(), dwgB->GetLibraryBezierC2() ) )
4745 return *cmp;
4746 }
4747 else if( dwgA->GetShape() == SHAPE_T::POLY )
4748 {
4749 const SHAPE_POLY_SET aLib = dwgA->GetLibraryPolyShape();
4750 const SHAPE_POLY_SET bLib = dwgB->GetLibraryPolyShape();
4751
4752 if( aLib.TotalVertices() != bLib.TotalVertices() )
4753 return aLib.TotalVertices() < bLib.TotalVertices();
4754
4755 for( int ii = 0; ii < aLib.TotalVertices(); ++ii )
4756 {
4757 if( std::optional<bool> cmp = cmp_points_opt( aLib.CVertex( ii ), bLib.CVertex( ii ) ) )
4758 return *cmp;
4759 }
4760 }
4761 else if( dwgA->GetShape() == SHAPE_T::ELLIPSE || dwgA->GetShape() == SHAPE_T::ELLIPSE_ARC )
4762 {
4763 if( std::optional<bool> cmp = cmp_points_opt( dwgA->GetEllipseCenter(), dwgB->GetEllipseCenter() ) )
4764 return *cmp;
4765
4766 if( dwgA->GetEllipseMajorRadius() != dwgB->GetEllipseMajorRadius() )
4767 return dwgA->GetEllipseMajorRadius() < dwgB->GetEllipseMajorRadius();
4768
4769 if( dwgA->GetEllipseMinorRadius() != dwgB->GetEllipseMinorRadius() )
4770 return dwgA->GetEllipseMinorRadius() < dwgB->GetEllipseMinorRadius();
4771
4774
4775 if( dwgA->GetShape() == SHAPE_T::ELLIPSE_ARC )
4776 {
4781
4783 return dwgA->GetEllipseEndAngle().AsTenthsOfADegree()
4785 }
4786 }
4787
4788 if( dwgA->GetWidth() != dwgB->GetWidth() )
4789 return dwgA->GetWidth() < dwgB->GetWidth();
4790
4791 break;
4792 }
4793 case PCB_TEXT_T:
4794 {
4795 const PCB_TEXT& textA = static_cast<const PCB_TEXT&>( *itemA );
4796 const PCB_TEXT& textB = static_cast<const PCB_TEXT&>( *itemB );
4797
4798 if( std::optional<bool> cmp = cmp_points_opt( textA.GetFPRelativePosition(), textB.GetFPRelativePosition() ) )
4799 return *cmp;
4800
4801 if( textA.GetTextAngle() != textB.GetTextAngle() )
4802 return textA.GetTextAngle() < textB.GetTextAngle();
4803
4804 if( std::optional<bool> cmp = cmp_points_opt( textA.GetTextSize(), textB.GetTextSize() ) )
4805 return *cmp;
4806
4807 if( textA.GetTextThickness() != textB.GetTextThickness() )
4808 return textA.GetTextThickness() < textB.GetTextThickness();
4809
4810 if( textA.IsBold() != textB.IsBold() )
4811 return textA.IsBold() < textB.IsBold();
4812
4813 if( textA.IsItalic() != textB.IsItalic() )
4814 return textA.IsItalic() < textB.IsItalic();
4815
4816 if( textA.IsMirrored() != textB.IsMirrored() )
4817 return textA.IsMirrored() < textB.IsMirrored();
4818
4819 if( textA.GetLineSpacing() != textB.GetLineSpacing() )
4820 return textA.GetLineSpacing() < textB.GetLineSpacing();
4821
4822 if( textA.GetText() != textB.GetText() )
4823 return textA.GetText().Cmp( textB.GetText() ) < 0;
4824
4825 break;
4826 }
4827 default:
4828 {
4829 // These items don't have their own specific sorting criteria.
4830 break;
4831 }
4832 }
4833
4834 if( itemA->m_Uuid != itemB->m_Uuid )
4835 return itemA->m_Uuid < itemB->m_Uuid;
4836
4837 return itemA < itemB;
4838}
4839
4840
4841bool FOOTPRINT::cmp_pads::operator()( const PAD* aFirst, const PAD* aSecond ) const
4842{
4843 if( aFirst->GetNumber() != aSecond->GetNumber() )
4844 return StrNumCmp( aFirst->GetNumber(), aSecond->GetNumber() ) < 0;
4845
4846 if( std::optional<bool> cmp = cmp_points_opt( aFirst->GetFPRelativePosition(), aSecond->GetFPRelativePosition() ) )
4847 return *cmp;
4848
4849 std::optional<bool> padCopperMatches;
4850
4851 // Pick the "most complex" padstack to iterate
4852 const PAD* checkPad = aFirst;
4853
4854 if( aSecond->Padstack().Mode() == PADSTACK::MODE::CUSTOM
4855 || ( aSecond->Padstack().Mode() == PADSTACK::MODE::FRONT_INNER_BACK &&
4856 aFirst->Padstack().Mode() == PADSTACK::MODE::NORMAL ) )
4857 {
4858 checkPad = aSecond;
4859 }
4860
4861 checkPad->Padstack().ForEachUniqueLayer(
4862 [&]( PCB_LAYER_ID aLayer )
4863 {
4864 if( aFirst->GetSize( aLayer ).x != aSecond->GetSize( aLayer ).x )
4865 padCopperMatches = aFirst->GetSize( aLayer ).x < aSecond->GetSize( aLayer ).x;
4866 else if( aFirst->GetSize( aLayer ).y != aSecond->GetSize( aLayer ).y )
4867 padCopperMatches = aFirst->GetSize( aLayer ).y < aSecond->GetSize( aLayer ).y;
4868 else if( aFirst->GetShape( aLayer ) != aSecond->GetShape( aLayer ) )
4869 padCopperMatches = aFirst->GetShape( aLayer ) < aSecond->GetShape( aLayer );
4870 } );
4871
4872 if( padCopperMatches.has_value() )
4873 return *padCopperMatches;
4874
4875 if( aFirst->GetLayerSet() != aSecond->GetLayerSet() )
4876 return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();
4877
4878 if( aFirst->m_Uuid != aSecond->m_Uuid )
4879 return aFirst->m_Uuid < aSecond->m_Uuid;
4880
4881 return aFirst < aSecond;
4882}
4883
4884
4885#if 0
4886bool FOOTPRINT::cmp_padstack::operator()( const PAD* aFirst, const PAD* aSecond ) const
4887{
4888 if( aFirst->GetSize().x != aSecond->GetSize().x )
4889 return aFirst->GetSize().x < aSecond->GetSize().x;
4890 if( aFirst->GetSize().y != aSecond->GetSize().y )
4891 return aFirst->GetSize().y < aSecond->GetSize().y;
4892
4893 if( aFirst->GetShape() != aSecond->GetShape() )
4894 return aFirst->GetShape() < aSecond->GetShape();
4895
4896 if( aFirst->GetLayerSet() != aSecond->GetLayerSet() )
4897 return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();
4898
4899 if( aFirst->GetDrillSize().x != aSecond->GetDrillSize().x )
4900 return aFirst->GetDrillSize().x < aSecond->GetDrillSize().x;
4901
4902 if( aFirst->GetDrillSize().y != aSecond->GetDrillSize().y )
4903 return aFirst->GetDrillSize().y < aSecond->GetDrillSize().y;
4904
4905 if( aFirst->GetDrillShape() != aSecond->GetDrillShape() )
4906 return aFirst->GetDrillShape() < aSecond->GetDrillShape();
4907
4908 if( aFirst->GetAttribute() != aSecond->GetAttribute() )
4909 return aFirst->GetAttribute() < aSecond->GetAttribute();
4910
4911 if( aFirst->GetOrientation() != aSecond->GetOrientation() )
4912 return aFirst->GetOrientation() < aSecond->GetOrientation();
4913
4914 if( aFirst->GetSolderMaskExpansion() != aSecond->GetSolderMaskExpansion() )
4915 return aFirst->GetSolderMaskExpansion() < aSecond->GetSolderMaskExpansion();
4916
4917 if( aFirst->GetSolderPasteMargin() != aSecond->GetSolderPasteMargin() )
4918 return aFirst->GetSolderPasteMargin() < aSecond->GetSolderPasteMargin();
4919
4920 if( aFirst->GetLocalSolderMaskMargin() != aSecond->GetLocalSolderMaskMargin() )
4921 return aFirst->GetLocalSolderMaskMargin() < aSecond->GetLocalSolderMaskMargin();
4922
4923 const std::shared_ptr<SHAPE_POLY_SET>& firstShape = aFirst->GetEffectivePolygon( ERROR_INSIDE );
4924 const std::shared_ptr<SHAPE_POLY_SET>& secondShape = aSecond->GetEffectivePolygon( ERROR_INSIDE );
4925
4926 if( firstShape->VertexCount() != secondShape->VertexCount() )
4927 return firstShape->VertexCount() < secondShape->VertexCount();
4928
4929 for( int ii = 0; ii < firstShape->VertexCount(); ++ii )
4930 {
4931 if( std::optional<bool> cmp = cmp_points_opt( firstShape->CVertex( ii ), secondShape->CVertex( ii ) ) )
4932 {
4933 return *cmp;
4934 }
4935 }
4936
4937 return false;
4938}
4939#endif
4940
4941
4942bool FOOTPRINT::cmp_zones::operator()( const ZONE* aFirst, const ZONE* aSecond ) const
4943{
4944 if( aFirst->GetAssignedPriority() != aSecond->GetAssignedPriority() )
4945 return aFirst->GetAssignedPriority() < aSecond->GetAssignedPriority();
4946
4947 if( aFirst->GetLayerSet() != aSecond->GetLayerSet() )
4948 return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();
4949
4950 const SHAPE_POLY_SET aLib = aFirst->GetLibraryOutline();
4951 const SHAPE_POLY_SET bLib = aSecond->GetLibraryOutline();
4952
4953 if( aLib.TotalVertices() != bLib.TotalVertices() )
4954 return aLib.TotalVertices() < bLib.TotalVertices();
4955
4956 for( int ii = 0; ii < aLib.TotalVertices(); ++ii )
4957 {
4958 if( std::optional<bool> cmp = cmp_points_opt( aLib.CVertex( ii ), bLib.CVertex( ii ) ) )
4959 return *cmp;
4960 }
4961
4962 if( aFirst->m_Uuid != aSecond->m_Uuid )
4963 return aFirst->m_Uuid < aSecond->m_Uuid;
4964
4965 return aFirst < aSecond;
4966}
4967
4968
4970 int aMaxError, ERROR_LOC aErrorLoc ) const
4971{
4972 auto processPad =
4973 [&]( const PAD* pad, PCB_LAYER_ID padLayer )
4974 {
4975 VECTOR2I clearance( aClearance, aClearance );
4976
4977 switch( aLayer )
4978 {
4979 case F_Mask:
4980 case B_Mask:
4981 clearance.x += pad->GetSolderMaskExpansion( padLayer );
4982 clearance.y += pad->GetSolderMaskExpansion( padLayer );
4983 break;
4984
4985 case F_Paste:
4986 case B_Paste:
4987 clearance += pad->GetSolderPasteMargin( padLayer );
4988 break;
4989
4990 default:
4991 break;
4992 }
4993
4994 // Our standard TransformShapeToPolygon() routines can't handle differing x:y clearance
4995 // values (which get generated when a relative paste margin is used with an oblong pad).
4996 // So we apply this huge hack and fake a larger pad to run the transform on.
4997 // Of course being a hack it falls down when dealing with custom shape pads (where the
4998 // size is only the size of the anchor), so for those we punt and just use clearance.x.
4999
5000 if( ( clearance.x < 0 || clearance.x != clearance.y )
5001 && pad->GetShape( padLayer ) != PAD_SHAPE::CUSTOM )
5002 {
5003 VECTOR2I dummySize = pad->GetSize( padLayer ) + clearance + clearance;
5004
5005 if( dummySize.x <= 0 || dummySize.y <= 0 )
5006 return;
5007
5008 PAD dummy( *pad );
5009 dummy.SetSize( padLayer, dummySize );
5010 dummy.TransformShapeToPolygon( aBuffer, padLayer, 0, aMaxError, aErrorLoc );
5011 }
5012 else
5013 {
5014 pad->TransformShapeToPolygon( aBuffer, padLayer, clearance.x, aMaxError, aErrorLoc );
5015 }
5016 };
5017
5018 for( const PAD* pad : m_pads )
5019 {
5020 if( !pad->FlashLayer( aLayer ) )
5021 continue;
5022
5023 if( aLayer == UNDEFINED_LAYER )
5024 {
5025 pad->Padstack().ForEachUniqueLayer(
5026 [&]( PCB_LAYER_ID l )
5027 {
5028 processPad( pad, l );
5029 } );
5030 }
5031 else
5032 {
5033 processPad( pad, aLayer );
5034 }
5035 }
5036}
5037
5038
5040 int aError, ERROR_LOC aErrorLoc, bool aIncludeText,
5041 bool aIncludeShapes, bool aIncludePrivateItems ) const
5042{
5043 for( BOARD_ITEM* item : GraphicalItems() )
5044 {
5045 if( GetPrivateLayers().test( item->GetLayer() ) && !aIncludePrivateItems )
5046 continue;
5047
5048 if( item->Type() == PCB_TEXT_T && aIncludeText )
5049 {
5050 PCB_TEXT* text = static_cast<PCB_TEXT*>( item );
5051
5052 if( aLayer == UNDEFINED_LAYER || text->GetLayer() == aLayer )
5053 text->TransformTextToPolySet( aBuffer, aClearance, aError, aErrorLoc );
5054 }
5055
5056 if( item->Type() == PCB_TEXTBOX_T && aIncludeText )
5057 {
5058 PCB_TEXTBOX* textbox = static_cast<PCB_TEXTBOX*>( item );
5059
5060 if( aLayer == UNDEFINED_LAYER || textbox->GetLayer() == aLayer )
5061 {
5062 // border
5063 if( textbox->IsBorderEnabled() )
5064 textbox->PCB_SHAPE::TransformShapeToPolygon( aBuffer, aLayer, 0, aError, aErrorLoc );
5065
5066 // text
5067 textbox->TransformTextToPolySet( aBuffer, 0, aError, aErrorLoc );
5068 }
5069 }
5070
5071 if( item->Type() == PCB_SHAPE_T && aIncludeShapes )
5072 {
5073 const PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
5074
5075 if( aLayer == UNDEFINED_LAYER || shape->GetLayer() == aLayer )
5076 shape->TransformShapeToPolySet( aBuffer, aLayer, 0, aError, aErrorLoc );
5077 }
5078
5079 if( item->Type() == PCB_BARCODE_T && aIncludeShapes )
5080 {
5081 const PCB_BARCODE* barcode = static_cast<PCB_BARCODE*>( item );
5082
5083 if( aLayer == UNDEFINED_LAYER || barcode->GetLayer() == aLayer )
5084 barcode->TransformShapeToPolySet( aBuffer, aLayer, 0, aError, aErrorLoc );
5085 }
5086 }
5087
5088 if( aIncludeText )
5089 {
5090 for( const PCB_FIELD* field : m_fields )
5091 {
5092 if( ( aLayer == UNDEFINED_LAYER || field->GetLayer() == aLayer ) && field->IsVisible() )
5093 field->TransformTextToPolySet( aBuffer, aClearance, aError, aErrorLoc );
5094 }
5095 }
5096}
5097
5098
5099std::set<KIFONT::OUTLINE_FONT*> FOOTPRINT::GetFonts() const
5100{
5102
5103 std::set<KIFONT::OUTLINE_FONT*> fonts;
5104
5105 auto processItem =
5106 [&]( BOARD_ITEM* item )
5107 {
5108 if( EDA_TEXT* text = dynamic_cast<EDA_TEXT*>( item ) )
5109 {
5110 KIFONT::FONT* font = text->GetFont();
5111
5112 if( font && font->IsOutline() )
5113 {
5114 KIFONT::OUTLINE_FONT* outlineFont = static_cast<KIFONT::OUTLINE_FONT*>( font );
5115 PERMISSION permission = outlineFont->GetEmbeddingPermission();
5116
5117 if( permission == PERMISSION::EDITABLE || permission == PERMISSION::INSTALLABLE )
5118 fonts.insert( outlineFont );
5119 }
5120 }
5121 };
5122
5123 for( BOARD_ITEM* item : GraphicalItems() )
5124 processItem( item );
5125
5126 for( PCB_FIELD* field : GetFields() )
5127 processItem( field );
5128
5129 return fonts;
5130}
5131
5132
5134{
5135 for( KIFONT::OUTLINE_FONT* font : GetFonts() )
5136 {
5137 EMBEDDED_FILES::EMBEDDED_FILE* file = GetEmbeddedFiles()->AddFile( font->GetFileName(), false );
5138
5139 if( !file )
5140 {
5141 wxLogTrace( "EMBED", "Failed to add font file: %s", font->GetFileName() );
5142 continue;
5143 }
5144
5146 }
5147}
5148
5149
5151{
5152 m_componentClassCacheProxy->SetStaticComponentClass( aClass );
5153}
5154
5155
5157{
5158 return m_componentClassCacheProxy->GetStaticComponentClass();
5159}
5160
5161
5163{
5164 m_componentClassCacheProxy->RecomputeComponentClass();
5165}
5166
5167
5169{
5170 return m_componentClassCacheProxy->GetComponentClass();
5171}
5172
5173
5175{
5176 if( !m_componentClassCacheProxy->GetComponentClass()->IsEmpty() )
5177 return m_componentClassCacheProxy->GetComponentClass()->GetName();
5178
5179 return wxEmptyString;
5180}
5181
5182
5184 const std::unordered_set<wxString>& aComponentClassNames )
5185{
5186 const COMPONENT_CLASS* componentClass =
5187 aBoard->GetComponentClassManager().GetEffectiveStaticComponentClass( aComponentClassNames );
5188 SetStaticComponentClass( componentClass );
5189}
5190
5191
5193{
5194 m_componentClassCacheProxy->InvalidateCache();
5195}
5196
5197
5199{
5200 m_stackupMode = aMode;
5201
5203 {
5204 // Reset the stackup layers to the default values
5206 }
5207}
5208
5209
5211{
5212 wxCHECK2( m_stackupMode == FOOTPRINT_STACKUP::CUSTOM_LAYERS, /*void*/ );
5213
5215 m_stackupLayers = std::move( aLayers );
5216}
5217
5218
5220{
5221 if( !aBoard )
5222 return;
5223
5225 return;
5226
5227 const LSET boardCopper = LSET::AllCuMask( aBoard->GetCopperLayerCount() );
5228
5229 for( PAD* pad : Pads() )
5230 {
5231 if( pad->GetAttribute() == PAD_ATTRIB::PTH )
5232 {
5233 LSET padLayers = pad->GetLayerSet();
5234 padLayers |= boardCopper;
5235 pad->SetLayerSet( padLayers );
5236 }
5237 }
5238}
5239
5240
5241static struct FOOTPRINT_DESC
5242{
5244 {
5246 .Map( FOOTPRINT_TYPE::THROUGH_HOLE, _HKI( "Through hole" ) )
5247 .Map( FOOTPRINT_TYPE::SMD, _HKI( "SMD" ) )
5248 .Map( FOOTPRINT_TYPE::UNSPECIFIED, _HKI( "Unspecified" ) );
5249
5251
5252 if( zcMap.Choices().GetCount() == 0 )
5253 {
5255 zcMap.Map( ZONE_CONNECTION::INHERITED, _HKI( "Inherited" ) )
5256 .Map( ZONE_CONNECTION::NONE, _HKI( "None" ) )
5257 .Map( ZONE_CONNECTION::THERMAL, _HKI( "Thermal reliefs" ) )
5258 .Map( ZONE_CONNECTION::FULL, _HKI( "Solid" ) )
5259 .Map( ZONE_CONNECTION::THT_THERMAL, _HKI( "Thermal reliefs for PTH" ) );
5260 }
5261
5263
5264 if( layerEnum.Choices().GetCount() == 0 )
5265 {
5266 layerEnum.Undefined( UNDEFINED_LAYER );
5267
5268 for( PCB_LAYER_ID layer : LSET::AllLayersMask() )
5269 layerEnum.Map( layer, LSET::Name( layer ) );
5270 }
5271
5272 wxPGChoices fpLayers; // footprints might be placed only on F.Cu & B.Cu
5273 fpLayers.Add( LSET::Name( F_Cu ), F_Cu );
5274 fpLayers.Add( LSET::Name( B_Cu ), B_Cu );
5275
5282
5283 auto isNotFootprintHolder =
5284 []( INSPECTABLE* aItem ) -> bool
5285 {
5286 if( FOOTPRINT* footprint = dynamic_cast<FOOTPRINT*>( aItem ) )
5287 {
5288 if( BOARD* board = footprint->GetBoard() )
5289 return !board->IsFootprintHolder();
5290 }
5291 return true;
5292 };
5293
5294 propMgr.ReplaceProperty( TYPE_HASH( BOARD_ITEM ), _HKI( "Layer" ),
5297 .SetAvailableFunc( isNotFootprintHolder )
5298 .SetChoices( fpLayers );
5299
5300 propMgr.AddProperty( new PROPERTY<FOOTPRINT, double>( _HKI( "Orientation" ),
5303 .SetAvailableFunc( isNotFootprintHolder );
5304
5305 propMgr.AddProperty( new PROPERTY<FOOTPRINT, double>( _HKI( "Scale X" ),
5307 .SetAvailableFunc( isNotFootprintHolder );
5308
5309 propMgr.AddProperty( new PROPERTY<FOOTPRINT, double>( _HKI( "Scale Y" ),
5311 .SetAvailableFunc( isNotFootprintHolder );
5312
5313 const wxString groupFields = _HKI( "Fields" );
5314
5315 propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Reference" ),
5317 groupFields );
5318
5319 const wxString propertyFields = _HKI( "Footprint Properties" );
5320
5321 propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Library Link" ),
5323 propertyFields );
5324 propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Library Description" ),
5326 propertyFields );
5327 propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Keywords" ),
5329 propertyFields );
5330
5331 propMgr.AddProperty( new PROPERTY<FOOTPRINT, int>( _HKI( "Height" ),
5333 propertyFields )
5334 .SetIsCopyable();
5335
5336 // Note: Also used by DRC engine
5337 propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Component Class" ),
5339 propertyFields )
5341
5342 const wxString groupAttributes = _HKI( "Attributes" );
5343
5344 propMgr.AddProperty( new PROPERTY_ENUM<FOOTPRINT, FOOTPRINT_TYPE>( _HKI( "Footprint Type" ),
5346 groupAttributes );
5347 propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Not in Schematic" ),
5348 &FOOTPRINT::SetBoardOnly, &FOOTPRINT::IsBoardOnly ), groupAttributes );
5349 propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exclude From Position Files" ),
5351 groupAttributes );
5352 propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exclude From Bill of Materials" ),
5354 groupAttributes );
5355 propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exclude From Simulation" ),
5357 groupAttributes );
5358 propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Do not Populate" ),
5360 groupAttributes );
5361
5362 const wxString groupOverrides = _HKI( "Overrides" );
5363
5364 propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exempt From Courtyard Requirement" ),
5366 groupOverrides );
5367 propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<int>>( _HKI( "Clearance Override" ),
5369 groupOverrides )
5370 .SetIsCopyable();
5371 propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<int>>( _HKI( "Solderpaste Margin Override" ),
5374 groupOverrides )
5375 .SetIsCopyable();
5376 propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<double>>( _HKI( "Solderpaste Margin Ratio Override" ),
5379 groupOverrides )
5380 .SetIsCopyable();
5381 propMgr.AddProperty( new PROPERTY_ENUM<FOOTPRINT, ZONE_CONNECTION>( _HKI( "Zone Connection Style" ),
5383 groupOverrides )
5384 .SetIsCopyable();
5385 }
5387
const char * name
KICOMMON_API types::KiCadObjectType ToProtoEnum(KICAD_T aValue)
KICOMMON_API KICAD_T FromProtoEnum(types::KiCadObjectType aValue)
Definition api_enums.cpp:56
std::unique_ptr< EDA_ITEM > CreateItemForType(KICAD_T aType, EDA_ITEM *aContainer)
ERROR_LOC
When approximating an arc or circle, should the error be placed on the outside or inside of the curve...
@ ERROR_OUTSIDE
@ ERROR_INSIDE
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
constexpr int ARC_LOW_DEF
Definition base_units.h:143
BITMAPS
A list of all bitmap identifiers.
@ FPHOLDER
Definition board.h:403
#define DEFAULT_COURTYARD_WIDTH
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
BASE_SET & set(size_t pos)
Definition base_set.h:126
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
Abstract interface for BOARD_ITEMs capable of storing other items inside.
BOARD_ITEM_CONTAINER(BOARD_ITEM *aParent, KICAD_T aType)
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
BOARD_ITEM(BOARD_ITEM *aParent, KICAD_T idtype, PCB_LAYER_ID aLayer=F_Cu)
Definition board_item.h:101
void SetUuidDirect(const KIID &aUuid)
Raw UUID assignment.
void ResetUuidDirect()
Definition board_item.h:292
virtual BOARD_ITEM * Duplicate(bool addToParentGroup, BOARD_COMMIT *aCommit=nullptr) const
Create a copy of this BOARD_ITEM.
void SetLocked(bool aLocked) override
Definition board_item.h:441
PCB_LAYER_ID GetFlippedLayer(PCB_LAYER_ID aLayer) const
Return the layer paired with aLayer on the opposite side of the board.
static double polygonArea(SHAPE_POLY_SET &aPolySet)
Area of aPolySet with every contour closed first, holes subtracted.
PCB_LAYER_ID m_layer
Definition board_item.h:625
bool IsLocked() const override
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
virtual void TransformShapeToPolygon(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aError, ERROR_LOC aErrorLoc, bool ignoreLineWidth=false) const
Convert the item shape to a closed polygon.
void SetX(int aX)
Definition board_item.h:170
void SetY(int aY)
Definition board_item.h:176
virtual void SetLayer(PCB_LAYER_ID aLayer)
Set the layer this item is on.
Definition board_item.h:397
virtual const BOARD * GetBoard() const
Return the BOARD in which this BOARD_ITEM resides, or NULL if none.
VECTOR2I GetFPRelativePosition() const
virtual void TransformShapeToPolySet(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aError, ERROR_LOC aErrorLoc, KIGFX::RENDER_SETTINGS *aRenderSettings=nullptr) const
Convert the item shape to a polyset.
Definition board_item.h:582
BOARD_ITEM & operator=(const BOARD_ITEM &aOther)
Definition board_item.h:118
BOARD_ITEM_CONTAINER * GetParent() const
Definition board_item.h:281
wxString GetLayerName() const
Return the name of the PCB layer on which the item resides.
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
bool IsFootprintHolder() const
Find out if the board is being used to hold a single footprint for editing/viewing.
Definition board.h:441
int GetCopperLayerCount() const
Definition board.cpp:1155
wxString GetCurrentVariant() const
Definition board.h:530
COMPONENT_CLASS_MANAGER & GetComponentClassManager()
Gets the component class manager.
Definition board.h:1708
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition box2.h:556
constexpr size_type GetWidth() const
Definition box2.h:217
constexpr BOX2< Vec > & Merge(const BOX2< Vec > &aRect)
Modify the position and size of the rectangle in order to contain aRect.
Definition box2.h:597
constexpr const Vec GetCenter() const
Definition box2.h:233
constexpr size_type GetHeight() const
Definition box2.h:218
constexpr bool Contains(const Vec &aPoint) const
Definition box2.h:171
constexpr coord_type GetTop() const
Definition box2.h:232
constexpr bool Intersects(const BOX2< Vec > &aRect) const
Definition box2.h:314
constexpr coord_type GetBottom() const
Definition box2.h:225
virtual int Accuracy() const =0
int GetCount() const
Return the number of objects in the list.
Definition collector.h:79
const COMPONENT_CLASS * GetStaticComponentClass() const
Gets the static component class.
COMPONENT_CLASS * GetEffectiveStaticComponentClass(const std::unordered_set< wxString > &classNames)
Computes and returns an effective component class for a (possibly empty) set of constituent class nam...
A lightweight representation of a component class.
int AsTenthsOfADegree() const
Definition eda_angle.h:117
EDA_ANGLE Normalize180()
Definition eda_angle.h:273
bool IsType(FRAME_T aType) const
The base class for create windows for drawing purpose.
std::unordered_set< EDA_ITEM * > & GetItems()
Definition eda_group.h:78
void AddItem(EDA_ITEM *aItem)
Add item to group.
Definition eda_group.cpp:58
virtual void ClearEditFlags()
Definition eda_item.h:178
void SetFlags(EDA_ITEM_FLAGS aMask)
Definition eda_item.h:158
std::vector< PROPERTY_BASE * > GetCustomPropertiesAsInspectables() const
Definition eda_item.cpp:210
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:160
virtual bool Matches(const EDA_SEARCH_DATA &aSearchData, void *aAuxData) const
Compare the item against the search criteria in aSearchData.
Definition eda_item.h:484
static INSPECT_RESULT IterateForward(std::deque< T > &aList, INSPECTOR inspector, void *testData, const std::vector< KICAD_T > &scanTypes)
This changes first parameter to avoid the DList and use the main queue instead.
Definition eda_item.h:401
bool HasFlag(EDA_ITEM_FLAGS aFlag) const
Definition eda_item.h:168
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
EDA_ITEM(EDA_ITEM *parent, KICAD_T idType, bool isSCH_ITEM=false, bool isBOARD_ITEM=false)
Definition eda_item.cpp:84
int GetEllipseMinorRadius() const
Definition eda_shape.h:404
const VECTOR2I & GetEllipseCenter() const
Definition eda_shape.h:386
EDA_ANGLE GetEllipseEndAngle() const
Definition eda_shape.h:432
int GetEllipseMajorRadius() const
Definition eda_shape.h:395
EDA_ANGLE GetEllipseRotation() const
Definition eda_shape.h:413
SHAPE_T GetShape() const
Definition eda_shape.h:178
EDA_ANGLE GetEllipseStartAngle() const
Definition eda_shape.h:423
A mix-in class (via multiple inheritance) that handles texts such as labels, parts,...
Definition eda_text.h:94
bool IsItalic() const
Definition eda_text.h:200
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
virtual bool IsVisible() const
Definition eda_text.h:226
void SetVertJustify(GR_TEXT_V_ALIGN_T aType)
Definition eda_text.cpp:379
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
double GetLineSpacing() const
Definition eda_text.h:298
bool IsMirrored() const
Definition eda_text.h:229
bool IsBold() const
Definition eda_text.h:215
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
void SetHorizJustify(GR_TEXT_H_ALIGN_T aType)
Definition eda_text.cpp:371
EMBEDDED_FILES & operator=(EMBEDDED_FILES &&other) noexcept
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
EMBEDDED_FILES()=default
bool m_embedFonts
If set, fonts will be embedded in the element on save.
ENUM_MAP & Map(T aValue, const wxString &aName)
Definition property.h:817
static ENUM_MAP< T > & Instance()
Definition property.h:811
ENUM_MAP & Undefined(T aValue)
Definition property.h:824
wxPGChoices & Choices()
Definition property.h:862
Variant information for a footprint.
Definition footprint.h:178
wxString GetName() const
Definition footprint.h:189
bool HasFieldValue(const wxString &aFieldName) const
Definition footprint.h:237
void SetExcludedFromPosFiles(bool aExclude)
Definition footprint.h:202
wxString GetFieldValue(const wxString &aFieldName) const
Get a field value override for this variant.
Definition footprint.h:209
void SetName(const wxString &aName)
Definition footprint.h:190
bool GetExcludedFromSim() const
Definition footprint.h:198
bool GetExcludedFromBOM() const
Definition footprint.h:195
void SetExcludedFromSim(bool aExclude)
Definition footprint.h:199
void SetDNP(bool aDNP)
Definition footprint.h:193
bool GetExcludedFromPosFiles() const
Definition footprint.h:201
bool GetDNP() const
Definition footprint.h:192
void SetFieldValue(const wxString &aFieldName, const wxString &aValue)
Set a field value override for this variant.
Definition footprint.h:224
void SetExcludedFromBOM(bool aExclude)
Definition footprint.h:196
bool FixUuids()
Old footprints do not always have a valid UUID (some can be set to null uuid) However null UUIDs,...
bool GetDuplicatePadNumbersAreJumpers() const
Definition footprint.h:1133
double GetCoverageArea(int aTextMargin) const override
Return the board area this item covers, used to rank candidates under the cursor so a click on a smal...
void EmbedFonts() override
bool AllowSolderMaskBridges() const
Definition footprint.h:518
void SetPosition(const VECTOR2I &aPos) override
void SetFPID(const LIB_ID &aFPID)
Definition footprint.h:418
LIB_ID m_fpid
Definition footprint.h:1394
wxString GetLibDescription() const
Definition footprint.h:449
ZONE_CONNECTION GetLocalZoneConnection() const
Definition footprint.h:491
KIID_PATH m_path
Definition footprint.h:1451
std::deque< BOARD_ITEM * > m_drawings
Definition footprint.h:1385
void SetStackupLayers(LSET aLayers)
If the footprint has a non-default stackup, set the layers that should be used for the stackup.
bool IsBoardOnly() const
Definition footprint.h:911
void SerializeDefinition(kiapi::board::types::Footprint *aOutput) const
void InvalidateComponentClassCache() const
Forces deferred (on next access) recalculation of the component class for this footprint.
bool IsDNP() const
Definition footprint.h:947
void SetFootprintType(FOOTPRINT_TYPE aFootprintType)
std::vector< PAD * > GetNetTiePads(PAD *aPad) const
EDA_ANGLE GetOrientation() const
Definition footprint.h:382
PCB_3D_BODY & EnsureBody()
ZONES & Zones()
Definition footprint.h:361
bool Deserialize(const google::protobuf::Any &aContainer) override
Deserializes the given protobuf message into this object.
std::deque< PCB_POINT * > m_points
Definition footprint.h:1390
void Remove(BOARD_ITEM *aItem, REMOVE_MODE aMode=REMOVE_MODE::NORMAL) override
Removes an item from the container.
ZONE_CONNECTION m_zoneConnection
Definition footprint.h:1438
int GetNextFieldOrdinal() const
Return the next ordinal for a user field for this footprint.
PCB_POINTS & Points()
Definition footprint.h:370
bool IsExcludedFromBOM() const
Definition footprint.h:929
std::shared_ptr< SHAPE > GetEffectiveShape(PCB_LAYER_ID aLayer=UNDEFINED_LAYER, FLASHING aFlash=FLASHING::DEFAULT, DRC_CONSTRAINT_T aUsage=NULL_CONSTRAINT) const override
Some pad shapes can be complex (rounded/chamfered rectangle), even without considering custom shapes.
void SetOrientation(const EDA_ANGLE &aNewAngle)
std::optional< double > m_solderPasteMarginRatio
Definition footprint.h:1442
void SetDNP(bool aDNP=true)
Definition footprint.h:948
void SetAllowSolderMaskBridges(bool aAllow)
Definition footprint.h:519
void RecomputeComponentClass() const
Forces immediate recalculation of the component class for this footprint.
std::vector< ZONE * > m_zones
Definition footprint.h:1387
bool GetExcludedFromSimForVariant(const wxString &aVariantName) const
Get the exclude-from-simulation status for a specific variant.
static bool IsLibNameValid(const wxString &aName)
Test for validity of a name of a footprint to be used in a footprint library ( no spaces,...
void SetStackupMode(FOOTPRINT_STACKUP aMode)
Set the stackup mode for this footprint.
void SetLocalSolderPasteMarginRatio(std::optional< double > aRatio)
Definition footprint.h:488
std::vector< SEARCH_TERM > & GetSearchTerms() override
double ViewGetLOD(int aLayer, const KIGFX::VIEW *aView) const override
Return the level of detail (LOD) of the item.
std::optional< int > m_clearance
Definition footprint.h:1439
bool m_duplicatePadNumbersAreJumpers
Flag that this footprint should automatically treat sets of two or more pads with the same number as ...
Definition footprint.h:1432
void SetExcludedFromSim(bool aExclude=true)
Definition footprint.h:939
void SetExcludedFromBOM(bool aExclude=true)
Definition footprint.h:930
int m_fpStatus
Definition footprint.h:1396
std::map< wxString, std::unique_ptr< PCB_FOOTPRINT_FIELD_PROPERTY > > m_fieldPropsStorageCache
Per-object cache of dynamic property descriptors for custom fields, keyed by descriptor name and popu...
Definition footprint.h:1417
void SetKeywords(const wxString &aKeywords)
Definition footprint.h:453
void SetStaticComponentClass(const COMPONENT_CLASS *aClass) const
Sets the component class object pointer for this footprint.
wxString DisambiguateItemDescription(UNITS_PROVIDER *aUnitsProvider, bool aFull) const override
int m_attributes
Definition footprint.h:1395
PCB_LAYER_ID GetSide() const
Use instead of IsFlipped() when you also need to account for unsided footprints (those purely on user...
wxString GetLibNickname() const override
Definition footprint.h:444
const BOX2I GetLayerBoundingBox(const LSET &aLayers) const
Return the bounding box of the footprint on a given set of layers.
std::vector< FP_3DMODEL > m_3D_Drawings
Definition footprint.h:1459
double CoverageRatio(const GENERAL_COLLECTOR &aCollector) const
Calculate the ratio of total area of the footprint pads and graphical items to the area of the footpr...
FOOTPRINT_TYPE GetFootprintType() const
void RunOnChildren(const std::function< void(BOARD_ITEM *)> &aFunction, RECURSE_MODE aMode) const override
Invoke a function on all children.
bool m_allowMissingCourtyard
Definition footprint.h:1434
BITMAPS GetMenuImage() const override
Return a pointer to an image to be used in menus.
std::optional< int > GetLocalSolderPasteMargin() const
Definition footprint.h:484
std::unique_ptr< COMPONENT_CLASS_CACHE_PROXY > m_componentClassCacheProxy
Definition footprint.h:1469
wxArrayString * m_initial_comments
Definition footprint.h:1462
EDA_ITEM * Clone() const override
Create a duplicate of this item with linked list members set to NULL.
BOX2I GetFpPadsLocalBbox() const
Return the bounding box containing pads when the footprint is on the front side, orientation 0,...
LIB_ID GetLIB_ID() const override
Definition footprint.h:442
std::deque< PCB_FIELD * > m_fields
Definition footprint.h:1384
std::mutex m_geometry_cache_mutex
Definition footprint.h:1412
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:831
void Rotate(const VECTOR2I &aRotCentre, const EDA_ANGLE &aAngle) override
Rotate this object.
std::optional< int > m_solderPasteMargin
Definition footprint.h:1441
std::mutex m_courtyard_cache_mutex
Definition footprint.h:1466
void SetExcludedFromPosFiles(bool aExclude=true)
Definition footprint.h:921
bool IsWithinSchematicSheet(const KIID_PATH &aSheetPath) const
Test whether this footprint's symbol lives on aSheetPath or any sheet below it.
void SetOrientationDegrees(double aOrientation)
Definition footprint.h:408
unsigned GetPadCount() const
std::map< wxString, int > MapPadNumbersToNetTieGroups() const
std::optional< int > GetLocalClearance() const
Definition footprint.h:478
void UpdateFields(const std::vector< PCB_FIELD > &aFields, std::vector< PCB_FIELD * > &aAdded, std::vector< PCB_FIELD * > &aDetached)
Replace the fields with aFields, reusing the existing mandatory field objects.
double Similarity(const BOARD_ITEM &aOther) const override
Return a measure of how likely the other object is to represent the same object.
const FOOTPRINT_VARIANT * GetVariant(const wxString &aVariantName) const
Get a variant by name.
void MoveAnchorPosition(const VECTOR2I &aMoveVector)
Move the reference point of the footprint.
void SetDuplicatePadNumbersAreJumpers(bool aEnabled)
Definition footprint.h:1134
bool m_allowSolderMaskBridges
Definition footprint.h:1435
FOOTPRINT & operator=(const FOOTPRINT &aOther)
bool HasField(const wxString &aFieldName) const
CONSTRAINTS & Constraints()
Definition footprint.h:367
PCB_FIELD * GetField(FIELD_T aFieldType)
Return a mandatory field in this footprint.
void SetScaleY(double aScaleY)
Definition footprint.h:404
void TransformPadsToPolySet(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aMaxError, ERROR_LOC aErrorLoc) const
Generate pads shapes on layer aLayer as polygons and adds these polygons to aBuffer.
double GetOrientationDegrees() const
Definition footprint.h:412
INSPECT_RESULT Visit(INSPECTOR inspector, void *testData, const std::vector< KICAD_T > &aScanTypes) override
May be re-implemented for each derived class in order to handle all the types given by its member dat...
std::deque< PAD * > & Pads()
Definition footprint.h:355
void ResolveComponentClassNames(BOARD *aBoard, const std::unordered_set< wxString > &aComponentClassNames)
Resolves a set of component class names to this footprint's actual component class.
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
bool Matches(const EDA_SEARCH_DATA &aSearchData, void *aAuxData) const override
Compare the item against the search criteria in aSearchData.
const COMPONENT_CLASS * GetComponentClass() const
Returns the component class for this footprint.
void SetLocalZoneConnection(ZONE_CONNECTION aType)
Definition footprint.h:490
BOARD_ITEM * DuplicateItem(bool addToParentGroup, BOARD_COMMIT *aCommit, const BOARD_ITEM *aItem, bool addToFootprint=false)
Duplicate a given item within the footprint, optionally adding it to the board.
FOOTPRINT(BOARD *parent)
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition footprint.h:393
bool ResolveTextVar(wxString *aToken, int aDepth=0) const
Resolve any references to system tokens supported by the component.
LSET GetPrivateLayers() const
Definition footprint.h:295
wxString GetFPIDAsString() const
Definition footprint.h:419
CASE_INSENSITIVE_MAP< FOOTPRINT_VARIANT > m_variants
Variant data for this footprint, keyed by variant name.
Definition footprint.h:1400
double GetScaleX() const
Definition footprint.h:399
bool AllowMissingCourtyard() const
Definition footprint.h:515
void DeleteVariant(const wxString &aVariantName)
Delete a variant by name.
wxString GetComponentClassAsString() const
Used for display in the properties panel.
JUMPER_GROUP_SET m_jumperPadGroups
A list of jumper pad groups, each of which is a set of pad numbers that should be jumpered together (...
Definition footprint.h:1428
SHAPE_POLY_SET GetBoundingHull() const
Return a bounding polygon for the shapes and pads in the footprint.
void TransformFPShapesToPolySet(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aError, ERROR_LOC aErrorLoc, bool aIncludeText=true, bool aIncludeShapes=true, bool aIncludePrivateItems=false) const
Generate shapes of graphic items (outlines) on layer aLayer as polygons and adds these polygons to aB...
bool m_flipped
Definition footprint.h:1393
std::deque< PCB_CONSTRAINT * > m_constraints
Definition footprint.h:1389
wxString GetTypeName() const
Get the type of footprint.
const std::vector< wxString > & GetNetTiePadGroups() const
Definition footprint.h:567
const PCB_3D_BODY * GetBody() const
Definition footprint.h:427
const LIB_ID & GetFPID() const
Definition footprint.h:417
int GetHeight() const
The overall height of the footprint, or 0 if not specified.
Definition footprint.h:438
bool DeserializeDefinition(const kiapi::board::types::Footprint &aInput)
void SetReference(const wxString &aReference)
Definition footprint.h:799
std::vector< FP_UNIT_INFO > m_unitInfo
Definition footprint.h:1472
bool IsExcludedFromPosFiles() const
Definition footprint.h:920
void SetLayerAndFlip(PCB_LAYER_ID aLayer)
Used as Layer property setter – performs a flip if necessary to set the footprint layer.
unsigned GetNumberedPadCount() const
Return the number of unique pads whose pad number represents an electrical pin.
void SetHeight(int aHeight)
Definition footprint.h:439
wxString GetFieldValueForVariant(const wxString &aVariantName, const wxString &aFieldName) const
Get a field value for a specific variant.
void AddNetTiePadGroup(const wxString &aGroup)
Definition footprint.h:574
virtual const BOX2I ViewBBox() const override
Return the bounding box of the item covering all its layers.
LSET m_privateLayers
Definition footprint.h:1447
bool IsExcludedFromSim() const
Definition footprint.h:938
const std::deque< PCB_FIELD * > & GetFields() const
Return a reference to the deque holding the footprint's fields.
Definition footprint.h:869
int GetLikelyAttribute() const
Return the most likely attribute based on pads.
std::deque< PCB_GROUP * > m_groups
Definition footprint.h:1388
void Move(const VECTOR2I &aMoveVector) override
Move this object.
wxString m_libDescription
Definition footprint.h:1449
bool HitTestOnLayer(const VECTOR2I &aPosition, PCB_LAYER_ID aLayer, int aAccuracy=0) const
Test if the point hits one or more of the footprint elements on a given layer.
void ApplyDefaultSettings(const BOARD &board, bool aStyleFields, bool aStyleText, bool aStyleShapes, bool aStyleDimensions, bool aStyleBarcodes)
Apply default board settings to the footprint field text properties.
std::vector< wxString > m_netTiePadGroups
Definition footprint.h:1421
void InvalidateGeometryCaches()
Resets the caches for this footprint, for example if it was modified via the API.
virtual std::vector< int > ViewGetLayers() const override
Return the all the layers within the VIEW the object is painted on.
std::set< KIFONT::OUTLINE_FONT * > GetFonts() const override
Get a list of outline fonts referenced in the footprint.
void Add3DModel(FP_3DMODEL *a3DModel)
Add a3DModel definition to the end of the 3D model list.
void GetMsgPanelInfo(EDA_DRAW_FRAME *aFrame, std::vector< MSG_PANEL_ITEM > &aList) override
Populate aList of MSG_PANEL_ITEM objects with it's internal state for display purposes.
void SetTransformScale(double aScaleX, double aScaleY)
FOOTPRINT_STACKUP m_stackupMode
Definition footprint.h:1446
PCB_FIELD & Reference()
Definition footprint.h:832
wxString GetReferenceAsString() const
Definition footprint.h:802
JUMPER_GROUP_SET & JumperPadGroups()
Each jumper pad group is a set of pad numbers that should be treated as internally connected.
Definition footprint.h:1140
std::deque< PCB_3D_BODY * > m_bodies
Definition footprint.h:1458
wxString m_sheetfile
Definition footprint.h:1453
PAD * FindPadByUuid(const KIID &aUuid) const
void GetContextualTextVars(wxArrayString *aVars) const
Return the list of system text vars for this footprint.
std::optional< int > m_solderMaskMargin
Definition footprint.h:1440
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Adds an item to the container.
std::vector< const PAD * > GetPads(const wxString &aPadNumber, const PAD *aIgnore=nullptr) const
void AutoPositionFields()
Position Reference and Value fields at the top and bottom of footprint's bounding box.
wxString m_keywords
Definition footprint.h:1450
void SetScaleX(double aScaleX)
Definition footprint.h:402
void ClearAllNets()
Clear (i.e.
std::deque< PAD * > m_pads
Definition footprint.h:1386
void RescaleAroundPoint(const VECTOR2I &aCenter, double aSx, double aSy)
bool HasThroughHolePads() const
void BuildCourtyardCaches(OUTLINE_ERROR_HANDLER *aErrorHandler=nullptr)
Build complex polygons of the courtyard areas from graphic items on the courtyard layers.
bool IsOnLayer(PCB_LAYER_ID aLayer) const override
Test to see if this object is on the given layer.
bool HitTestAccurate(const VECTOR2I &aPosition, int aAccuracy=0) const
Test if a point is inside the bounding polygon of the footprint.
bool GetDNPForVariant(const wxString &aVariantName) const
Get the DNP status for a specific variant.
wxString GetClass() const override
Return the class name.
Definition footprint.h:1179
void SetVariant(const FOOTPRINT_VARIANT &aVariant)
Add or update a variant.
std::unique_ptr< FOOTPRINT_COURTYARD_CACHE_DATA > m_courtyard_cache
Definition footprint.h:1465
void SetLayer(PCB_LAYER_ID aLayer) override
Set the layer this item is on.
void IncrementReference(int aDelta)
Bump the current reference by aDelta.
std::optional< double > GetLocalSolderPasteMarginRatio() const
Definition footprint.h:487
void Flip(const VECTOR2I &aCentre, FLIP_DIRECTION aFlipDirection) override
Flip this object, i.e.
KIID m_link
Definition footprint.h:1457
GROUPS & Groups()
Definition footprint.h:364
std::set< wxString > GetUniquePadNumbers() const
A complex pad can be built with many pads having the same pad name to create a complex shape or fragm...
void GetFields(std::vector< PCB_FIELD * > &aVector, bool aVisibleOnly) const
Populate a std::vector with PCB_TEXTs.
void SetAllowMissingCourtyard(bool aAllow)
Definition footprint.h:516
void BuildNetTieCache()
Cache the pads that are allowed to connect to each other in the footprint.
bool IsConflicting() const
std::vector< FP_3DMODEL > & Models()
Definition footprint.h:375
BOARD_ITEM * Duplicate(bool addToParentGroup, BOARD_COMMIT *aCommit=nullptr) const override
Create a copy of this BOARD_ITEM.
void ClearBody()
const SHAPE_POLY_SET & GetCachedCourtyard(PCB_LAYER_ID aLayer) const
Return the cached courtyard area.
wxString GetName() const override
Definition footprint.h:443
static const wxChar * StringLibNameInvalidChars(bool aUserReadable)
Test for validity of the name in a library of the footprint ( no spaces, dir separators ....
void SetLibDescription(const wxString &aDesc)
Definition footprint.h:450
bool TextOnly() const
const COMPONENT_CLASS * GetStaticComponentClass() const
Returns the component class for this footprint.
void FixUpPadsForBoard(BOARD *aBoard)
Used post-loading of a footprint to adjust the layers on pads to match board inner layers.
bool GetExcludedFromPosFilesForVariant(const wxString &aVariantName) const
Get the exclude-from-position-files status for a specific variant.
FOOTPRINT_VARIANT * AddVariant(const wxString &aVariantName)
Add a new variant with the given name.
double GetArea(int aPadding=0) const
wxString m_filters
Definition footprint.h:1454
const wxString & GetReference() const
Definition footprint.h:793
std::unique_ptr< FOOTPRINT_GEOMETRY_CACHE_DATA > m_geometry_cache
Definition footprint.h:1413
bool GetExcludedFromBOMForVariant(const wxString &aVariantName) const
Get the exclude-from-BOM status for a specific variant.
void CopyFrom(const BOARD_ITEM *aOther) override
void RenameVariant(const wxString &aOldName, const wxString &aNewName)
Rename a variant.
wxString GetItemDescription(UNITS_PROVIDER *aUnitsProvider, bool aFull) const override
Return a user-visible description string of this item.
void SetBoardOnly(bool aIsBoardOnly=true)
Definition footprint.h:912
void SetLocalSolderMaskMargin(std::optional< int > aMargin)
Definition footprint.h:482
TRANSFORM_TRS m_transform
Definition footprint.h:1392
timestamp_t m_lastEditTime
Definition footprint.h:1455
PAD * GetPad(const VECTOR2I &aPosition, const LSET &aLayerMask=LSET::AllLayersMask())
Get a pad at aPosition on aLayerMask in the footprint.
const SHAPE_POLY_SET & GetCourtyard(PCB_LAYER_ID aLayer) const
Used in DRC to test the courtyard area (a complex polygon).
std::map< const BOARD_ITEM *, std::set< int > > m_netTieCache
Definition footprint.h:1424
std::vector< PROPERTY_BASE * > GetDynamicProperties() const override
Return dynamically-computed properties specific to this object instance (e.g.
wxString m_sheetname
Definition footprint.h:1452
LSET m_stackupLayers
Definition footprint.h:1445
int m_fileFormatVersionAtLoad
Definition footprint.h:1397
void SetLocalClearance(std::optional< int > aClearance)
Definition footprint.h:479
void SetPrivateLayers(const LSET &aLayers)
Definition footprint.h:296
std::optional< int > GetLocalSolderMaskMargin() const
Definition footprint.h:481
void SetLocalSolderPasteMargin(std::optional< int > aMargin)
Definition footprint.h:485
wxString GetKeywords() const
Definition footprint.h:452
bool operator==(const BOARD_ITEM &aOther) const override
EMBEDDED_FILES * GetEmbeddedFiles() override
Definition footprint.h:1286
std::deque< PCB_3D_BODY * > & Bodies()
Definition footprint.h:422
FOOTPRINT_STACKUP GetStackupMode() const
Definition footprint.h:500
virtual void swapData(BOARD_ITEM *aImage) override
wxString GetNextPadNumber(const wxString &aLastPadName) const
Return the next available pad number in the footprint.
double GetScaleY() const
Definition footprint.h:400
bool IsPlaced() const
Definition footprint.h:656
bool HasVariant(const wxString &aVariantName) const
Check if a variant exists.
VECTOR2I GetPosition() const override
Definition footprint.h:379
DRAWINGS & GraphicalItems()
Definition footprint.h:358
bool HitTest(const VECTOR2I &aPosition, int aAccuracy=0) const override
Test if aPosition is inside or on the boundary of this item.
PAD * FindPadByNumber(const wxString &aPadNumber, PAD *aSearchAfterMe=nullptr) const
Return a PAD with a matching number.
std::vector< SEARCH_TERM > m_searchTerms
Definition footprint.h:1474
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
wxString m_Filename
The 3D shape filename in 3D library.
Definition footprint.h:136
Used when the right click button is pressed, or when the select tool is in effect.
Definition collectors.h:203
const COLLECTORS_GUIDE * GetGuide() const
Definition collectors.h:289
Class that other classes need to inherit from, in order to be inspectable.
Definition inspectable.h:39
wxAny Get(PROPERTY_BASE *aProperty) const
Represents an (ordered) list of JUMPER_GROUP objects.
void Add(JUMPER_GROUP aGroup)
Add a JUMPER_GROUP to the set.
Represents a group of jumper pins or pads, keyed by name.
A typed sum value used to carry the before/after of any single property.
wxString ToDisplayString() const
Human-readable representation with no unit context.
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
virtual bool IsOutline() const
Definition font.h:102
Implement outline font drawing.
EMBEDDING_PERMISSION GetEmbeddingPermission() const
virtual wxString GetClass() const =0
Return the class name.
static constexpr double LOD_HIDE
Return this constant from ViewGetLOD() to hide the item unconditionally.
Definition view_item.h:176
static constexpr double LOD_SHOW
Return this constant from ViewGetLOD() to show the item unconditionally.
Definition view_item.h:181
Hold a (potentially large) number of VIEW_ITEMs and renders them on a graphics device provided by the...
Definition view.h:68
bool IsLayerVisible(int aLayer) const
Return information about visibility of a particular layer.
Definition view.h:457
Definition kiid.h:46
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
static const LSET & SideSpecificMask()
Definition lset.cpp:732
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
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:184
static const int ORPHANED
Constant that forces initialization of a netinfo item to the NETINFO_ITEM ORPHANED (typically -1) whe...
Definition netinfo.h:285
void ForEachUniqueLayer(const std::function< void(PCB_LAYER_ID)> &aMethod) const
Runs the given callable for each active unique copper layer in this padstack, meaning F_Cu for MODE::...
@ 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
MODE Mode() const
Definition padstack.h:351
Definition pad.h:61
LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition pad.h:579
PAD_ATTRIB GetAttribute() const
Definition pad.h:582
const wxString & GetNumber() const
Definition pad.h:143
VECTOR2I GetDrillSize() const
Definition pad.h:320
PAD_SHAPE GetShape(PCB_LAYER_ID aLayer) const
Definition pad.h:205
int GetSolderMaskExpansion(PCB_LAYER_ID aLayer) const
Definition pad.cpp:1960
VECTOR2I GetSize(PCB_LAYER_ID aLayer) const
Definition pad.cpp:297
const PADSTACK & Padstack() const
Definition pad.h:331
EDA_ANGLE GetOrientation() const
Return the rotation angle of the pad.
Definition pad.cpp:1672
PAD_DRILL_SHAPE GetDrillShape() const
Definition pad.h:438
const std::shared_ptr< SHAPE_POLY_SET > & GetEffectivePolygon(PCB_LAYER_ID aLayer, ERROR_LOC aErrorLoc=ERROR_INSIDE) const
Definition pad.cpp:1111
std::optional< int > GetLocalSolderMaskMargin() const
Definition pad.h:608
VECTOR2I GetSolderPasteMargin(PCB_LAYER_ID aLayer) const
Usually < 0 (mask shape smaller than pad)because the margin can be dependent on the pad size,...
Definition pad.cpp:2022
A 3D body attached to a footprint (or, later, placed on a board).
Definition pcb_3d_body.h:93
EDA_ITEM * Clone() const override
Create a duplicate of this item with linked list members set to NULL.
A geometric constraint between board items (issue #2329).
Abstract dimension API.
wxString GetUntranslatedName() const
Get the untranslated field name for storage, variable look-up, etc.
void Serialize(google::protobuf::Any &aContainer) const override
Serializes this object to the given Any message.
Definition pcb_field.cpp:81
bool Deserialize(const google::protobuf::Any &aContainer) override
Deserializes the given protobuf message into this object.
PCB_FIELD * CloneField() const
Same as Clone, but returns a PCB_FIELD item.
Definition pcb_field.h:102
size_t OwnerHash() const override
Return type-id of the Owner class.
Definition footprint.cpp:95
size_t TypeHash() const override
Return type-id of the property type.
Definition footprint.cpp:97
void setter(void *obj, wxAny &v) override
Definition footprint.cpp:99
size_t BaseHash() const override
Return type-id of the Base class.
Definition footprint.cpp:96
PCB_FOOTPRINT_FIELD_PROPERTY(const wxString &aName)
Definition footprint.cpp:88
wxAny getter(const void *obj) const override
A set of BOARD_ITEMs (i.e., without duplicates).
Definition pcb_group.h:51
A PCB_POINT is a 0-dimensional point that is used to mark a position on a PCB, or more usually a foot...
Definition pcb_point.h:39
Object to handle a bitmap image that can be inserted in a PCB.
VECTOR2I GetLibraryBezierC1() const
int GetWidth() const override
void TransformShapeToPolySet(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aError, ERROR_LOC aErrorLoc, KIGFX::RENDER_SETTINGS *aRenderSettings=nullptr) const override
Convert the item shape to a polyset.
VECTOR2I GetLibraryEnd() const
Definition pcb_shape.h:235
VECTOR2I GetLibraryStart() const
Definition pcb_shape.h:234
STROKE_PARAMS GetStroke() const override
SHAPE_POLY_SET GetLibraryPolyShape() const
VECTOR2I GetLibraryBezierC2() const
VECTOR2I GetLibraryArcMid() const
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition pcb_shape.h:70
bool IsBorderEnabled() const
Tests whether the border is disabled, as configured by the stroke.
void TransformTextToPolySet(SHAPE_POLY_SET &aBuffer, int aClearance, int aMaxError, ERROR_LOC aErrorLoc) const
Convert the text to a polygonSet describing the actual character strokes (one per segment).
EDA_ANGLE GetTextAngle() const override
Definition pcb_text.cpp:562
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
Definition pcb_text.cpp:413
int GetTextThickness() const override
Definition pcb_text.cpp:499
void SetTextAngle(const EDA_ANGLE &aAngle) override
Definition pcb_text.cpp:574
VECTOR2I GetTextSize() const override
Definition pcb_text.cpp:472
PROPERTY_BASE & SetAvailableFunc(std::function< bool(INSPECTABLE *)> aFunc)
Set a callback function to determine whether an object provides this property.
Definition property.h:275
PROPERTY_BASE(const wxString &aName, PROPERTY_DISPLAY aDisplay=PT_DEFAULT, ORIGIN_TRANSFORMS::COORD_TYPES_T aCoordType=ORIGIN_TRANSFORMS::NOT_A_COORD)
Used to generate unique IDs. Must come up front so it's initialized before ctor.
Definition property.h:201
PROPERTY_BASE & SetGroup(const wxString &aGroup)
Definition property.h:395
PROPERTY_BASE & SetIsCopyable(bool aIsCopyable=true)
Definition property.h:388
virtual void SetChoices(const wxPGChoices &aChoices)
Set the possible values for for the property.
Definition property.h:250
PROPERTY_BASE & SetIsHiddenFromLibraryEditors(bool aIsHidden=true)
Definition property.h:368
Provide class metadata.
void InheritsAfter(TYPE_ID aDerived, TYPE_ID aBase)
Declare an inheritance relationship between types.
static PROPERTY_MANAGER & Instance()
PROPERTY_BASE & AddProperty(PROPERTY_BASE *aProperty, const wxString &aGroup=wxEmptyString)
Register a property.
PROPERTY_BASE * GetProperty(TYPE_ID aType, const wxString &aProperty) const
Return a property for a specific type.
bool IsAvailableFor(TYPE_ID aItemClass, PROPERTY_BASE *aProp, INSPECTABLE *aItem)
Checks overriden availability and original availability of a property, returns false if the property ...
PROPERTY_BASE & ReplaceProperty(size_t aBase, const wxString &aName, PROPERTY_BASE *aNew, const wxString &aGroup=wxEmptyString)
Replace an existing property for a specific type.
void AddTypeCast(TYPE_CAST_BASE *aCast)
Register a type converter.
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
Represent a set of closed polygons.
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index.
bool Collide(const SHAPE *aShape, int aClearance=0, int *aActual=nullptr, VECTOR2I *aLocation=nullptr) const override
Check if the boundary of shape (this) lies closer to the shape aShape than aClearance,...
int TotalVertices() const
Return total number of vertices stored in the set.
int FullPointCount() const
Return the number of points in the shape poly 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)
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
int NewOutline()
Creates a new empty polygon in the set and returns its index.
void BooleanIntersection(const SHAPE_POLY_SET &b)
Perform boolean polyset intersection.
const VECTOR2I & CVertex(int aIndex, int aOutline, int aHole) const
Return the index-th vertex in a given hole outline within a given outline.
int OutlineCount() const
Return the number of outlines in the set.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
Represent a simple polygon consisting of a zero-thickness closed chain of connected line segments.
int GetWidth() const
double GetScaleX() const
double GetScaleY() const
const VECTOR2I & GetTranslate() const
Handle a list of polygons defining a copper zone.
Definition zone.h:70
bool SetNetCode(int aNetCode, bool aNoAssert) override
Override that clamps the netcode to 0 when this zone is in copper-thieving fill mode.
Definition zone.cpp:659
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
SHAPE_POLY_SET GetLibraryOutline() const
Definition zone.cpp:947
unsigned GetAssignedPriority() const
Definition zone.h:122
@ INTERNAL
Definition common.h:96
This file is part of the common library.
bool ConvertOutlineToPolygon(std::vector< PCB_SHAPE * > &aShapeList, SHAPE_POLY_SET &aPolygons, int aErrorMax, int aChainingEpsilon, bool aAllowDisjoint, OUTLINE_ERROR_HANDLER *aErrorHandler, bool aAllowUseArcsInPolygons)
Build a polygon set with holes from a PCB_SHAPE list.
const std::function< void(const wxString &msg, BOARD_ITEM *itemA, BOARD_ITEM *itemB, const VECTOR2I &pt)> OUTLINE_ERROR_HANDLER
void BuildConvexHull(std::vector< VECTOR2I > &aResult, const std::vector< VECTOR2I > &aPoly)
Calculate the convex hull of a list of points in counter-clockwise order.
@ CHAMFER_ACUTE_CORNERS
Acute angles are chamfered.
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:476
RECURSE_MODE
Definition eda_item.h:50
@ RECURSE
Definition eda_item.h:51
@ NO_RECURSE
Definition eda_item.h:52
INSPECT_RESULT
Definition eda_item.h:44
const INSPECTOR_FUNC & INSPECTOR
std::function passed to nested users by ref, avoids copying std::function.
Definition eda_item.h:91
#define COURTYARD_CONFLICT
temporary set when moving footprints having courtyard overlapping
#define MALFORMED_F_COURTYARD
#define MALFORMED_B_COURTYARD
#define STRUCT_DELETED
flag indication structures to be erased
#define MALFORMED_COURTYARDS
@ ELLIPSE
Definition eda_shape.h:63
@ ELLIPSE_ARC
Definition eda_shape.h:64
static struct FOOTPRINT_DESC _FOOTPRINT_DESC
static std::vector< wxString > parseNetTiePadGroup(const wxString &aGroup)
static constexpr std::optional< bool > cmp_points_opt(const VECTOR2I &aPtA, const VECTOR2I &aPtB)
Compare two points, returning std::nullopt if they are identical.
FOOTPRINT_TYPE
Definition footprint.h:98
@ FP_SMD
Definition footprint.h:87
@ FP_THROUGH_HOLE
Definition footprint.h:86
FOOTPRINT_STACKUP
Definition footprint.h:106
@ EXPAND_INNER_LAYERS
The 'normal' stackup handling, where there is a single inner layer (In1) and rule areas using it expa...
Definition footprint.h:111
@ CUSTOM_LAYERS
Stackup handling where the footprint can have any number of copper layers, and objects on those layer...
Definition footprint.h:116
@ FRAME_FOOTPRINT_VIEWER
Definition frame_type.h:41
@ FRAME_FOOTPRINT_CHOOSER
Definition frame_type.h:40
@ FRAME_FOOTPRINT_EDITOR
Definition frame_type.h:39
a few functions useful in geometry calculations.
const wxChar *const traceApi
Flag to enable debug output related to the IPC API and its plugin system.
Definition api_utils.cpp:33
Some functions to handle hotkeys in KiCad.
KIID niluuid(0)
FLASHING
Enum used during connectivity building to ensure we do not query connectivity while building the data...
Definition layer_ids.h:180
bool IsBackLayer(PCB_LAYER_ID aLayerId)
Layer classification: check if it's a back layer.
Definition layer_ids.h:870
@ LAYER_CONFLICTS_SHADOW
Shadow layer for items flagged conflicting.
Definition layer_ids.h:306
@ LAYER_FOOTPRINTS_FR
Show footprints on front.
Definition layer_ids.h:255
@ LAYER_FP_REFERENCES
Show footprints references (when texts are visible).
Definition layer_ids.h:262
@ LAYER_FP_TEXT
Definition layer_ids.h:236
@ LAYER_FOOTPRINTS_BK
Show footprints on back.
Definition layer_ids.h:256
@ LAYER_ANCHOR
Anchor of items having an anchor point (texts, footprints).
Definition layer_ids.h:244
@ LAYER_FP_VALUES
Show footprints values (when texts are visible).
Definition layer_ids.h:259
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_CrtYd
Definition layer_ids.h:112
@ Dwgs_User
Definition layer_ids.h:103
@ 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
@ Eco1_User
Definition layer_ids.h:105
@ 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
@ Eco2_User
Definition layer_ids.h:106
@ In1_Cu
Definition layer_ids.h:62
@ B_SilkS
Definition layer_ids.h:97
@ F_Cu
Definition layer_ids.h:60
bool IsValidLayer(int aLayerId)
Test whether a given integer is a valid layer index, i.e.
Definition layer_ids.h:722
const wxString & GetLibFilenameForbiddenChars()
Characters illegal in a footprint library filename.
Definition lib_id.cpp:40
This file contains miscellaneous commonly used macros and functions.
#define KI_FALLTHROUGH
The KI_FALLTHROUGH macro is to be used when switch statement cases should purposely fallthrough from ...
Definition macros.h:79
constexpr void MIRROR(T &aPoint, const T &aMirrorRef)
Updates aPoint with the mirror of aPoint relative to the aMirrorRef.
Definition mirror.h:44
FLIP_DIRECTION
Definition mirror.h:26
@ LEFT_RIGHT
Flip left to right (around the Y axis)
Definition mirror.h:27
@ TOP_BOTTOM
Flip top to bottom (around the X axis)
Definition mirror.h:28
DIFF_VALUE WxAnyToDiffValue(const wxAny &aValue, PROPERTY_BASE *aProperty)
Convert a wxAny value read from a PROPERTY_BASE getter into a DIFF_VALUE that the engine can store,...
bool BoxHitTest(const VECTOR2I &aHitPoint, const BOX2I &aHittee, int aAccuracy)
Perform a point-to-box hit test.
wxString GetRefDesPrefix(const wxString &aRefDes)
Get the (non-numeric) prefix from a refdes - e.g.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
void PackEmbeddedFiles(common::types::EmbeddedFiles &aOutput, const EMBEDDED_FILES &aFiles)
bool UnpackEmbeddedFiles(EMBEDDED_FILES &aOutput, const common::types::EmbeddedFiles &aProto)
KICOMMON_API int UnpackDistance(const types::Distance &aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API KIID_PATH UnpackSheetPath(const types::SheetPath &aInput)
KICOMMON_API std::optional< KICAD_T > TypeNameFromAny(const google::protobuf::Any &aMessage)
Definition api_utils.cpp:50
KICOMMON_API VECTOR3D UnpackVector3D(const types::Vector3D &aInput)
KICOMMON_API void PackCustomProperties(google::protobuf::RepeatedPtrField< types::CustomProperty > *aOutput, const EDA_ITEM &aItem)
KICOMMON_API void PackDistance(types::Distance &aOutput, int aInput, const EDA_IU_SCALE &aScale)
KICOMMON_API void PackSheetPath(types::SheetPath &aOutput, const KIID_PATH &aInput)
KICOMMON_API void PackLibId(types::LibraryIdentifier *aOutput, const LIB_ID &aId)
KICOMMON_API LIB_ID UnpackLibId(const types::LibraryIdentifier &aId)
KICOMMON_API void UnpackCustomProperties(const google::protobuf::RepeatedPtrField< types::CustomProperty > &aInput, EDA_ITEM &aItem)
KICOMMON_API void PackVector3D(types::Vector3D &aOutput, const VECTOR3D &aInput)
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
@ NON_COMPONENT
Pad with no hole that does not connect to a physical component, but rather provides a connection poin...
Definition padstack.h:106
@ SMD
Smd pad, appears on the solder paste layer (default)
Definition padstack.h:100
@ PTH
Plated through hole pad.
Definition padstack.h:99
@ CONN
Like smd, does not appear on the solder paste layer (default) Note: also has a special attribute in G...
Definition padstack.h:101
@ FIDUCIAL_LOCAL
a fiducial (usually a smd) local to the parent footprint
Definition padstack.h:122
@ FIDUCIAL_GLBL
a fiducial (usually a smd) for the full board
Definition padstack.h:121
@ MECHANICAL
a pad used for mechanical support
Definition padstack.h:126
@ PRESSFIT
a PTH with a hole diameter with tight tolerances for press fit pin
Definition padstack.h:127
@ HEATSINK
a pad used as heat sink, usually in SMD footprints
Definition padstack.h:124
@ NONE
no special fabrication property
Definition padstack.h:119
@ TESTPOINT
a test point pad
Definition padstack.h:123
@ CASTELLATED
a pad with a castellated through hole
Definition padstack.h:125
@ BGA
Smd pad, used in BGA footprints.
Definition padstack.h:120
#define _HKI(x)
Definition page_info.cpp:40
BARCODE class definition.
Class to handle a set of BOARD_ITEMs.
#define TYPE_HASH(x)
Macro to generate unique identifier for a type.
Definition property.h:74
#define NO_SETTER(owner, type)
Macro to define read-only fields (no setter method available)
Definition property.h:923
#define ENUM_TO_WXANY(type)
Definition property.h:918
@ PT_DEGREE
Angle expressed in degrees.
Definition property.h:66
@ PT_RATIO
Definition property.h:68
@ PT_SIZE
Size expressed in distance units (mm/inch)
Definition property.h:63
#define REGISTER_TYPE(x)
Helper macro to map type hashes to names.
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, const CPTREE &aTree)
Output a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition ptree.cpp:194
Collection of utility functions for component reference designators (refdes)
std::vector< FAB_LAYER_COLOR > dummy
int StrNumCmp(const wxString &aString1, const wxString &aString2, CMP_T aCaseSensitivity)
Compare two strings with alphanumerical content.
wxString GetDefaultVariantName()
int GetTrailingInt(const wxString &aStr)
Gets the trailing int, if any, from a string.
wxString UnescapeString(const wxString &aSource)
std::vector< wxString > m_pins
Definition footprint.h:905
bool operator()(const BOARD_ITEM *itemA, const BOARD_ITEM *itemB) const
bool operator()(const PAD *aFirst, const PAD *aSecond) const
bool operator()(const ZONE *aFirst, const ZONE *aSecond) const
A structure for storing weighted search terms.
wxString GetDefaultFieldName(FIELD_T aFieldId, TRANSLATION aTranslation)
Return a default symbol field name for a mandatory field type.
FIELD_T
The set of all field indices assuming an array like sequence that a SCH_COMPONENT or LIB_PART can hol...
@ USER
The field ID hasn't been set yet; field is invalid.
@ DESCRIPTION
Field Description of part, i.e. "1/4W 1% Metal Film Resistor".
@ DATASHEET
name of datasheet
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ VALUE
Field Value of part, i.e. "3.3K".
@ UNTRANSLATED
static EDA_ORIENTATION orientation(double d)
KIBIS_MODEL * model
int clearance
int delta
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_CENTER
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
constexpr KICAD_T BaseType(const KICAD_T aType)
Return the underlying type of the given type.
Definition typeinfo.h:261
KICAD_T
The set of class identification values stored in EDA_ITEM::m_structType.
Definition typeinfo.h:70
@ PCB_CONSTRAINT_T
a geometric constraint between board items
Definition typeinfo.h:237
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
Definition typeinfo.h:98
@ PCB_DIM_LEADER_T
class PCB_DIM_LEADER, a leader dimension (graphic item)
Definition typeinfo.h:95
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_DIM_CENTER_T
class PCB_DIM_CENTER, a center point marking (graphic item)
Definition typeinfo.h:96
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition typeinfo.h:103
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
Definition typeinfo.h:85
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:100
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_3D_BODY_T
class PCB_3D_BODY, a 3D body (extruded or model) on a footprint
Definition typeinfo.h:241
@ PCB_REFERENCE_IMAGE_T
class PCB_REFERENCE_IMAGE, bitmap on a layer
Definition typeinfo.h:81
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition typeinfo.h:82
@ PCB_MARKER_T
class PCB_MARKER, a marker used to show something
Definition typeinfo.h:91
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
Definition typeinfo.h:93
@ PCB_TABLECELL_T
class PCB_TABLECELL, PCB_TEXTBOX for use in tables
Definition typeinfo.h:87
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition typeinfo.h:78
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition typeinfo.h:94
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:79
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:90
@ PCB_DIMENSION_T
class PCB_DIMENSION_BASE: abstract dimension meta-type
Definition typeinfo.h:92
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition typeinfo.h:86
@ PCB_POINT_T
class PCB_POINT, a 0-dimensional point
Definition typeinfo.h:105
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:88
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition typeinfo.h:97
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)
ZONE_CONNECTION
How pads are covered by copper in zone.
Definition zones.h:43
@ THERMAL
Use thermal relief for pads.
Definition zones.h:46
@ THT_THERMAL
Thermal relief only for THT pads.
Definition zones.h:48
@ NONE
Pads are not covered.
Definition zones.h:45
@ FULL
pads are covered by copper
Definition zones.h:47