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.

1644 lines
61 KiB

Clean up arc/circle polygonization. 1) For a while now we've been using a calculated seg count from a given maxError, and a correction factor to push the radius out so that all the error is outside the arc/circle. However, the second calculation (which pre-dates the first) is pretty much just the inverse of the first (and yields nothing more than maxError back). This is particularly sub-optimal given the cost of trig functions. 2) There are a lot of old optimizations to reduce segcounts in certain situations, someting that our error-based calculation compensates for anyway. (Smaller radii need fewer segments to meet the maxError condition.) But perhaps more importantly we now surface maxError in the UI and we don't really want to call it "Max deviation except when it's not". 3) We were also clamping the segCount twice: once in the calculation routine and once in most of it's callers. Furthermore, the caller clamping was inconsistent (both in being done and in the clamping value). We now clamp only in the calculation routine. 4) There's no reason to use the correction factors in the 3Dviewer; it's just a visualization and whether the polygonization error is inside or outside the shape isn't really material. 5) The arc-correction-disabling stuff (used for solder mask layer) was somewhat fragile in that it depended on the caller to turn it back on afterwards. It's now only exposed as a RAII object which automatically cleans up when it goes out of scope. 6) There were also bugs in a couple of the polygonization routines where we'd accumulate round-off error in adding up the segments and end up with an overly long last segment (which of course would voilate the error max). This was the cause of the linked bug and also some issues with vias that we had fudged in the past with extra clearance. Fixes https://gitlab.com/kicad/code/kicad/issues/5567
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
5 years ago
5 years ago
5 years ago
5 years ago
Clean up arc/circle polygonization. 1) For a while now we've been using a calculated seg count from a given maxError, and a correction factor to push the radius out so that all the error is outside the arc/circle. However, the second calculation (which pre-dates the first) is pretty much just the inverse of the first (and yields nothing more than maxError back). This is particularly sub-optimal given the cost of trig functions. 2) There are a lot of old optimizations to reduce segcounts in certain situations, someting that our error-based calculation compensates for anyway. (Smaller radii need fewer segments to meet the maxError condition.) But perhaps more importantly we now surface maxError in the UI and we don't really want to call it "Max deviation except when it's not". 3) We were also clamping the segCount twice: once in the calculation routine and once in most of it's callers. Furthermore, the caller clamping was inconsistent (both in being done and in the clamping value). We now clamp only in the calculation routine. 4) There's no reason to use the correction factors in the 3Dviewer; it's just a visualization and whether the polygonization error is inside or outside the shape isn't really material. 5) The arc-correction-disabling stuff (used for solder mask layer) was somewhat fragile in that it depended on the caller to turn it back on afterwards. It's now only exposed as a RAII object which automatically cleans up when it goes out of scope. 6) There were also bugs in a couple of the polygonization routines where we'd accumulate round-off error in adding up the segments and end up with an overly long last segment (which of course would voilate the error max). This was the cause of the linked bug and also some issues with vias that we had fudged in the past with extra clearance. Fixes https://gitlab.com/kicad/code/kicad/issues/5567
5 years ago
4 years ago
4 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2014-2017 CERN
  5. * Copyright (C) 2014-2022 KiCad Developers, see AUTHORS.txt for contributors.
  6. * @author Tomasz Włostowski <tomasz.wlostowski@cern.ch>
  7. *
  8. * This program is free software: you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the
  10. * Free Software Foundation, either version 3 of the License, or (at your
  11. * option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, you may find one here:
  20. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. * or you may search the http://www.gnu.org website for the version 2 license,
  22. * or you may write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  24. */
  25. #include <thread>
  26. #include <future>
  27. #include <core/kicad_algo.h>
  28. #include <advanced_config.h>
  29. #include <board.h>
  30. #include <board_design_settings.h>
  31. #include <zone.h>
  32. #include <footprint.h>
  33. #include <pad.h>
  34. #include <pcb_shape.h>
  35. #include <pcb_target.h>
  36. #include <pcb_track.h>
  37. #include <connectivity/connectivity_data.h>
  38. #include <convert_basic_shapes_to_polygon.h>
  39. #include <board_commit.h>
  40. #include <progress_reporter.h>
  41. #include <geometry/shape_poly_set.h>
  42. #include <geometry/convex_hull.h>
  43. #include <geometry/geometry_utils.h>
  44. #include <confirm.h>
  45. #include <convert_to_biu.h>
  46. #include <math/util.h> // for KiROUND
  47. #include "zone_filler.h"
  48. ZONE_FILLER::ZONE_FILLER( BOARD* aBoard, COMMIT* aCommit ) :
  49. m_board( aBoard ),
  50. m_brdOutlinesValid( false ),
  51. m_commit( aCommit ),
  52. m_progressReporter( nullptr ),
  53. m_maxError( ARC_HIGH_DEF ),
  54. m_worstClearance( 0 )
  55. {
  56. // To enable add "DebugZoneFiller=1" to kicad_advanced settings file.
  57. m_debugZoneFiller = ADVANCED_CFG::GetCfg().m_DebugZoneFiller;
  58. }
  59. ZONE_FILLER::~ZONE_FILLER()
  60. {
  61. }
  62. void ZONE_FILLER::SetProgressReporter( PROGRESS_REPORTER* aReporter )
  63. {
  64. m_progressReporter = aReporter;
  65. wxASSERT_MSG( m_commit, "ZONE_FILLER must have a valid commit to call SetProgressReporter" );
  66. }
  67. bool ZONE_FILLER::Fill( std::vector<ZONE*>& aZones, bool aCheck, wxWindow* aParent )
  68. {
  69. std::lock_guard<KISPINLOCK> lock( m_board->GetConnectivity()->GetLock() );
  70. std::vector<std::pair<ZONE*, PCB_LAYER_ID>> toFill;
  71. std::vector<CN_ZONE_ISOLATED_ISLAND_LIST> islandsList;
  72. std::shared_ptr<CONNECTIVITY_DATA> connectivity = m_board->GetConnectivity();
  73. // Rebuild just in case. This really needs to be reliable.
  74. connectivity->Clear();
  75. connectivity->Build( m_board, m_progressReporter );
  76. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  77. m_worstClearance = bds.GetBiggestClearanceValue();
  78. if( m_progressReporter )
  79. {
  80. m_progressReporter->Report( aCheck ? _( "Checking zone fills..." )
  81. : _( "Building zone fills..." ) );
  82. m_progressReporter->SetMaxProgress( aZones.size() );
  83. m_progressReporter->KeepRefreshing();
  84. }
  85. // The board outlines is used to clip solid areas inside the board (when outlines are valid)
  86. m_boardOutline.RemoveAllContours();
  87. m_brdOutlinesValid = m_board->GetBoardPolygonOutlines( m_boardOutline );
  88. // Update and cache zone bounding boxes and pad effective shapes so that we don't have to
  89. // make them thread-safe.
  90. for( ZONE* zone : m_board->Zones() )
  91. {
  92. zone->CacheBoundingBox();
  93. m_worstClearance = std::max( m_worstClearance, zone->GetLocalClearance() );
  94. }
  95. for( FOOTPRINT* footprint : m_board->Footprints() )
  96. {
  97. for( PAD* pad : footprint->Pads() )
  98. {
  99. if( pad->IsDirty() )
  100. {
  101. pad->BuildEffectiveShapes( UNDEFINED_LAYER );
  102. pad->BuildEffectivePolygon();
  103. }
  104. m_worstClearance = std::max( m_worstClearance, pad->GetLocalClearance() );
  105. }
  106. for( ZONE* zone : footprint->Zones() )
  107. {
  108. zone->CacheBoundingBox();
  109. m_worstClearance = std::max( m_worstClearance, zone->GetLocalClearance() );
  110. }
  111. // Rules may depend on insideCourtyard() or other expressions
  112. footprint->BuildPolyCourtyards();
  113. }
  114. // Sort by priority to reduce deferrals waiting on higher priority zones.
  115. std::sort( aZones.begin(), aZones.end(),
  116. []( const ZONE* lhs, const ZONE* rhs )
  117. {
  118. return lhs->GetPriority() > rhs->GetPriority();
  119. } );
  120. for( ZONE* zone : aZones )
  121. {
  122. // Rule areas are not filled
  123. if( zone->GetIsRuleArea() )
  124. continue;
  125. if( m_commit )
  126. m_commit->Modify( zone );
  127. // calculate the hash value for filled areas. it will be used later
  128. // to know if the current filled areas are up to date
  129. for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
  130. {
  131. zone->BuildHashValue( layer );
  132. // Add the zone to the list of zones to test or refill
  133. toFill.emplace_back( std::make_pair( zone, layer ) );
  134. }
  135. islandsList.emplace_back( CN_ZONE_ISOLATED_ISLAND_LIST( zone ) );
  136. // Remove existing fill first to prevent drawing invalid polygons
  137. // on some platforms
  138. zone->UnFill();
  139. zone->SetFillVersion( bds.m_ZoneFillVersion );
  140. }
  141. size_t cores = std::thread::hardware_concurrency();
  142. std::atomic<size_t> nextItem;
  143. auto check_fill_dependency =
  144. [&]( ZONE* aZone, PCB_LAYER_ID aLayer, ZONE* aOtherZone ) -> bool
  145. {
  146. // Check to see if we have to knock-out the filled areas of a higher-priority
  147. // zone. If so we have to wait until said zone is filled before we can fill.
  148. // If the other zone is already filled then we're good-to-go
  149. if( aOtherZone->GetFillFlag( aLayer ) )
  150. return false;
  151. // Even if keepouts exclude copper pours the exclusion is by outline, not by
  152. // filled area, so we're good-to-go here too.
  153. if( aOtherZone->GetIsRuleArea() )
  154. return false;
  155. // If the zones share no common layers
  156. if( !aOtherZone->GetLayerSet().test( aLayer ) )
  157. return false;
  158. if( aOtherZone->GetPriority() <= aZone->GetPriority() )
  159. return false;
  160. // Same-net zones always use outline to produce predictable results
  161. if( aOtherZone->GetNetCode() == aZone->GetNetCode() )
  162. return false;
  163. // A higher priority zone is found: if we intersect and it's not filled yet
  164. // then we have to wait.
  165. EDA_RECT inflatedBBox = aZone->GetCachedBoundingBox();
  166. inflatedBBox.Inflate( m_worstClearance );
  167. return inflatedBBox.Intersects( aOtherZone->GetCachedBoundingBox() );
  168. };
  169. auto fill_lambda =
  170. [&]( PROGRESS_REPORTER* aReporter )
  171. {
  172. size_t num = 0;
  173. for( size_t i = nextItem++; i < toFill.size(); i = nextItem++ )
  174. {
  175. PCB_LAYER_ID layer = toFill[i].second;
  176. ZONE* zone = toFill[i].first;
  177. bool canFill = true;
  178. // Check for any fill dependencies. If our zone needs to be clipped by
  179. // another zone then we can't fill until that zone is filled.
  180. for( ZONE* otherZone : aZones )
  181. {
  182. if( otherZone == zone )
  183. continue;
  184. if( check_fill_dependency( zone, layer, otherZone ) )
  185. {
  186. canFill = false;
  187. break;
  188. }
  189. }
  190. if( m_progressReporter && m_progressReporter->IsCancelled() )
  191. break;
  192. if( !canFill )
  193. continue;
  194. // Now we're ready to fill.
  195. SHAPE_POLY_SET rawPolys, finalPolys;
  196. fillSingleZone( zone, layer, rawPolys, finalPolys );
  197. std::unique_lock<std::mutex> zoneLock( zone->GetLock() );
  198. zone->SetRawPolysList( layer, rawPolys );
  199. zone->SetFilledPolysList( layer, finalPolys );
  200. zone->SetFillFlag( layer, true );
  201. if( m_progressReporter )
  202. m_progressReporter->AdvanceProgress();
  203. num++;
  204. }
  205. return num;
  206. };
  207. while( !toFill.empty() )
  208. {
  209. size_t parallelThreadCount = std::min( cores, toFill.size() );
  210. std::vector<std::future<size_t>> returns( parallelThreadCount );
  211. nextItem = 0;
  212. if( parallelThreadCount <= 1 )
  213. fill_lambda( m_progressReporter );
  214. else
  215. {
  216. for( size_t ii = 0; ii < parallelThreadCount; ++ii )
  217. returns[ii] = std::async( std::launch::async, fill_lambda, m_progressReporter );
  218. for( size_t ii = 0; ii < parallelThreadCount; ++ii )
  219. {
  220. // Here we balance returns with a 100ms timeout to allow UI updating
  221. std::future_status status;
  222. do
  223. {
  224. if( m_progressReporter )
  225. m_progressReporter->KeepRefreshing();
  226. status = returns[ii].wait_for( std::chrono::milliseconds( 100 ) );
  227. } while( status != std::future_status::ready );
  228. }
  229. }
  230. alg::delete_if( toFill, [&]( const std::pair<ZONE*, PCB_LAYER_ID> pair ) -> bool
  231. {
  232. return pair.first->GetFillFlag( pair.second );
  233. } );
  234. if( m_progressReporter && m_progressReporter->IsCancelled() )
  235. break;
  236. }
  237. // Now update the connectivity to check for copper islands
  238. if( m_progressReporter )
  239. {
  240. if( m_progressReporter->IsCancelled() )
  241. return false;
  242. m_progressReporter->AdvancePhase();
  243. m_progressReporter->Report( _( "Removing isolated copper islands..." ) );
  244. m_progressReporter->KeepRefreshing();
  245. }
  246. connectivity->SetProgressReporter( m_progressReporter );
  247. connectivity->FindIsolatedCopperIslands( islandsList );
  248. connectivity->SetProgressReporter( nullptr );
  249. if( m_progressReporter && m_progressReporter->IsCancelled() )
  250. return false;
  251. for( ZONE* zone : aZones )
  252. {
  253. // Keepout zones are not filled
  254. if( zone->GetIsRuleArea() )
  255. continue;
  256. zone->SetIsFilled( true );
  257. }
  258. // Now remove insulated copper islands
  259. for( CN_ZONE_ISOLATED_ISLAND_LIST& zone : islandsList )
  260. {
  261. for( PCB_LAYER_ID layer : zone.m_zone->GetLayerSet().Seq() )
  262. {
  263. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
  264. continue;
  265. if( !zone.m_islands.count( layer ) )
  266. continue;
  267. std::vector<int>& islands = zone.m_islands.at( layer );
  268. // The list of polygons to delete must be explored from last to first in list,
  269. // to allow deleting a polygon from list without breaking the remaining of the list
  270. std::sort( islands.begin(), islands.end(), std::greater<int>() );
  271. SHAPE_POLY_SET poly = zone.m_zone->GetFilledPolysList( layer );
  272. long long int minArea = zone.m_zone->GetMinIslandArea();
  273. ISLAND_REMOVAL_MODE mode = zone.m_zone->GetIslandRemovalMode();
  274. for( int idx : islands )
  275. {
  276. SHAPE_LINE_CHAIN& outline = poly.Outline( idx );
  277. if( mode == ISLAND_REMOVAL_MODE::ALWAYS )
  278. poly.DeletePolygon( idx );
  279. else if ( mode == ISLAND_REMOVAL_MODE::AREA && outline.Area() < minArea )
  280. poly.DeletePolygon( idx );
  281. else
  282. zone.m_zone->SetIsIsland( layer, idx );
  283. }
  284. zone.m_zone->SetFilledPolysList( layer, poly );
  285. zone.m_zone->CalculateFilledArea();
  286. if( m_progressReporter && m_progressReporter->IsCancelled() )
  287. return false;
  288. }
  289. }
  290. // Now remove islands outside the board edge
  291. for( ZONE* zone : aZones )
  292. {
  293. LSET zoneCopperLayers = zone->GetLayerSet() & LSET::AllCuMask( MAX_CU_LAYERS );
  294. for( PCB_LAYER_ID layer : zoneCopperLayers.Seq() )
  295. {
  296. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
  297. continue;
  298. SHAPE_POLY_SET poly = zone->GetFilledPolysList( layer );
  299. for( int ii = poly.OutlineCount() - 1; ii >= 0; ii-- )
  300. {
  301. std::vector<SHAPE_LINE_CHAIN>& island = poly.Polygon( ii );
  302. if( island.empty() || !m_boardOutline.Contains( island.front().CPoint( 0 ) ) )
  303. poly.DeletePolygon( ii );
  304. }
  305. zone->SetFilledPolysList( layer, poly );
  306. zone->CalculateFilledArea();
  307. if( m_progressReporter && m_progressReporter->IsCancelled() )
  308. return false;
  309. }
  310. }
  311. if( aCheck )
  312. {
  313. bool outOfDate = false;
  314. for( ZONE* zone : aZones )
  315. {
  316. // Keepout zones are not filled
  317. if( zone->GetIsRuleArea() )
  318. continue;
  319. for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
  320. {
  321. MD5_HASH was = zone->GetHashValue( layer );
  322. zone->CacheTriangulation( layer );
  323. zone->BuildHashValue( layer );
  324. MD5_HASH is = zone->GetHashValue( layer );
  325. if( is != was )
  326. outOfDate = true;
  327. }
  328. }
  329. if( outOfDate )
  330. {
  331. KIDIALOG dlg( aParent, _( "Zone fills are out-of-date. Refill?" ),
  332. _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
  333. dlg.SetOKCancelLabels( _( "Refill" ), _( "Continue without Refill" ) );
  334. dlg.DoNotShowCheckbox( __FILE__, __LINE__ );
  335. if( dlg.ShowModal() == wxID_CANCEL )
  336. return false;
  337. }
  338. else
  339. {
  340. // No need to commit something that hasn't changed (and committing will set
  341. // the modified flag).
  342. return false;
  343. }
  344. }
  345. if( m_progressReporter )
  346. {
  347. m_progressReporter->AdvancePhase();
  348. m_progressReporter->Report( _( "Performing polygon fills..." ) );
  349. m_progressReporter->SetMaxProgress( islandsList.size() );
  350. }
  351. nextItem = 0;
  352. auto tri_lambda =
  353. [&]( PROGRESS_REPORTER* aReporter ) -> size_t
  354. {
  355. size_t num = 0;
  356. for( size_t i = nextItem++; i < islandsList.size(); i = nextItem++ )
  357. {
  358. islandsList[i].m_zone->CacheTriangulation();
  359. num++;
  360. if( m_progressReporter )
  361. {
  362. m_progressReporter->AdvanceProgress();
  363. if( m_progressReporter->IsCancelled() )
  364. break;
  365. }
  366. }
  367. return num;
  368. };
  369. size_t parallelThreadCount = std::min( cores, islandsList.size() );
  370. std::vector<std::future<size_t>> returns( parallelThreadCount );
  371. if( parallelThreadCount <= 1 )
  372. tri_lambda( m_progressReporter );
  373. else
  374. {
  375. for( size_t ii = 0; ii < parallelThreadCount; ++ii )
  376. returns[ii] = std::async( std::launch::async, tri_lambda, m_progressReporter );
  377. for( size_t ii = 0; ii < parallelThreadCount; ++ii )
  378. {
  379. // Here we balance returns with a 100ms timeout to allow UI updating
  380. std::future_status status;
  381. do
  382. {
  383. if( m_progressReporter )
  384. {
  385. m_progressReporter->KeepRefreshing();
  386. if( m_progressReporter->IsCancelled() )
  387. break;
  388. }
  389. status = returns[ii].wait_for( std::chrono::milliseconds( 100 ) );
  390. } while( status != std::future_status::ready );
  391. }
  392. }
  393. if( m_progressReporter )
  394. {
  395. if( m_progressReporter->IsCancelled() )
  396. return false;
  397. m_progressReporter->AdvancePhase();
  398. m_progressReporter->KeepRefreshing();
  399. }
  400. return true;
  401. }
  402. /**
  403. * Add a knockout for a pad. The knockout is 'aGap' larger than the pad (which might be
  404. * either the thermal clearance or the electrical clearance).
  405. */
  406. void ZONE_FILLER::addKnockout( PAD* aPad, PCB_LAYER_ID aLayer, int aGap, SHAPE_POLY_SET& aHoles )
  407. {
  408. if( aPad->GetShape() == PAD_SHAPE::CUSTOM )
  409. {
  410. SHAPE_POLY_SET poly;
  411. aPad->TransformShapeWithClearanceToPolygon( poly, aLayer, aGap, m_maxError,
  412. ERROR_OUTSIDE );
  413. // the pad shape in zone can be its convex hull or the shape itself
  414. if( aPad->GetCustomShapeInZoneOpt() == CUST_PAD_SHAPE_IN_ZONE_CONVEXHULL )
  415. {
  416. std::vector<VECTOR2I> convex_hull;
  417. BuildConvexHull( convex_hull, poly );
  418. aHoles.NewOutline();
  419. for( const VECTOR2I& pt : convex_hull )
  420. aHoles.Append( pt );
  421. }
  422. else
  423. aHoles.Append( poly );
  424. }
  425. else
  426. {
  427. aPad->TransformShapeWithClearanceToPolygon( aHoles, aLayer, aGap, m_maxError,
  428. ERROR_OUTSIDE );
  429. }
  430. }
  431. /**
  432. * Add a knockout for a pad's hole.
  433. */
  434. void ZONE_FILLER::addHoleKnockout( PAD* aPad, int aGap, SHAPE_POLY_SET& aHoles )
  435. {
  436. // Note: drill size represents finish size, which means the actual hole size is the plating
  437. // thickness larger.
  438. if( aPad->GetAttribute() == PAD_ATTRIB::PTH )
  439. aGap += aPad->GetBoard()->GetDesignSettings().GetHolePlatingThickness();
  440. aPad->TransformHoleWithClearanceToPolygon( aHoles, aGap, m_maxError, ERROR_OUTSIDE );
  441. }
  442. /**
  443. * Add a knockout for a graphic item. The knockout is 'aGap' larger than the item (which
  444. * might be either the electrical clearance or the board edge clearance).
  445. */
  446. void ZONE_FILLER::addKnockout( BOARD_ITEM* aItem, PCB_LAYER_ID aLayer, int aGap,
  447. bool aIgnoreLineWidth, SHAPE_POLY_SET& aHoles )
  448. {
  449. switch( aItem->Type() )
  450. {
  451. case PCB_SHAPE_T:
  452. case PCB_TEXT_T:
  453. case PCB_FP_SHAPE_T:
  454. aItem->TransformShapeWithClearanceToPolygon( aHoles, aLayer, aGap, m_maxError,
  455. ERROR_OUTSIDE, aIgnoreLineWidth );
  456. break;
  457. case PCB_FP_TEXT_T:
  458. {
  459. FP_TEXT* text = static_cast<FP_TEXT*>( aItem );
  460. if( text->IsVisible() )
  461. {
  462. text->TransformShapeWithClearanceToPolygon( aHoles, aLayer, aGap, m_maxError,
  463. ERROR_OUTSIDE, aIgnoreLineWidth );
  464. }
  465. }
  466. break;
  467. default:
  468. break;
  469. }
  470. }
  471. /**
  472. * Removes thermal reliefs from the shape for any pads connected to the zone. Does NOT add
  473. * in spokes, which must be done later.
  474. */
  475. void ZONE_FILLER::knockoutThermalReliefs( const ZONE* aZone, PCB_LAYER_ID aLayer,
  476. SHAPE_POLY_SET& aFill,
  477. std::vector<PAD*>& aThermalConnectionPads,
  478. std::vector<PAD*>& aNoConnectionPads )
  479. {
  480. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  481. DRC_CONSTRAINT constraint;
  482. SHAPE_POLY_SET holes;
  483. for( FOOTPRINT* footprint : m_board->Footprints() )
  484. {
  485. for( PAD* pad : footprint->Pads() )
  486. {
  487. if( !pad->IsOnLayer( aLayer )
  488. || pad->GetNetCode() != aZone->GetNetCode()
  489. || pad->GetNetCode() <= 0 )
  490. {
  491. aNoConnectionPads.push_back( pad );
  492. continue;
  493. }
  494. // a teardrop area is always fully connected to its pad
  495. // (always equiv to ZONE_CONNECTION::FULL)
  496. if( aZone->IsTeardropArea() )
  497. continue;
  498. constraint = bds.m_DRCEngine->EvalZoneConnection( pad, aZone, aLayer );
  499. ZONE_CONNECTION conn = constraint.m_ZoneConnection;
  500. if( conn == ZONE_CONNECTION::FULL )
  501. continue;
  502. constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad, aZone,
  503. aLayer );
  504. int gap = constraint.GetValue().Min();
  505. EDA_RECT item_boundingbox = pad->GetBoundingBox();
  506. item_boundingbox.Inflate( gap, gap );
  507. if( !item_boundingbox.Intersects( aZone->GetCachedBoundingBox() ) )
  508. continue;
  509. // If the pad is flashed to the current layer, or is on the same layer and shares a
  510. // netcode, then we need to knock out the thermal relief.
  511. if( pad->FlashLayer( aLayer ) )
  512. {
  513. if( conn == ZONE_CONNECTION::THERMAL )
  514. aThermalConnectionPads.push_back( pad );
  515. else if( conn == ZONE_CONNECTION::NONE )
  516. aNoConnectionPads.push_back( pad );
  517. addKnockout( pad, aLayer, gap, holes );
  518. }
  519. else
  520. {
  521. // If the pad isn't flashed on the current layer but has a hole, knock out a
  522. // thermal relief for the hole.
  523. if( pad->GetDrillSize().x == 0 && pad->GetDrillSize().y == 0 )
  524. continue;
  525. aNoConnectionPads.push_back( pad );
  526. // Note: drill size represents finish size, which means the actual holes size is
  527. // the plating thickness larger.
  528. if( pad->GetAttribute() == PAD_ATTRIB::PTH )
  529. gap += pad->GetBoard()->GetDesignSettings().GetHolePlatingThickness();
  530. pad->TransformHoleWithClearanceToPolygon( holes, gap, m_maxError, ERROR_OUTSIDE );
  531. }
  532. }
  533. }
  534. aFill.BooleanSubtract( holes, SHAPE_POLY_SET::PM_FAST );
  535. }
  536. /**
  537. * Removes clearance from the shape for copper items which share the zone's layer but are
  538. * not connected to it.
  539. */
  540. void ZONE_FILLER::buildCopperItemClearances( const ZONE* aZone, PCB_LAYER_ID aLayer,
  541. const std::vector<PAD*> aNoConnectionPads,
  542. SHAPE_POLY_SET& aHoles )
  543. {
  544. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  545. long ticker = 0;
  546. auto checkForCancel =
  547. [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
  548. {
  549. return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
  550. };
  551. // A small extra clearance to be sure actual track clearances are not smaller than
  552. // requested clearance due to many approximations in calculations, like arc to segment
  553. // approx, rounding issues, etc.
  554. EDA_RECT zone_boundingbox = aZone->GetCachedBoundingBox();
  555. int extra_margin = Millimeter2iu( ADVANCED_CFG::GetCfg().m_ExtraClearance );
  556. // Items outside the zone bounding box are skipped, so it needs to be inflated by the
  557. // largest clearance value found in the netclasses and rules
  558. zone_boundingbox.Inflate( m_worstClearance + extra_margin );
  559. auto evalRulesForItems =
  560. [&bds]( DRC_CONSTRAINT_T aConstraint, const BOARD_ITEM* a, const BOARD_ITEM* b,
  561. PCB_LAYER_ID aEvalLayer ) -> int
  562. {
  563. auto c = bds.m_DRCEngine->EvalRules( aConstraint, a, b, aEvalLayer );
  564. return c.GetValue().Min();
  565. };
  566. // Add non-connected pad clearances
  567. //
  568. auto knockoutPadClearance =
  569. [&]( PAD* aPad )
  570. {
  571. if( aPad->GetBoundingBox().Intersects( zone_boundingbox ) )
  572. {
  573. int gap = 0;
  574. bool knockoutHoleClearance = true;
  575. if( aPad->GetNetCode() > 0 && aPad->GetNetCode() == aZone->GetNetCode() )
  576. {
  577. // For pads having the same netcode as the zone, the net and hole
  578. // clearances have no meanings.
  579. // So just knock out the greater of the zone's local clearance and
  580. // thermal relief.
  581. gap = std::max( aZone->GetLocalClearance(), aZone->GetThermalReliefGap() );
  582. knockoutHoleClearance = false;
  583. }
  584. else
  585. {
  586. gap = evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, aPad, aLayer );
  587. }
  588. gap += extra_margin;
  589. if( aPad->FlashLayer( aLayer ) )
  590. addKnockout( aPad, aLayer, gap, aHoles );
  591. else if( aPad->GetDrillSize().x > 0 )
  592. addHoleKnockout( aPad, gap, aHoles );
  593. if( knockoutHoleClearance && aPad->GetDrillSize().x > 0 )
  594. {
  595. gap = evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT, aZone, aPad, aLayer );
  596. gap += extra_margin;
  597. addHoleKnockout( aPad, gap, aHoles );
  598. }
  599. }
  600. };
  601. for( PAD* pad : aNoConnectionPads )
  602. {
  603. if( checkForCancel( m_progressReporter ) )
  604. return;
  605. knockoutPadClearance( pad );
  606. }
  607. // Add non-connected track clearances
  608. //
  609. auto knockoutTrackClearance =
  610. [&]( PCB_TRACK* aTrack )
  611. {
  612. if( aTrack->GetBoundingBox().Intersects( zone_boundingbox ) )
  613. {
  614. if( aTrack->Type() == PCB_VIA_T )
  615. {
  616. PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
  617. int gap = 0;
  618. bool checkHoleClearance = true;
  619. if( via->GetNetCode() > 0 && via->GetNetCode() == aZone->GetNetCode() )
  620. {
  621. // For pads having the same netcode as the zone, the net and hole
  622. // clearances have no meanings.
  623. // So just knock out the zone's local clearance.
  624. gap = aZone->GetLocalClearance();
  625. checkHoleClearance = false;
  626. }
  627. else
  628. {
  629. gap = evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, aTrack, aLayer );
  630. }
  631. if( via->FlashLayer( aLayer ) )
  632. {
  633. via->TransformShapeWithClearanceToPolygon( aHoles, aLayer,
  634. gap + extra_margin,
  635. m_maxError, ERROR_OUTSIDE );
  636. }
  637. if( checkHoleClearance )
  638. {
  639. gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
  640. aZone, via, aLayer ) );
  641. }
  642. int radius = via->GetDrillValue() / 2 + bds.GetHolePlatingThickness();
  643. TransformCircleToPolygon( aHoles, via->GetPosition(),
  644. radius + gap + extra_margin,
  645. m_maxError, ERROR_OUTSIDE );
  646. }
  647. else
  648. {
  649. int gap = evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, aTrack, aLayer );
  650. aTrack->TransformShapeWithClearanceToPolygon( aHoles, aLayer,
  651. gap + extra_margin,
  652. m_maxError, ERROR_OUTSIDE );
  653. }
  654. }
  655. };
  656. for( PCB_TRACK* track : m_board->Tracks() )
  657. {
  658. if( !track->IsOnLayer( aLayer ) )
  659. continue;
  660. if( track->GetNetCode() == aZone->GetNetCode() && ( aZone->GetNetCode() != 0) )
  661. continue;
  662. if( checkForCancel( m_progressReporter ) )
  663. return;
  664. knockoutTrackClearance( track );
  665. }
  666. // Add graphic item clearances. They are by definition unconnected, and have no clearance
  667. // definitions of their own.
  668. //
  669. auto knockoutGraphicClearance =
  670. [&]( BOARD_ITEM* aItem )
  671. {
  672. // A item on the Edge_Cuts or Margin is always seen as on any layer:
  673. if( aItem->IsOnLayer( aLayer )
  674. || aItem->IsOnLayer( Edge_Cuts )
  675. || aItem->IsOnLayer( Margin ) )
  676. {
  677. if( aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
  678. {
  679. bool ignoreLineWidths = false;
  680. int gap = evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, aItem, aLayer );
  681. if( aItem->IsOnLayer( Edge_Cuts ) )
  682. {
  683. gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
  684. aZone, aItem, Edge_Cuts ) );
  685. ignoreLineWidths = true;
  686. gap = std::max( gap, bds.GetDRCEpsilon() );
  687. }
  688. if( aItem->IsOnLayer( Margin ) )
  689. {
  690. gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
  691. aZone, aItem, Margin ) );
  692. }
  693. addKnockout( aItem, aLayer, gap, ignoreLineWidths, aHoles );
  694. }
  695. }
  696. };
  697. for( FOOTPRINT* footprint : m_board->Footprints() )
  698. {
  699. bool skipFootprint = false;
  700. knockoutGraphicClearance( &footprint->Reference() );
  701. knockoutGraphicClearance( &footprint->Value() );
  702. // Don't knock out holes in zones that share a net
  703. // with a nettie footprint
  704. if( footprint->IsNetTie() )
  705. {
  706. for( PAD* pad : footprint->Pads() )
  707. {
  708. if( aZone->GetNetCode() == pad->GetNetCode() )
  709. {
  710. skipFootprint = true;
  711. break;
  712. }
  713. }
  714. }
  715. if( skipFootprint )
  716. continue;
  717. for( BOARD_ITEM* item : footprint->GraphicalItems() )
  718. {
  719. if( checkForCancel( m_progressReporter ) )
  720. return;
  721. knockoutGraphicClearance( item );
  722. }
  723. }
  724. for( BOARD_ITEM* item : m_board->Drawings() )
  725. {
  726. if( checkForCancel( m_progressReporter ) )
  727. return;
  728. knockoutGraphicClearance( item );
  729. }
  730. // Add non-connected zone clearances
  731. //
  732. auto knockoutZoneClearance =
  733. [&]( ZONE* aKnockout )
  734. {
  735. // If the zones share no common layers
  736. if( !aKnockout->GetLayerSet().test( aLayer ) )
  737. return;
  738. if( aKnockout->GetCachedBoundingBox().Intersects( zone_boundingbox ) )
  739. {
  740. if( aKnockout->GetIsRuleArea() )
  741. {
  742. // Keepouts use outline with no clearance
  743. aKnockout->TransformSmoothedOutlineToPolygon( aHoles, 0, nullptr );
  744. }
  745. else if( bds.m_ZoneFillVersion == 5 )
  746. {
  747. // 5.x used outline with clearance
  748. int gap = evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, aKnockout,
  749. aLayer );
  750. aKnockout->TransformSmoothedOutlineToPolygon( aHoles, gap, nullptr );
  751. }
  752. else
  753. {
  754. // 6.0 uses filled areas with clearance
  755. int gap = evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, aKnockout,
  756. aLayer );
  757. SHAPE_POLY_SET poly;
  758. aKnockout->TransformShapeWithClearanceToPolygon( poly, aLayer, gap,
  759. m_maxError,
  760. ERROR_OUTSIDE );
  761. aHoles.Append( poly );
  762. }
  763. }
  764. };
  765. for( ZONE* otherZone : m_board->Zones() )
  766. {
  767. if( checkForCancel( m_progressReporter ) )
  768. return;
  769. if( otherZone->GetIsRuleArea() )
  770. {
  771. if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
  772. knockoutZoneClearance( otherZone );
  773. }
  774. else
  775. {
  776. if( otherZone->GetNetCode() != aZone->GetNetCode()
  777. && otherZone->GetPriority() > aZone->GetPriority() )
  778. {
  779. knockoutZoneClearance( otherZone );
  780. }
  781. }
  782. }
  783. for( FOOTPRINT* footprint : m_board->Footprints() )
  784. {
  785. for( ZONE* otherZone : footprint->Zones() )
  786. {
  787. if( checkForCancel( m_progressReporter ) )
  788. return;
  789. if( otherZone->GetIsRuleArea() )
  790. {
  791. if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
  792. knockoutZoneClearance( otherZone );
  793. }
  794. else
  795. {
  796. if( otherZone->GetNetCode() != aZone->GetNetCode()
  797. && otherZone->GetPriority() > aZone->GetPriority() )
  798. {
  799. knockoutZoneClearance( otherZone );
  800. }
  801. }
  802. }
  803. }
  804. aHoles.Simplify( SHAPE_POLY_SET::PM_FAST );
  805. }
  806. /**
  807. * Removes the outlines of higher-proirity zones with the same net. These zones should be
  808. * in charge of the fill parameters within their own outlines.
  809. */
  810. void ZONE_FILLER::subtractHigherPriorityZones( const ZONE* aZone, PCB_LAYER_ID aLayer,
  811. SHAPE_POLY_SET& aRawFill )
  812. {
  813. auto knockoutZoneOutline =
  814. [&]( ZONE* aKnockout )
  815. {
  816. // If the zones share no common layers
  817. if( !aKnockout->GetLayerSet().test( aLayer ) )
  818. return;
  819. if( aKnockout->GetCachedBoundingBox().Intersects( aZone->GetCachedBoundingBox() ) )
  820. {
  821. aRawFill.BooleanSubtract( *aKnockout->Outline(), SHAPE_POLY_SET::PM_FAST );
  822. }
  823. };
  824. for( ZONE* otherZone : m_board->Zones() )
  825. {
  826. if( otherZone->GetNetCode() == aZone->GetNetCode()
  827. && otherZone->GetPriority() > aZone->GetPriority() )
  828. {
  829. // Do not remove teardrop area: it is not useful and not good
  830. if( !otherZone->IsTeardropArea() )
  831. knockoutZoneOutline( otherZone );
  832. }
  833. }
  834. for( FOOTPRINT* footprint : m_board->Footprints() )
  835. {
  836. for( ZONE* otherZone : footprint->Zones() )
  837. {
  838. if( otherZone->GetNetCode() == aZone->GetNetCode()
  839. && otherZone->GetPriority() > aZone->GetPriority() )
  840. {
  841. // Do not remove teardrop area: it is not useful and not good
  842. if( !otherZone->IsTeardropArea() )
  843. knockoutZoneOutline( otherZone );
  844. }
  845. }
  846. }
  847. }
  848. #define DUMP_POLYS_TO_COPPER_LAYER( a, b, c ) \
  849. { if( m_debugZoneFiller && aDebugLayer == b ) \
  850. { \
  851. m_board->SetLayerName( b, c ); \
  852. SHAPE_POLY_SET d = a; \
  853. d.Simplify( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE ); \
  854. d.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE ); \
  855. aRawPolys = d; \
  856. return false; \
  857. } \
  858. }
  859. /**
  860. * 1 - Creates the main zone outline using a correction to shrink the resulting area by
  861. * m_ZoneMinThickness / 2. The result is areas with a margin of m_ZoneMinThickness / 2
  862. * so that when drawing outline with segments having a thickness of m_ZoneMinThickness the
  863. * outlines will match exactly the initial outlines
  864. * 2 - Knocks out thermal reliefs around thermally-connected pads
  865. * 3 - Builds a set of thermal spoke for the whole zone
  866. * 4 - Knocks out unconnected copper items, deleting any affected spokes
  867. * 5 - Removes unconnected copper islands, deleting any affected spokes
  868. * 6 - Adds in the remaining spokes
  869. */
  870. bool ZONE_FILLER::computeRawFilledArea( const ZONE* aZone,
  871. PCB_LAYER_ID aLayer, PCB_LAYER_ID aDebugLayer,
  872. const SHAPE_POLY_SET& aSmoothedOutline,
  873. const SHAPE_POLY_SET& aMaxExtents,
  874. SHAPE_POLY_SET& aRawPolys )
  875. {
  876. m_maxError = m_board->GetDesignSettings().m_MaxError;
  877. // Features which are min_width should survive pruning; features that are *less* than
  878. // min_width should not. Therefore we subtract epsilon from the min_width when
  879. // deflating/inflating.
  880. int half_min_width = aZone->GetMinThickness() / 2;
  881. int epsilon = Millimeter2iu( 0.001 );
  882. int numSegs = GetArcToSegmentCount( half_min_width, m_maxError, FULL_CIRCLE );
  883. // Solid polygons are deflated and inflated during calculations. Deflating doesn't cause
  884. // issues, but inflate is tricky as it can create excessively long and narrow spikes for
  885. // acute angles.
  886. // ALLOW_ACUTE_CORNERS cannot be used due to the spike problem.
  887. // CHAMFER_ACUTE_CORNERS is tempting, but can still produce spikes in some unusual
  888. // circumstances (https://gitlab.com/kicad/code/kicad/-/issues/5581).
  889. // It's unclear if ROUND_ACUTE_CORNERS would have the same issues, but is currently avoided
  890. // as a "less-safe" option.
  891. // ROUND_ALL_CORNERS produces the uniformly nicest shapes, but also a lot of segments.
  892. // CHAMFER_ALL_CORNERS improves the segment count.
  893. SHAPE_POLY_SET::CORNER_STRATEGY fastCornerStrategy = SHAPE_POLY_SET::CHAMFER_ALL_CORNERS;
  894. SHAPE_POLY_SET::CORNER_STRATEGY cornerStrategy = SHAPE_POLY_SET::ROUND_ALL_CORNERS;
  895. std::vector<PAD*> thermalConnectionPads;
  896. std::vector<PAD*> noConnectionPads;
  897. std::deque<SHAPE_LINE_CHAIN> thermalSpokes;
  898. SHAPE_POLY_SET clearanceHoles;
  899. aRawPolys = aSmoothedOutline;
  900. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In1_Cu, "smoothed-outline" );
  901. if( m_progressReporter && m_progressReporter->IsCancelled() )
  902. return false;
  903. knockoutThermalReliefs( aZone, aLayer, aRawPolys, thermalConnectionPads, noConnectionPads );
  904. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In2_Cu, "minus-thermal-reliefs" );
  905. if( m_progressReporter && m_progressReporter->IsCancelled() )
  906. return false;
  907. buildCopperItemClearances( aZone, aLayer, noConnectionPads, clearanceHoles );
  908. DUMP_POLYS_TO_COPPER_LAYER( clearanceHoles, In3_Cu, "clearance-holes" );
  909. if( m_progressReporter && m_progressReporter->IsCancelled() )
  910. return false;
  911. buildThermalSpokes( aZone, aLayer, thermalConnectionPads, thermalSpokes );
  912. if( m_progressReporter && m_progressReporter->IsCancelled() )
  913. return false;
  914. // Create a temporary zone that we can hit-test spoke-ends against. It's only temporary
  915. // because the "real" subtract-clearance-holes has to be done after the spokes are added.
  916. static const bool USE_BBOX_CACHES = true;
  917. SHAPE_POLY_SET testAreas = aRawPolys;
  918. testAreas.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  919. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In4_Cu, "minus-clearance-holes" );
  920. // Prune features that don't meet minimum-width criteria
  921. if( half_min_width - epsilon > epsilon )
  922. {
  923. testAreas.Deflate( half_min_width - epsilon, numSegs, fastCornerStrategy );
  924. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In5_Cu, "spoke-test-deflated" );
  925. testAreas.Inflate( half_min_width - epsilon, numSegs, fastCornerStrategy );
  926. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In6_Cu, "spoke-test-reinflated" );
  927. }
  928. if( m_progressReporter && m_progressReporter->IsCancelled() )
  929. return false;
  930. // Spoke-end-testing is hugely expensive so we generate cached bounding-boxes to speed
  931. // things up a bit.
  932. testAreas.BuildBBoxCaches();
  933. int interval = 0;
  934. SHAPE_POLY_SET debugSpokes;
  935. for( const SHAPE_LINE_CHAIN& spoke : thermalSpokes )
  936. {
  937. const VECTOR2I& testPt = spoke.CPoint( 3 );
  938. // Hit-test against zone body
  939. if( testAreas.Contains( testPt, -1, 1, USE_BBOX_CACHES ) )
  940. {
  941. if( m_debugZoneFiller )
  942. debugSpokes.AddOutline( spoke );
  943. aRawPolys.AddOutline( spoke );
  944. continue;
  945. }
  946. if( interval++ > 400 )
  947. {
  948. if( m_progressReporter && m_progressReporter->IsCancelled() )
  949. return false;
  950. interval = 0;
  951. }
  952. // Hit-test against other spokes
  953. for( const SHAPE_LINE_CHAIN& other : thermalSpokes )
  954. {
  955. if( &other != &spoke && other.PointInside( testPt, 1, USE_BBOX_CACHES ) )
  956. {
  957. if( m_debugZoneFiller )
  958. debugSpokes.AddOutline( spoke );
  959. aRawPolys.AddOutline( spoke );
  960. break;
  961. }
  962. }
  963. }
  964. DUMP_POLYS_TO_COPPER_LAYER( debugSpokes, In7_Cu, "spokes" );
  965. if( m_progressReporter && m_progressReporter->IsCancelled() )
  966. return false;
  967. aRawPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  968. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In8_Cu, "after-spoke-trimming" );
  969. // Prune features that don't meet minimum-width criteria
  970. if( half_min_width - epsilon > epsilon )
  971. aRawPolys.Deflate( half_min_width - epsilon, numSegs, cornerStrategy );
  972. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In9_Cu, "deflated" );
  973. if( m_progressReporter && m_progressReporter->IsCancelled() )
  974. return false;
  975. // Now remove the non filled areas due to the hatch pattern
  976. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  977. {
  978. if( !addHatchFillTypeOnZone( aZone, aLayer, aDebugLayer, aRawPolys ) )
  979. return false;
  980. }
  981. if( m_progressReporter && m_progressReporter->IsCancelled() )
  982. return false;
  983. // Re-inflate after pruning of areas that don't meet minimum-width criteria
  984. if( aZone->GetFilledPolysUseThickness() )
  985. {
  986. // If we're stroking the zone with a min_width stroke then this will naturally inflate
  987. // the zone by half_min_width
  988. }
  989. else if( half_min_width - epsilon > epsilon )
  990. {
  991. aRawPolys.Inflate( half_min_width - epsilon, numSegs, cornerStrategy );
  992. }
  993. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In15_Cu, "after-reinflating" );
  994. // Ensure additive changes (thermal stubs and particularly inflating acute corners) do not
  995. // add copper outside the zone boundary or inside the clearance holes
  996. aRawPolys.BooleanIntersection( aMaxExtents, SHAPE_POLY_SET::PM_FAST );
  997. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In16_Cu, "after-trim-to-outline" );
  998. aRawPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  999. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In17_Cu, "after-trim-to-clearance-holes" );
  1000. // Lastly give any same-net but higher-priority zones control over their own area.
  1001. subtractHigherPriorityZones( aZone, aLayer, aRawPolys );
  1002. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In18_Cu, "minus-higher-priority-zones" );
  1003. aRawPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
  1004. return true;
  1005. }
  1006. /*
  1007. * Build the filled solid areas data from real outlines (stored in m_Poly)
  1008. * The solid areas can be more than one on copper layers, and do not have holes
  1009. * ( holes are linked by overlapping segments to the main outline)
  1010. */
  1011. bool ZONE_FILLER::fillSingleZone( ZONE* aZone, PCB_LAYER_ID aLayer, SHAPE_POLY_SET& aRawPolys,
  1012. SHAPE_POLY_SET& aFinalPolys )
  1013. {
  1014. SHAPE_POLY_SET* boardOutline = m_brdOutlinesValid ? &m_boardOutline : nullptr;
  1015. SHAPE_POLY_SET maxExtents;
  1016. SHAPE_POLY_SET smoothedPoly;
  1017. PCB_LAYER_ID debugLayer = UNDEFINED_LAYER;
  1018. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( aLayer ) )
  1019. {
  1020. debugLayer = aLayer;
  1021. aLayer = F_Cu;
  1022. }
  1023. if ( !aZone->BuildSmoothedPoly( maxExtents, aLayer, boardOutline, &smoothedPoly ) )
  1024. return false;
  1025. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1026. return false;
  1027. if( aZone->IsOnCopperLayer() )
  1028. {
  1029. if( computeRawFilledArea( aZone, aLayer, debugLayer, smoothedPoly, maxExtents, aRawPolys ) )
  1030. aZone->SetNeedRefill( false );
  1031. aFinalPolys = aRawPolys;
  1032. }
  1033. else
  1034. {
  1035. // Features which are min_width should survive pruning; features that are *less* than
  1036. // min_width should not. Therefore we subtract epsilon from the min_width when
  1037. // deflating/inflating.
  1038. int half_min_width = aZone->GetMinThickness() / 2;
  1039. int epsilon = Millimeter2iu( 0.001 );
  1040. int numSegs = GetArcToSegmentCount( half_min_width, m_maxError, FULL_CIRCLE );
  1041. smoothedPoly.Deflate( half_min_width - epsilon, numSegs );
  1042. // Remove the non filled areas due to the hatch pattern
  1043. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  1044. addHatchFillTypeOnZone( aZone, aLayer, debugLayer, smoothedPoly );
  1045. // Re-inflate after pruning of areas that don't meet minimum-width criteria
  1046. if( aZone->GetFilledPolysUseThickness() )
  1047. {
  1048. // If we're stroking the zone with a min_width stroke then this will naturally
  1049. // inflate the zone by half_min_width
  1050. }
  1051. else if( half_min_width - epsilon > epsilon )
  1052. {
  1053. smoothedPoly.Inflate( half_min_width - epsilon, numSegs );
  1054. }
  1055. aRawPolys = smoothedPoly;
  1056. aFinalPolys = smoothedPoly;
  1057. aFinalPolys.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
  1058. aZone->SetNeedRefill( false );
  1059. }
  1060. return true;
  1061. }
  1062. /**
  1063. * Function buildThermalSpokes
  1064. */
  1065. void ZONE_FILLER::buildThermalSpokes( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1066. const std::vector<PAD*>& aSpokedPadsList,
  1067. std::deque<SHAPE_LINE_CHAIN>& aSpokesList )
  1068. {
  1069. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  1070. EDA_RECT zoneBB = aZone->GetCachedBoundingBox();
  1071. DRC_CONSTRAINT constraint;
  1072. zoneBB.Inflate( std::max( bds.GetBiggestClearanceValue(), aZone->GetLocalClearance() ) );
  1073. // Is a point on the boundary of the polygon inside or outside? This small epsilon lets
  1074. // us avoid the question.
  1075. int epsilon = KiROUND( IU_PER_MM * 0.04 ); // about 1.5 mil
  1076. for( PAD* pad : aSpokedPadsList )
  1077. {
  1078. // We currently only connect to pads, not pad holes
  1079. if( !pad->IsOnLayer( aLayer ) )
  1080. continue;
  1081. constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad, aZone, aLayer );
  1082. int thermalReliefGap = constraint.GetValue().Min();
  1083. constraint = bds.m_DRCEngine->EvalRules( THERMAL_SPOKE_WIDTH_CONSTRAINT, pad, aZone, aLayer );
  1084. int spoke_w = constraint.GetValue().Opt();
  1085. // Spoke width should ideally be smaller than the pad minor axis.
  1086. // Otherwise the thermal shape is not really a thermal relief,
  1087. // and the algo to count the actual number of spokes can fail
  1088. int spoke_max_allowed_w = std::min( pad->GetSize().x, pad->GetSize().y );
  1089. spoke_w = std::max( spoke_w, constraint.Value().Min() );
  1090. spoke_w = std::min( spoke_w, constraint.Value().Max() );
  1091. // ensure the spoke width is smaller than the pad minor size
  1092. spoke_w = std::min( spoke_w, spoke_max_allowed_w );
  1093. // Cannot create stubs having a width < zone min thickness
  1094. if( spoke_w < aZone->GetMinThickness() )
  1095. continue;
  1096. int spoke_half_w = spoke_w / 2;
  1097. // Quick test here to possibly save us some work
  1098. BOX2I itemBB = pad->GetBoundingBox();
  1099. itemBB.Inflate( thermalReliefGap + epsilon );
  1100. if( !( itemBB.Intersects( zoneBB ) ) )
  1101. continue;
  1102. // Thermal spokes consist of segments from the pad center to points just outside
  1103. // the thermal relief.
  1104. VECTOR2I shapePos = pad->ShapePos();
  1105. EDA_ANGLE spokesAngle = pad->GetThermalSpokeAngle();
  1106. // We use the bounding-box to lay out the spokes, but for this to work the
  1107. // bounding box has to be built at the same rotation as the spokes.
  1108. // We have to use a dummy pad to avoid dirtying the cached shapes
  1109. PAD dummy_pad( *pad );
  1110. dummy_pad.SetOrientation( spokesAngle );
  1111. // Spokes are from center of pad, not from hole
  1112. dummy_pad.SetPosition( -1*pad->GetOffset() );
  1113. BOX2I reliefBB = dummy_pad.GetBoundingBox();
  1114. reliefBB.Inflate( thermalReliefGap + epsilon );
  1115. for( int i = 0; i < 4; i++ )
  1116. {
  1117. SHAPE_LINE_CHAIN spoke;
  1118. switch( i )
  1119. {
  1120. case 0: // lower stub
  1121. spoke.Append( +spoke_half_w, -spoke_half_w );
  1122. spoke.Append( -spoke_half_w, -spoke_half_w );
  1123. spoke.Append( -spoke_half_w, reliefBB.GetBottom() );
  1124. spoke.Append( 0, reliefBB.GetBottom() ); // test pt
  1125. spoke.Append( +spoke_half_w, reliefBB.GetBottom() );
  1126. break;
  1127. case 1: // upper stub
  1128. spoke.Append( +spoke_half_w, spoke_half_w );
  1129. spoke.Append( -spoke_half_w, spoke_half_w );
  1130. spoke.Append( -spoke_half_w, reliefBB.GetTop() );
  1131. spoke.Append( 0, reliefBB.GetTop() ); // test pt
  1132. spoke.Append( +spoke_half_w, reliefBB.GetTop() );
  1133. break;
  1134. case 2: // right stub
  1135. spoke.Append( -spoke_half_w, spoke_half_w );
  1136. spoke.Append( -spoke_half_w, -spoke_half_w );
  1137. spoke.Append( reliefBB.GetRight(), -spoke_half_w );
  1138. spoke.Append( reliefBB.GetRight(), 0 ); // test pt
  1139. spoke.Append( reliefBB.GetRight(), spoke_half_w );
  1140. break;
  1141. case 3: // left stub
  1142. spoke.Append( spoke_half_w, spoke_half_w );
  1143. spoke.Append( spoke_half_w, -spoke_half_w );
  1144. spoke.Append( reliefBB.GetLeft(), -spoke_half_w );
  1145. spoke.Append( reliefBB.GetLeft(), 0 ); // test pt
  1146. spoke.Append( reliefBB.GetLeft(), spoke_half_w );
  1147. break;
  1148. }
  1149. // Rotate and move the spokes tho the right position
  1150. spoke.Rotate( pad->GetOrientation() + spokesAngle );
  1151. spoke.Move( shapePos );
  1152. spoke.SetClosed( true );
  1153. spoke.GenerateBBoxCache();
  1154. aSpokesList.push_back( std::move( spoke ) );
  1155. }
  1156. }
  1157. }
  1158. bool ZONE_FILLER::addHatchFillTypeOnZone( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1159. PCB_LAYER_ID aDebugLayer, SHAPE_POLY_SET& aRawPolys )
  1160. {
  1161. // Build grid:
  1162. // obviously line thickness must be > zone min thickness.
  1163. // It can happens if a board file was edited by hand by a python script
  1164. // Use 1 micron margin to be *sure* there is no issue in Gerber files
  1165. // (Gbr file unit = 1 or 10 nm) due to some truncation in coordinates or calculations
  1166. // This margin also avoid problems due to rounding coordinates in next calculations
  1167. // that can create incorrect polygons
  1168. int thickness = std::max( aZone->GetHatchThickness(),
  1169. aZone->GetMinThickness() + Millimeter2iu( 0.001 ) );
  1170. int linethickness = thickness - aZone->GetMinThickness();
  1171. int gridsize = thickness + aZone->GetHatchGap();
  1172. SHAPE_POLY_SET filledPolys = aRawPolys;
  1173. // Use a area that contains the rotated bbox by orientation, and after rotate the result
  1174. // by -orientation.
  1175. if( !aZone->GetHatchOrientation().IsZero() )
  1176. filledPolys.Rotate( - aZone->GetHatchOrientation() );
  1177. BOX2I bbox = filledPolys.BBox( 0 );
  1178. // Build hole shape
  1179. // the hole size is aZone->GetHatchGap(), but because the outline thickness
  1180. // is aZone->GetMinThickness(), the hole shape size must be larger
  1181. SHAPE_LINE_CHAIN hole_base;
  1182. int hole_size = aZone->GetHatchGap() + aZone->GetMinThickness();
  1183. VECTOR2I corner( 0, 0 );;
  1184. hole_base.Append( corner );
  1185. corner.x += hole_size;
  1186. hole_base.Append( corner );
  1187. corner.y += hole_size;
  1188. hole_base.Append( corner );
  1189. corner.x = 0;
  1190. hole_base.Append( corner );
  1191. hole_base.SetClosed( true );
  1192. // Calculate minimal area of a grid hole.
  1193. // All holes smaller than a threshold will be removed
  1194. double minimal_hole_area = hole_base.Area() * aZone->GetHatchHoleMinArea();
  1195. // Now convert this hole to a smoothed shape:
  1196. if( aZone->GetHatchSmoothingLevel() > 0 )
  1197. {
  1198. // the actual size of chamfer, or rounded corner radius is the half size
  1199. // of the HatchFillTypeGap scaled by aZone->GetHatchSmoothingValue()
  1200. // aZone->GetHatchSmoothingValue() = 1.0 is the max value for the chamfer or the
  1201. // radius of corner (radius = half size of the hole)
  1202. int smooth_value = KiROUND( aZone->GetHatchGap()
  1203. * aZone->GetHatchSmoothingValue() / 2 );
  1204. // Minimal optimization:
  1205. // make smoothing only for reasonable smooth values, to avoid a lot of useless segments
  1206. // and if the smooth value is small, use chamfer even if fillet is requested
  1207. #define SMOOTH_MIN_VAL_MM 0.02
  1208. #define SMOOTH_SMALL_VAL_MM 0.04
  1209. if( smooth_value > Millimeter2iu( SMOOTH_MIN_VAL_MM ) )
  1210. {
  1211. SHAPE_POLY_SET smooth_hole;
  1212. smooth_hole.AddOutline( hole_base );
  1213. int smooth_level = aZone->GetHatchSmoothingLevel();
  1214. if( smooth_value < Millimeter2iu( SMOOTH_SMALL_VAL_MM ) && smooth_level > 1 )
  1215. smooth_level = 1;
  1216. // Use a larger smooth_value to compensate the outline tickness
  1217. // (chamfer is not visible is smooth value < outline thickess)
  1218. smooth_value += aZone->GetMinThickness() / 2;
  1219. // smooth_value cannot be bigger than the half size oh the hole:
  1220. smooth_value = std::min( smooth_value, aZone->GetHatchGap() / 2 );
  1221. // the error to approximate a circle by segments when smoothing corners by a arc
  1222. int error_max = std::max( Millimeter2iu( 0.01 ), smooth_value / 20 );
  1223. switch( smooth_level )
  1224. {
  1225. case 1:
  1226. // Chamfer() uses the distance from a corner to create a end point
  1227. // for the chamfer.
  1228. hole_base = smooth_hole.Chamfer( smooth_value ).Outline( 0 );
  1229. break;
  1230. default:
  1231. if( aZone->GetHatchSmoothingLevel() > 2 )
  1232. error_max /= 2; // Force better smoothing
  1233. hole_base = smooth_hole.Fillet( smooth_value, error_max ).Outline( 0 );
  1234. break;
  1235. case 0:
  1236. break;
  1237. };
  1238. }
  1239. }
  1240. // Build holes
  1241. SHAPE_POLY_SET holes;
  1242. for( int xx = 0; ; xx++ )
  1243. {
  1244. int xpos = xx * gridsize;
  1245. if( xpos > bbox.GetWidth() )
  1246. break;
  1247. for( int yy = 0; ; yy++ )
  1248. {
  1249. int ypos = yy * gridsize;
  1250. if( ypos > bbox.GetHeight() )
  1251. break;
  1252. // Generate hole
  1253. SHAPE_LINE_CHAIN hole( hole_base );
  1254. hole.Move( VECTOR2I( xpos, ypos ) );
  1255. holes.AddOutline( hole );
  1256. }
  1257. }
  1258. holes.Move( bbox.GetPosition() );
  1259. if( !aZone->GetHatchOrientation().IsZero() )
  1260. holes.Rotate( aZone->GetHatchOrientation() );
  1261. DUMP_POLYS_TO_COPPER_LAYER( holes, In10_Cu, "hatch-holes" );
  1262. int outline_margin = aZone->GetMinThickness() * 1.1;
  1263. // Using GetHatchThickness() can look more consistent than GetMinThickness().
  1264. if( aZone->GetHatchBorderAlgorithm() && aZone->GetHatchThickness() > outline_margin )
  1265. outline_margin = aZone->GetHatchThickness();
  1266. // The fill has already been deflated to ensure GetMinThickness() so we just have to
  1267. // account for anything beyond that.
  1268. SHAPE_POLY_SET deflatedFilledPolys = aRawPolys;
  1269. deflatedFilledPolys.Deflate( outline_margin - aZone->GetMinThickness(), 16 );
  1270. holes.BooleanIntersection( deflatedFilledPolys, SHAPE_POLY_SET::PM_FAST );
  1271. DUMP_POLYS_TO_COPPER_LAYER( holes, In11_Cu, "fill-clipped-hatch-holes" );
  1272. SHAPE_POLY_SET deflatedOutline = *aZone->Outline();
  1273. deflatedOutline.Deflate( outline_margin, 16 );
  1274. holes.BooleanIntersection( deflatedOutline, SHAPE_POLY_SET::PM_FAST );
  1275. DUMP_POLYS_TO_COPPER_LAYER( holes, In12_Cu, "outline-clipped-hatch-holes" );
  1276. if( aZone->GetNetCode() != 0 )
  1277. {
  1278. // Vias and pads connected to the zone must not be allowed to become isolated inside
  1279. // one of the holes. Effectively this means their copper outline needs to be expanded
  1280. // to be at least as wide as the gap so that it is guaranteed to touch at least one
  1281. // edge.
  1282. EDA_RECT zone_boundingbox = aZone->GetCachedBoundingBox();
  1283. SHAPE_POLY_SET aprons;
  1284. int min_apron_radius = ( aZone->GetHatchGap() * 10 ) / 19;
  1285. for( PCB_TRACK* track : m_board->Tracks() )
  1286. {
  1287. if( track->Type() == PCB_VIA_T )
  1288. {
  1289. PCB_VIA* via = static_cast<PCB_VIA*>( track );
  1290. if( via->GetNetCode() == aZone->GetNetCode()
  1291. && via->IsOnLayer( aLayer )
  1292. && via->GetBoundingBox().Intersects( zone_boundingbox ) )
  1293. {
  1294. int r = std::max( min_apron_radius,
  1295. via->GetDrillValue() / 2 + outline_margin );
  1296. TransformCircleToPolygon( aprons, via->GetPosition(), r, ARC_HIGH_DEF,
  1297. ERROR_OUTSIDE );
  1298. }
  1299. }
  1300. }
  1301. for( FOOTPRINT* footprint : m_board->Footprints() )
  1302. {
  1303. for( PAD* pad : footprint->Pads() )
  1304. {
  1305. if( pad->GetNetCode() == aZone->GetNetCode()
  1306. && pad->IsOnLayer( aLayer )
  1307. && pad->GetBoundingBox().Intersects( zone_boundingbox ) )
  1308. {
  1309. // What we want is to bulk up the pad shape so that the narrowest bit of
  1310. // copper between the hole and the apron edge is at least outline_margin
  1311. // wide (and that the apron itself meets min_apron_radius. But that would
  1312. // take a lot of code and math, and the following approximation is close
  1313. // enough.
  1314. int pad_width = std::min( pad->GetSize().x, pad->GetSize().y );
  1315. int slot_width = std::min( pad->GetDrillSize().x, pad->GetDrillSize().y );
  1316. int min_annular_ring_width = ( pad_width - slot_width ) / 2;
  1317. int clearance = std::max( min_apron_radius - pad_width / 2,
  1318. outline_margin - min_annular_ring_width );
  1319. clearance = std::max( 0, clearance - linethickness / 2 );
  1320. pad->TransformShapeWithClearanceToPolygon( aprons, aLayer, clearance,
  1321. ARC_HIGH_DEF, ERROR_OUTSIDE );
  1322. }
  1323. }
  1324. }
  1325. holes.BooleanSubtract( aprons, SHAPE_POLY_SET::PM_FAST );
  1326. }
  1327. DUMP_POLYS_TO_COPPER_LAYER( holes, In13_Cu, "pad-via-clipped-hatch-holes" );
  1328. // Now filter truncated holes to avoid small holes in pattern
  1329. // It happens for holes near the zone outline
  1330. for( int ii = 0; ii < holes.OutlineCount(); )
  1331. {
  1332. double area = holes.Outline( ii ).Area();
  1333. if( area < minimal_hole_area ) // The current hole is too small: remove it
  1334. holes.DeletePolygon( ii );
  1335. else
  1336. ++ii;
  1337. }
  1338. // create grid. Use SHAPE_POLY_SET::PM_STRICTLY_SIMPLE to
  1339. // generate strictly simple polygons needed by Gerber files and Fracture()
  1340. aRawPolys.BooleanSubtract( aRawPolys, holes, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
  1341. DUMP_POLYS_TO_COPPER_LAYER( aRawPolys, In14_Cu, "after-hatching" );
  1342. return true;
  1343. }