You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4204 lines
127 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
9 months ago
5 years ago
5 years ago
9 months ago
9 months ago
9 months ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
14 years ago
12 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
* KIWAY Milestone A): Make major modules into DLL/DSOs. ! The initial testing of this commit should be done using a Debug build so that all the wxASSERT()s are enabled. Also, be sure and keep enabled the USE_KIWAY_DLLs option. The tree won't likely build without it. Turning it off is senseless anyways. If you want stable code, go back to a prior version, the one tagged with "stable". * Relocate all functionality out of the wxApp derivative into more finely targeted purposes: a) DLL/DSO specific b) PROJECT specific c) EXE or process specific d) configuration file specific data e) configuration file manipulations functions. All of this functionality was blended into an extremely large wxApp derivative and that was incompatible with the desire to support multiple concurrently loaded DLL/DSO's ("KIFACE")s and multiple concurrently open projects. An amazing amount of organization come from simply sorting each bit of functionality into the proper box. * Switch to wxConfigBase from wxConfig everywhere except instantiation. * Add classes KIWAY, KIFACE, KIFACE_I, SEARCH_STACK, PGM_BASE, PGM_KICAD, PGM_SINGLE_TOP, * Remove "Return" prefix on many function names. * Remove obvious comments from CMakeLists.txt files, and from else() and endif()s. * Fix building boost for use in a DSO on linux. * Remove some of the assumptions in the CMakeLists.txt files that windows had to be the host platform when building windows binaries. * Reduce the number of wxStrings being constructed at program load time via static construction. * Pass wxConfigBase* to all SaveSettings() and LoadSettings() functions so that these functions are useful even when the wxConfigBase comes from another source, as is the case in the KICAD_MANAGER_FRAME. * Move the setting of the KIPRJMOD environment variable into class PROJECT, so that it can be moved into a project variable soon, and out of FP_LIB_TABLE. * Add the KIWAY_PLAYER which is associated with a particular PROJECT, and all its child wxFrames and wxDialogs now have a Kiway() member function which returns a KIWAY& that that window tree branch is in support of. This is like wxWindows DNA in that child windows get this member with proper value at time of construction. * Anticipate some of the needs for milestones B) and C) and make code adjustments now in an effort to reduce work in those milestones. * No testing has been done for python scripting, since milestone C) has that being largely reworked and re-thought-out.
12 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
11 months ago
11 months ago
11 months ago
5 years ago
11 months ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
11 years ago
11 months ago
5 years ago
5 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  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 <dick@softplc.com>
  6. * Copyright (C) 2015 Wayne Stambaugh <stambaughw@gmail.com>
  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, you may find one here:
  21. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  22. * or you may search the http://www.gnu.org website for the version 2 license,
  23. * or you may write to the Free Software Foundation, Inc.,
  24. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  25. */
  26. #include <magic_enum.hpp>
  27. #include <unordered_set>
  28. #include <bitmaps.h>
  29. #include <board.h>
  30. #include <board_design_settings.h>
  31. #include <confirm.h>
  32. #include <convert_basic_shapes_to_polygon.h>
  33. #include <convert_shape_list_to_polygon.h>
  34. #include <component_classes/component_class.h>
  35. #include <component_classes/component_class_cache_proxy.h>
  36. #include <drc/drc_item.h>
  37. #include <embedded_files.h>
  38. #include <font/font.h>
  39. #include <font/outline_font.h>
  40. #include <footprint.h>
  41. #include <geometry/convex_hull.h>
  42. #include <geometry/shape_segment.h>
  43. #include <geometry/shape_simple.h>
  44. #include <i18n_utility.h>
  45. #include <lset.h>
  46. #include <macros.h>
  47. #include <pad.h>
  48. #include <pcb_dimension.h>
  49. #include <pcb_edit_frame.h>
  50. #include <pcb_field.h>
  51. #include <pcb_group.h>
  52. #include <pcb_marker.h>
  53. #include <pcb_reference_image.h>
  54. #include <pcb_textbox.h>
  55. #include <pcb_track.h>
  56. #include <refdes_utils.h>
  57. #include <string_utils.h>
  58. #include <view/view.h>
  59. #include <zone.h>
  60. #include <google/protobuf/any.pb.h>
  61. #include <api/board/board_types.pb.h>
  62. #include <api/api_enums.h>
  63. #include <api/api_utils.h>
  64. #include <api/api_pcb_utils.h>
  65. #include <wx/log.h>
  66. FOOTPRINT::FOOTPRINT( BOARD* parent ) :
  67. BOARD_ITEM_CONTAINER( (BOARD_ITEM*) parent, PCB_FOOTPRINT_T ),
  68. m_boundingBoxCacheTimeStamp( 0 ), m_textExcludedBBoxCacheTimeStamp( 0 ),
  69. m_hullCacheTimeStamp( 0 ), m_initial_comments( nullptr ),
  70. m_componentClassCacheProxy( std::make_unique<COMPONENT_CLASS_CACHE_PROXY>( this ) )
  71. {
  72. m_attributes = 0;
  73. m_layer = F_Cu;
  74. m_orient = ANGLE_0;
  75. m_fpStatus = FP_PADS_are_LOCKED;
  76. m_arflag = 0;
  77. m_link = 0;
  78. m_lastEditTime = 0;
  79. m_zoneConnection = ZONE_CONNECTION::INHERITED;
  80. m_fileFormatVersionAtLoad = 0;
  81. m_embedFonts = false;
  82. auto addField =
  83. [this]( FIELD_T id, PCB_LAYER_ID layer, bool visible )
  84. {
  85. PCB_FIELD* field = new PCB_FIELD( this, id );
  86. field->SetLayer( layer );
  87. field->SetVisible( visible );
  88. m_fields.push_back( field );
  89. };
  90. addField( FIELD_T::REFERENCE, F_SilkS, true );
  91. addField( FIELD_T::VALUE, F_Fab, true );
  92. addField( FIELD_T::DATASHEET, F_Fab, false );
  93. addField( FIELD_T::DESCRIPTION, F_Fab, false );
  94. m_3D_Drawings.clear();
  95. }
  96. FOOTPRINT::FOOTPRINT( const FOOTPRINT& aFootprint ) :
  97. BOARD_ITEM_CONTAINER( aFootprint ), EMBEDDED_FILES( aFootprint ),
  98. m_componentClassCacheProxy( std::make_unique<COMPONENT_CLASS_CACHE_PROXY>( this ) )
  99. {
  100. m_pos = aFootprint.m_pos;
  101. m_fpid = aFootprint.m_fpid;
  102. m_attributes = aFootprint.m_attributes;
  103. m_fpStatus = aFootprint.m_fpStatus;
  104. m_orient = aFootprint.m_orient;
  105. m_lastEditTime = aFootprint.m_lastEditTime;
  106. m_link = aFootprint.m_link;
  107. m_path = aFootprint.m_path;
  108. m_embedFonts = aFootprint.m_embedFonts;
  109. m_cachedBoundingBox = aFootprint.m_cachedBoundingBox;
  110. m_boundingBoxCacheTimeStamp = aFootprint.m_boundingBoxCacheTimeStamp;
  111. m_cachedTextExcludedBBox = aFootprint.m_cachedTextExcludedBBox;
  112. m_textExcludedBBoxCacheTimeStamp = aFootprint.m_textExcludedBBoxCacheTimeStamp;
  113. m_cachedHull = aFootprint.m_cachedHull;
  114. m_hullCacheTimeStamp = aFootprint.m_hullCacheTimeStamp;
  115. m_clearance = aFootprint.m_clearance;
  116. m_solderMaskMargin = aFootprint.m_solderMaskMargin;
  117. m_solderPasteMargin = aFootprint.m_solderPasteMargin;
  118. m_solderPasteMarginRatio = aFootprint.m_solderPasteMarginRatio;
  119. m_zoneConnection = aFootprint.m_zoneConnection;
  120. m_netTiePadGroups = aFootprint.m_netTiePadGroups;
  121. m_fileFormatVersionAtLoad = aFootprint.m_fileFormatVersionAtLoad;
  122. std::map<BOARD_ITEM*, BOARD_ITEM*> ptrMap;
  123. // Copy fields
  124. for( PCB_FIELD* field : aFootprint.m_fields )
  125. {
  126. if( field->IsMandatory() )
  127. {
  128. PCB_FIELD* existingField = GetField( field->GetId() );
  129. ptrMap[field] = existingField;
  130. *existingField = *field;
  131. existingField->SetParent( this );
  132. }
  133. else
  134. {
  135. PCB_FIELD* newField = static_cast<PCB_FIELD*>( field->Clone() );
  136. ptrMap[field] = newField;
  137. Add( newField );
  138. }
  139. }
  140. // Copy pads
  141. for( PAD* pad : aFootprint.Pads() )
  142. {
  143. PAD* newPad = static_cast<PAD*>( pad->Clone() );
  144. ptrMap[ pad ] = newPad;
  145. Add( newPad, ADD_MODE::APPEND ); // Append to ensure indexes are identical
  146. }
  147. // Copy zones
  148. for( ZONE* zone : aFootprint.Zones() )
  149. {
  150. ZONE* newZone = static_cast<ZONE*>( zone->Clone() );
  151. ptrMap[ zone ] = newZone;
  152. Add( newZone, ADD_MODE::APPEND ); // Append to ensure indexes are identical
  153. // Ensure the net info is OK and especially uses the net info list
  154. // living in the current board
  155. // Needed when copying a fp from fp editor that has its own board
  156. // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
  157. newZone->SetNetCode( -1 );
  158. }
  159. // Copy drawings
  160. for( BOARD_ITEM* item : aFootprint.GraphicalItems() )
  161. {
  162. BOARD_ITEM* newItem = static_cast<BOARD_ITEM*>( item->Clone() );
  163. ptrMap[ item ] = newItem;
  164. Add( newItem, ADD_MODE::APPEND ); // Append to ensure indexes are identical
  165. }
  166. // Copy groups
  167. for( PCB_GROUP* group : aFootprint.Groups() )
  168. {
  169. PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( group->Clone() );
  170. ptrMap[ group ] = newGroup;
  171. Add( newGroup, ADD_MODE::APPEND ); // Append to ensure indexes are identical
  172. }
  173. // Rebuild groups
  174. for( PCB_GROUP* group : aFootprint.Groups() )
  175. {
  176. PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( ptrMap[ group ] );
  177. newGroup->GetItems().clear();
  178. for( BOARD_ITEM* member : group->GetItems() )
  179. {
  180. if( ptrMap.count( member ) )
  181. newGroup->AddItem( ptrMap[ member ] );
  182. }
  183. }
  184. for( auto& [ name, file ] : aFootprint.EmbeddedFileMap() )
  185. AddFile( new EMBEDDED_FILES::EMBEDDED_FILE( *file ) );
  186. // Copy auxiliary data
  187. m_3D_Drawings = aFootprint.m_3D_Drawings;
  188. m_libDescription = aFootprint.m_libDescription;
  189. m_keywords = aFootprint.m_keywords;
  190. m_privateLayers = aFootprint.m_privateLayers;
  191. m_arflag = 0;
  192. m_initial_comments = aFootprint.m_initial_comments ?
  193. new wxArrayString( *aFootprint.m_initial_comments ) : nullptr;
  194. }
  195. FOOTPRINT::FOOTPRINT( FOOTPRINT&& aFootprint ) :
  196. BOARD_ITEM_CONTAINER( aFootprint )
  197. {
  198. *this = std::move( aFootprint );
  199. }
  200. FOOTPRINT::~FOOTPRINT()
  201. {
  202. // Untangle group parents before doing any deleting
  203. for( PCB_GROUP* group : m_groups )
  204. {
  205. for( BOARD_ITEM* item : group->GetItems() )
  206. item->SetParentGroup( nullptr );
  207. }
  208. // Clean up the owned elements
  209. delete m_initial_comments;
  210. for( PCB_FIELD* f : m_fields )
  211. delete f;
  212. m_fields.clear();
  213. for( PAD* p : m_pads )
  214. delete p;
  215. m_pads.clear();
  216. for( ZONE* zone : m_zones )
  217. delete zone;
  218. m_zones.clear();
  219. for( PCB_GROUP* group : m_groups )
  220. delete group;
  221. m_groups.clear();
  222. for( BOARD_ITEM* d : m_drawings )
  223. delete d;
  224. m_drawings.clear();
  225. if( BOARD* board = GetBoard() )
  226. board->IncrementTimeStamp();
  227. }
  228. void FOOTPRINT::Serialize( google::protobuf::Any &aContainer ) const
  229. {
  230. using namespace kiapi::board;
  231. types::FootprintInstance footprint;
  232. footprint.mutable_id()->set_value( m_Uuid.AsStdString() );
  233. footprint.mutable_position()->set_x_nm( GetPosition().x );
  234. footprint.mutable_position()->set_y_nm( GetPosition().y );
  235. footprint.mutable_orientation()->set_value_degrees( GetOrientationDegrees() );
  236. footprint.set_layer( ToProtoEnum<PCB_LAYER_ID, types::BoardLayer>( GetLayer() ) );
  237. footprint.set_locked( IsLocked() ? kiapi::common::types::LockedState::LS_LOCKED
  238. : kiapi::common::types::LockedState::LS_UNLOCKED );
  239. google::protobuf::Any buf;
  240. GetField( FIELD_T::REFERENCE )->Serialize( buf );
  241. buf.UnpackTo( footprint.mutable_reference_field() );
  242. GetField( FIELD_T::VALUE )->Serialize( buf );
  243. buf.UnpackTo( footprint.mutable_value_field() );
  244. GetField( FIELD_T::DATASHEET )->Serialize( buf );
  245. buf.UnpackTo( footprint.mutable_datasheet_field() );
  246. GetField( FIELD_T::DESCRIPTION )->Serialize( buf );
  247. buf.UnpackTo( footprint.mutable_description_field() );
  248. types::FootprintAttributes* attrs = footprint.mutable_attributes();
  249. attrs->set_not_in_schematic( IsBoardOnly() );
  250. attrs->set_exclude_from_position_files( IsExcludedFromPosFiles() );
  251. attrs->set_exclude_from_bill_of_materials( IsExcludedFromBOM() );
  252. attrs->set_exempt_from_courtyard_requirement( AllowMissingCourtyard() );
  253. attrs->set_do_not_populate( IsDNP() );
  254. if( m_attributes & FP_THROUGH_HOLE )
  255. attrs->set_mounting_style( types::FootprintMountingStyle::FMS_THROUGH_HOLE );
  256. else if( m_attributes & FP_SMD )
  257. attrs->set_mounting_style( types::FootprintMountingStyle::FMS_SMD );
  258. else
  259. attrs->set_mounting_style( types::FootprintMountingStyle::FMS_UNSPECIFIED );
  260. types::Footprint* def = footprint.mutable_definition();
  261. def->mutable_id()->CopyFrom( kiapi::common::LibIdToProto( GetFPID() ) );
  262. // anchor?
  263. def->mutable_attributes()->set_description( GetLibDescription().ToStdString() );
  264. def->mutable_attributes()->set_keywords( GetKeywords().ToStdString() );
  265. // TODO: serialize library mandatory fields
  266. types::FootprintDesignRuleOverrides* overrides = def->mutable_overrides();
  267. if( GetLocalClearance().has_value() )
  268. overrides->mutable_copper_clearance()->set_value_nm( *GetLocalClearance() );
  269. if( GetLocalSolderMaskMargin().has_value() )
  270. overrides->mutable_solder_mask()->mutable_solder_mask_margin()->set_value_nm( *GetLocalSolderMaskMargin() );
  271. if( GetLocalSolderPasteMargin().has_value() )
  272. overrides->mutable_solder_paste()->mutable_solder_paste_margin()->set_value_nm( *GetLocalSolderPasteMargin() );
  273. if( GetLocalSolderPasteMarginRatio().has_value() )
  274. overrides->mutable_solder_paste()->mutable_solder_paste_margin_ratio()->set_value( *GetLocalSolderPasteMarginRatio() );
  275. overrides->set_zone_connection(
  276. ToProtoEnum<ZONE_CONNECTION, types::ZoneConnectionStyle>( GetLocalZoneConnection() ) );
  277. for( const wxString& group : GetNetTiePadGroups() )
  278. {
  279. types::NetTieDefinition* netTie = def->add_net_ties();
  280. wxStringTokenizer tokenizer( group, " " );
  281. while( tokenizer.HasMoreTokens() )
  282. netTie->add_pad_number( tokenizer.GetNextToken().ToStdString() );
  283. }
  284. for( PCB_LAYER_ID layer : GetPrivateLayers().Seq() )
  285. def->add_private_layers( ToProtoEnum<PCB_LAYER_ID, types::BoardLayer>( layer ) );
  286. for( const PCB_FIELD* item : m_fields )
  287. {
  288. if( item->IsMandatory() )
  289. continue;
  290. google::protobuf::Any* itemMsg = def->add_items();
  291. item->Serialize( *itemMsg );
  292. }
  293. for( const PAD* item : Pads() )
  294. {
  295. google::protobuf::Any* itemMsg = def->add_items();
  296. item->Serialize( *itemMsg );
  297. }
  298. for( const BOARD_ITEM* item : GraphicalItems() )
  299. {
  300. google::protobuf::Any* itemMsg = def->add_items();
  301. item->Serialize( *itemMsg );
  302. }
  303. for( const ZONE* item : Zones() )
  304. {
  305. google::protobuf::Any* itemMsg = def->add_items();
  306. item->Serialize( *itemMsg );
  307. }
  308. for( const FP_3DMODEL& model : Models() )
  309. {
  310. google::protobuf::Any* itemMsg = def->add_items();
  311. types::Footprint3DModel modelMsg;
  312. modelMsg.set_filename( model.m_Filename.ToUTF8() );
  313. kiapi::common::PackVector3D( *modelMsg.mutable_scale(), model.m_Scale );
  314. kiapi::common::PackVector3D( *modelMsg.mutable_rotation(), model.m_Rotation );
  315. kiapi::common::PackVector3D( *modelMsg.mutable_offset(), model.m_Offset );
  316. modelMsg.set_visible( model.m_Show );
  317. modelMsg.set_opacity( model.m_Opacity );
  318. itemMsg->PackFrom( modelMsg );
  319. }
  320. aContainer.PackFrom( footprint );
  321. }
  322. bool FOOTPRINT::Deserialize( const google::protobuf::Any &aContainer )
  323. {
  324. using namespace kiapi::board;
  325. types::FootprintInstance footprint;
  326. if( !aContainer.UnpackTo( &footprint ) )
  327. return false;
  328. const_cast<KIID&>( m_Uuid ) = KIID( footprint.id().value() );
  329. SetPosition( VECTOR2I( footprint.position().x_nm(), footprint.position().y_nm() ) );
  330. SetOrientationDegrees( footprint.orientation().value_degrees() );
  331. SetLayer( FromProtoEnum<PCB_LAYER_ID, types::BoardLayer>( footprint.layer() ) );
  332. SetLocked( footprint.locked() == kiapi::common::types::LockedState::LS_LOCKED );
  333. google::protobuf::Any buf;
  334. types::Field mandatoryField;
  335. if( footprint.has_reference_field() )
  336. {
  337. mandatoryField = footprint.reference_field();
  338. mandatoryField.mutable_id()->set_id( (int) FIELD_T::REFERENCE );
  339. buf.PackFrom( mandatoryField );
  340. GetField( FIELD_T::REFERENCE )->Deserialize( buf );
  341. }
  342. if( footprint.has_value_field() )
  343. {
  344. mandatoryField = footprint.value_field();
  345. mandatoryField.mutable_id()->set_id( (int) FIELD_T::VALUE );
  346. buf.PackFrom( mandatoryField );
  347. GetField( FIELD_T::VALUE )->Deserialize( buf );
  348. }
  349. if( footprint.has_datasheet_field() )
  350. {
  351. mandatoryField = footprint.datasheet_field();
  352. mandatoryField.mutable_id()->set_id( (int) FIELD_T::DATASHEET );
  353. buf.PackFrom( mandatoryField );
  354. GetField( FIELD_T::DATASHEET )->Deserialize( buf );
  355. }
  356. if( footprint.has_description_field() )
  357. {
  358. mandatoryField = footprint.description_field();
  359. mandatoryField.mutable_id()->set_id( (int) FIELD_T::DESCRIPTION );
  360. buf.PackFrom( mandatoryField );
  361. GetField( FIELD_T::DESCRIPTION )->Deserialize( buf );
  362. }
  363. m_attributes = 0;
  364. switch( footprint.attributes().mounting_style() )
  365. {
  366. case types::FootprintMountingStyle::FMS_THROUGH_HOLE:
  367. m_attributes |= FP_THROUGH_HOLE;
  368. break;
  369. case types::FootprintMountingStyle::FMS_SMD:
  370. m_attributes |= FP_SMD;
  371. break;
  372. default:
  373. break;
  374. }
  375. SetBoardOnly( footprint.attributes().not_in_schematic() );
  376. SetExcludedFromBOM( footprint.attributes().exclude_from_bill_of_materials() );
  377. SetExcludedFromPosFiles( footprint.attributes().exclude_from_position_files() );
  378. SetAllowMissingCourtyard( footprint.attributes().exempt_from_courtyard_requirement() );
  379. SetDNP( footprint.attributes().do_not_populate() );
  380. // Definition
  381. SetFPID( kiapi::common::LibIdFromProto( footprint.definition().id() ) );
  382. // TODO: how should anchor be handled?
  383. SetLibDescription( footprint.definition().attributes().description() );
  384. SetKeywords( footprint.definition().attributes().keywords() );
  385. const types::FootprintDesignRuleOverrides& overrides = footprint.overrides();
  386. if( overrides.has_copper_clearance() )
  387. SetLocalClearance( overrides.copper_clearance().value_nm() );
  388. else
  389. SetLocalClearance( std::nullopt );
  390. if( overrides.has_solder_mask() && overrides.solder_mask().has_solder_mask_margin() )
  391. SetLocalSolderMaskMargin( overrides.solder_mask().solder_mask_margin().value_nm() );
  392. else
  393. SetLocalSolderMaskMargin( std::nullopt );
  394. if( overrides.has_solder_paste() )
  395. {
  396. const types::SolderPasteOverrides& pasteSettings = overrides.solder_paste();
  397. if( pasteSettings.has_solder_paste_margin() )
  398. SetLocalSolderPasteMargin( pasteSettings.solder_paste_margin().value_nm() );
  399. else
  400. SetLocalSolderPasteMargin( std::nullopt );
  401. if( pasteSettings.has_solder_paste_margin_ratio() )
  402. SetLocalSolderPasteMarginRatio( pasteSettings.solder_paste_margin_ratio().value() );
  403. else
  404. SetLocalSolderPasteMarginRatio( std::nullopt );
  405. }
  406. SetLocalZoneConnection( FromProtoEnum<ZONE_CONNECTION>( overrides.zone_connection() ) );
  407. for( const types::NetTieDefinition& netTieMsg : footprint.definition().net_ties() )
  408. {
  409. wxString group;
  410. for( const std::string& pad : netTieMsg.pad_number() )
  411. group.Append( wxString::Format( wxT( "%s " ), pad ) );
  412. group.Trim();
  413. AddNetTiePadGroup( group );
  414. }
  415. LSET privateLayers;
  416. for( int layerMsg : footprint.definition().private_layers() )
  417. {
  418. auto layer = static_cast<types::BoardLayer>( layerMsg );
  419. privateLayers.set( FromProtoEnum<PCB_LAYER_ID, types::BoardLayer>( layer ) );
  420. }
  421. SetPrivateLayers( privateLayers );
  422. // Footprint items
  423. for( PCB_FIELD* field : m_fields )
  424. {
  425. if( !field->IsMandatory() )
  426. Remove( field );
  427. }
  428. Pads().clear();
  429. GraphicalItems().clear();
  430. Zones().clear();
  431. Groups().clear();
  432. Models().clear();
  433. for( const google::protobuf::Any& itemMsg : footprint.definition().items() )
  434. {
  435. std::optional<KICAD_T> type = kiapi::common::TypeNameFromAny( itemMsg );
  436. if( !type )
  437. {
  438. // Bit of a hack here, but eventually 3D models should be promoted to a first-class
  439. // object, at which point they can get their own serialization
  440. if( itemMsg.type_url() == "type.googleapis.com/kiapi.board.types.Footprint3DModel" )
  441. {
  442. types::Footprint3DModel modelMsg;
  443. if( !itemMsg.UnpackTo( &modelMsg ) )
  444. continue;
  445. FP_3DMODEL model;
  446. model.m_Filename = wxString::FromUTF8( modelMsg.filename() );
  447. model.m_Show = modelMsg.visible();
  448. model.m_Opacity = modelMsg.opacity();
  449. model.m_Scale = kiapi::common::UnpackVector3D( modelMsg.scale() );
  450. model.m_Rotation = kiapi::common::UnpackVector3D( modelMsg.rotation() );
  451. model.m_Offset = kiapi::common::UnpackVector3D( modelMsg.offset() );
  452. Models().push_back( model );
  453. }
  454. else
  455. {
  456. wxLogTrace( traceApi, wxString::Format( wxS( "Attempting to unpack unknown type %s "
  457. "from footprint message, skipping" ),
  458. itemMsg.type_url() ) );
  459. }
  460. continue;
  461. }
  462. std::unique_ptr<BOARD_ITEM> item = CreateItemForType( *type, this );
  463. if( item && item->Deserialize( itemMsg ) )
  464. Add( item.release(), ADD_MODE::APPEND );
  465. }
  466. return true;
  467. }
  468. PCB_FIELD* FOOTPRINT::GetField( FIELD_T aFieldType )
  469. {
  470. for( PCB_FIELD* field : m_fields )
  471. {
  472. if( field->GetId() == aFieldType )
  473. return field;
  474. }
  475. PCB_FIELD* field = new PCB_FIELD( this, aFieldType );
  476. m_fields.push_back( field );
  477. return field;
  478. }
  479. const PCB_FIELD* FOOTPRINT::GetField( FIELD_T aFieldType ) const
  480. {
  481. for( const PCB_FIELD* field : m_fields )
  482. {
  483. if( field->GetId() == aFieldType )
  484. return field;
  485. }
  486. return nullptr;
  487. }
  488. bool FOOTPRINT::HasField( const wxString& aFieldName ) const
  489. {
  490. return GetField( aFieldName ) != nullptr;
  491. }
  492. PCB_FIELD* FOOTPRINT::GetField( const wxString& aFieldName ) const
  493. {
  494. for( PCB_FIELD* field : m_fields )
  495. {
  496. if( field->GetName() == aFieldName )
  497. return field;
  498. }
  499. return nullptr;
  500. }
  501. void FOOTPRINT::GetFields( std::vector<PCB_FIELD*>& aVector, bool aVisibleOnly ) const
  502. {
  503. aVector.clear();
  504. for( PCB_FIELD* field : m_fields )
  505. {
  506. if( aVisibleOnly )
  507. {
  508. if( !field->IsVisible() || field->GetText().IsEmpty() )
  509. continue;
  510. }
  511. aVector.push_back( field );
  512. }
  513. std::sort( aVector.begin(), aVector.end(),
  514. []( PCB_FIELD* lhs, PCB_FIELD* rhs )
  515. {
  516. return lhs->GetOrdinal() < rhs->GetOrdinal();
  517. } );
  518. }
  519. int FOOTPRINT::GetNextFieldOrdinal() const
  520. {
  521. int ordinal = 42; // Arbitrarily larger than any mandatory FIELD_T id
  522. for( const PCB_FIELD* field : m_fields )
  523. ordinal = std::max( ordinal, field->GetOrdinal() + 1 );
  524. return ordinal;
  525. }
  526. void FOOTPRINT::ApplyDefaultSettings( const BOARD& board, bool aStyleFields, bool aStyleText,
  527. bool aStyleShapes )
  528. {
  529. if( aStyleFields )
  530. {
  531. for( PCB_FIELD* field : m_fields )
  532. field->StyleFromSettings( board.GetDesignSettings() );
  533. }
  534. for( BOARD_ITEM* item : m_drawings )
  535. {
  536. switch( item->Type() )
  537. {
  538. case PCB_TEXT_T:
  539. case PCB_TEXTBOX_T:
  540. if( aStyleText )
  541. item->StyleFromSettings( board.GetDesignSettings() );
  542. break;
  543. case PCB_SHAPE_T:
  544. if( aStyleShapes && !item->IsOnCopperLayer() )
  545. item->StyleFromSettings( board.GetDesignSettings() );
  546. break;
  547. default:
  548. break;
  549. }
  550. }
  551. }
  552. bool FOOTPRINT::FixUuids()
  553. {
  554. // replace null UUIDs if any by a valid uuid
  555. std::vector< BOARD_ITEM* > item_list;
  556. for( PCB_FIELD* field : m_fields )
  557. item_list.push_back( field );
  558. for( PAD* pad : m_pads )
  559. item_list.push_back( pad );
  560. for( BOARD_ITEM* gr_item : m_drawings )
  561. item_list.push_back( gr_item );
  562. // Note: one cannot fix null UUIDs inside the group, but it should not happen
  563. // because null uuids can be found in old footprints, therefore without group
  564. for( PCB_GROUP* group : m_groups )
  565. item_list.push_back( group );
  566. // Probably notneeded, because old fp do not have zones. But just in case.
  567. for( ZONE* zone : m_zones )
  568. item_list.push_back( zone );
  569. bool changed = false;
  570. for( BOARD_ITEM* item : item_list )
  571. {
  572. if( item->m_Uuid == niluuid )
  573. {
  574. const_cast<KIID&>( item->m_Uuid ) = KIID();
  575. changed = true;
  576. }
  577. }
  578. return changed;
  579. }
  580. FOOTPRINT& FOOTPRINT::operator=( FOOTPRINT&& aOther )
  581. {
  582. BOARD_ITEM::operator=( aOther );
  583. m_pos = aOther.m_pos;
  584. m_fpid = aOther.m_fpid;
  585. m_attributes = aOther.m_attributes;
  586. m_fpStatus = aOther.m_fpStatus;
  587. m_orient = aOther.m_orient;
  588. m_lastEditTime = aOther.m_lastEditTime;
  589. m_link = aOther.m_link;
  590. m_path = aOther.m_path;
  591. m_cachedBoundingBox = aOther.m_cachedBoundingBox;
  592. m_boundingBoxCacheTimeStamp = aOther.m_boundingBoxCacheTimeStamp;
  593. m_cachedTextExcludedBBox = aOther.m_cachedTextExcludedBBox;
  594. m_textExcludedBBoxCacheTimeStamp = aOther.m_textExcludedBBoxCacheTimeStamp;
  595. m_cachedHull = aOther.m_cachedHull;
  596. m_hullCacheTimeStamp = aOther.m_hullCacheTimeStamp;
  597. m_clearance = aOther.m_clearance;
  598. m_solderMaskMargin = aOther.m_solderMaskMargin;
  599. m_solderPasteMargin = aOther.m_solderPasteMargin;
  600. m_solderPasteMarginRatio = aOther.m_solderPasteMarginRatio;
  601. m_zoneConnection = aOther.m_zoneConnection;
  602. m_netTiePadGroups = aOther.m_netTiePadGroups;
  603. // Move the fields
  604. for( PCB_FIELD* field : m_fields )
  605. delete field;
  606. m_fields.clear();
  607. for( PCB_FIELD* field : aOther.m_fields )
  608. Add( field );
  609. aOther.m_fields.clear();
  610. // Move the pads
  611. for( PAD* pad : m_pads )
  612. delete pad;
  613. m_pads.clear();
  614. for( PAD* pad : aOther.Pads() )
  615. Add( pad );
  616. aOther.Pads().clear();
  617. // Move the zones
  618. for( ZONE* zone : m_zones )
  619. delete zone;
  620. m_zones.clear();
  621. for( ZONE* item : aOther.Zones() )
  622. {
  623. Add( item );
  624. // Ensure the net info is OK and especially uses the net info list
  625. // living in the current board
  626. // Needed when copying a fp from fp editor that has its own board
  627. // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
  628. item->SetNetCode( -1 );
  629. }
  630. aOther.Zones().clear();
  631. // Move the drawings
  632. for( BOARD_ITEM* item : m_drawings )
  633. delete item;
  634. m_drawings.clear();
  635. for( BOARD_ITEM* item : aOther.GraphicalItems() )
  636. Add( item );
  637. aOther.GraphicalItems().clear();
  638. // Move the groups
  639. for( PCB_GROUP* group : m_groups )
  640. delete group;
  641. m_groups.clear();
  642. for( PCB_GROUP* group : aOther.Groups() )
  643. Add( group );
  644. aOther.Groups().clear();
  645. EMBEDDED_FILES::operator=( std::move( aOther ) );
  646. // Copy auxiliary data
  647. m_3D_Drawings = aOther.m_3D_Drawings;
  648. m_libDescription = aOther.m_libDescription;
  649. m_keywords = aOther.m_keywords;
  650. m_privateLayers = aOther.m_privateLayers;
  651. m_initial_comments = aOther.m_initial_comments;
  652. // Clear the other item's containers since this is a move
  653. aOther.m_fields.clear();
  654. aOther.Pads().clear();
  655. aOther.Zones().clear();
  656. aOther.GraphicalItems().clear();
  657. aOther.m_initial_comments = nullptr;
  658. return *this;
  659. }
  660. FOOTPRINT& FOOTPRINT::operator=( const FOOTPRINT& aOther )
  661. {
  662. BOARD_ITEM::operator=( aOther );
  663. m_pos = aOther.m_pos;
  664. m_fpid = aOther.m_fpid;
  665. m_attributes = aOther.m_attributes;
  666. m_fpStatus = aOther.m_fpStatus;
  667. m_orient = aOther.m_orient;
  668. m_lastEditTime = aOther.m_lastEditTime;
  669. m_link = aOther.m_link;
  670. m_path = aOther.m_path;
  671. m_cachedBoundingBox = aOther.m_cachedBoundingBox;
  672. m_boundingBoxCacheTimeStamp = aOther.m_boundingBoxCacheTimeStamp;
  673. m_cachedTextExcludedBBox = aOther.m_cachedTextExcludedBBox;
  674. m_textExcludedBBoxCacheTimeStamp = aOther.m_textExcludedBBoxCacheTimeStamp;
  675. m_cachedHull = aOther.m_cachedHull;
  676. m_hullCacheTimeStamp = aOther.m_hullCacheTimeStamp;
  677. m_clearance = aOther.m_clearance;
  678. m_solderMaskMargin = aOther.m_solderMaskMargin;
  679. m_solderPasteMargin = aOther.m_solderPasteMargin;
  680. m_solderPasteMarginRatio = aOther.m_solderPasteMarginRatio;
  681. m_zoneConnection = aOther.m_zoneConnection;
  682. m_netTiePadGroups = aOther.m_netTiePadGroups;
  683. std::map<BOARD_ITEM*, BOARD_ITEM*> ptrMap;
  684. // Copy fields
  685. m_fields.clear();
  686. for( PCB_FIELD* field : aOther.m_fields )
  687. {
  688. PCB_FIELD* newField = new PCB_FIELD( *field );
  689. ptrMap[field] = newField;
  690. Add( newField );
  691. }
  692. // Copy pads
  693. m_pads.clear();
  694. for( PAD* pad : aOther.Pads() )
  695. {
  696. PAD* newPad = new PAD( *pad );
  697. ptrMap[ pad ] = newPad;
  698. Add( newPad );
  699. }
  700. // Copy zones
  701. m_zones.clear();
  702. for( ZONE* zone : aOther.Zones() )
  703. {
  704. ZONE* newZone = static_cast<ZONE*>( zone->Clone() );
  705. ptrMap[ zone ] = newZone;
  706. Add( newZone );
  707. // Ensure the net info is OK and especially uses the net info list
  708. // living in the current board
  709. // Needed when copying a fp from fp editor that has its own board
  710. // Must be NETINFO_LIST::ORPHANED_ITEM for a keepout that has no net.
  711. newZone->SetNetCode( -1 );
  712. }
  713. // Copy drawings
  714. m_drawings.clear();
  715. for( BOARD_ITEM* item : aOther.GraphicalItems() )
  716. {
  717. BOARD_ITEM* newItem = static_cast<BOARD_ITEM*>( item->Clone() );
  718. ptrMap[ item ] = newItem;
  719. Add( newItem );
  720. }
  721. // Copy groups
  722. m_groups.clear();
  723. for( PCB_GROUP* group : aOther.Groups() )
  724. {
  725. PCB_GROUP* newGroup = static_cast<PCB_GROUP*>( group->Clone() );
  726. newGroup->GetItems().clear();
  727. for( BOARD_ITEM* member : group->GetItems() )
  728. newGroup->AddItem( ptrMap[ member ] );
  729. Add( newGroup );
  730. }
  731. // Copy auxiliary data
  732. m_3D_Drawings = aOther.m_3D_Drawings;
  733. m_libDescription = aOther.m_libDescription;
  734. m_keywords = aOther.m_keywords;
  735. m_privateLayers = aOther.m_privateLayers;
  736. m_initial_comments = aOther.m_initial_comments ?
  737. new wxArrayString( *aOther.m_initial_comments ) : nullptr;
  738. EMBEDDED_FILES::operator=( aOther );
  739. return *this;
  740. }
  741. bool FOOTPRINT::IsConflicting() const
  742. {
  743. return HasFlag( COURTYARD_CONFLICT );
  744. }
  745. void FOOTPRINT::GetContextualTextVars( wxArrayString* aVars ) const
  746. {
  747. aVars->push_back( wxT( "REFERENCE" ) );
  748. aVars->push_back( wxT( "VALUE" ) );
  749. aVars->push_back( wxT( "LAYER" ) );
  750. aVars->push_back( wxT( "FOOTPRINT_LIBRARY" ) );
  751. aVars->push_back( wxT( "FOOTPRINT_NAME" ) );
  752. aVars->push_back( wxT( "SHORT_NET_NAME(<pad_number>)" ) );
  753. aVars->push_back( wxT( "NET_NAME(<pad_number>)" ) );
  754. aVars->push_back( wxT( "NET_CLASS(<pad_number>)" ) );
  755. aVars->push_back( wxT( "PIN_NAME(<pad_number>)" ) );
  756. }
  757. bool FOOTPRINT::ResolveTextVar( wxString* token, int aDepth ) const
  758. {
  759. if( GetBoard() && GetBoard()->GetBoardUse() == BOARD_USE::FPHOLDER )
  760. return false;
  761. if( token->IsSameAs( wxT( "REFERENCE" ) ) )
  762. {
  763. *token = Reference().GetShownText( false, aDepth + 1 );
  764. return true;
  765. }
  766. else if( token->IsSameAs( wxT( "VALUE" ) ) )
  767. {
  768. *token = Value().GetShownText( false, aDepth + 1 );
  769. return true;
  770. }
  771. else if( token->IsSameAs( wxT( "LAYER" ) ) )
  772. {
  773. *token = GetLayerName();
  774. return true;
  775. }
  776. else if( token->IsSameAs( wxT( "FOOTPRINT_LIBRARY" ) ) )
  777. {
  778. *token = m_fpid.GetUniStringLibNickname();
  779. return true;
  780. }
  781. else if( token->IsSameAs( wxT( "FOOTPRINT_NAME" ) ) )
  782. {
  783. *token = m_fpid.GetUniStringLibItemName();
  784. return true;
  785. }
  786. else if( token->StartsWith( wxT( "SHORT_NET_NAME(" ) )
  787. || token->StartsWith( wxT( "NET_NAME(" ) )
  788. || token->StartsWith( wxT( "NET_CLASS(" ) )
  789. || token->StartsWith( wxT( "PIN_NAME(" ) ) )
  790. {
  791. wxString padNumber = token->AfterFirst( '(' );
  792. padNumber = padNumber.BeforeLast( ')' );
  793. for( PAD* pad : Pads() )
  794. {
  795. if( pad->GetNumber() == padNumber )
  796. {
  797. if( token->StartsWith( wxT( "SHORT_NET_NAME" ) ) )
  798. *token = pad->GetShortNetname();
  799. else if( token->StartsWith( wxT( "NET_NAME" ) ) )
  800. *token = pad->GetNetname();
  801. else if( token->StartsWith( wxT( "NET_CLASS" ) ) )
  802. *token = pad->GetNetClassName();
  803. else
  804. *token = pad->GetPinFunction();
  805. return true;
  806. }
  807. }
  808. }
  809. else if( PCB_FIELD* field = GetField( *token ) )
  810. {
  811. *token = field->GetText();
  812. return true;
  813. }
  814. if( GetBoard() && GetBoard()->ResolveTextVar( token, aDepth + 1 ) )
  815. return true;
  816. return false;
  817. }
  818. void FOOTPRINT::ClearAllNets()
  819. {
  820. // Force the ORPHANED dummy net info for all pads.
  821. // ORPHANED dummy net does not depend on a board
  822. for( PAD* pad : m_pads )
  823. pad->SetNetCode( NETINFO_LIST::ORPHANED );
  824. }
  825. void FOOTPRINT::Add( BOARD_ITEM* aBoardItem, ADD_MODE aMode, bool aSkipConnectivity )
  826. {
  827. switch( aBoardItem->Type() )
  828. {
  829. case PCB_FIELD_T:
  830. m_fields.push_back( static_cast<PCB_FIELD*>( aBoardItem ) );
  831. break;
  832. case PCB_TEXT_T:
  833. case PCB_DIM_ALIGNED_T:
  834. case PCB_DIM_LEADER_T:
  835. case PCB_DIM_CENTER_T:
  836. case PCB_DIM_RADIAL_T:
  837. case PCB_DIM_ORTHOGONAL_T:
  838. case PCB_SHAPE_T:
  839. case PCB_TEXTBOX_T:
  840. case PCB_TABLE_T:
  841. case PCB_REFERENCE_IMAGE_T:
  842. if( aMode == ADD_MODE::APPEND )
  843. m_drawings.push_back( aBoardItem );
  844. else
  845. m_drawings.push_front( aBoardItem );
  846. break;
  847. case PCB_PAD_T:
  848. if( aMode == ADD_MODE::APPEND )
  849. m_pads.push_back( static_cast<PAD*>( aBoardItem ) );
  850. else
  851. m_pads.push_front( static_cast<PAD*>( aBoardItem ) );
  852. break;
  853. case PCB_ZONE_T:
  854. if( aMode == ADD_MODE::APPEND )
  855. m_zones.push_back( static_cast<ZONE*>( aBoardItem ) );
  856. else
  857. m_zones.insert( m_zones.begin(), static_cast<ZONE*>( aBoardItem ) );
  858. break;
  859. case PCB_GROUP_T:
  860. if( aMode == ADD_MODE::APPEND )
  861. m_groups.push_back( static_cast<PCB_GROUP*>( aBoardItem ) );
  862. else
  863. m_groups.insert( m_groups.begin(), static_cast<PCB_GROUP*>( aBoardItem ) );
  864. break;
  865. default:
  866. wxFAIL_MSG( wxString::Format( wxT( "FOOTPRINT::Add(): BOARD_ITEM type (%d) not handled" ),
  867. aBoardItem->Type() ) );
  868. return;
  869. }
  870. aBoardItem->ClearEditFlags();
  871. aBoardItem->SetParent( this );
  872. }
  873. void FOOTPRINT::Remove( BOARD_ITEM* aBoardItem, REMOVE_MODE aMode )
  874. {
  875. switch( aBoardItem->Type() )
  876. {
  877. case PCB_FIELD_T:
  878. for( auto it = m_fields.begin(); it != m_fields.end(); ++it )
  879. {
  880. if( *it == aBoardItem )
  881. {
  882. m_fields.erase( it );
  883. break;
  884. }
  885. }
  886. break;
  887. case PCB_TEXT_T:
  888. case PCB_DIM_ALIGNED_T:
  889. case PCB_DIM_CENTER_T:
  890. case PCB_DIM_ORTHOGONAL_T:
  891. case PCB_DIM_RADIAL_T:
  892. case PCB_DIM_LEADER_T:
  893. case PCB_SHAPE_T:
  894. case PCB_TEXTBOX_T:
  895. case PCB_TABLE_T:
  896. case PCB_REFERENCE_IMAGE_T:
  897. for( auto it = m_drawings.begin(); it != m_drawings.end(); ++it )
  898. {
  899. if( *it == aBoardItem )
  900. {
  901. m_drawings.erase( it );
  902. break;
  903. }
  904. }
  905. break;
  906. case PCB_PAD_T:
  907. for( auto it = m_pads.begin(); it != m_pads.end(); ++it )
  908. {
  909. if( *it == static_cast<PAD*>( aBoardItem ) )
  910. {
  911. m_pads.erase( it );
  912. break;
  913. }
  914. }
  915. break;
  916. case PCB_ZONE_T:
  917. for( auto it = m_zones.begin(); it != m_zones.end(); ++it )
  918. {
  919. if( *it == static_cast<ZONE*>( aBoardItem ) )
  920. {
  921. m_zones.erase( it );
  922. break;
  923. }
  924. }
  925. break;
  926. case PCB_GROUP_T:
  927. for( auto it = m_groups.begin(); it != m_groups.end(); ++it )
  928. {
  929. if( *it == static_cast<PCB_GROUP*>( aBoardItem ) )
  930. {
  931. m_groups.erase( it );
  932. break;
  933. }
  934. }
  935. break;
  936. default:
  937. {
  938. wxString msg;
  939. msg.Printf( wxT( "FOOTPRINT::Remove() needs work: BOARD_ITEM type (%d) not handled" ),
  940. aBoardItem->Type() );
  941. wxFAIL_MSG( msg );
  942. }
  943. }
  944. aBoardItem->SetFlags( STRUCT_DELETED );
  945. PCB_GROUP* parentGroup = aBoardItem->GetParentGroup();
  946. if( parentGroup && !( parentGroup->GetFlags() & STRUCT_DELETED ) )
  947. parentGroup->RemoveItem( aBoardItem );
  948. }
  949. double FOOTPRINT::GetArea( int aPadding ) const
  950. {
  951. BOX2I bbox = GetBoundingBox( false );
  952. double w = std::abs( static_cast<double>( bbox.GetWidth() ) ) + aPadding;
  953. double h = std::abs( static_cast<double>( bbox.GetHeight() ) ) + aPadding;
  954. return w * h;
  955. }
  956. int FOOTPRINT::GetLikelyAttribute() const
  957. {
  958. int smd_count = 0;
  959. int tht_count = 0;
  960. for( PAD* pad : m_pads )
  961. {
  962. switch( pad->GetProperty() )
  963. {
  964. case PAD_PROP::FIDUCIAL_GLBL:
  965. case PAD_PROP::FIDUCIAL_LOCAL:
  966. continue;
  967. case PAD_PROP::HEATSINK:
  968. case PAD_PROP::CASTELLATED:
  969. case PAD_PROP::MECHANICAL:
  970. continue;
  971. case PAD_PROP::NONE:
  972. case PAD_PROP::BGA:
  973. case PAD_PROP::TESTPOINT:
  974. break;
  975. }
  976. switch( pad->GetAttribute() )
  977. {
  978. case PAD_ATTRIB::PTH:
  979. tht_count++;
  980. break;
  981. case PAD_ATTRIB::SMD:
  982. if( pad->IsOnCopperLayer() )
  983. smd_count++;
  984. break;
  985. default:
  986. break;
  987. }
  988. }
  989. // Footprints with plated through-hole pads should usually be marked through hole even if they
  990. // also have SMD because they might not be auto-placed. Exceptions to this might be shielded
  991. if( tht_count > 0 )
  992. return FP_THROUGH_HOLE;
  993. if( smd_count > 0 )
  994. return FP_SMD;
  995. return 0;
  996. }
  997. wxString FOOTPRINT::GetTypeName() const
  998. {
  999. if( ( m_attributes & FP_SMD ) == FP_SMD )
  1000. return _( "SMD" );
  1001. if( ( m_attributes & FP_THROUGH_HOLE ) == FP_THROUGH_HOLE )
  1002. return _( "Through hole" );
  1003. return _( "Other" );
  1004. }
  1005. BOX2I FOOTPRINT::GetFpPadsLocalBbox() const
  1006. {
  1007. BOX2I bbox;
  1008. // We want the bounding box of the footprint pads at rot 0, not flipped
  1009. // Create such a image:
  1010. FOOTPRINT dummy( *this );
  1011. dummy.SetPosition( VECTOR2I( 0, 0 ) );
  1012. dummy.SetOrientation( ANGLE_0 );
  1013. if( dummy.IsFlipped() )
  1014. dummy.Flip( VECTOR2I( 0, 0 ), FLIP_DIRECTION::TOP_BOTTOM );
  1015. for( PAD* pad : dummy.Pads() )
  1016. bbox.Merge( pad->GetBoundingBox() );
  1017. // Remove the parent and the group from the dummy footprint before deletion
  1018. dummy.SetParent( nullptr );
  1019. dummy.SetParentGroup( nullptr );
  1020. return bbox;
  1021. }
  1022. bool FOOTPRINT::TextOnly() const
  1023. {
  1024. for( BOARD_ITEM* item : m_drawings )
  1025. {
  1026. if( m_privateLayers.test( item->GetLayer() ) )
  1027. continue;
  1028. if( item->Type() != PCB_FIELD_T && item->Type() != PCB_TEXT_T )
  1029. return false;
  1030. }
  1031. return true;
  1032. }
  1033. const BOX2I FOOTPRINT::GetBoundingBox() const
  1034. {
  1035. return GetBoundingBox( true );
  1036. }
  1037. const BOX2I FOOTPRINT::GetBoundingBox( bool aIncludeText ) const
  1038. {
  1039. const BOARD* board = GetBoard();
  1040. if( board )
  1041. {
  1042. if( aIncludeText )
  1043. {
  1044. if( m_boundingBoxCacheTimeStamp >= board->GetTimeStamp() )
  1045. return m_cachedBoundingBox;
  1046. }
  1047. else
  1048. {
  1049. if( m_textExcludedBBoxCacheTimeStamp >= board->GetTimeStamp() )
  1050. return m_cachedTextExcludedBBox;
  1051. }
  1052. }
  1053. std::vector<PCB_TEXT*> texts;
  1054. bool isFPEdit = board && board->IsFootprintHolder();
  1055. BOX2I bbox( m_pos );
  1056. bbox.Inflate( pcbIUScale.mmToIU( 0.25 ) ); // Give a min size to the bbox
  1057. // Calculate the footprint side
  1058. PCB_LAYER_ID footprintSide = GetSide();
  1059. for( BOARD_ITEM* item : m_drawings )
  1060. {
  1061. if( m_privateLayers.test( item->GetLayer() ) && !isFPEdit )
  1062. continue;
  1063. // We want the bitmap bounding box just in the footprint editor
  1064. // so it will start with the correct initial zoom
  1065. if( item->Type() == PCB_REFERENCE_IMAGE_T && !isFPEdit )
  1066. continue;
  1067. // Handle text separately
  1068. if( item->Type() == PCB_TEXT_T )
  1069. {
  1070. texts.push_back( static_cast<PCB_TEXT*>( item ) );
  1071. continue;
  1072. }
  1073. // If we're not including text then drop annotations as well -- unless, of course, it's
  1074. // an unsided footprint -- in which case it's likely to be nothing *but* annotations.
  1075. if( !aIncludeText && footprintSide != UNDEFINED_LAYER )
  1076. {
  1077. if( BaseType( item->Type() ) == PCB_DIMENSION_T )
  1078. continue;
  1079. if( item->GetLayer() == Cmts_User || item->GetLayer() == Dwgs_User
  1080. || item->GetLayer() == Eco1_User || item->GetLayer() == Eco2_User )
  1081. {
  1082. continue;
  1083. }
  1084. }
  1085. bbox.Merge( item->GetBoundingBox() );
  1086. }
  1087. for( PCB_FIELD* field : m_fields )
  1088. {
  1089. // Reference and value get their own processing
  1090. if( field->IsReference() || field->IsValue() )
  1091. continue;
  1092. texts.push_back( field );
  1093. }
  1094. for( PAD* pad : m_pads )
  1095. bbox.Merge( pad->GetBoundingBox() );
  1096. for( ZONE* zone : m_zones )
  1097. bbox.Merge( zone->GetBoundingBox() );
  1098. bool noDrawItems = ( m_drawings.empty() && m_pads.empty() && m_zones.empty() );
  1099. // Groups do not contribute to the rect, only their members
  1100. if( aIncludeText || noDrawItems )
  1101. {
  1102. // Only PCB_TEXT and PCB_FIELD items are independently selectable; PCB_TEXTBOX items go
  1103. // in with other graphic items above.
  1104. for( PCB_TEXT* text : texts )
  1105. {
  1106. if( !isFPEdit && m_privateLayers.test( text->GetLayer() ) )
  1107. continue;
  1108. if( text->Type() == PCB_FIELD_T && !text->IsVisible() )
  1109. continue;
  1110. bbox.Merge( text->GetBoundingBox() );
  1111. }
  1112. // This can be further optimized when aIncludeInvisibleText is true, but currently
  1113. // leaving this as is until it's determined there is a noticeable speed hit.
  1114. bool valueLayerIsVisible = true;
  1115. bool refLayerIsVisible = true;
  1116. if( board )
  1117. {
  1118. // The first "&&" conditional handles the user turning layers off as well as layers
  1119. // not being present in the current PCB stackup. Values, references, and all
  1120. // footprint text can also be turned off via the GAL meta-layers, so the 2nd and
  1121. // 3rd "&&" conditionals handle that.
  1122. valueLayerIsVisible = board->IsLayerVisible( Value().GetLayer() )
  1123. && board->IsElementVisible( LAYER_FP_VALUES )
  1124. && board->IsElementVisible( LAYER_FP_TEXT );
  1125. refLayerIsVisible = board->IsLayerVisible( Reference().GetLayer() )
  1126. && board->IsElementVisible( LAYER_FP_REFERENCES )
  1127. && board->IsElementVisible( LAYER_FP_TEXT );
  1128. }
  1129. if( ( Value().IsVisible() && valueLayerIsVisible ) || noDrawItems )
  1130. {
  1131. bbox.Merge( Value().GetBoundingBox() );
  1132. }
  1133. if( ( Reference().IsVisible() && refLayerIsVisible ) || noDrawItems )
  1134. {
  1135. bbox.Merge( Reference().GetBoundingBox() );
  1136. }
  1137. }
  1138. if( board )
  1139. {
  1140. if( aIncludeText || noDrawItems )
  1141. {
  1142. m_boundingBoxCacheTimeStamp = board->GetTimeStamp();
  1143. m_cachedBoundingBox = bbox;
  1144. }
  1145. else
  1146. {
  1147. m_textExcludedBBoxCacheTimeStamp = board->GetTimeStamp();
  1148. m_cachedTextExcludedBBox = bbox;
  1149. }
  1150. }
  1151. return bbox;
  1152. }
  1153. const BOX2I FOOTPRINT::GetLayerBoundingBox( LSET aLayers ) const
  1154. {
  1155. std::vector<PCB_TEXT*> texts;
  1156. const BOARD* board = GetBoard();
  1157. bool isFPEdit = board && board->IsFootprintHolder();
  1158. // Start with an uninitialized bounding box
  1159. BOX2I bbox;
  1160. for( BOARD_ITEM* item : m_drawings )
  1161. {
  1162. if( m_privateLayers.test( item->GetLayer() ) && !isFPEdit )
  1163. continue;
  1164. if( ( aLayers & item->GetLayerSet() ).none() )
  1165. continue;
  1166. // We want the bitmap bounding box just in the footprint editor
  1167. // so it will start with the correct initial zoom
  1168. if( item->Type() == PCB_REFERENCE_IMAGE_T && !isFPEdit )
  1169. continue;
  1170. bbox.Merge( item->GetBoundingBox() );
  1171. }
  1172. for( PAD* pad : m_pads )
  1173. {
  1174. if( ( aLayers & pad->GetLayerSet() ).none() )
  1175. continue;
  1176. bbox.Merge( pad->GetBoundingBox() );
  1177. }
  1178. for( ZONE* zone : m_zones )
  1179. {
  1180. if( ( aLayers & zone->GetLayerSet() ).none() )
  1181. continue;
  1182. bbox.Merge( zone->GetBoundingBox() );
  1183. }
  1184. return bbox;
  1185. }
  1186. SHAPE_POLY_SET FOOTPRINT::GetBoundingHull() const
  1187. {
  1188. const BOARD* board = GetBoard();
  1189. bool isFPEdit = board && board->IsFootprintHolder();
  1190. if( board )
  1191. {
  1192. if( m_hullCacheTimeStamp >= board->GetTimeStamp() )
  1193. return m_cachedHull;
  1194. }
  1195. SHAPE_POLY_SET rawPolys;
  1196. for( BOARD_ITEM* item : m_drawings )
  1197. {
  1198. if( !isFPEdit && m_privateLayers.test( item->GetLayer() ) )
  1199. continue;
  1200. if( item->Type() != PCB_FIELD_T && item->Type() != PCB_REFERENCE_IMAGE_T )
  1201. {
  1202. item->TransformShapeToPolygon( rawPolys, UNDEFINED_LAYER, 0, ARC_LOW_DEF,
  1203. ERROR_OUTSIDE );
  1204. }
  1205. // We intentionally exclude footprint fields from the bounding hull.
  1206. }
  1207. for( PAD* pad : m_pads )
  1208. {
  1209. pad->Padstack().ForEachUniqueLayer(
  1210. [&]( PCB_LAYER_ID aLayer )
  1211. {
  1212. pad->TransformShapeToPolygon( rawPolys, aLayer, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
  1213. } );
  1214. // In case hole is larger than pad
  1215. pad->TransformHoleToPolygon( rawPolys, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
  1216. }
  1217. for( ZONE* zone : m_zones )
  1218. {
  1219. for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
  1220. {
  1221. const SHAPE_POLY_SET& layerPoly = *zone->GetFilledPolysList( layer );
  1222. for( int ii = 0; ii < layerPoly.OutlineCount(); ii++ )
  1223. {
  1224. const SHAPE_LINE_CHAIN& poly = layerPoly.COutline( ii );
  1225. rawPolys.AddOutline( poly );
  1226. }
  1227. }
  1228. }
  1229. // If there are some graphic items, build the actual hull.
  1230. // However if no items, create a minimal polygon (can happen if a footprint
  1231. // is created with no item: it contains only 2 texts.
  1232. if( rawPolys.OutlineCount() == 0 || rawPolys.FullPointCount() < 3 )
  1233. {
  1234. // generate a small dummy rectangular outline around the anchor
  1235. const int halfsize = pcbIUScale.mmToIU( 1.0 );
  1236. rawPolys.NewOutline();
  1237. // add a square:
  1238. rawPolys.Append( GetPosition().x - halfsize, GetPosition().y - halfsize );
  1239. rawPolys.Append( GetPosition().x + halfsize, GetPosition().y - halfsize );
  1240. rawPolys.Append( GetPosition().x + halfsize, GetPosition().y + halfsize );
  1241. rawPolys.Append( GetPosition().x - halfsize, GetPosition().y + halfsize );
  1242. }
  1243. std::vector<VECTOR2I> convex_hull;
  1244. BuildConvexHull( convex_hull, rawPolys );
  1245. m_cachedHull.RemoveAllContours();
  1246. m_cachedHull.NewOutline();
  1247. for( const VECTOR2I& pt : convex_hull )
  1248. m_cachedHull.Append( pt );
  1249. if( board )
  1250. m_hullCacheTimeStamp = board->GetTimeStamp();
  1251. return m_cachedHull;
  1252. }
  1253. SHAPE_POLY_SET FOOTPRINT::GetBoundingHull( PCB_LAYER_ID aLayer ) const
  1254. {
  1255. const BOARD* board = GetBoard();
  1256. bool isFPEdit = board && board->IsFootprintHolder();
  1257. SHAPE_POLY_SET rawPolys;
  1258. SHAPE_POLY_SET hull;
  1259. for( BOARD_ITEM* item : m_drawings )
  1260. {
  1261. if( !isFPEdit && m_privateLayers.test( item->GetLayer() ) )
  1262. continue;
  1263. if( item->IsOnLayer( aLayer ) )
  1264. {
  1265. if( item->Type() != PCB_FIELD_T && item->Type() != PCB_REFERENCE_IMAGE_T )
  1266. {
  1267. item->TransformShapeToPolygon( rawPolys, UNDEFINED_LAYER, 0, ARC_LOW_DEF,
  1268. ERROR_OUTSIDE );
  1269. }
  1270. // We intentionally exclude footprint fields from the bounding hull.
  1271. }
  1272. }
  1273. for( PAD* pad : m_pads )
  1274. {
  1275. if( pad->IsOnLayer( aLayer ) )
  1276. pad->TransformShapeToPolygon( rawPolys, aLayer, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
  1277. }
  1278. for( ZONE* zone : m_zones )
  1279. {
  1280. if( zone->GetIsRuleArea() )
  1281. continue;
  1282. if( zone->IsOnLayer( aLayer ) )
  1283. {
  1284. const std::shared_ptr<SHAPE_POLY_SET>& layerPoly = zone->GetFilledPolysList( aLayer );
  1285. for( int ii = 0; ii < layerPoly->OutlineCount(); ii++ )
  1286. rawPolys.AddOutline( layerPoly->COutline( ii ) );
  1287. }
  1288. }
  1289. std::vector<VECTOR2I> convex_hull;
  1290. BuildConvexHull( convex_hull, rawPolys );
  1291. hull.NewOutline();
  1292. for( const VECTOR2I& pt : convex_hull )
  1293. hull.Append( pt );
  1294. return hull;
  1295. }
  1296. void FOOTPRINT::GetMsgPanelInfo( EDA_DRAW_FRAME* aFrame, std::vector<MSG_PANEL_ITEM>& aList )
  1297. {
  1298. wxString msg, msg2;
  1299. // Don't use GetShownText(); we want to see the variable references here
  1300. aList.emplace_back( UnescapeString( Reference().GetText() ),
  1301. UnescapeString( Value().GetText() ) );
  1302. if( aFrame->IsType( FRAME_FOOTPRINT_VIEWER )
  1303. || aFrame->IsType( FRAME_FOOTPRINT_CHOOSER )
  1304. || aFrame->IsType( FRAME_FOOTPRINT_EDITOR ) )
  1305. {
  1306. size_t padCount = GetPadCount( DO_NOT_INCLUDE_NPTH );
  1307. aList.emplace_back( _( "Library" ), GetFPID().GetLibNickname().wx_str() );
  1308. aList.emplace_back( _( "Footprint Name" ), GetFPID().GetLibItemName().wx_str() );
  1309. aList.emplace_back( _( "Pads" ), wxString::Format( wxT( "%zu" ), padCount ) );
  1310. aList.emplace_back( wxString::Format( _( "Doc: %s" ), GetLibDescription() ),
  1311. wxString::Format( _( "Keywords: %s" ), GetKeywords() ) );
  1312. return;
  1313. }
  1314. // aFrame is the board editor:
  1315. switch( GetSide() )
  1316. {
  1317. case F_Cu: aList.emplace_back( _( "Board Side" ), _( "Front" ) ); break;
  1318. case B_Cu: aList.emplace_back( _( "Board Side" ), _( "Back (Flipped)" ) ); break;
  1319. default: /* unsided: user-layers only, etc. */ break;
  1320. }
  1321. auto addToken = []( wxString* aStr, const wxString& aAttr )
  1322. {
  1323. if( !aStr->IsEmpty() )
  1324. *aStr += wxT( ", " );
  1325. *aStr += aAttr;
  1326. };
  1327. wxString status;
  1328. wxString attrs;
  1329. if( IsLocked() )
  1330. addToken( &status, _( "Locked" ) );
  1331. if( m_fpStatus & FP_is_PLACED )
  1332. addToken( &status, _( "autoplaced" ) );
  1333. if( m_attributes & FP_BOARD_ONLY )
  1334. addToken( &attrs, _( "not in schematic" ) );
  1335. if( m_attributes & FP_EXCLUDE_FROM_POS_FILES )
  1336. addToken( &attrs, _( "exclude from pos files" ) );
  1337. if( m_attributes & FP_EXCLUDE_FROM_BOM )
  1338. addToken( &attrs, _( "exclude from BOM" ) );
  1339. if( m_attributes & FP_DNP )
  1340. addToken( &attrs, _( "DNP" ) );
  1341. aList.emplace_back( _( "Status: " ) + status, _( "Attributes:" ) + wxS( " " ) + attrs );
  1342. aList.emplace_back( _( "Rotation" ), wxString::Format( wxT( "%.4g" ),
  1343. GetOrientation().AsDegrees() ) );
  1344. if( !m_componentClassCacheProxy->GetComponentClass()->IsEmpty() )
  1345. {
  1346. aList.emplace_back(
  1347. _( "Component Class" ),
  1348. m_componentClassCacheProxy->GetComponentClass()->GetHumanReadableName() );
  1349. }
  1350. msg.Printf( _( "Footprint: %s" ), m_fpid.GetUniStringLibId() );
  1351. msg2.Printf( _( "3D-Shape: %s" ), m_3D_Drawings.empty() ? _( "<none>" )
  1352. : m_3D_Drawings.front().m_Filename );
  1353. aList.emplace_back( msg, msg2 );
  1354. msg.Printf( _( "Doc: %s" ), m_libDescription );
  1355. msg2.Printf( _( "Keywords: %s" ), m_keywords );
  1356. aList.emplace_back( msg, msg2 );
  1357. }
  1358. PCB_LAYER_ID FOOTPRINT::GetSide() const
  1359. {
  1360. if( const BOARD* board = GetBoard() )
  1361. {
  1362. if( board->IsFootprintHolder() )
  1363. return UNDEFINED_LAYER;
  1364. }
  1365. // Test pads first; they're the most likely to return a quick answer.
  1366. for( PAD* pad : m_pads )
  1367. {
  1368. if( ( LSET::SideSpecificMask() & pad->GetLayerSet() ).any() )
  1369. return GetLayer();
  1370. }
  1371. for( BOARD_ITEM* item : m_drawings )
  1372. {
  1373. if( LSET::SideSpecificMask().test( item->GetLayer() ) )
  1374. return GetLayer();
  1375. }
  1376. for( ZONE* zone : m_zones )
  1377. {
  1378. if( ( LSET::SideSpecificMask() & zone->GetLayerSet() ).any() )
  1379. return GetLayer();
  1380. }
  1381. return UNDEFINED_LAYER;
  1382. }
  1383. bool FOOTPRINT::IsOnLayer( PCB_LAYER_ID aLayer ) const
  1384. {
  1385. // If we have any pads, fall back on normal checking
  1386. for( PAD* pad : m_pads )
  1387. {
  1388. if( pad->IsOnLayer( aLayer ) )
  1389. return true;
  1390. }
  1391. for( ZONE* zone : m_zones )
  1392. {
  1393. if( zone->IsOnLayer( aLayer ) )
  1394. return true;
  1395. }
  1396. for( PCB_FIELD* field : m_fields )
  1397. {
  1398. if( field->IsOnLayer( aLayer ) )
  1399. return true;
  1400. }
  1401. for( BOARD_ITEM* item : m_drawings )
  1402. {
  1403. if( item->IsOnLayer( aLayer ) )
  1404. return true;
  1405. }
  1406. return false;
  1407. }
  1408. bool FOOTPRINT::HitTestOnLayer( const VECTOR2I& aPosition, PCB_LAYER_ID aLayer, int aAccuracy ) const
  1409. {
  1410. for( PAD* pad : m_pads )
  1411. {
  1412. if( pad->IsOnLayer( aLayer ) && pad->HitTest( aPosition, aAccuracy ) )
  1413. return true;
  1414. }
  1415. for( ZONE* zone : m_zones )
  1416. {
  1417. if( zone->IsOnLayer( aLayer ) && zone->HitTest( aPosition, aAccuracy ) )
  1418. return true;
  1419. }
  1420. for( BOARD_ITEM* item : m_drawings )
  1421. {
  1422. if( item->Type() != PCB_TEXT_T && item->IsOnLayer( aLayer )
  1423. && item->HitTest( aPosition, aAccuracy ) )
  1424. {
  1425. return true;
  1426. }
  1427. }
  1428. return false;
  1429. }
  1430. bool FOOTPRINT::HitTestOnLayer( const BOX2I& aRect, bool aContained, PCB_LAYER_ID aLayer, int aAccuracy ) const
  1431. {
  1432. std::vector<BOARD_ITEM*> items;
  1433. for( PAD* pad : m_pads )
  1434. {
  1435. if( pad->IsOnLayer( aLayer ) )
  1436. items.push_back( pad );
  1437. }
  1438. for( ZONE* zone : m_zones )
  1439. {
  1440. if( zone->IsOnLayer( aLayer ) )
  1441. items.push_back( zone );
  1442. }
  1443. for( BOARD_ITEM* item : m_drawings )
  1444. {
  1445. if( item->Type() != PCB_TEXT_T && item->IsOnLayer( aLayer ) )
  1446. items.push_back( item );
  1447. }
  1448. // If we require the elements to be contained in the rect and any of them are not,
  1449. // we can return false;
  1450. // Conversely, if we just require any of the elements to have a hit, we can return true
  1451. // when the first one is found.
  1452. for( BOARD_ITEM* item : items )
  1453. {
  1454. if( !aContained && item->HitTest( aRect, aContained, aAccuracy ) )
  1455. return true;
  1456. else if( aContained && !item->HitTest( aRect, aContained, aAccuracy ) )
  1457. return false;
  1458. }
  1459. // If we didn't exit in the loop, that means that we did not return false for aContained or
  1460. // we did not return true for !aContained. So we can just return the bool with a test of
  1461. // whether there were any elements or not.
  1462. return !items.empty() && aContained;
  1463. }
  1464. bool FOOTPRINT::HitTest( const VECTOR2I& aPosition, int aAccuracy ) const
  1465. {
  1466. BOX2I rect = GetBoundingBox( false );
  1467. return rect.Inflate( aAccuracy ).Contains( aPosition );
  1468. }
  1469. bool FOOTPRINT::HitTestAccurate( const VECTOR2I& aPosition, int aAccuracy ) const
  1470. {
  1471. return GetBoundingHull().Collide( aPosition, aAccuracy );
  1472. }
  1473. bool FOOTPRINT::HitTest( const BOX2I& aRect, bool aContained, int aAccuracy ) const
  1474. {
  1475. BOX2I arect = aRect;
  1476. arect.Inflate( aAccuracy );
  1477. if( aContained )
  1478. {
  1479. return arect.Contains( GetBoundingBox( false ) );
  1480. }
  1481. else
  1482. {
  1483. // If the rect does not intersect the bounding box, skip any tests
  1484. if( !aRect.Intersects( GetBoundingBox( false ) ) )
  1485. return false;
  1486. // If there are no pads, zones, or drawings, allow intersection with text
  1487. if( m_pads.empty() && m_zones.empty() && m_drawings.empty() )
  1488. return GetBoundingBox( true ).Intersects( arect );
  1489. // Determine if any elements in the FOOTPRINT intersect the rect
  1490. for( PAD* pad : m_pads )
  1491. {
  1492. if( pad->HitTest( arect, false, 0 ) )
  1493. return true;
  1494. }
  1495. for( ZONE* zone : m_zones )
  1496. {
  1497. if( zone->HitTest( arect, false, 0 ) )
  1498. return true;
  1499. }
  1500. // PCB fields are selectable on their own, so they don't get tested
  1501. for( BOARD_ITEM* item : m_drawings )
  1502. {
  1503. // Text items are selectable on their own, and are therefore excluded from this
  1504. // test. TextBox items are NOT selectable on their own, and so MUST be included
  1505. // here. Bitmaps aren't selectable since they aren't displayed.
  1506. if( item->Type() != PCB_TEXT_T && item->HitTest( arect, false, 0 ) )
  1507. return true;
  1508. }
  1509. // Groups are not hit-tested; only their members
  1510. // No items were hit
  1511. return false;
  1512. }
  1513. }
  1514. PAD* FOOTPRINT::FindPadByNumber( const wxString& aPadNumber, PAD* aSearchAfterMe ) const
  1515. {
  1516. bool can_select = aSearchAfterMe ? false : true;
  1517. for( PAD* pad : m_pads )
  1518. {
  1519. if( !can_select && pad == aSearchAfterMe )
  1520. {
  1521. can_select = true;
  1522. continue;
  1523. }
  1524. if( can_select && pad->GetNumber() == aPadNumber )
  1525. return pad;
  1526. }
  1527. return nullptr;
  1528. }
  1529. PAD* FOOTPRINT::GetPad( const VECTOR2I& aPosition, LSET aLayerMask )
  1530. {
  1531. for( PAD* pad : m_pads )
  1532. {
  1533. // ... and on the correct layer.
  1534. if( !( pad->GetLayerSet() & aLayerMask ).any() )
  1535. continue;
  1536. if( pad->HitTest( aPosition ) )
  1537. return pad;
  1538. }
  1539. return nullptr;
  1540. }
  1541. std::vector<const PAD*> FOOTPRINT::GetPads( const wxString& aPadNumber, const PAD* aIgnore ) const
  1542. {
  1543. std::vector<const PAD*> retv;
  1544. for( const PAD* pad : m_pads )
  1545. {
  1546. if( ( aIgnore && aIgnore == pad ) || ( pad->GetNumber() != aPadNumber ) )
  1547. continue;
  1548. retv.push_back( pad );
  1549. }
  1550. return retv;
  1551. }
  1552. unsigned FOOTPRINT::GetPadCount( INCLUDE_NPTH_T aIncludeNPTH ) const
  1553. {
  1554. if( aIncludeNPTH )
  1555. return m_pads.size();
  1556. unsigned cnt = 0;
  1557. for( PAD* pad : m_pads )
  1558. {
  1559. if( pad->GetAttribute() == PAD_ATTRIB::NPTH )
  1560. continue;
  1561. cnt++;
  1562. }
  1563. return cnt;
  1564. }
  1565. std::set<wxString> FOOTPRINT::GetUniquePadNumbers( INCLUDE_NPTH_T aIncludeNPTH ) const
  1566. {
  1567. std::set<wxString> usedNumbers;
  1568. // Create a set of used pad numbers
  1569. for( PAD* pad : m_pads )
  1570. {
  1571. // Skip pads not on copper layers (used to build complex
  1572. // solder paste shapes for instance)
  1573. if( ( pad->GetLayerSet() & LSET::AllCuMask() ).none() )
  1574. continue;
  1575. // Skip pads with no name, because they are usually "mechanical"
  1576. // pads, not "electrical" pads
  1577. if( pad->GetNumber().IsEmpty() )
  1578. continue;
  1579. if( !aIncludeNPTH )
  1580. {
  1581. // skip NPTH
  1582. if( pad->GetAttribute() == PAD_ATTRIB::NPTH )
  1583. continue;
  1584. }
  1585. usedNumbers.insert( pad->GetNumber() );
  1586. }
  1587. return usedNumbers;
  1588. }
  1589. unsigned FOOTPRINT::GetUniquePadCount( INCLUDE_NPTH_T aIncludeNPTH ) const
  1590. {
  1591. return GetUniquePadNumbers( aIncludeNPTH ).size();
  1592. }
  1593. void FOOTPRINT::Add3DModel( FP_3DMODEL* a3DModel )
  1594. {
  1595. if( nullptr == a3DModel )
  1596. return;
  1597. if( !a3DModel->m_Filename.empty() )
  1598. m_3D_Drawings.push_back( *a3DModel );
  1599. }
  1600. // see footprint.h
  1601. INSPECT_RESULT FOOTPRINT::Visit( INSPECTOR inspector, void* testData,
  1602. const std::vector<KICAD_T>& aScanTypes )
  1603. {
  1604. #if 0 && defined(DEBUG)
  1605. std::cout << GetClass().mb_str() << ' ';
  1606. #endif
  1607. bool drawingsScanned = false;
  1608. for( KICAD_T scanType : aScanTypes )
  1609. {
  1610. switch( scanType )
  1611. {
  1612. case PCB_FOOTPRINT_T:
  1613. if( inspector( this, testData ) == INSPECT_RESULT::QUIT )
  1614. return INSPECT_RESULT::QUIT;
  1615. break;
  1616. case PCB_PAD_T:
  1617. if( IterateForward<PAD*>( m_pads, inspector, testData, { scanType } )
  1618. == INSPECT_RESULT::QUIT )
  1619. {
  1620. return INSPECT_RESULT::QUIT;
  1621. }
  1622. break;
  1623. case PCB_ZONE_T:
  1624. if( IterateForward<ZONE*>( m_zones, inspector, testData, { scanType } )
  1625. == INSPECT_RESULT::QUIT )
  1626. {
  1627. return INSPECT_RESULT::QUIT;
  1628. }
  1629. break;
  1630. case PCB_FIELD_T:
  1631. if( IterateForward<PCB_FIELD*>( m_fields, inspector, testData, { scanType } )
  1632. == INSPECT_RESULT::QUIT )
  1633. {
  1634. return INSPECT_RESULT::QUIT;
  1635. }
  1636. break;
  1637. case PCB_TEXT_T:
  1638. case PCB_DIM_ALIGNED_T:
  1639. case PCB_DIM_LEADER_T:
  1640. case PCB_DIM_CENTER_T:
  1641. case PCB_DIM_RADIAL_T:
  1642. case PCB_DIM_ORTHOGONAL_T:
  1643. case PCB_SHAPE_T:
  1644. case PCB_TEXTBOX_T:
  1645. case PCB_TABLE_T:
  1646. case PCB_TABLECELL_T:
  1647. if( !drawingsScanned )
  1648. {
  1649. if( IterateForward<BOARD_ITEM*>( m_drawings, inspector, testData, aScanTypes )
  1650. == INSPECT_RESULT::QUIT )
  1651. {
  1652. return INSPECT_RESULT::QUIT;
  1653. }
  1654. drawingsScanned = true;
  1655. }
  1656. break;
  1657. case PCB_GROUP_T:
  1658. if( IterateForward<PCB_GROUP*>( m_groups, inspector, testData, { scanType } )
  1659. == INSPECT_RESULT::QUIT )
  1660. {
  1661. return INSPECT_RESULT::QUIT;
  1662. }
  1663. break;
  1664. default:
  1665. break;
  1666. }
  1667. }
  1668. return INSPECT_RESULT::CONTINUE;
  1669. }
  1670. wxString FOOTPRINT::GetItemDescription( UNITS_PROVIDER* aUnitsProvider, bool aFull ) const
  1671. {
  1672. wxString reference = GetReference();
  1673. if( reference.IsEmpty() )
  1674. reference = _( "<no reference designator>" );
  1675. return wxString::Format( _( "Footprint %s" ), reference );
  1676. }
  1677. BITMAPS FOOTPRINT::GetMenuImage() const
  1678. {
  1679. return BITMAPS::module;
  1680. }
  1681. EDA_ITEM* FOOTPRINT::Clone() const
  1682. {
  1683. return new FOOTPRINT( *this );
  1684. }
  1685. void FOOTPRINT::RunOnChildren( const std::function<void ( BOARD_ITEM* )>& aFunction ) const
  1686. {
  1687. try
  1688. {
  1689. for( PCB_FIELD* field : m_fields )
  1690. aFunction( field );
  1691. for( PAD* pad : m_pads )
  1692. aFunction( pad );
  1693. for( ZONE* zone : m_zones )
  1694. aFunction( zone );
  1695. for( PCB_GROUP* group : m_groups )
  1696. aFunction( group );
  1697. for( BOARD_ITEM* drawing : m_drawings )
  1698. aFunction( drawing );
  1699. }
  1700. catch( std::bad_function_call& )
  1701. {
  1702. wxFAIL_MSG( wxT( "Error running FOOTPRINT::RunOnChildren" ) );
  1703. }
  1704. }
  1705. void FOOTPRINT::RunOnDescendants( const std::function<void( BOARD_ITEM* )>& aFunction,
  1706. int aDepth ) const
  1707. {
  1708. // Avoid freezes with infinite recursion
  1709. if( aDepth > 20 )
  1710. return;
  1711. try
  1712. {
  1713. for( PCB_FIELD* field : m_fields )
  1714. aFunction( field );
  1715. for( PAD* pad : m_pads )
  1716. aFunction( pad );
  1717. for( ZONE* zone : m_zones )
  1718. aFunction( zone );
  1719. for( PCB_GROUP* group : m_groups )
  1720. aFunction( group );
  1721. for( BOARD_ITEM* drawing : m_drawings )
  1722. {
  1723. aFunction( drawing );
  1724. drawing->RunOnDescendants( aFunction, aDepth + 1 );
  1725. }
  1726. }
  1727. catch( std::bad_function_call& )
  1728. {
  1729. wxFAIL_MSG( wxT( "Error running FOOTPRINT::RunOnDescendants" ) );
  1730. }
  1731. }
  1732. std::vector<int> FOOTPRINT::ViewGetLayers() const
  1733. {
  1734. std::vector<int> layers;
  1735. layers.reserve( 6 );
  1736. layers.push_back( LAYER_ANCHOR );
  1737. switch( m_layer )
  1738. {
  1739. default:
  1740. wxASSERT_MSG( false, wxT( "Illegal layer" ) ); // do you really have footprints placed
  1741. // on other layers?
  1742. KI_FALLTHROUGH;
  1743. case F_Cu:
  1744. layers.push_back( LAYER_FOOTPRINTS_FR );
  1745. break;
  1746. case B_Cu:
  1747. layers.push_back( LAYER_FOOTPRINTS_BK );
  1748. break;
  1749. }
  1750. if( IsLocked() )
  1751. layers.push_back( LAYER_LOCKED_ITEM_SHADOW );
  1752. if( IsConflicting() )
  1753. layers.push_back( LAYER_CONFLICTS_SHADOW );
  1754. // If there are no pads, and only drawings on a silkscreen layer, then report the silkscreen
  1755. // layer as well so that the component can be edited with the silkscreen layer
  1756. bool f_silk = false, b_silk = false, non_silk = false;
  1757. for( BOARD_ITEM* item : m_drawings )
  1758. {
  1759. if( item->GetLayer() == F_SilkS )
  1760. f_silk = true;
  1761. else if( item->GetLayer() == B_SilkS )
  1762. b_silk = true;
  1763. else
  1764. non_silk = true;
  1765. }
  1766. if( ( f_silk || b_silk ) && !non_silk && m_pads.empty() )
  1767. {
  1768. if( f_silk )
  1769. layers.push_back( F_SilkS );
  1770. if( b_silk )
  1771. layers.push_back( B_SilkS );
  1772. }
  1773. return layers;
  1774. }
  1775. double FOOTPRINT::ViewGetLOD( int aLayer, const KIGFX::VIEW* aView ) const
  1776. {
  1777. if( aLayer == LAYER_LOCKED_ITEM_SHADOW )
  1778. {
  1779. // The locked shadow shape is shown only if the footprint itself is visible
  1780. if( ( m_layer == F_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_FR ) )
  1781. return LOD_SHOW;
  1782. if( ( m_layer == B_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_BK ) )
  1783. return LOD_SHOW;
  1784. return LOD_HIDE;
  1785. }
  1786. if( aLayer == LAYER_CONFLICTS_SHADOW && IsConflicting() )
  1787. {
  1788. // The locked shadow shape is shown only if the footprint itself is visible
  1789. if( ( m_layer == F_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_FR ) )
  1790. return LOD_SHOW;
  1791. if( ( m_layer == B_Cu ) && aView->IsLayerVisible( LAYER_FOOTPRINTS_BK ) )
  1792. return LOD_SHOW;
  1793. return LOD_HIDE;
  1794. }
  1795. int layer = ( m_layer == F_Cu ) ? LAYER_FOOTPRINTS_FR :
  1796. ( m_layer == B_Cu ) ? LAYER_FOOTPRINTS_BK : LAYER_ANCHOR;
  1797. // Currently this is only pertinent for the anchor layer; everything else is drawn from the
  1798. // children.
  1799. // The "good" value is experimentally chosen.
  1800. constexpr double MINIMAL_ZOOM_LEVEL_FOR_VISIBILITY = 1.5;
  1801. if( aView->IsLayerVisible( layer ) )
  1802. return MINIMAL_ZOOM_LEVEL_FOR_VISIBILITY;
  1803. return LOD_HIDE;
  1804. }
  1805. const BOX2I FOOTPRINT::ViewBBox() const
  1806. {
  1807. BOX2I area = GetBoundingBox( true );
  1808. // Inflate in case clearance lines are drawn around pads, etc.
  1809. if( const BOARD* board = GetBoard() )
  1810. {
  1811. int biggest_clearance = board->GetMaxClearanceValue();
  1812. area.Inflate( biggest_clearance );
  1813. }
  1814. return area;
  1815. }
  1816. bool FOOTPRINT::IsLibNameValid( const wxString & aName )
  1817. {
  1818. const wxChar * invalids = StringLibNameInvalidChars( false );
  1819. if( aName.find_first_of( invalids ) != std::string::npos )
  1820. return false;
  1821. return true;
  1822. }
  1823. const wxChar* FOOTPRINT::StringLibNameInvalidChars( bool aUserReadable )
  1824. {
  1825. // This list of characters is also duplicated in validators.cpp and
  1826. // lib_id.cpp
  1827. // TODO: Unify forbidden character lists - Warning, invalid filename characters are not the same
  1828. // as invalid LIB_ID characters. We will need to separate the FP filenames from FP names before this
  1829. // can be unified
  1830. static const wxChar invalidChars[] = wxT("%$<>\t\n\r\"\\/:");
  1831. static const wxChar invalidCharsReadable[] = wxT("% $ < > 'tab' 'return' 'line feed' \\ \" / :");
  1832. if( aUserReadable )
  1833. return invalidCharsReadable;
  1834. else
  1835. return invalidChars;
  1836. }
  1837. void FOOTPRINT::Move( const VECTOR2I& aMoveVector )
  1838. {
  1839. if( aMoveVector.x == 0 && aMoveVector.y == 0 )
  1840. return;
  1841. VECTOR2I newpos = m_pos + aMoveVector;
  1842. SetPosition( newpos );
  1843. }
  1844. void FOOTPRINT::Rotate( const VECTOR2I& aRotCentre, const EDA_ANGLE& aAngle )
  1845. {
  1846. if( aAngle == ANGLE_0 )
  1847. return;
  1848. EDA_ANGLE orientation = GetOrientation();
  1849. EDA_ANGLE newOrientation = orientation + aAngle;
  1850. VECTOR2I newpos = m_pos;
  1851. RotatePoint( newpos, aRotCentre, aAngle );
  1852. SetPosition( newpos );
  1853. SetOrientation( newOrientation );
  1854. for( PCB_FIELD* field : m_fields )
  1855. field->KeepUpright();
  1856. for( BOARD_ITEM* item : m_drawings )
  1857. {
  1858. if( item->Type() == PCB_TEXT_T )
  1859. static_cast<PCB_TEXT*>( item )->KeepUpright();
  1860. }
  1861. }
  1862. void FOOTPRINT::SetLayerAndFlip( PCB_LAYER_ID aLayer )
  1863. {
  1864. wxASSERT( aLayer == F_Cu || aLayer == B_Cu );
  1865. if( aLayer != GetLayer() )
  1866. Flip( GetPosition(), FLIP_DIRECTION::LEFT_RIGHT );
  1867. }
  1868. void FOOTPRINT::Flip( const VECTOR2I& aCentre, FLIP_DIRECTION aFlipDirection )
  1869. {
  1870. // Move footprint to its final position:
  1871. VECTOR2I finalPos = m_pos;
  1872. // Now Flip the footprint.
  1873. // Flipping a footprint is a specific transform: it is not mirrored like a text.
  1874. // We have to change the side, and ensure the footprint rotation is modified according to the
  1875. // transform, because this parameter is used in pick and place files, and when updating the
  1876. // footprint from library.
  1877. // When flipped around the X axis (Y coordinates changed) orientation is negated
  1878. // When flipped around the Y axis (X coordinates changed) orientation is 180 - old orient.
  1879. // Because it is specific to a footprint, we flip around the X axis, and after rotate 180 deg
  1880. MIRROR( finalPos.y, aCentre.y ); /// Mirror the Y position (around the X axis)
  1881. SetPosition( finalPos );
  1882. // Flip layer
  1883. BOARD_ITEM::SetLayer( GetBoard()->FlipLayer( GetLayer() ) );
  1884. // Calculate the new orientation, and then clear it for pad flipping.
  1885. EDA_ANGLE newOrientation = -m_orient;
  1886. newOrientation.Normalize180();
  1887. m_orient = ANGLE_0;
  1888. // Mirror fields to other side of board.
  1889. for( PCB_FIELD* field : m_fields )
  1890. field->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );
  1891. // Mirror pads to other side of board.
  1892. for( PAD* pad : m_pads )
  1893. pad->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );
  1894. // Now set the new orientation.
  1895. m_orient = newOrientation;
  1896. // Mirror zones to other side of board.
  1897. for( ZONE* zone : m_zones )
  1898. zone->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );
  1899. // Reverse mirror footprint graphics and texts.
  1900. for( BOARD_ITEM* item : m_drawings )
  1901. item->Flip( m_pos, FLIP_DIRECTION::TOP_BOTTOM );
  1902. // Now rotate 180 deg if required
  1903. if( aFlipDirection == FLIP_DIRECTION::LEFT_RIGHT )
  1904. Rotate( aCentre, ANGLE_180 );
  1905. m_boundingBoxCacheTimeStamp = 0;
  1906. m_textExcludedBBoxCacheTimeStamp = 0;
  1907. m_cachedHull.Mirror( m_pos, aFlipDirection );
  1908. // The courtyard caches must be rebuilt after geometry change
  1909. BuildCourtyardCaches();
  1910. }
  1911. void FOOTPRINT::SetPosition( const VECTOR2I& aPos )
  1912. {
  1913. VECTOR2I delta = aPos - m_pos;
  1914. m_pos += delta;
  1915. for( PCB_FIELD* field : m_fields )
  1916. field->EDA_TEXT::Offset( delta );
  1917. for( PAD* pad : m_pads )
  1918. pad->SetPosition( pad->GetPosition() + delta );
  1919. for( ZONE* zone : m_zones )
  1920. zone->Move( delta );
  1921. for( BOARD_ITEM* item : m_drawings )
  1922. item->Move( delta );
  1923. m_cachedBoundingBox.Move( delta );
  1924. m_cachedTextExcludedBBox.Move( delta );
  1925. m_cachedHull.Move( delta );
  1926. // The geometry work has been conserved by using Move(). But the hashes
  1927. // need to be updated, otherwise the cached polygons will still be rebuild.
  1928. m_courtyard_cache_back.Move( delta );
  1929. m_courtyard_cache_back_hash = m_courtyard_cache_back.GetHash();
  1930. m_courtyard_cache_front.Move( delta );
  1931. m_courtyard_cache_front_hash = m_courtyard_cache_front.GetHash();
  1932. }
  1933. void FOOTPRINT::MoveAnchorPosition( const VECTOR2I& aMoveVector )
  1934. {
  1935. /*
  1936. * Move the reference point of the footprint
  1937. * the footprints elements (pads, outlines, edges .. ) are moved
  1938. * but:
  1939. * - the footprint position is not modified.
  1940. * - the relative (local) coordinates of these items are modified
  1941. * - Draw coordinates are updated
  1942. */
  1943. // Update (move) the relative coordinates relative to the new anchor point.
  1944. VECTOR2I moveVector = aMoveVector;
  1945. RotatePoint( moveVector, -GetOrientation() );
  1946. // Update field local coordinates
  1947. for( PCB_FIELD* field : m_fields )
  1948. field->Move( moveVector );
  1949. // Update the pad local coordinates.
  1950. for( PAD* pad : m_pads )
  1951. pad->Move( moveVector );
  1952. // Update the draw element coordinates.
  1953. for( BOARD_ITEM* item : GraphicalItems() )
  1954. item->Move( moveVector );
  1955. // Update the keepout zones
  1956. for( ZONE* zone : Zones() )
  1957. zone->Move( moveVector );
  1958. // Update the 3D models
  1959. for( FP_3DMODEL& model : Models() )
  1960. {
  1961. model.m_Offset.x += pcbIUScale.IUTomm( moveVector.x );
  1962. model.m_Offset.y -= pcbIUScale.IUTomm( moveVector.y );
  1963. }
  1964. m_cachedBoundingBox.Move( moveVector );
  1965. m_cachedTextExcludedBBox.Move( moveVector );
  1966. m_cachedHull.Move( moveVector );
  1967. // The geometry work have been conserved by using Move(). But the hashes
  1968. // need to be updated, otherwise the cached polygons will still be rebuild.
  1969. m_courtyard_cache_back.Move( moveVector );
  1970. m_courtyard_cache_back_hash = m_courtyard_cache_back.GetHash();
  1971. m_courtyard_cache_front.Move( moveVector );
  1972. m_courtyard_cache_front_hash = m_courtyard_cache_front.GetHash();
  1973. }
  1974. void FOOTPRINT::SetOrientation( const EDA_ANGLE& aNewAngle )
  1975. {
  1976. EDA_ANGLE angleChange = aNewAngle - m_orient; // change in rotation
  1977. m_orient = aNewAngle;
  1978. m_orient.Normalize180();
  1979. for( PCB_FIELD* field : m_fields )
  1980. field->Rotate( GetPosition(), angleChange );
  1981. for( PAD* pad : m_pads )
  1982. pad->Rotate( GetPosition(), angleChange );
  1983. for( ZONE* zone : m_zones )
  1984. zone->Rotate( GetPosition(), angleChange );
  1985. for( BOARD_ITEM* item : m_drawings )
  1986. item->Rotate( GetPosition(), angleChange );
  1987. m_boundingBoxCacheTimeStamp = 0;
  1988. m_textExcludedBBoxCacheTimeStamp = 0;
  1989. m_hullCacheTimeStamp = 0;
  1990. // The courtyard caches need to be rebuilt, as the geometry has changed
  1991. BuildCourtyardCaches();
  1992. }
  1993. BOARD_ITEM* FOOTPRINT::Duplicate() const
  1994. {
  1995. FOOTPRINT* dupe = static_cast<FOOTPRINT*>( BOARD_ITEM::Duplicate() );
  1996. dupe->RunOnDescendants( [&]( BOARD_ITEM* child )
  1997. {
  1998. const_cast<KIID&>( child->m_Uuid ) = KIID();
  1999. });
  2000. return dupe;
  2001. }
  2002. BOARD_ITEM* FOOTPRINT::DuplicateItem( const BOARD_ITEM* aItem, bool aAddToFootprint )
  2003. {
  2004. BOARD_ITEM* new_item = nullptr;
  2005. switch( aItem->Type() )
  2006. {
  2007. case PCB_PAD_T:
  2008. {
  2009. PAD* new_pad = new PAD( *static_cast<const PAD*>( aItem ) );
  2010. const_cast<KIID&>( new_pad->m_Uuid ) = KIID();
  2011. if( aAddToFootprint )
  2012. m_pads.push_back( new_pad );
  2013. new_item = new_pad;
  2014. break;
  2015. }
  2016. case PCB_ZONE_T:
  2017. {
  2018. ZONE* new_zone = new ZONE( *static_cast<const ZONE*>( aItem ) );
  2019. const_cast<KIID&>( new_zone->m_Uuid ) = KIID();
  2020. if( aAddToFootprint )
  2021. m_zones.push_back( new_zone );
  2022. new_item = new_zone;
  2023. break;
  2024. }
  2025. case PCB_FIELD_T:
  2026. case PCB_TEXT_T:
  2027. {
  2028. PCB_TEXT* new_text = new PCB_TEXT( *static_cast<const PCB_TEXT*>( aItem ) );
  2029. const_cast<KIID&>( new_text->m_Uuid ) = KIID();
  2030. if( aItem->Type() == PCB_FIELD_T )
  2031. {
  2032. switch( static_cast<const PCB_FIELD*>( aItem )->GetId() )
  2033. {
  2034. case FIELD_T::REFERENCE: new_text->SetText( wxT( "${REFERENCE}" ) ); break;
  2035. case FIELD_T::VALUE: new_text->SetText( wxT( "${VALUE}" ) ); break;
  2036. case FIELD_T::DATASHEET: new_text->SetText( wxT( "${DATASHEET}" ) ); break;
  2037. default: break;
  2038. }
  2039. }
  2040. if( aAddToFootprint )
  2041. Add( new_text );
  2042. new_item = new_text;
  2043. break;
  2044. }
  2045. case PCB_SHAPE_T:
  2046. {
  2047. PCB_SHAPE* new_shape = new PCB_SHAPE( *static_cast<const PCB_SHAPE*>( aItem ) );
  2048. const_cast<KIID&>( new_shape->m_Uuid ) = KIID();
  2049. if( aAddToFootprint )
  2050. Add( new_shape );
  2051. new_item = new_shape;
  2052. break;
  2053. }
  2054. case PCB_TEXTBOX_T:
  2055. {
  2056. PCB_TEXTBOX* new_textbox = new PCB_TEXTBOX( *static_cast<const PCB_TEXTBOX*>( aItem ) );
  2057. const_cast<KIID&>( new_textbox->m_Uuid ) = KIID();
  2058. if( aAddToFootprint )
  2059. Add( new_textbox );
  2060. new_item = new_textbox;
  2061. break;
  2062. }
  2063. case PCB_DIM_ALIGNED_T:
  2064. case PCB_DIM_LEADER_T:
  2065. case PCB_DIM_CENTER_T:
  2066. case PCB_DIM_RADIAL_T:
  2067. case PCB_DIM_ORTHOGONAL_T:
  2068. {
  2069. PCB_DIMENSION_BASE* dimension = static_cast<PCB_DIMENSION_BASE*>( aItem->Duplicate() );
  2070. if( aAddToFootprint )
  2071. Add( dimension );
  2072. new_item = dimension;
  2073. break;
  2074. }
  2075. case PCB_GROUP_T:
  2076. {
  2077. PCB_GROUP* group = static_cast<const PCB_GROUP*>( aItem )->DeepDuplicate();
  2078. if( aAddToFootprint )
  2079. {
  2080. group->RunOnDescendants(
  2081. [&]( BOARD_ITEM* aCurrItem )
  2082. {
  2083. Add( aCurrItem );
  2084. } );
  2085. Add( group );
  2086. }
  2087. new_item = group;
  2088. break;
  2089. }
  2090. case PCB_FOOTPRINT_T:
  2091. // Ignore the footprint itself
  2092. break;
  2093. default:
  2094. // Un-handled item for duplication
  2095. wxFAIL_MSG( wxT( "Duplication not supported for items of class " ) + aItem->GetClass() );
  2096. break;
  2097. }
  2098. return new_item;
  2099. }
  2100. wxString FOOTPRINT::GetNextPadNumber( const wxString& aLastPadNumber ) const
  2101. {
  2102. std::set<wxString> usedNumbers;
  2103. // Create a set of used pad numbers
  2104. for( PAD* pad : m_pads )
  2105. usedNumbers.insert( pad->GetNumber() );
  2106. // Pad numbers aren't technically reference designators, but the formatting is close enough
  2107. // for these to give us what we need.
  2108. wxString prefix = UTIL::GetRefDesPrefix( aLastPadNumber );
  2109. int num = GetTrailingInt( aLastPadNumber );
  2110. while( usedNumbers.count( wxString::Format( wxT( "%s%d" ), prefix, num ) ) )
  2111. num++;
  2112. return wxString::Format( wxT( "%s%d" ), prefix, num );
  2113. }
  2114. void FOOTPRINT::AutoPositionFields()
  2115. {
  2116. // Auto-position reference and value
  2117. BOX2I bbox = GetBoundingBox( false );
  2118. bbox.Inflate( pcbIUScale.mmToIU( 0.2 ) ); // Gap between graphics and text
  2119. if( Reference().GetPosition() == VECTOR2I( 0, 0 ) )
  2120. {
  2121. Reference().SetHorizJustify( GR_TEXT_H_ALIGN_CENTER );
  2122. Reference().SetVertJustify( GR_TEXT_V_ALIGN_CENTER );
  2123. Reference().SetTextAngle( ANGLE_0 );
  2124. Reference().SetX( bbox.GetCenter().x );
  2125. Reference().SetY( bbox.GetTop() - Reference().GetTextSize().y / 2 );
  2126. }
  2127. if( Value().GetPosition() == VECTOR2I( 0, 0 ) )
  2128. {
  2129. Value().SetHorizJustify( GR_TEXT_H_ALIGN_CENTER );
  2130. Value().SetVertJustify( GR_TEXT_V_ALIGN_CENTER );
  2131. Value().SetTextAngle( ANGLE_0 );
  2132. Value().SetX( bbox.GetCenter().x );
  2133. Value().SetY( bbox.GetBottom() + Value().GetTextSize().y / 2 );
  2134. }
  2135. }
  2136. void FOOTPRINT::IncrementReference( int aDelta )
  2137. {
  2138. const wxString& refdes = GetReference();
  2139. SetReference( wxString::Format( wxT( "%s%i" ),
  2140. UTIL::GetRefDesPrefix( refdes ),
  2141. GetTrailingInt( refdes ) + aDelta ) );
  2142. }
  2143. // Calculate the area of a PolySet, polygons with hole are allowed.
  2144. static double polygonArea( SHAPE_POLY_SET& aPolySet )
  2145. {
  2146. // Ensure all outlines are closed, before calculating the SHAPE_POLY_SET area
  2147. for( int ii = 0; ii < aPolySet.OutlineCount(); ii++ )
  2148. {
  2149. SHAPE_LINE_CHAIN& outline = aPolySet.Outline( ii );
  2150. outline.SetClosed( true );
  2151. for( int jj = 0; jj < aPolySet.HoleCount( ii ); jj++ )
  2152. aPolySet.Hole( ii, jj ).SetClosed( true );
  2153. }
  2154. return aPolySet.Area();
  2155. }
  2156. double FOOTPRINT::GetCoverageArea( const BOARD_ITEM* aItem, const GENERAL_COLLECTOR& aCollector )
  2157. {
  2158. int textMargin = aCollector.GetGuide()->Accuracy();
  2159. SHAPE_POLY_SET poly;
  2160. if( aItem->Type() == PCB_MARKER_T )
  2161. {
  2162. const PCB_MARKER* marker = static_cast<const PCB_MARKER*>( aItem );
  2163. SHAPE_LINE_CHAIN markerShape;
  2164. marker->ShapeToPolygon( markerShape );
  2165. return markerShape.Area();
  2166. }
  2167. else if( aItem->Type() == PCB_GROUP_T || aItem->Type() == PCB_GENERATOR_T )
  2168. {
  2169. double combinedArea = 0.0;
  2170. for( BOARD_ITEM* member : static_cast<const PCB_GROUP*>( aItem )->GetItems() )
  2171. combinedArea += GetCoverageArea( member, aCollector );
  2172. return combinedArea;
  2173. }
  2174. if( aItem->Type() == PCB_FOOTPRINT_T )
  2175. {
  2176. const FOOTPRINT* footprint = static_cast<const FOOTPRINT*>( aItem );
  2177. poly = footprint->GetBoundingHull();
  2178. }
  2179. else if( aItem->Type() == PCB_FIELD_T || aItem->Type() == PCB_TEXT_T )
  2180. {
  2181. const PCB_TEXT* text = static_cast<const PCB_TEXT*>( aItem );
  2182. text->TransformTextToPolySet( poly, textMargin, ARC_LOW_DEF, ERROR_INSIDE );
  2183. }
  2184. else if( aItem->Type() == PCB_TEXTBOX_T )
  2185. {
  2186. const PCB_TEXTBOX* tb = static_cast<const PCB_TEXTBOX*>( aItem );
  2187. tb->TransformTextToPolySet( poly, textMargin, ARC_LOW_DEF, ERROR_INSIDE );
  2188. }
  2189. else if( aItem->Type() == PCB_SHAPE_T )
  2190. {
  2191. // Approximate "linear" shapes with just their width squared, as we don't want to consider
  2192. // a linear shape as being much bigger than another for purposes of selection filtering
  2193. // just because it happens to be really long.
  2194. const PCB_SHAPE* shape = static_cast<const PCB_SHAPE*>( aItem );
  2195. switch( shape->GetShape() )
  2196. {
  2197. case SHAPE_T::SEGMENT:
  2198. case SHAPE_T::ARC:
  2199. case SHAPE_T::BEZIER:
  2200. return shape->GetWidth() * shape->GetWidth();
  2201. case SHAPE_T::RECTANGLE:
  2202. case SHAPE_T::CIRCLE:
  2203. case SHAPE_T::POLY:
  2204. {
  2205. if( !shape->IsAnyFill() )
  2206. return shape->GetWidth() * shape->GetWidth();
  2207. KI_FALLTHROUGH;
  2208. }
  2209. default:
  2210. shape->TransformShapeToPolygon( poly, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
  2211. }
  2212. }
  2213. else if( aItem->Type() == PCB_TRACE_T || aItem->Type() == PCB_ARC_T )
  2214. {
  2215. double width = static_cast<const PCB_TRACK*>( aItem )->GetWidth();
  2216. return width * width;
  2217. }
  2218. else if( aItem->Type() == PCB_PAD_T )
  2219. {
  2220. static_cast<const PAD*>( aItem )->Padstack().ForEachUniqueLayer(
  2221. [&]( PCB_LAYER_ID aLayer )
  2222. {
  2223. SHAPE_POLY_SET padPoly;
  2224. aItem->TransformShapeToPolygon( padPoly, aLayer, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
  2225. poly.BooleanAdd( padPoly );
  2226. } );
  2227. }
  2228. else
  2229. {
  2230. aItem->TransformShapeToPolygon( poly, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
  2231. }
  2232. return polygonArea( poly );
  2233. }
  2234. double FOOTPRINT::CoverageRatio( const GENERAL_COLLECTOR& aCollector ) const
  2235. {
  2236. int textMargin = aCollector.GetGuide()->Accuracy();
  2237. SHAPE_POLY_SET footprintRegion( GetBoundingHull() );
  2238. SHAPE_POLY_SET coveredRegion;
  2239. TransformPadsToPolySet( coveredRegion, UNDEFINED_LAYER, 0, ARC_LOW_DEF, ERROR_OUTSIDE );
  2240. TransformFPShapesToPolySet( coveredRegion, UNDEFINED_LAYER, textMargin, ARC_LOW_DEF,
  2241. ERROR_OUTSIDE,
  2242. true, /* include text */
  2243. false, /* include shapes */
  2244. false /* include private items */ );
  2245. for( int i = 0; i < aCollector.GetCount(); ++i )
  2246. {
  2247. const BOARD_ITEM* item = aCollector[i];
  2248. switch( item->Type() )
  2249. {
  2250. case PCB_FIELD_T:
  2251. case PCB_TEXT_T:
  2252. case PCB_TEXTBOX_T:
  2253. case PCB_SHAPE_T:
  2254. case PCB_TRACE_T:
  2255. case PCB_ARC_T:
  2256. case PCB_VIA_T:
  2257. if( item->GetParent() != this )
  2258. {
  2259. item->TransformShapeToPolygon( coveredRegion, UNDEFINED_LAYER, 0, ARC_LOW_DEF,
  2260. ERROR_OUTSIDE );
  2261. }
  2262. break;
  2263. case PCB_FOOTPRINT_T:
  2264. if( item != this )
  2265. {
  2266. const FOOTPRINT* footprint = static_cast<const FOOTPRINT*>( item );
  2267. coveredRegion.AddOutline( footprint->GetBoundingHull().Outline( 0 ) );
  2268. }
  2269. break;
  2270. default:
  2271. break;
  2272. }
  2273. }
  2274. coveredRegion.BooleanIntersection( footprintRegion );
  2275. double footprintRegionArea = polygonArea( footprintRegion );
  2276. double uncoveredRegionArea = footprintRegionArea - polygonArea( coveredRegion );
  2277. double coveredArea = footprintRegionArea - uncoveredRegionArea;
  2278. double ratio = ( coveredArea / footprintRegionArea );
  2279. // Test for negative ratio (should not occur).
  2280. // better to be conservative (this will result in the disambiguate dialog)
  2281. if( ratio < 0.0 )
  2282. return 1.0;
  2283. return std::min( ratio, 1.0 );
  2284. }
  2285. std::shared_ptr<SHAPE> FOOTPRINT::GetEffectiveShape( PCB_LAYER_ID aLayer, FLASHING aFlash ) const
  2286. {
  2287. std::shared_ptr<SHAPE_COMPOUND> shape = std::make_shared<SHAPE_COMPOUND>();
  2288. // There are several possible interpretations here:
  2289. // 1) the bounding box (without or without invisible items)
  2290. // 2) just the pads and "edges" (ie: non-text graphic items)
  2291. // 3) the courtyard
  2292. // We'll go with (2) for now, unless the caller is clearly looking for (3)
  2293. if( aLayer == F_CrtYd || aLayer == B_CrtYd )
  2294. {
  2295. const SHAPE_POLY_SET& courtyard = GetCourtyard( aLayer );
  2296. if( courtyard.OutlineCount() == 0 ) // malformed/empty polygon
  2297. return shape;
  2298. shape->AddShape( new SHAPE_SIMPLE( courtyard.COutline( 0 ) ) );
  2299. }
  2300. else
  2301. {
  2302. for( PAD* pad : Pads() )
  2303. shape->AddShape( pad->GetEffectiveShape( aLayer, aFlash )->Clone() );
  2304. for( BOARD_ITEM* item : GraphicalItems() )
  2305. {
  2306. if( item->Type() == PCB_SHAPE_T )
  2307. shape->AddShape( item->GetEffectiveShape( aLayer, aFlash )->Clone() );
  2308. }
  2309. }
  2310. return shape;
  2311. }
  2312. const SHAPE_POLY_SET& FOOTPRINT::GetCourtyard( PCB_LAYER_ID aLayer ) const
  2313. {
  2314. std::lock_guard<std::mutex> lock( m_courtyard_cache_mutex );
  2315. if( m_courtyard_cache_front_hash != m_courtyard_cache_front.GetHash()
  2316. || m_courtyard_cache_back_hash != m_courtyard_cache_back.GetHash() )
  2317. {
  2318. const_cast<FOOTPRINT*>(this)->BuildCourtyardCaches();
  2319. }
  2320. return GetCachedCourtyard( aLayer );
  2321. }
  2322. const SHAPE_POLY_SET& FOOTPRINT::GetCachedCourtyard( PCB_LAYER_ID aLayer ) const
  2323. {
  2324. if( IsBackLayer( aLayer ) )
  2325. return m_courtyard_cache_back;
  2326. else
  2327. return m_courtyard_cache_front;
  2328. }
  2329. void FOOTPRINT::BuildCourtyardCaches( OUTLINE_ERROR_HANDLER* aErrorHandler )
  2330. {
  2331. m_courtyard_cache_front.RemoveAllContours();
  2332. m_courtyard_cache_back.RemoveAllContours();
  2333. ClearFlags( MALFORMED_COURTYARDS );
  2334. // Build the courtyard area from graphic items on the courtyard.
  2335. // Only PCB_SHAPE_T have meaning, graphic texts are ignored.
  2336. // Collect items:
  2337. std::vector<PCB_SHAPE*> list_front;
  2338. std::vector<PCB_SHAPE*> list_back;
  2339. std::map<int, int> front_width_histogram;
  2340. std::map<int, int> back_width_histogram;
  2341. for( BOARD_ITEM* item : GraphicalItems() )
  2342. {
  2343. if( item->GetLayer() == B_CrtYd && item->Type() == PCB_SHAPE_T )
  2344. {
  2345. PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
  2346. list_back.push_back( shape );
  2347. back_width_histogram[ shape->GetStroke().GetWidth() ]++;
  2348. }
  2349. if( item->GetLayer() == F_CrtYd && item->Type() == PCB_SHAPE_T )
  2350. {
  2351. PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
  2352. list_front.push_back( shape );
  2353. front_width_histogram[ shape->GetStroke().GetWidth() ]++;
  2354. }
  2355. }
  2356. if( !list_front.size() && !list_back.size() )
  2357. return;
  2358. int maxError = pcbIUScale.mmToIU( 0.005 ); // max error for polygonization
  2359. int chainingEpsilon = pcbIUScale.mmToIU( 0.02 ); // max dist from one endPt to next startPt
  2360. if( ConvertOutlineToPolygon( list_front, m_courtyard_cache_front, maxError, chainingEpsilon,
  2361. true, aErrorHandler ) )
  2362. {
  2363. int width = 0;
  2364. // Touching courtyards, or courtyards -at- the clearance distance are legal.
  2365. // Use maxError here because that is the allowed deviation when transforming arcs/circles to
  2366. // polygons.
  2367. m_courtyard_cache_front.Inflate( -maxError, CORNER_STRATEGY::CHAMFER_ACUTE_CORNERS, maxError );
  2368. m_courtyard_cache_front.CacheTriangulation( false );
  2369. auto max = std::max_element( front_width_histogram.begin(), front_width_histogram.end(),
  2370. []( const std::pair<int, int>& a, const std::pair<int, int>& b )
  2371. {
  2372. return a.second < b.second;
  2373. } );
  2374. if( max != front_width_histogram.end() )
  2375. width = max->first;
  2376. if( width == 0 )
  2377. width = pcbIUScale.mmToIU( DEFAULT_COURTYARD_WIDTH );
  2378. if( m_courtyard_cache_front.OutlineCount() > 0 )
  2379. m_courtyard_cache_front.Outline( 0 ).SetWidth( width );
  2380. }
  2381. else
  2382. {
  2383. SetFlags( MALFORMED_F_COURTYARD );
  2384. }
  2385. if( ConvertOutlineToPolygon( list_back, m_courtyard_cache_back, maxError, chainingEpsilon, true,
  2386. aErrorHandler ) )
  2387. {
  2388. int width = 0;
  2389. // Touching courtyards, or courtyards -at- the clearance distance are legal.
  2390. m_courtyard_cache_back.Inflate( -maxError, CORNER_STRATEGY::CHAMFER_ACUTE_CORNERS, maxError );
  2391. m_courtyard_cache_back.CacheTriangulation( false );
  2392. auto max = std::max_element( back_width_histogram.begin(), back_width_histogram.end(),
  2393. []( const std::pair<int, int>& a, const std::pair<int, int>& b )
  2394. {
  2395. return a.second < b.second;
  2396. } );
  2397. if( max != back_width_histogram.end() )
  2398. width = max->first;
  2399. if( width == 0 )
  2400. width = pcbIUScale.mmToIU( DEFAULT_COURTYARD_WIDTH );
  2401. if( m_courtyard_cache_back.OutlineCount() > 0 )
  2402. m_courtyard_cache_back.Outline( 0 ).SetWidth( width );
  2403. }
  2404. else
  2405. {
  2406. SetFlags( MALFORMED_B_COURTYARD );
  2407. }
  2408. m_courtyard_cache_front_hash = m_courtyard_cache_front.GetHash();
  2409. m_courtyard_cache_back_hash = m_courtyard_cache_back.GetHash();
  2410. }
  2411. void FOOTPRINT::BuildNetTieCache()
  2412. {
  2413. m_netTieCache.clear();
  2414. std::map<wxString, int> map = MapPadNumbersToNetTieGroups();
  2415. std::map<PCB_LAYER_ID, std::vector<PCB_SHAPE*>> layer_shapes;
  2416. std::for_each( m_drawings.begin(), m_drawings.end(),
  2417. [&]( BOARD_ITEM* item )
  2418. {
  2419. if( item->Type() != PCB_SHAPE_T )
  2420. return;
  2421. for( PCB_LAYER_ID layer : item->GetLayerSet() )
  2422. layer_shapes[layer].push_back( static_cast<PCB_SHAPE*>( item ) );
  2423. } );
  2424. for( size_t ii = 0; ii < m_pads.size(); ++ii )
  2425. {
  2426. PAD* pad = m_pads[ ii ];
  2427. bool has_nettie = false;
  2428. auto it = map.find( pad->GetNumber() );
  2429. if( it == map.end() || it->second < 0 )
  2430. continue;
  2431. for( size_t jj = ii + 1; jj < m_pads.size(); ++jj )
  2432. {
  2433. PAD* other = m_pads[ jj ];
  2434. auto it2 = map.find( other->GetNumber() );
  2435. if( it2 == map.end() || it2->second < 0 )
  2436. continue;
  2437. if( it2->second == it->second )
  2438. {
  2439. m_netTieCache[pad].insert( pad->GetNetCode() );
  2440. m_netTieCache[pad].insert( other->GetNetCode() );
  2441. m_netTieCache[other].insert( other->GetNetCode() );
  2442. m_netTieCache[other].insert( pad->GetNetCode() );
  2443. has_nettie = true;
  2444. }
  2445. }
  2446. if( !has_nettie )
  2447. continue;
  2448. for( auto& [ layer, shapes ] : layer_shapes )
  2449. {
  2450. auto pad_shape = pad->GetEffectiveShape( layer );
  2451. for( auto other_shape : shapes )
  2452. {
  2453. auto shape = other_shape->GetEffectiveShape( layer );
  2454. if( pad_shape->Collide( shape.get() ) )
  2455. {
  2456. std::set<int>& nettie = m_netTieCache[pad];
  2457. m_netTieCache[other_shape].insert( nettie.begin(), nettie.end() );
  2458. }
  2459. }
  2460. }
  2461. }
  2462. }
  2463. std::map<wxString, int> FOOTPRINT::MapPadNumbersToNetTieGroups() const
  2464. {
  2465. std::map<wxString, int> padNumberToGroupIdxMap;
  2466. for( const PAD* pad : m_pads )
  2467. padNumberToGroupIdxMap[ pad->GetNumber() ] = -1;
  2468. auto processPad =
  2469. [&]( wxString aPad, int aGroup )
  2470. {
  2471. aPad.Trim( true ).Trim( false );
  2472. if( !aPad.IsEmpty() )
  2473. padNumberToGroupIdxMap[ aPad ] = aGroup;
  2474. };
  2475. for( int ii = 0; ii < (int) m_netTiePadGroups.size(); ++ii )
  2476. {
  2477. wxString group( m_netTiePadGroups[ ii ] );
  2478. bool esc = false;
  2479. wxString pad;
  2480. for( wxUniCharRef ch : group )
  2481. {
  2482. if( esc )
  2483. {
  2484. esc = false;
  2485. pad.Append( ch );
  2486. continue;
  2487. }
  2488. switch( static_cast<unsigned char>( ch ) )
  2489. {
  2490. case '\\':
  2491. esc = true;
  2492. break;
  2493. case ',':
  2494. processPad( pad, ii );
  2495. pad.Clear();
  2496. break;
  2497. default:
  2498. pad.Append( ch );
  2499. break;
  2500. }
  2501. }
  2502. processPad( pad, ii );
  2503. }
  2504. return padNumberToGroupIdxMap;
  2505. }
  2506. std::vector<PAD*> FOOTPRINT::GetNetTiePads( PAD* aPad ) const
  2507. {
  2508. // First build a map from pad numbers to allowed-shorting-group indexes. This ends up being
  2509. // something like O(3n), but it still beats O(n^2) for large numbers of pads.
  2510. std::map<wxString, int> padToNetTieGroupMap = MapPadNumbersToNetTieGroups();
  2511. int groupIdx = padToNetTieGroupMap[ aPad->GetNumber() ];
  2512. std::vector<PAD*> otherPads;
  2513. if( groupIdx >= 0 )
  2514. {
  2515. for( PAD* pad : m_pads )
  2516. {
  2517. if( padToNetTieGroupMap[ pad->GetNumber() ] == groupIdx )
  2518. otherPads.push_back( pad );
  2519. }
  2520. }
  2521. return otherPads;
  2522. }
  2523. void FOOTPRINT::CheckFootprintAttributes( const std::function<void( const wxString& )>& aErrorHandler )
  2524. {
  2525. int likelyAttr = ( GetLikelyAttribute() & ( FP_SMD | FP_THROUGH_HOLE ) );
  2526. int setAttr = ( GetAttributes() & ( FP_SMD | FP_THROUGH_HOLE ) );
  2527. if( setAttr && likelyAttr && setAttr != likelyAttr )
  2528. {
  2529. wxString msg;
  2530. switch( likelyAttr )
  2531. {
  2532. case FP_THROUGH_HOLE:
  2533. msg.Printf( _( "(expected 'Through hole'; actual '%s')" ), GetTypeName() );
  2534. break;
  2535. case FP_SMD:
  2536. msg.Printf( _( "(expected 'SMD'; actual '%s')" ), GetTypeName() );
  2537. break;
  2538. }
  2539. if( aErrorHandler )
  2540. (aErrorHandler)( msg );
  2541. }
  2542. }
  2543. void FOOTPRINT::CheckPads( UNITS_PROVIDER* aUnitsProvider,
  2544. const std::function<void( const PAD*, int,
  2545. const wxString& )>& aErrorHandler )
  2546. {
  2547. if( aErrorHandler == nullptr )
  2548. return;
  2549. for( PAD* pad: Pads() )
  2550. {
  2551. pad->CheckPad( aUnitsProvider, false,
  2552. [&]( int errorCode, const wxString& msg )
  2553. {
  2554. aErrorHandler( pad, errorCode, msg );
  2555. } );
  2556. }
  2557. }
  2558. void FOOTPRINT::CheckShortingPads( const std::function<void( const PAD*, const PAD*,
  2559. int aErrorCode,
  2560. const VECTOR2I& )>& aErrorHandler )
  2561. {
  2562. std::unordered_map<PTR_PTR_CACHE_KEY, int> checkedPairs;
  2563. for( PAD* pad : Pads() )
  2564. {
  2565. std::vector<PAD*> netTiePads = GetNetTiePads( pad );
  2566. for( PAD* other : Pads() )
  2567. {
  2568. if( other == pad )
  2569. continue;
  2570. // store canonical order so we don't collide in both directions (a:b and b:a)
  2571. PAD* a = pad;
  2572. PAD* b = other;
  2573. if( static_cast<void*>( a ) > static_cast<void*>( b ) )
  2574. std::swap( a, b );
  2575. if( checkedPairs.find( { a, b } ) == checkedPairs.end() )
  2576. {
  2577. checkedPairs[ { a, b } ] = 1;
  2578. if( pad->HasDrilledHole() && other->HasDrilledHole() )
  2579. {
  2580. VECTOR2I pos = pad->GetPosition();
  2581. if( pad->GetPosition() == other->GetPosition() )
  2582. {
  2583. aErrorHandler( pad, other, DRCE_DRILLED_HOLES_COLOCATED, pos );
  2584. }
  2585. else
  2586. {
  2587. std::shared_ptr<SHAPE_SEGMENT> holeA = pad->GetEffectiveHoleShape();
  2588. std::shared_ptr<SHAPE_SEGMENT> holeB = other->GetEffectiveHoleShape();
  2589. if( holeA->Collide( holeB->GetSeg(), 0 ) )
  2590. aErrorHandler( pad, other, DRCE_DRILLED_HOLES_TOO_CLOSE, pos );
  2591. }
  2592. }
  2593. if( pad->SameLogicalPadAs( other ) || alg::contains( netTiePads, other ) )
  2594. continue;
  2595. if( !( ( pad->GetLayerSet() & other->GetLayerSet() ) & LSET::AllCuMask() ).any() )
  2596. continue;
  2597. if( pad->GetBoundingBox().Intersects( other->GetBoundingBox() ) )
  2598. {
  2599. VECTOR2I pos;
  2600. for( PCB_LAYER_ID l : pad->Padstack().RelevantShapeLayers( other->Padstack() ) )
  2601. {
  2602. SHAPE* padShape = pad->GetEffectiveShape( l ).get();
  2603. SHAPE* otherShape = other->GetEffectiveShape( l ).get();
  2604. if( padShape->Collide( otherShape, 0, nullptr, &pos ) )
  2605. aErrorHandler( pad, other, DRCE_SHORTING_ITEMS, pos );
  2606. }
  2607. }
  2608. }
  2609. }
  2610. }
  2611. }
  2612. void FOOTPRINT::CheckNetTies( const std::function<void( const BOARD_ITEM* aItem,
  2613. const BOARD_ITEM* bItem,
  2614. const BOARD_ITEM* cItem,
  2615. const VECTOR2I& )>& aErrorHandler )
  2616. {
  2617. // First build a map from pad numbers to allowed-shorting-group indexes. This ends up being
  2618. // something like O(3n), but it still beats O(n^2) for large numbers of pads.
  2619. std::map<wxString, int> padNumberToGroupIdxMap = MapPadNumbersToNetTieGroups();
  2620. // Now collect all the footprint items which are on copper layers
  2621. std::vector<BOARD_ITEM*> copperItems;
  2622. for( BOARD_ITEM* item : m_drawings )
  2623. {
  2624. if( item->IsOnCopperLayer() )
  2625. copperItems.push_back( item );
  2626. item->RunOnDescendants(
  2627. [&]( BOARD_ITEM* descendent )
  2628. {
  2629. if( descendent->IsOnCopperLayer() )
  2630. copperItems.push_back( descendent );
  2631. } );
  2632. }
  2633. for( ZONE* zone : m_zones )
  2634. {
  2635. if( !zone->GetIsRuleArea() && zone->IsOnCopperLayer() )
  2636. copperItems.push_back( zone );
  2637. }
  2638. for( PCB_FIELD* field : m_fields )
  2639. {
  2640. if( field->IsOnCopperLayer() )
  2641. copperItems.push_back( field );
  2642. }
  2643. for( PCB_LAYER_ID layer : { F_Cu, In1_Cu, B_Cu } )
  2644. {
  2645. // Next, build a polygon-set for the copper on this layer. We don't really care about
  2646. // nets here, we just want to end up with a set of outlines describing the distinct
  2647. // copper polygons of the footprint.
  2648. SHAPE_POLY_SET copperOutlines;
  2649. std::map<int, std::vector<const PAD*>> outlineIdxToPadsMap;
  2650. for( BOARD_ITEM* item : copperItems )
  2651. {
  2652. if( item->IsOnLayer( layer ) )
  2653. {
  2654. item->TransformShapeToPolygon( copperOutlines, layer, 0, ARC_HIGH_DEF,
  2655. ERROR_OUTSIDE );
  2656. }
  2657. }
  2658. copperOutlines.Simplify();
  2659. // Index each pad to the outline in the set that it is part of.
  2660. for( const PAD* pad : m_pads )
  2661. {
  2662. for( int ii = 0; ii < copperOutlines.OutlineCount(); ++ii )
  2663. {
  2664. if( pad->GetEffectiveShape( layer )->Collide( &copperOutlines.Outline( ii ), 0 ) )
  2665. outlineIdxToPadsMap[ ii ].emplace_back( pad );
  2666. }
  2667. }
  2668. // Finally, ensure that each outline which contains multiple pads has all its pads
  2669. // listed in an allowed-shorting group.
  2670. for( const auto& [ outlineIdx, pads ] : outlineIdxToPadsMap )
  2671. {
  2672. if( pads.size() > 1 )
  2673. {
  2674. const PAD* firstPad = pads[0];
  2675. int firstGroupIdx = padNumberToGroupIdxMap[ firstPad->GetNumber() ];
  2676. for( size_t ii = 1; ii < pads.size(); ++ii )
  2677. {
  2678. const PAD* thisPad = pads[ii];
  2679. int thisGroupIdx = padNumberToGroupIdxMap[ thisPad->GetNumber() ];
  2680. if( thisGroupIdx < 0 || thisGroupIdx != firstGroupIdx )
  2681. {
  2682. BOARD_ITEM* shortingItem = nullptr;
  2683. VECTOR2I pos = ( firstPad->GetPosition() + thisPad->GetPosition() ) / 2;
  2684. pos = copperOutlines.Outline( outlineIdx ).NearestPoint( pos );
  2685. for( BOARD_ITEM* item : copperItems )
  2686. {
  2687. if( item->HitTest( pos, 1 ) )
  2688. {
  2689. shortingItem = item;
  2690. break;
  2691. }
  2692. }
  2693. if( shortingItem )
  2694. aErrorHandler( shortingItem, firstPad, thisPad, pos );
  2695. else
  2696. aErrorHandler( firstPad, thisPad, nullptr, pos );
  2697. }
  2698. }
  2699. }
  2700. }
  2701. }
  2702. }
  2703. void FOOTPRINT::CheckNetTiePadGroups( const std::function<void( const wxString& )>& aErrorHandler )
  2704. {
  2705. std::set<wxString> padNumbers;
  2706. wxString msg;
  2707. for( const auto& [ padNumber, _ ] : MapPadNumbersToNetTieGroups() )
  2708. {
  2709. const PAD* pad = FindPadByNumber( padNumber );
  2710. if( !pad )
  2711. {
  2712. msg.Printf( _( "(net-tie pad group contains unknown pad number %s)" ), padNumber );
  2713. aErrorHandler( msg );
  2714. }
  2715. else if( !padNumbers.insert( pad->GetNumber() ).second )
  2716. {
  2717. msg.Printf( _( "(pad %s appears in more than one net-tie pad group)" ), padNumber );
  2718. aErrorHandler( msg );
  2719. }
  2720. }
  2721. }
  2722. void FOOTPRINT::CheckClippedSilk( const std::function<void( BOARD_ITEM* aItemA,
  2723. BOARD_ITEM* aItemB,
  2724. const VECTOR2I& aPt )>& aErrorHandler )
  2725. {
  2726. auto checkColliding =
  2727. [&]( BOARD_ITEM* item, BOARD_ITEM* other )
  2728. {
  2729. for( PCB_LAYER_ID silk : { F_SilkS, B_SilkS } )
  2730. {
  2731. PCB_LAYER_ID mask = silk == F_SilkS ? F_Mask : B_Mask;
  2732. if( !item->IsOnLayer( silk ) || !other->IsOnLayer( mask ) )
  2733. continue;
  2734. std::shared_ptr<SHAPE> itemShape = item->GetEffectiveShape( silk );
  2735. std::shared_ptr<SHAPE> otherShape = other->GetEffectiveShape( mask );
  2736. int actual;
  2737. VECTOR2I pos;
  2738. if( itemShape->Collide( otherShape.get(), 0, &actual, &pos ) )
  2739. aErrorHandler( item, other, pos );
  2740. }
  2741. };
  2742. for( BOARD_ITEM* item : m_drawings )
  2743. {
  2744. for( BOARD_ITEM* other : m_drawings )
  2745. {
  2746. if( other != item )
  2747. checkColliding( item, other );
  2748. }
  2749. for( PAD* pad : m_pads )
  2750. checkColliding( item, pad );
  2751. }
  2752. }
  2753. void FOOTPRINT::swapData( BOARD_ITEM* aImage )
  2754. {
  2755. wxASSERT( aImage->Type() == PCB_FOOTPRINT_T );
  2756. FOOTPRINT* image = static_cast<FOOTPRINT*>( aImage );
  2757. std::swap( *this, *image );
  2758. RunOnChildren(
  2759. [&]( BOARD_ITEM* child )
  2760. {
  2761. child->SetParent( this );
  2762. } );
  2763. image->RunOnChildren(
  2764. [&]( BOARD_ITEM* child )
  2765. {
  2766. child->SetParent( image );
  2767. } );
  2768. }
  2769. bool FOOTPRINT::HasThroughHolePads() const
  2770. {
  2771. for( PAD* pad : Pads() )
  2772. {
  2773. if( pad->GetAttribute() != PAD_ATTRIB::SMD )
  2774. return true;
  2775. }
  2776. return false;
  2777. }
  2778. bool FOOTPRINT::operator==( const BOARD_ITEM& aOther ) const
  2779. {
  2780. if( aOther.Type() != PCB_FOOTPRINT_T )
  2781. return false;
  2782. const FOOTPRINT& other = static_cast<const FOOTPRINT&>( aOther );
  2783. return *this == other;
  2784. }
  2785. bool FOOTPRINT::operator==( const FOOTPRINT& aOther ) const
  2786. {
  2787. if( m_pads.size() != aOther.m_pads.size() )
  2788. return false;
  2789. for( size_t ii = 0; ii < m_pads.size(); ++ii )
  2790. {
  2791. if( !( *m_pads[ii] == *aOther.m_pads[ii] ) )
  2792. return false;
  2793. }
  2794. if( m_drawings.size() != aOther.m_drawings.size() )
  2795. return false;
  2796. for( size_t ii = 0; ii < m_drawings.size(); ++ii )
  2797. {
  2798. if( !( *m_drawings[ii] == *aOther.m_drawings[ii] ) )
  2799. return false;
  2800. }
  2801. if( m_zones.size() != aOther.m_zones.size() )
  2802. return false;
  2803. for( size_t ii = 0; ii < m_zones.size(); ++ii )
  2804. {
  2805. if( !( *m_zones[ii] == *aOther.m_zones[ii] ) )
  2806. return false;
  2807. }
  2808. // Compare fields in ordinally-sorted order
  2809. std::vector<PCB_FIELD*> fields, otherFields;
  2810. GetFields( fields, false );
  2811. aOther.GetFields( otherFields, false );
  2812. if( fields.size() != otherFields.size() )
  2813. return false;
  2814. for( size_t ii = 0; ii < fields.size(); ++ii )
  2815. {
  2816. if( fields[ii] )
  2817. {
  2818. if( !( *fields[ii] == *otherFields[ii] ) )
  2819. return false;
  2820. }
  2821. }
  2822. return true;
  2823. }
  2824. double FOOTPRINT::Similarity( const BOARD_ITEM& aOther ) const
  2825. {
  2826. if( aOther.Type() != PCB_FOOTPRINT_T )
  2827. return 0.0;
  2828. const FOOTPRINT& other = static_cast<const FOOTPRINT&>( aOther );
  2829. double similarity = 1.0;
  2830. for( const PAD* pad : m_pads)
  2831. {
  2832. const PAD* otherPad = other.FindPadByNumber( pad->GetNumber() );
  2833. if( !otherPad )
  2834. continue;
  2835. similarity *= pad->Similarity( *otherPad );
  2836. }
  2837. return similarity;
  2838. }
  2839. bool FOOTPRINT::cmp_drawings::operator()( const BOARD_ITEM* itemA, const BOARD_ITEM* itemB ) const
  2840. {
  2841. if( itemA->Type() != itemB->Type() )
  2842. return itemA->Type() < itemB->Type();
  2843. if( itemA->GetLayer() != itemB->GetLayer() )
  2844. return itemA->GetLayer() < itemB->GetLayer();
  2845. if( itemA->Type() == PCB_SHAPE_T )
  2846. {
  2847. const PCB_SHAPE* dwgA = static_cast<const PCB_SHAPE*>( itemA );
  2848. const PCB_SHAPE* dwgB = static_cast<const PCB_SHAPE*>( itemB );
  2849. if( dwgA->GetShape() != dwgB->GetShape() )
  2850. return dwgA->GetShape() < dwgB->GetShape();
  2851. // GetStart() and GetEnd() have no meaning with polygons.
  2852. // We cannot use them for sorting polygons
  2853. if( dwgA->GetShape() != SHAPE_T::POLY )
  2854. {
  2855. if( dwgA->GetStart().x != dwgB->GetStart().x )
  2856. return dwgA->GetStart().x < dwgB->GetStart().x;
  2857. if( dwgA->GetStart().y != dwgB->GetStart().y )
  2858. return dwgA->GetStart().y < dwgB->GetStart().y;
  2859. if( dwgA->GetEnd().x != dwgB->GetEnd().x )
  2860. return dwgA->GetEnd().x < dwgB->GetEnd().x;
  2861. if( dwgA->GetEnd().y != dwgB->GetEnd().y )
  2862. return dwgA->GetEnd().y < dwgB->GetEnd().y;
  2863. }
  2864. if( dwgA->GetShape() == SHAPE_T::ARC )
  2865. {
  2866. if( dwgA->GetCenter().x != dwgB->GetCenter().x )
  2867. return dwgA->GetCenter().x < dwgB->GetCenter().x;
  2868. if( dwgA->GetCenter().y != dwgB->GetCenter().y )
  2869. return dwgA->GetCenter().y < dwgB->GetCenter().y;
  2870. }
  2871. else if( dwgA->GetShape() == SHAPE_T::BEZIER )
  2872. {
  2873. if( dwgA->GetBezierC1().x != dwgB->GetBezierC1().x )
  2874. return dwgA->GetBezierC1().x < dwgB->GetBezierC1().x;
  2875. if( dwgA->GetBezierC1().y != dwgB->GetBezierC1().y )
  2876. return dwgA->GetBezierC1().y < dwgB->GetBezierC1().y;
  2877. if( dwgA->GetBezierC2().x != dwgB->GetBezierC2().x )
  2878. return dwgA->GetBezierC2().x < dwgB->GetBezierC2().x;
  2879. if( dwgA->GetBezierC2().y != dwgB->GetBezierC2().y )
  2880. return dwgA->GetBezierC2().y < dwgB->GetBezierC2().y;
  2881. }
  2882. else if( dwgA->GetShape() == SHAPE_T::POLY )
  2883. {
  2884. if( dwgA->GetPolyShape().TotalVertices() != dwgB->GetPolyShape().TotalVertices() )
  2885. return dwgA->GetPolyShape().TotalVertices() < dwgB->GetPolyShape().TotalVertices();
  2886. for( int ii = 0; ii < dwgA->GetPolyShape().TotalVertices(); ++ii )
  2887. {
  2888. if( dwgA->GetPolyShape().CVertex( ii ).x != dwgB->GetPolyShape().CVertex( ii ).x )
  2889. return dwgA->GetPolyShape().CVertex( ii ).x
  2890. < dwgB->GetPolyShape().CVertex( ii ).x;
  2891. if( dwgA->GetPolyShape().CVertex( ii ).y != dwgB->GetPolyShape().CVertex( ii ).y )
  2892. return dwgA->GetPolyShape().CVertex( ii ).y
  2893. < dwgB->GetPolyShape().CVertex( ii ).y;
  2894. }
  2895. }
  2896. if( dwgA->GetWidth() != dwgB->GetWidth() )
  2897. return dwgA->GetWidth() < dwgB->GetWidth();
  2898. }
  2899. if( itemA->m_Uuid != itemB->m_Uuid )
  2900. return itemA->m_Uuid < itemB->m_Uuid;
  2901. return itemA < itemB;
  2902. }
  2903. bool FOOTPRINT::cmp_pads::operator()( const PAD* aFirst, const PAD* aSecond ) const
  2904. {
  2905. if( aFirst->GetNumber() != aSecond->GetNumber() )
  2906. return StrNumCmp( aFirst->GetNumber(), aSecond->GetNumber() ) < 0;
  2907. if( aFirst->GetFPRelativePosition().x != aSecond->GetFPRelativePosition().x )
  2908. return aFirst->GetFPRelativePosition().x < aSecond->GetFPRelativePosition().x;
  2909. if( aFirst->GetFPRelativePosition().y != aSecond->GetFPRelativePosition().y )
  2910. return aFirst->GetFPRelativePosition().y < aSecond->GetFPRelativePosition().y;
  2911. std::optional<bool> padCopperMatches;
  2912. // Pick the "most complex" padstack to iterate
  2913. const PAD* checkPad = aFirst;
  2914. if( aSecond->Padstack().Mode() == PADSTACK::MODE::CUSTOM
  2915. || ( aSecond->Padstack().Mode() == PADSTACK::MODE::FRONT_INNER_BACK &&
  2916. aFirst->Padstack().Mode() == PADSTACK::MODE::NORMAL ) )
  2917. {
  2918. checkPad = aSecond;
  2919. }
  2920. checkPad->Padstack().ForEachUniqueLayer(
  2921. [&]( PCB_LAYER_ID aLayer )
  2922. {
  2923. if( aFirst->GetSize( aLayer ).x != aSecond->GetSize( aLayer ).x )
  2924. padCopperMatches = aFirst->GetSize( aLayer ).x < aSecond->GetSize( aLayer ).x;
  2925. else if( aFirst->GetSize( aLayer ).y != aSecond->GetSize( aLayer ).y )
  2926. padCopperMatches = aFirst->GetSize( aLayer ).y < aSecond->GetSize( aLayer ).y;
  2927. else if( aFirst->GetShape( aLayer ) != aSecond->GetShape( aLayer ) )
  2928. padCopperMatches = aFirst->GetShape( aLayer ) < aSecond->GetShape( aLayer );
  2929. } );
  2930. if( padCopperMatches.has_value() )
  2931. return *padCopperMatches;
  2932. if( aFirst->GetLayerSet().Seq() != aSecond->GetLayerSet().Seq() )
  2933. return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();
  2934. if( aFirst->m_Uuid != aSecond->m_Uuid )
  2935. return aFirst->m_Uuid < aSecond->m_Uuid;
  2936. return aFirst < aSecond;
  2937. }
  2938. #if 0
  2939. bool FOOTPRINT::cmp_padstack::operator()( const PAD* aFirst, const PAD* aSecond ) const
  2940. {
  2941. if( aFirst->GetSize().x != aSecond->GetSize().x )
  2942. return aFirst->GetSize().x < aSecond->GetSize().x;
  2943. if( aFirst->GetSize().y != aSecond->GetSize().y )
  2944. return aFirst->GetSize().y < aSecond->GetSize().y;
  2945. if( aFirst->GetShape() != aSecond->GetShape() )
  2946. return aFirst->GetShape() < aSecond->GetShape();
  2947. if( aFirst->GetLayerSet().Seq() != aSecond->GetLayerSet().Seq() )
  2948. return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();
  2949. if( aFirst->GetDrillSizeX() != aSecond->GetDrillSizeX() )
  2950. return aFirst->GetDrillSizeX() < aSecond->GetDrillSizeX();
  2951. if( aFirst->GetDrillSizeY() != aSecond->GetDrillSizeY() )
  2952. return aFirst->GetDrillSizeY() < aSecond->GetDrillSizeY();
  2953. if( aFirst->GetDrillShape() != aSecond->GetDrillShape() )
  2954. return aFirst->GetDrillShape() < aSecond->GetDrillShape();
  2955. if( aFirst->GetAttribute() != aSecond->GetAttribute() )
  2956. return aFirst->GetAttribute() < aSecond->GetAttribute();
  2957. if( aFirst->GetOrientation() != aSecond->GetOrientation() )
  2958. return aFirst->GetOrientation() < aSecond->GetOrientation();
  2959. if( aFirst->GetSolderMaskExpansion() != aSecond->GetSolderMaskExpansion() )
  2960. return aFirst->GetSolderMaskExpansion() < aSecond->GetSolderMaskExpansion();
  2961. if( aFirst->GetSolderPasteMargin() != aSecond->GetSolderPasteMargin() )
  2962. return aFirst->GetSolderPasteMargin() < aSecond->GetSolderPasteMargin();
  2963. if( aFirst->GetLocalSolderMaskMargin() != aSecond->GetLocalSolderMaskMargin() )
  2964. return aFirst->GetLocalSolderMaskMargin() < aSecond->GetLocalSolderMaskMargin();
  2965. const std::shared_ptr<SHAPE_POLY_SET>& firstShape = aFirst->GetEffectivePolygon( ERROR_INSIDE );
  2966. const std::shared_ptr<SHAPE_POLY_SET>& secondShape = aSecond->GetEffectivePolygon( ERROR_INSIDE );
  2967. if( firstShape->VertexCount() != secondShape->VertexCount() )
  2968. return firstShape->VertexCount() < secondShape->VertexCount();
  2969. for( int ii = 0; ii < firstShape->VertexCount(); ++ii )
  2970. {
  2971. if( firstShape->CVertex( ii ).x != secondShape->CVertex( ii ).x )
  2972. return firstShape->CVertex( ii ).x < secondShape->CVertex( ii ).x;
  2973. if( firstShape->CVertex( ii ).y != secondShape->CVertex( ii ).y )
  2974. return firstShape->CVertex( ii ).y < secondShape->CVertex( ii ).y;
  2975. }
  2976. return false;
  2977. }
  2978. #endif
  2979. bool FOOTPRINT::cmp_zones::operator()( const ZONE* aFirst, const ZONE* aSecond ) const
  2980. {
  2981. if( aFirst->GetAssignedPriority() != aSecond->GetAssignedPriority() )
  2982. return aFirst->GetAssignedPriority() < aSecond->GetAssignedPriority();
  2983. if( aFirst->GetLayerSet().Seq() != aSecond->GetLayerSet().Seq() )
  2984. return aFirst->GetLayerSet().Seq() < aSecond->GetLayerSet().Seq();
  2985. if( aFirst->Outline()->TotalVertices() != aSecond->Outline()->TotalVertices() )
  2986. return aFirst->Outline()->TotalVertices() < aSecond->Outline()->TotalVertices();
  2987. for( int ii = 0; ii < aFirst->Outline()->TotalVertices(); ++ii )
  2988. {
  2989. if( aFirst->Outline()->CVertex( ii ).x != aSecond->Outline()->CVertex( ii ).x )
  2990. return aFirst->Outline()->CVertex( ii ).x < aSecond->Outline()->CVertex( ii ).x;
  2991. if( aFirst->Outline()->CVertex( ii ).y != aSecond->Outline()->CVertex( ii ).y )
  2992. return aFirst->Outline()->CVertex( ii ).y < aSecond->Outline()->CVertex( ii ).y;
  2993. }
  2994. if( aFirst->m_Uuid != aSecond->m_Uuid )
  2995. return aFirst->m_Uuid < aSecond->m_Uuid;
  2996. return aFirst < aSecond;
  2997. }
  2998. void FOOTPRINT::TransformPadsToPolySet( SHAPE_POLY_SET& aBuffer, PCB_LAYER_ID aLayer,
  2999. int aClearance, int aMaxError, ERROR_LOC aErrorLoc,
  3000. bool aSkipNPTHPadsWihNoCopper, bool aSkipPlatedPads,
  3001. bool aSkipNonPlatedPads ) const
  3002. {
  3003. auto processPad =
  3004. [&]( const PAD* pad, PCB_LAYER_ID padLayer )
  3005. {
  3006. VECTOR2I clearance( aClearance, aClearance );
  3007. switch( aLayer )
  3008. {
  3009. case F_Cu:
  3010. if( aSkipPlatedPads && pad->FlashLayer( F_Mask ) )
  3011. return;
  3012. if( aSkipNonPlatedPads && !pad->FlashLayer( F_Mask ) )
  3013. return;
  3014. break;
  3015. case B_Cu:
  3016. if( aSkipPlatedPads && pad->FlashLayer( B_Mask ) )
  3017. return;
  3018. if( aSkipNonPlatedPads && !pad->FlashLayer( B_Mask ) )
  3019. return;
  3020. break;
  3021. case F_Mask:
  3022. case B_Mask:
  3023. clearance.x += pad->GetSolderMaskExpansion( padLayer );
  3024. clearance.y += pad->GetSolderMaskExpansion( padLayer );
  3025. break;
  3026. case F_Paste:
  3027. case B_Paste:
  3028. clearance += pad->GetSolderPasteMargin( padLayer );
  3029. break;
  3030. default:
  3031. break;
  3032. }
  3033. // Our standard TransformShapeToPolygon() routines can't handle differing x:y clearance
  3034. // values (which get generated when a relative paste margin is used with an oblong pad).
  3035. // So we apply this huge hack and fake a larger pad to run the transform on.
  3036. // Of course being a hack it falls down when dealing with custom shape pads (where the
  3037. // size is only the size of the anchor), so for those we punt and just use clearance.x.
  3038. if( ( clearance.x < 0 || clearance.x != clearance.y )
  3039. && pad->GetShape( padLayer ) != PAD_SHAPE::CUSTOM )
  3040. {
  3041. VECTOR2I dummySize = pad->GetSize( padLayer ) + clearance + clearance;
  3042. if( dummySize.x <= 0 || dummySize.y <= 0 )
  3043. return;
  3044. PAD dummy( *pad );
  3045. dummy.SetSize( padLayer, dummySize );
  3046. dummy.TransformShapeToPolygon( aBuffer, padLayer, 0, aMaxError, aErrorLoc );
  3047. }
  3048. else
  3049. {
  3050. pad->TransformShapeToPolygon( aBuffer, padLayer, clearance.x, aMaxError,
  3051. aErrorLoc );
  3052. }
  3053. };
  3054. for( const PAD* pad : m_pads )
  3055. {
  3056. if( !pad->FlashLayer( aLayer ) )
  3057. continue;
  3058. if( aLayer == UNDEFINED_LAYER )
  3059. {
  3060. pad->Padstack().ForEachUniqueLayer(
  3061. [&]( PCB_LAYER_ID l )
  3062. {
  3063. processPad( pad, l );
  3064. } );
  3065. }
  3066. else
  3067. {
  3068. processPad( pad, aLayer );
  3069. }
  3070. }
  3071. }
  3072. void FOOTPRINT::TransformFPShapesToPolySet( SHAPE_POLY_SET& aBuffer, PCB_LAYER_ID aLayer,
  3073. int aClearance, int aError, ERROR_LOC aErrorLoc,
  3074. bool aIncludeText, bool aIncludeShapes,
  3075. bool aIncludePrivateItems ) const
  3076. {
  3077. for( BOARD_ITEM* item : GraphicalItems() )
  3078. {
  3079. if( GetPrivateLayers().test( item->GetLayer() ) && !aIncludePrivateItems )
  3080. continue;
  3081. if( item->Type() == PCB_TEXT_T && aIncludeText )
  3082. {
  3083. PCB_TEXT* text = static_cast<PCB_TEXT*>( item );
  3084. if( aLayer != UNDEFINED_LAYER && text->GetLayer() == aLayer )
  3085. text->TransformTextToPolySet( aBuffer, aClearance, aError, aErrorLoc );
  3086. }
  3087. if( item->Type() == PCB_TEXTBOX_T && aIncludeText )
  3088. {
  3089. PCB_TEXTBOX* textbox = static_cast<PCB_TEXTBOX*>( item );
  3090. if( aLayer != UNDEFINED_LAYER && textbox->GetLayer() == aLayer )
  3091. {
  3092. // border
  3093. if( textbox->IsBorderEnabled() )
  3094. {
  3095. textbox->PCB_SHAPE::TransformShapeToPolygon( aBuffer, aLayer, 0, aError,
  3096. aErrorLoc );
  3097. }
  3098. // text
  3099. textbox->TransformTextToPolySet( aBuffer, 0, aError, aErrorLoc );
  3100. }
  3101. }
  3102. if( item->Type() == PCB_SHAPE_T && aIncludeShapes )
  3103. {
  3104. const PCB_SHAPE* shape = static_cast<PCB_SHAPE*>( item );
  3105. if( aLayer != UNDEFINED_LAYER && shape->GetLayer() == aLayer )
  3106. shape->TransformShapeToPolySet( aBuffer, aLayer, 0, aError, aErrorLoc );
  3107. }
  3108. }
  3109. if( aIncludeText )
  3110. {
  3111. for( const PCB_FIELD* field : m_fields )
  3112. {
  3113. if( field->GetLayer() == aLayer && field->IsVisible() )
  3114. field->TransformTextToPolySet( aBuffer, aClearance, aError, aErrorLoc );
  3115. }
  3116. }
  3117. }
  3118. std::set<KIFONT::OUTLINE_FONT*> FOOTPRINT::GetFonts() const
  3119. {
  3120. using OUTLINE_FONT = KIFONT::OUTLINE_FONT;
  3121. using EMBEDDING_PERMISSION = OUTLINE_FONT::EMBEDDING_PERMISSION;
  3122. std::set<OUTLINE_FONT*> fonts;
  3123. for( BOARD_ITEM* item : GraphicalItems() )
  3124. {
  3125. if( auto* text = dynamic_cast<EDA_TEXT*>( item ) )
  3126. {
  3127. if( auto* font = text->GetFont(); font && !font->IsStroke() )
  3128. {
  3129. auto* outline = static_cast<OUTLINE_FONT*>( font );
  3130. auto permission = outline->GetEmbeddingPermission();
  3131. if( permission == EMBEDDING_PERMISSION::EDITABLE
  3132. || permission == EMBEDDING_PERMISSION::INSTALLABLE )
  3133. {
  3134. fonts.insert( outline );
  3135. }
  3136. }
  3137. }
  3138. }
  3139. return fonts;
  3140. }
  3141. void FOOTPRINT::EmbedFonts()
  3142. {
  3143. std::set<KIFONT::OUTLINE_FONT*> fonts = GetFonts();
  3144. for( auto* font : fonts )
  3145. {
  3146. auto file = GetEmbeddedFiles()->AddFile( font->GetFileName(), false );
  3147. file->type = EMBEDDED_FILES::EMBEDDED_FILE::FILE_TYPE::FONT;
  3148. }
  3149. }
  3150. void FOOTPRINT::SetStaticComponentClass( const COMPONENT_CLASS* aClass ) const
  3151. {
  3152. m_componentClassCacheProxy->SetStaticComponentClass( aClass );
  3153. }
  3154. const COMPONENT_CLASS* FOOTPRINT::GetStaticComponentClass() const
  3155. {
  3156. return m_componentClassCacheProxy->GetStaticComponentClass();
  3157. }
  3158. void FOOTPRINT::RecomputeComponentClass() const
  3159. {
  3160. m_componentClassCacheProxy->RecomputeComponentClass();
  3161. }
  3162. const COMPONENT_CLASS* FOOTPRINT::GetComponentClass() const
  3163. {
  3164. return m_componentClassCacheProxy->GetComponentClass();
  3165. }
  3166. wxString FOOTPRINT::GetComponentClassAsString() const
  3167. {
  3168. if( !m_componentClassCacheProxy->GetComponentClass()->IsEmpty() )
  3169. {
  3170. return m_componentClassCacheProxy->GetComponentClass()->GetName();
  3171. }
  3172. return wxEmptyString;
  3173. }
  3174. void FOOTPRINT::ResolveComponentClassNames(
  3175. BOARD* aBoard, const std::unordered_set<wxString>& aComponentClassNames )
  3176. {
  3177. const COMPONENT_CLASS* componentClass =
  3178. aBoard->GetComponentClassManager().GetEffectiveStaticComponentClass(
  3179. aComponentClassNames );
  3180. SetStaticComponentClass( componentClass );
  3181. }
  3182. void FOOTPRINT::InvalidateComponentClassCache() const
  3183. {
  3184. m_componentClassCacheProxy->InvalidateCache();
  3185. }
  3186. static struct FOOTPRINT_DESC
  3187. {
  3188. FOOTPRINT_DESC()
  3189. {
  3190. ENUM_MAP<ZONE_CONNECTION>& zcMap = ENUM_MAP<ZONE_CONNECTION>::Instance();
  3191. if( zcMap.Choices().GetCount() == 0 )
  3192. {
  3193. zcMap.Undefined( ZONE_CONNECTION::INHERITED );
  3194. zcMap.Map( ZONE_CONNECTION::INHERITED, _HKI( "Inherited" ) )
  3195. .Map( ZONE_CONNECTION::NONE, _HKI( "None" ) )
  3196. .Map( ZONE_CONNECTION::THERMAL, _HKI( "Thermal reliefs" ) )
  3197. .Map( ZONE_CONNECTION::FULL, _HKI( "Solid" ) )
  3198. .Map( ZONE_CONNECTION::THT_THERMAL, _HKI( "Thermal reliefs for PTH" ) );
  3199. }
  3200. ENUM_MAP<PCB_LAYER_ID>& layerEnum = ENUM_MAP<PCB_LAYER_ID>::Instance();
  3201. if( layerEnum.Choices().GetCount() == 0 )
  3202. {
  3203. layerEnum.Undefined( UNDEFINED_LAYER );
  3204. for( PCB_LAYER_ID layer : LSET::AllLayersMask().Seq() )
  3205. layerEnum.Map( layer, LSET::Name( layer ) );
  3206. }
  3207. wxPGChoices fpLayers; // footprints might be placed only on F.Cu & B.Cu
  3208. fpLayers.Add( LSET::Name( F_Cu ), F_Cu );
  3209. fpLayers.Add( LSET::Name( B_Cu ), B_Cu );
  3210. PROPERTY_MANAGER& propMgr = PROPERTY_MANAGER::Instance();
  3211. REGISTER_TYPE( FOOTPRINT );
  3212. propMgr.AddTypeCast( new TYPE_CAST<FOOTPRINT, BOARD_ITEM> );
  3213. propMgr.AddTypeCast( new TYPE_CAST<FOOTPRINT, BOARD_ITEM_CONTAINER> );
  3214. propMgr.InheritsAfter( TYPE_HASH( FOOTPRINT ), TYPE_HASH( BOARD_ITEM ) );
  3215. propMgr.InheritsAfter( TYPE_HASH( FOOTPRINT ), TYPE_HASH( BOARD_ITEM_CONTAINER ) );
  3216. auto layer = new PROPERTY_ENUM<FOOTPRINT, PCB_LAYER_ID>( _HKI( "Layer" ),
  3217. &FOOTPRINT::SetLayerAndFlip, &FOOTPRINT::GetLayer );
  3218. layer->SetChoices( fpLayers );
  3219. propMgr.ReplaceProperty( TYPE_HASH( BOARD_ITEM ), _HKI( "Layer" ), layer );
  3220. propMgr.AddProperty( new PROPERTY<FOOTPRINT, double>( _HKI( "Orientation" ),
  3221. &FOOTPRINT::SetOrientationDegrees, &FOOTPRINT::GetOrientationDegrees,
  3222. PROPERTY_DISPLAY::PT_DEGREE ) );
  3223. const wxString groupFields = _HKI( "Fields" );
  3224. propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Reference" ),
  3225. &FOOTPRINT::SetReference, &FOOTPRINT::GetReferenceAsString ),
  3226. groupFields );
  3227. propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Value" ),
  3228. &FOOTPRINT::SetValue, &FOOTPRINT::GetValueAsString ),
  3229. groupFields );
  3230. propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Library Link" ),
  3231. NO_SETTER( FOOTPRINT, wxString ), &FOOTPRINT::GetFPIDAsString ),
  3232. groupFields );
  3233. propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Library Description" ),
  3234. NO_SETTER( FOOTPRINT, wxString ), &FOOTPRINT::GetLibDescription ),
  3235. groupFields );
  3236. propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>( _HKI( "Keywords" ),
  3237. NO_SETTER( FOOTPRINT, wxString ), &FOOTPRINT::GetKeywords ),
  3238. groupFields );
  3239. // Note: Also used by DRC engine
  3240. propMgr.AddProperty( new PROPERTY<FOOTPRINT, wxString>(
  3241. _HKI( "Component Class" ), NO_SETTER( FOOTPRINT, wxString ),
  3242. &FOOTPRINT::GetComponentClassAsString ), groupFields )
  3243. .SetIsHiddenFromLibraryEditors();
  3244. const wxString groupAttributes = _HKI( "Attributes" );
  3245. propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Not in Schematic" ),
  3246. &FOOTPRINT::SetBoardOnly, &FOOTPRINT::IsBoardOnly ), groupAttributes );
  3247. propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exclude From Position Files" ),
  3248. &FOOTPRINT::SetExcludedFromPosFiles, &FOOTPRINT::IsExcludedFromPosFiles ),
  3249. groupAttributes );
  3250. propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Exclude From Bill of Materials" ),
  3251. &FOOTPRINT::SetExcludedFromBOM, &FOOTPRINT::IsExcludedFromBOM ),
  3252. groupAttributes );
  3253. propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>( _HKI( "Do not Populate" ),
  3254. &FOOTPRINT::SetDNP, &FOOTPRINT::IsDNP ),
  3255. groupAttributes );
  3256. const wxString groupOverrides = _HKI( "Overrides" );
  3257. propMgr.AddProperty( new PROPERTY<FOOTPRINT, bool>(
  3258. _HKI( "Exempt From Courtyard Requirement" ),
  3259. &FOOTPRINT::SetAllowMissingCourtyard, &FOOTPRINT::AllowMissingCourtyard ),
  3260. groupOverrides );
  3261. propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<int>>(
  3262. _HKI( "Clearance Override" ),
  3263. &FOOTPRINT::SetLocalClearance, &FOOTPRINT::GetLocalClearance,
  3264. PROPERTY_DISPLAY::PT_SIZE ),
  3265. groupOverrides );
  3266. propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<int>>(
  3267. _HKI( "Solderpaste Margin Override" ),
  3268. &FOOTPRINT::SetLocalSolderPasteMargin, &FOOTPRINT::GetLocalSolderPasteMargin,
  3269. PROPERTY_DISPLAY::PT_SIZE ),
  3270. groupOverrides );
  3271. propMgr.AddProperty( new PROPERTY<FOOTPRINT, std::optional<double>>(
  3272. _HKI( "Solderpaste Margin Ratio Override" ),
  3273. &FOOTPRINT::SetLocalSolderPasteMarginRatio,
  3274. &FOOTPRINT::GetLocalSolderPasteMarginRatio,
  3275. PROPERTY_DISPLAY::PT_RATIO ),
  3276. groupOverrides );
  3277. propMgr.AddProperty( new PROPERTY_ENUM<FOOTPRINT, ZONE_CONNECTION>(
  3278. _HKI( "Zone Connection Style" ),
  3279. &FOOTPRINT::SetLocalZoneConnection, &FOOTPRINT::GetLocalZoneConnection ),
  3280. groupOverrides );
  3281. }
  3282. } _FOOTPRINT_DESC;