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.

2456 lines
89 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
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
  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-2024 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 <future>
  26. #include <core/kicad_algo.h>
  27. #include <advanced_config.h>
  28. #include <board.h>
  29. #include <board_design_settings.h>
  30. #include <zone.h>
  31. #include <footprint.h>
  32. #include <pad.h>
  33. #include <pcb_target.h>
  34. #include <pcb_track.h>
  35. #include <pcb_text.h>
  36. #include <pcb_textbox.h>
  37. #include <pcb_tablecell.h>
  38. #include <pcb_table.h>
  39. #include <pcb_dimension.h>
  40. #include <connectivity/connectivity_data.h>
  41. #include <convert_basic_shapes_to_polygon.h>
  42. #include <board_commit.h>
  43. #include <progress_reporter.h>
  44. #include <geometry/shape_poly_set.h>
  45. #include <geometry/convex_hull.h>
  46. #include <geometry/geometry_utils.h>
  47. #include <geometry/vertex_set.h>
  48. #include <kidialog.h>
  49. #include <core/thread_pool.h>
  50. #include <math/util.h> // for KiROUND
  51. #include "zone_filler.h"
  52. // Helper classes for connect_nearby_polys
  53. class RESULTS
  54. {
  55. public:
  56. RESULTS( int aOutline1, int aOutline2, int aVertex1, int aVertex2 ) :
  57. m_outline1( aOutline1 ), m_outline2( aOutline2 ),
  58. m_vertex1( aVertex1 ), m_vertex2( aVertex2 )
  59. {
  60. }
  61. bool operator<( const RESULTS& aOther ) const
  62. {
  63. if( m_outline1 != aOther.m_outline1 )
  64. return m_outline1 < aOther.m_outline1;
  65. if( m_outline2 != aOther.m_outline2 )
  66. return m_outline2 < aOther.m_outline2;
  67. if( m_vertex1 != aOther.m_vertex1 )
  68. return m_vertex1 < aOther.m_vertex1;
  69. return m_vertex2 < aOther.m_vertex2;
  70. }
  71. int m_outline1;
  72. int m_outline2;
  73. int m_vertex1;
  74. int m_vertex2;
  75. };
  76. class VERTEX_CONNECTOR : protected VERTEX_SET
  77. {
  78. public:
  79. VERTEX_CONNECTOR( const BOX2I& aBBox, const SHAPE_POLY_SET& aPolys, int aDist ) : VERTEX_SET( 0 )
  80. {
  81. SetBoundingBox( aBBox );
  82. VERTEX* tail = nullptr;
  83. for( int i = 0; i < aPolys.OutlineCount(); i++ )
  84. tail = createList( aPolys.Outline( i ), tail, (void*)( intptr_t )( i ) );
  85. tail->updateList();
  86. m_dist = aDist;
  87. }
  88. VERTEX* getPoint( VERTEX* aPt ) const
  89. {
  90. // z-order range for the current point ± limit bounding box
  91. const int32_t maxZ = zOrder( aPt->x + m_dist, aPt->y + m_dist );
  92. const int32_t minZ = zOrder( aPt->x - m_dist, aPt->y - m_dist );
  93. const SEG::ecoord limit2 = SEG::Square( m_dist );
  94. // first look for points in increasing z-order
  95. SEG::ecoord min_dist = std::numeric_limits<SEG::ecoord>::max();
  96. VERTEX* retval = nullptr;
  97. auto check_pt = [&]( VERTEX* p )
  98. {
  99. VECTOR2D diff( p->x - aPt->x, p->y - aPt->y );
  100. SEG::ecoord dist2 = diff.SquaredEuclideanNorm();
  101. if( dist2 < limit2 && dist2 < min_dist
  102. && p->isEar() )
  103. {
  104. min_dist = dist2;
  105. retval = p;
  106. }
  107. };
  108. VERTEX* p = aPt->nextZ;
  109. while( p && p->z <= maxZ )
  110. {
  111. check_pt( p );
  112. p = p->nextZ;
  113. }
  114. p = aPt->prevZ;
  115. while( p && p->z >= minZ )
  116. {
  117. check_pt( p );
  118. p = p->prevZ;
  119. }
  120. return retval;
  121. }
  122. void FindResults()
  123. {
  124. VERTEX* p = m_vertices.front().next;
  125. std::set<VERTEX*> visited;
  126. while( p != &m_vertices.front() )
  127. {
  128. // Skip points that are concave
  129. if( !p->isEar() )
  130. {
  131. p = p->next;
  132. continue;
  133. }
  134. VERTEX* q = nullptr;
  135. if( ( visited.empty() || !visited.contains( p ) ) && ( q = getPoint( p ) ) )
  136. {
  137. visited.insert( p );
  138. if( !visited.contains( q ) &&
  139. m_results.emplace( (intptr_t) p->GetUserData(), (intptr_t) q->GetUserData(),
  140. p->i, q->i ).second )
  141. {
  142. // We don't want to connect multiple points in the same vicinity, so skip
  143. // 2 points before and after each point and match.
  144. visited.insert( p->prev );
  145. visited.insert( p->prev->prev );
  146. visited.insert( p->next );
  147. visited.insert( p->next->next );
  148. visited.insert( q->prev );
  149. visited.insert( q->prev->prev );
  150. visited.insert( q->next );
  151. visited.insert( q->next->next );
  152. visited.insert( q );
  153. }
  154. }
  155. p = p->next;
  156. }
  157. }
  158. std::set<RESULTS> GetResults() const
  159. {
  160. return m_results;
  161. }
  162. private:
  163. std::set<RESULTS> m_results;
  164. int m_dist;
  165. };
  166. ZONE_FILLER::ZONE_FILLER( BOARD* aBoard, COMMIT* aCommit ) :
  167. m_board( aBoard ),
  168. m_brdOutlinesValid( false ),
  169. m_commit( aCommit ),
  170. m_progressReporter( nullptr ),
  171. m_maxError( ARC_HIGH_DEF ),
  172. m_worstClearance( 0 )
  173. {
  174. // To enable add "DebugZoneFiller=1" to kicad_advanced settings file.
  175. m_debugZoneFiller = ADVANCED_CFG::GetCfg().m_DebugZoneFiller;
  176. }
  177. ZONE_FILLER::~ZONE_FILLER()
  178. {
  179. }
  180. void ZONE_FILLER::SetProgressReporter( PROGRESS_REPORTER* aReporter )
  181. {
  182. m_progressReporter = aReporter;
  183. wxASSERT_MSG( m_commit, wxT( "ZONE_FILLER must have a valid commit to call "
  184. "SetProgressReporter" ) );
  185. }
  186. /**
  187. * Fills the given list of zones.
  188. *
  189. * NB: Invalidates connectivity - it is up to the caller to obtain a lock on the connectivity
  190. * data before calling Fill to prevent access to stale data by other coroutines (for example,
  191. * ratsnest redraw). This will generally be required if a UI-based progress reporter has been
  192. * installed.
  193. *
  194. * Caller is also responsible for re-building connectivity afterwards.
  195. */
  196. bool ZONE_FILLER::Fill( const std::vector<ZONE*>& aZones, bool aCheck, wxWindow* aParent )
  197. {
  198. std::lock_guard<KISPINLOCK> lock( m_board->GetConnectivity()->GetLock() );
  199. std::vector<std::pair<ZONE*, PCB_LAYER_ID>> toFill;
  200. std::map<std::pair<ZONE*, PCB_LAYER_ID>, HASH_128> oldFillHashes;
  201. std::map<ZONE*, std::map<PCB_LAYER_ID, ISOLATED_ISLANDS>> isolatedIslandsMap;
  202. std::shared_ptr<CONNECTIVITY_DATA> connectivity = m_board->GetConnectivity();
  203. // Rebuild (from scratch, ignoring dirty flags) just in case. This really needs to be reliable.
  204. connectivity->ClearRatsnest();
  205. connectivity->Build( m_board, m_progressReporter );
  206. m_worstClearance = m_board->GetMaxClearanceValue();
  207. if( m_progressReporter )
  208. {
  209. m_progressReporter->Report( aCheck ? _( "Checking zone fills..." )
  210. : _( "Building zone fills..." ) );
  211. m_progressReporter->SetMaxProgress( aZones.size() );
  212. m_progressReporter->KeepRefreshing();
  213. }
  214. // The board outlines is used to clip solid areas inside the board (when outlines are valid)
  215. m_boardOutline.RemoveAllContours();
  216. m_brdOutlinesValid = m_board->GetBoardPolygonOutlines( m_boardOutline );
  217. // Update and cache zone bounding boxes and pad effective shapes so that we don't have to
  218. // make them thread-safe.
  219. //
  220. for( ZONE* zone : m_board->Zones() )
  221. zone->CacheBoundingBox();
  222. for( FOOTPRINT* footprint : m_board->Footprints() )
  223. {
  224. for( PAD* pad : footprint->Pads() )
  225. {
  226. if( pad->IsDirty() )
  227. {
  228. pad->BuildEffectiveShapes();
  229. pad->BuildEffectivePolygon( ERROR_OUTSIDE );
  230. }
  231. }
  232. for( ZONE* zone : footprint->Zones() )
  233. zone->CacheBoundingBox();
  234. // Rules may depend on insideCourtyard() or other expressions
  235. footprint->BuildCourtyardCaches();
  236. }
  237. LSET boardCuMask = m_board->GetEnabledLayers() & LSET::AllCuMask();
  238. auto findHighestPriorityZone = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
  239. const int aNetcode,
  240. const std::function<bool( const ZONE* )> aTestFn ) -> ZONE*
  241. {
  242. unsigned highestPriority = 0;
  243. ZONE* highestPriorityZone = nullptr;
  244. for( ZONE* zone : m_board->Zones() )
  245. {
  246. // Rule areas are not filled
  247. if( zone->GetIsRuleArea() )
  248. continue;
  249. if( zone->GetAssignedPriority() < highestPriority )
  250. continue;
  251. if( !zone->IsOnLayer( aItemLayer ) )
  252. continue;
  253. // Degenerate zones will cause trouble; skip them
  254. if( zone->GetNumCorners() <= 2 )
  255. continue;
  256. if( !zone->GetBoundingBox().Intersects( aBBox ) )
  257. continue;
  258. if( !aTestFn( zone ) )
  259. continue;
  260. // Prefer highest priority and matching netcode
  261. if( zone->GetAssignedPriority() > highestPriority || zone->GetNetCode() == aNetcode )
  262. {
  263. highestPriority = zone->GetAssignedPriority();
  264. highestPriorityZone = zone;
  265. }
  266. }
  267. return highestPriorityZone;
  268. };
  269. auto isInPourKeepoutArea = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
  270. const VECTOR2I aTestPoint ) -> bool
  271. {
  272. for( ZONE* zone : m_board->Zones() )
  273. {
  274. if( !zone->GetIsRuleArea() )
  275. continue;
  276. if( !zone->HasKeepoutParametersSet() )
  277. continue;
  278. if( !zone->GetDoNotAllowCopperPour() )
  279. continue;
  280. if( !zone->IsOnLayer( aItemLayer ) )
  281. continue;
  282. // Degenerate zones will cause trouble; skip them
  283. if( zone->GetNumCorners() <= 2 )
  284. continue;
  285. if( !zone->GetBoundingBox().Intersects( aBBox ) )
  286. continue;
  287. if( zone->Outline()->Contains( aTestPoint ) )
  288. return true;
  289. }
  290. return false;
  291. };
  292. // Determine state of conditional via flashing
  293. for( PCB_TRACK* track : m_board->Tracks() )
  294. {
  295. if( track->Type() == PCB_VIA_T )
  296. {
  297. PCB_VIA* via = static_cast<PCB_VIA*>( track );
  298. via->ClearZoneLayerOverrides();
  299. if( !via->GetRemoveUnconnected() )
  300. continue;
  301. BOX2I bbox = via->GetBoundingBox();
  302. VECTOR2I center = via->GetPosition();
  303. int testRadius = via->GetDrillValue() / 2 + 1;
  304. unsigned netcode = via->GetNetCode();
  305. LSET layers = via->GetLayerSet() & boardCuMask;
  306. // Checking if the via hole touches the zone outline
  307. auto viaTestFn = [&]( const ZONE* aZone ) -> bool
  308. {
  309. return aZone->Outline()->Contains( center, -1, testRadius );
  310. };
  311. for( PCB_LAYER_ID layer : layers.Seq() )
  312. {
  313. if( !via->ConditionallyFlashed( layer ) )
  314. continue;
  315. if( isInPourKeepoutArea( bbox, layer, center ) )
  316. {
  317. via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  318. }
  319. else
  320. {
  321. ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, viaTestFn );
  322. if( zone && zone->GetNetCode() == via->GetNetCode() )
  323. via->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
  324. else
  325. via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  326. }
  327. }
  328. }
  329. }
  330. // Determine state of conditional pad flashing
  331. for( FOOTPRINT* footprint : m_board->Footprints() )
  332. {
  333. for( PAD* pad : footprint->Pads() )
  334. {
  335. pad->ClearZoneLayerOverrides();
  336. if( !pad->GetRemoveUnconnected() )
  337. continue;
  338. BOX2I bbox = pad->GetBoundingBox();
  339. VECTOR2I center = pad->GetPosition();
  340. unsigned netcode = pad->GetNetCode();
  341. LSET layers = pad->GetLayerSet() & boardCuMask;
  342. auto padTestFn = [&]( const ZONE* aZone ) -> bool
  343. {
  344. return aZone->Outline()->Contains( center );
  345. };
  346. for( PCB_LAYER_ID layer : layers.Seq() )
  347. {
  348. if( !pad->ConditionallyFlashed( layer ) )
  349. continue;
  350. if( isInPourKeepoutArea( bbox, layer, center ) )
  351. {
  352. pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  353. }
  354. else
  355. {
  356. ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, padTestFn );
  357. if( zone && zone->GetNetCode() == pad->GetNetCode() )
  358. pad->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
  359. else
  360. pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  361. }
  362. }
  363. }
  364. }
  365. for( ZONE* zone : aZones )
  366. {
  367. // Rule areas are not filled
  368. if( zone->GetIsRuleArea() )
  369. continue;
  370. // Degenerate zones will cause trouble; skip them
  371. if( zone->GetNumCorners() <= 2 )
  372. continue;
  373. if( m_commit )
  374. m_commit->Modify( zone );
  375. // calculate the hash value for filled areas. it will be used later to know if the
  376. // current filled areas are up to date
  377. for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
  378. {
  379. zone->BuildHashValue( layer );
  380. oldFillHashes[ { zone, layer } ] = zone->GetHashValue( layer );
  381. // Add the zone to the list of zones to test or refill
  382. toFill.emplace_back( std::make_pair( zone, layer ) );
  383. isolatedIslandsMap[ zone ][ layer ] = ISOLATED_ISLANDS();
  384. }
  385. // Remove existing fill first to prevent drawing invalid polygons on some platforms
  386. zone->UnFill();
  387. }
  388. auto check_fill_dependency =
  389. [&]( ZONE* aZone, PCB_LAYER_ID aLayer, ZONE* aOtherZone ) -> bool
  390. {
  391. // Check to see if we have to knock-out the filled areas of a higher-priority
  392. // zone. If so we have to wait until said zone is filled before we can fill.
  393. // If the other zone is already filled on the requested layer then we're
  394. // good-to-go
  395. if( aOtherZone->GetFillFlag( aLayer ) )
  396. return false;
  397. // Even if keepouts exclude copper pours, the exclusion is by outline rather than
  398. // filled area, so we're good-to-go here too
  399. if( aOtherZone->GetIsRuleArea() )
  400. return false;
  401. // If the other zone is never going to be filled then don't wait for it
  402. if( aOtherZone->GetNumCorners() <= 2 )
  403. return false;
  404. // If the zones share no common layers
  405. if( !aOtherZone->GetLayerSet().test( aLayer ) )
  406. return false;
  407. if( aZone->HigherPriority( aOtherZone ) )
  408. return false;
  409. // Same-net zones always use outlines to produce determinate results
  410. if( aOtherZone->SameNet( aZone ) )
  411. return false;
  412. // A higher priority zone is found: if we intersect and it's not filled yet
  413. // then we have to wait.
  414. BOX2I inflatedBBox = aZone->GetBoundingBox();
  415. inflatedBBox.Inflate( m_worstClearance );
  416. if( !inflatedBBox.Intersects( aOtherZone->GetBoundingBox() ) )
  417. return false;
  418. return aZone->Outline()->Collide( aOtherZone->Outline(), m_worstClearance );
  419. };
  420. auto fill_lambda =
  421. [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
  422. {
  423. PCB_LAYER_ID layer = aFillItem.second;
  424. ZONE* zone = aFillItem.first;
  425. bool canFill = true;
  426. // Check for any fill dependencies. If our zone needs to be clipped by
  427. // another zone then we can't fill until that zone is filled.
  428. for( ZONE* otherZone : aZones )
  429. {
  430. if( otherZone == zone )
  431. continue;
  432. if( check_fill_dependency( zone, layer, otherZone ) )
  433. {
  434. canFill = false;
  435. break;
  436. }
  437. }
  438. if( m_progressReporter && m_progressReporter->IsCancelled() )
  439. return 0;
  440. if( !canFill )
  441. return 0;
  442. // Now we're ready to fill.
  443. {
  444. std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
  445. if( !zoneLock.owns_lock() )
  446. return 0;
  447. SHAPE_POLY_SET fillPolys;
  448. if( !fillSingleZone( zone, layer, fillPolys ) )
  449. return 0;
  450. zone->SetFilledPolysList( layer, fillPolys );
  451. }
  452. if( m_progressReporter )
  453. m_progressReporter->AdvanceProgress();
  454. return 1;
  455. };
  456. auto tesselate_lambda =
  457. [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
  458. {
  459. if( m_progressReporter && m_progressReporter->IsCancelled() )
  460. return 0;
  461. PCB_LAYER_ID layer = aFillItem.second;
  462. ZONE* zone = aFillItem.first;
  463. {
  464. std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
  465. if( !zoneLock.owns_lock() )
  466. return 0;
  467. zone->CacheTriangulation( layer );
  468. zone->SetFillFlag( layer, true );
  469. }
  470. return 1;
  471. };
  472. // Calculate the copper fills (NB: this is multi-threaded)
  473. //
  474. std::vector<std::pair<std::future<int>, int>> returns;
  475. returns.reserve( toFill.size() );
  476. size_t finished = 0;
  477. bool cancelled = false;
  478. thread_pool& tp = GetKiCadThreadPool();
  479. for( const std::pair<ZONE*, PCB_LAYER_ID>& fillItem : toFill )
  480. returns.emplace_back( std::make_pair( tp.submit( fill_lambda, fillItem ), 0 ) );
  481. while( !cancelled && finished != 2 * toFill.size() )
  482. {
  483. for( size_t ii = 0; ii < returns.size(); ++ii )
  484. {
  485. auto& ret = returns[ii];
  486. if( ret.second > 1 )
  487. continue;
  488. std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
  489. if( status == std::future_status::ready )
  490. {
  491. if( ret.first.get() ) // lambda completed
  492. {
  493. ++finished;
  494. ret.second++; // go to next step
  495. }
  496. if( !cancelled )
  497. {
  498. // Queue the next step (will re-queue the existing step if it didn't complete)
  499. if( ret.second == 0 )
  500. returns[ii].first = tp.submit( fill_lambda, toFill[ii] );
  501. else if( ret.second == 1 )
  502. returns[ii].first = tp.submit( tesselate_lambda, toFill[ii] );
  503. }
  504. }
  505. }
  506. std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
  507. if( m_progressReporter )
  508. {
  509. m_progressReporter->KeepRefreshing();
  510. if( m_progressReporter->IsCancelled() )
  511. cancelled = true;
  512. }
  513. }
  514. // Make sure that all futures have finished.
  515. // This can happen when the user cancels the above operation
  516. for( auto& ret : returns )
  517. {
  518. if( ret.first.valid() )
  519. {
  520. std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
  521. while( status != std::future_status::ready )
  522. {
  523. if( m_progressReporter )
  524. m_progressReporter->KeepRefreshing();
  525. status = ret.first.wait_for( std::chrono::milliseconds( 100 ) );
  526. }
  527. }
  528. }
  529. // Now update the connectivity to check for isolated copper islands
  530. // (NB: FindIsolatedCopperIslands() is multi-threaded)
  531. //
  532. if( m_progressReporter )
  533. {
  534. if( m_progressReporter->IsCancelled() )
  535. return false;
  536. m_progressReporter->AdvancePhase();
  537. m_progressReporter->Report( _( "Removing isolated copper islands..." ) );
  538. m_progressReporter->KeepRefreshing();
  539. }
  540. connectivity->SetProgressReporter( m_progressReporter );
  541. connectivity->FillIsolatedIslandsMap( isolatedIslandsMap );
  542. connectivity->SetProgressReporter( nullptr );
  543. if( m_progressReporter && m_progressReporter->IsCancelled() )
  544. return false;
  545. for( ZONE* zone : aZones )
  546. {
  547. // Keepout zones are not filled
  548. if( zone->GetIsRuleArea() )
  549. continue;
  550. zone->SetIsFilled( true );
  551. }
  552. // Now remove isolated copper islands according to the isolated islands strategy assigned
  553. // by the user (always, never, below-certain-size).
  554. //
  555. for( const auto& [ zone, zoneIslands ] : isolatedIslandsMap )
  556. {
  557. // If *all* the polygons are islands, do not remove any of them
  558. bool allIslands = true;
  559. for( const auto& [ layer, layerIslands ] : zoneIslands )
  560. {
  561. if( layerIslands.m_IsolatedOutlines.size()
  562. != static_cast<size_t>( zone->GetFilledPolysList( layer )->OutlineCount() ) )
  563. {
  564. allIslands = false;
  565. break;
  566. }
  567. }
  568. if( allIslands )
  569. continue;
  570. for( const auto& [ layer, layerIslands ] : zoneIslands )
  571. {
  572. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
  573. continue;
  574. if( layerIslands.m_IsolatedOutlines.empty() )
  575. continue;
  576. std::vector<int> islands = layerIslands.m_IsolatedOutlines;
  577. // The list of polygons to delete must be explored from last to first in list,
  578. // to allow deleting a polygon from list without breaking the remaining of the list
  579. std::sort( islands.begin(), islands.end(), std::greater<int>() );
  580. std::shared_ptr<SHAPE_POLY_SET> poly = zone->GetFilledPolysList( layer );
  581. long long int minArea = zone->GetMinIslandArea();
  582. ISLAND_REMOVAL_MODE mode = zone->GetIslandRemovalMode();
  583. for( int idx : islands )
  584. {
  585. SHAPE_LINE_CHAIN& outline = poly->Outline( idx );
  586. if( mode == ISLAND_REMOVAL_MODE::ALWAYS )
  587. poly->DeletePolygonAndTriangulationData( idx, false );
  588. else if ( mode == ISLAND_REMOVAL_MODE::AREA && outline.Area( true ) < minArea )
  589. poly->DeletePolygonAndTriangulationData( idx, false );
  590. else
  591. zone->SetIsIsland( layer, idx );
  592. }
  593. poly->UpdateTriangulationDataHash();
  594. zone->CalculateFilledArea();
  595. if( m_progressReporter && m_progressReporter->IsCancelled() )
  596. return false;
  597. }
  598. }
  599. // Now remove islands which are either outside the board edge or fail to meet the minimum
  600. // area requirements
  601. using island_check_return = std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, int>>;
  602. std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, double>> polys_to_check;
  603. // rough estimate to save re-allocation time
  604. polys_to_check.reserve( m_board->GetCopperLayerCount() * aZones.size() );
  605. for( ZONE* zone : aZones )
  606. {
  607. // Don't check for connections on layers that only exist in the zone but
  608. // were disabled in the board
  609. BOARD* board = zone->GetBoard();
  610. LSET zoneCopperLayers = zone->GetLayerSet() & LSET::AllCuMask() & board->GetEnabledLayers();
  611. // Min-thickness is the web thickness. On the other hand, a blob min-thickness by
  612. // min-thickness is not useful. Since there's no obvious definition of web vs. blob, we
  613. // arbitrarily choose "at least 3X the area".
  614. double minArea = (double) zone->GetMinThickness() * zone->GetMinThickness() * 3;
  615. for( PCB_LAYER_ID layer : zoneCopperLayers.Seq() )
  616. {
  617. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
  618. continue;
  619. polys_to_check.emplace_back( zone->GetFilledPolysList( layer ), minArea );
  620. }
  621. }
  622. auto island_lambda =
  623. [&]( int aStart, int aEnd ) -> island_check_return
  624. {
  625. island_check_return retval;
  626. for( int ii = aStart; ii < aEnd && !cancelled; ++ii )
  627. {
  628. auto [poly, minArea] = polys_to_check[ii];
  629. for( int jj = poly->OutlineCount() - 1; jj >= 0; jj-- )
  630. {
  631. SHAPE_POLY_SET island;
  632. SHAPE_POLY_SET intersection;
  633. const SHAPE_LINE_CHAIN& test_poly = poly->Polygon( jj ).front();
  634. double island_area = test_poly.Area();
  635. if( island_area < minArea )
  636. continue;
  637. island.AddOutline( test_poly );
  638. intersection.BooleanIntersection( m_boardOutline, island,
  639. SHAPE_POLY_SET::POLYGON_MODE::PM_FAST );
  640. // Nominally, all of these areas should be either inside or outside the
  641. // board outline. So this test should be able to just compare areas (if
  642. // they are equal, you are inside). But in practice, we sometimes have
  643. // slight overlap at the edges, so testing against half-size area acts as
  644. // a fail-safe.
  645. if( intersection.Area() < island_area / 2.0 )
  646. retval.emplace_back( poly, jj );
  647. }
  648. }
  649. return retval;
  650. };
  651. auto island_returns = tp.parallelize_loop( 0, polys_to_check.size(), island_lambda );
  652. cancelled = false;
  653. // Allow island removal threads to finish
  654. for( size_t ii = 0; ii < island_returns.size(); ++ii )
  655. {
  656. std::future<island_check_return>& ret = island_returns[ii];
  657. if( ret.valid() )
  658. {
  659. std::future_status status = ret.wait_for( std::chrono::seconds( 0 ) );
  660. while( status != std::future_status::ready )
  661. {
  662. if( m_progressReporter )
  663. {
  664. m_progressReporter->KeepRefreshing();
  665. if( m_progressReporter->IsCancelled() )
  666. cancelled = true;
  667. }
  668. status = ret.wait_for( std::chrono::milliseconds( 100 ) );
  669. }
  670. }
  671. }
  672. if( cancelled )
  673. return false;
  674. for( size_t ii = 0; ii < island_returns.size(); ++ii )
  675. {
  676. std::future<island_check_return>& ret = island_returns[ii];
  677. if( ret.valid() )
  678. {
  679. for( auto& action_item : ret.get() )
  680. action_item.first->DeletePolygonAndTriangulationData( action_item.second, true );
  681. }
  682. }
  683. for( ZONE* zone : aZones )
  684. zone->CalculateFilledArea();
  685. if( aCheck )
  686. {
  687. bool outOfDate = false;
  688. for( ZONE* zone : aZones )
  689. {
  690. // Keepout zones are not filled
  691. if( zone->GetIsRuleArea() )
  692. continue;
  693. for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
  694. {
  695. zone->BuildHashValue( layer );
  696. if( oldFillHashes[ { zone, layer } ] != zone->GetHashValue( layer ) )
  697. outOfDate = true;
  698. }
  699. }
  700. if( outOfDate )
  701. {
  702. KIDIALOG dlg( aParent, _( "Zone fills are out-of-date. Refill?" ),
  703. _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
  704. dlg.SetOKCancelLabels( _( "Refill" ), _( "Continue without Refill" ) );
  705. dlg.DoNotShowCheckbox( __FILE__, __LINE__ );
  706. if( dlg.ShowModal() == wxID_CANCEL )
  707. return false;
  708. }
  709. else
  710. {
  711. // No need to commit something that hasn't changed (and committing will set
  712. // the modified flag).
  713. return false;
  714. }
  715. }
  716. if( m_progressReporter )
  717. {
  718. if( m_progressReporter->IsCancelled() )
  719. return false;
  720. m_progressReporter->AdvancePhase();
  721. m_progressReporter->KeepRefreshing();
  722. }
  723. return true;
  724. }
  725. /**
  726. * Add a knockout for a pad. The knockout is 'aGap' larger than the pad (which might be
  727. * either the thermal clearance or the electrical clearance).
  728. */
  729. void ZONE_FILLER::addKnockout( PAD* aPad, PCB_LAYER_ID aLayer, int aGap, SHAPE_POLY_SET& aHoles )
  730. {
  731. if( aPad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
  732. {
  733. SHAPE_POLY_SET poly;
  734. aPad->TransformShapeToPolygon( poly, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  735. // the pad shape in zone can be its convex hull or the shape itself
  736. if( aPad->GetCustomShapeInZoneOpt() == PADSTACK::CUSTOM_SHAPE_ZONE_MODE::CONVEXHULL )
  737. {
  738. std::vector<VECTOR2I> convex_hull;
  739. BuildConvexHull( convex_hull, poly );
  740. aHoles.NewOutline();
  741. for( const VECTOR2I& pt : convex_hull )
  742. aHoles.Append( pt );
  743. }
  744. else
  745. aHoles.Append( poly );
  746. }
  747. else
  748. {
  749. aPad->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  750. }
  751. }
  752. /**
  753. * Add a knockout for a pad's hole.
  754. */
  755. void ZONE_FILLER::addHoleKnockout( PAD* aPad, int aGap, SHAPE_POLY_SET& aHoles )
  756. {
  757. aPad->TransformHoleToPolygon( aHoles, aGap, m_maxError, ERROR_OUTSIDE );
  758. }
  759. /**
  760. * Add a knockout for a graphic item. The knockout is 'aGap' larger than the item (which
  761. * might be either the electrical clearance or the board edge clearance).
  762. */
  763. void ZONE_FILLER::addKnockout( BOARD_ITEM* aItem, PCB_LAYER_ID aLayer, int aGap,
  764. bool aIgnoreLineWidth, SHAPE_POLY_SET& aHoles )
  765. {
  766. switch( aItem->Type() )
  767. {
  768. case PCB_FIELD_T:
  769. case PCB_TEXT_T:
  770. {
  771. PCB_TEXT* text = static_cast<PCB_TEXT*>( aItem );
  772. if( text->IsVisible() )
  773. {
  774. if( text->IsKnockout() )
  775. {
  776. // Knockout text should only leave holes where the text is, not where the copper fill
  777. // around it would be.
  778. PCB_TEXT textCopy = *text;
  779. textCopy.SetIsKnockout( false );
  780. textCopy.TransformShapeToPolygon( aHoles, aLayer, 0, m_maxError, ERROR_OUTSIDE );
  781. }
  782. else
  783. {
  784. text->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  785. }
  786. }
  787. break;
  788. }
  789. case PCB_TEXTBOX_T:
  790. case PCB_TABLE_T:
  791. case PCB_SHAPE_T:
  792. case PCB_TARGET_T:
  793. aItem->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE,
  794. aIgnoreLineWidth );
  795. break;
  796. case PCB_DIM_ALIGNED_T:
  797. case PCB_DIM_LEADER_T:
  798. case PCB_DIM_CENTER_T:
  799. case PCB_DIM_RADIAL_T:
  800. case PCB_DIM_ORTHOGONAL_T:
  801. {
  802. PCB_DIMENSION_BASE* dim = static_cast<PCB_DIMENSION_BASE*>( aItem );
  803. dim->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE, false );
  804. dim->PCB_TEXT::TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  805. break;
  806. }
  807. default:
  808. break;
  809. }
  810. }
  811. /**
  812. * Removes thermal reliefs from the shape for any pads connected to the zone. Does NOT add
  813. * in spokes, which must be done later.
  814. */
  815. void ZONE_FILLER::knockoutThermalReliefs( const ZONE* aZone, PCB_LAYER_ID aLayer,
  816. SHAPE_POLY_SET& aFill,
  817. std::vector<PAD*>& aThermalConnectionPads,
  818. std::vector<PAD*>& aNoConnectionPads )
  819. {
  820. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  821. ZONE_CONNECTION connection;
  822. DRC_CONSTRAINT constraint;
  823. int padClearance;
  824. std::shared_ptr<SHAPE> padShape;
  825. int holeClearance;
  826. SHAPE_POLY_SET holes;
  827. for( FOOTPRINT* footprint : m_board->Footprints() )
  828. {
  829. for( PAD* pad : footprint->Pads() )
  830. {
  831. BOX2I padBBox = pad->GetBoundingBox();
  832. padBBox.Inflate( m_worstClearance );
  833. if( !padBBox.Intersects( aZone->GetBoundingBox() ) )
  834. continue;
  835. bool noConnection = pad->GetNetCode() != aZone->GetNetCode();
  836. if( !aZone->IsTeardropArea() )
  837. {
  838. if( aZone->GetNetCode() == 0
  839. || pad->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
  840. {
  841. noConnection = true;
  842. }
  843. }
  844. if( noConnection )
  845. {
  846. // collect these for knockout in buildCopperItemClearances()
  847. aNoConnectionPads.push_back( pad );
  848. continue;
  849. }
  850. if( aZone->IsTeardropArea() )
  851. {
  852. connection = ZONE_CONNECTION::FULL;
  853. }
  854. else
  855. {
  856. constraint = bds.m_DRCEngine->EvalZoneConnection( pad, aZone, aLayer );
  857. connection = constraint.m_ZoneConnection;
  858. }
  859. if( connection == ZONE_CONNECTION::THERMAL && !pad->CanFlashLayer( aLayer ) )
  860. connection = ZONE_CONNECTION::NONE;
  861. switch( connection )
  862. {
  863. case ZONE_CONNECTION::THERMAL:
  864. padShape = pad->GetEffectiveShape( aLayer, FLASHING::ALWAYS_FLASHED );
  865. if( aFill.Collide( padShape.get(), 0 ) )
  866. {
  867. constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad,
  868. aZone, aLayer );
  869. padClearance = constraint.GetValue().Min();
  870. aThermalConnectionPads.push_back( pad );
  871. addKnockout( pad, aLayer, padClearance, holes );
  872. }
  873. break;
  874. case ZONE_CONNECTION::NONE:
  875. constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_CLEARANCE_CONSTRAINT, pad,
  876. aZone, aLayer );
  877. if( constraint.GetValue().Min() > aZone->GetLocalClearance().value() )
  878. padClearance = constraint.GetValue().Min();
  879. else
  880. padClearance = aZone->GetLocalClearance().value();
  881. if( pad->FlashLayer( aLayer ) )
  882. {
  883. addKnockout( pad, aLayer, padClearance, holes );
  884. }
  885. else if( pad->GetDrillSize().x > 0 )
  886. {
  887. constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
  888. pad, aZone, aLayer );
  889. if( constraint.GetValue().Min() > padClearance )
  890. holeClearance = constraint.GetValue().Min();
  891. else
  892. holeClearance = padClearance;
  893. pad->TransformHoleToPolygon( holes, holeClearance, m_maxError, ERROR_OUTSIDE );
  894. }
  895. break;
  896. default:
  897. // No knockout
  898. continue;
  899. }
  900. }
  901. }
  902. aFill.BooleanSubtract( holes, SHAPE_POLY_SET::PM_FAST );
  903. }
  904. /**
  905. * Removes clearance from the shape for copper items which share the zone's layer but are
  906. * not connected to it.
  907. */
  908. void ZONE_FILLER::buildCopperItemClearances( const ZONE* aZone, PCB_LAYER_ID aLayer,
  909. const std::vector<PAD*>& aNoConnectionPads,
  910. SHAPE_POLY_SET& aHoles )
  911. {
  912. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  913. long ticker = 0;
  914. auto checkForCancel =
  915. [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
  916. {
  917. return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
  918. };
  919. // A small extra clearance to be sure actual track clearances are not smaller than
  920. // requested clearance due to many approximations in calculations, like arc to segment
  921. // approx, rounding issues, etc.
  922. BOX2I zone_boundingbox = aZone->GetBoundingBox();
  923. int extra_margin = pcbIUScale.mmToIU( ADVANCED_CFG::GetCfg().m_ExtraClearance );
  924. // Items outside the zone bounding box are skipped, so it needs to be inflated by the
  925. // largest clearance value found in the netclasses and rules
  926. zone_boundingbox.Inflate( m_worstClearance + extra_margin );
  927. auto evalRulesForItems =
  928. [&bds]( DRC_CONSTRAINT_T aConstraint, const BOARD_ITEM* a, const BOARD_ITEM* b,
  929. PCB_LAYER_ID aEvalLayer ) -> int
  930. {
  931. DRC_CONSTRAINT c = bds.m_DRCEngine->EvalRules( aConstraint, a, b, aEvalLayer );
  932. if( c.IsNull() )
  933. return -1;
  934. else
  935. return c.GetValue().Min();
  936. };
  937. // Add non-connected pad clearances
  938. //
  939. auto knockoutPadClearance =
  940. [&]( PAD* aPad )
  941. {
  942. int init_gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone, aPad, aLayer );
  943. int gap = init_gap;
  944. bool hasHole = aPad->GetDrillSize().x > 0;
  945. bool flashLayer = aPad->FlashLayer( aLayer );
  946. bool platedHole = hasHole && aPad->GetAttribute() == PAD_ATTRIB::PTH;
  947. if( flashLayer || platedHole )
  948. {
  949. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
  950. aZone, aPad, aLayer ) );
  951. }
  952. if( flashLayer && gap >= 0 )
  953. addKnockout( aPad, aLayer, gap + extra_margin, aHoles );
  954. if( hasHole )
  955. {
  956. // NPTH do not need copper clearance gaps to their holes
  957. if( aPad->GetAttribute() == PAD_ATTRIB::NPTH )
  958. gap = init_gap;
  959. gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
  960. aZone, aPad, aLayer ) );
  961. gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
  962. aZone, aPad, aLayer ) );
  963. if( gap >= 0 )
  964. addHoleKnockout( aPad, gap + extra_margin, aHoles );
  965. }
  966. };
  967. for( PAD* pad : aNoConnectionPads )
  968. {
  969. if( checkForCancel( m_progressReporter ) )
  970. return;
  971. knockoutPadClearance( pad );
  972. }
  973. // Add non-connected track clearances
  974. //
  975. auto knockoutTrackClearance =
  976. [&]( PCB_TRACK* aTrack )
  977. {
  978. if( aTrack->GetBoundingBox().Intersects( zone_boundingbox ) )
  979. {
  980. bool sameNet = aTrack->GetNetCode() == aZone->GetNetCode();
  981. if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
  982. sameNet = false;
  983. int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
  984. aZone, aTrack, aLayer );
  985. if( aTrack->Type() == PCB_VIA_T )
  986. {
  987. PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
  988. if( via->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
  989. sameNet = false;
  990. }
  991. if( !sameNet )
  992. {
  993. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
  994. aZone, aTrack, aLayer ) );
  995. }
  996. if( aTrack->Type() == PCB_VIA_T )
  997. {
  998. PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
  999. if( via->FlashLayer( aLayer ) && gap > 0 )
  1000. {
  1001. via->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
  1002. m_maxError, ERROR_OUTSIDE );
  1003. }
  1004. gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
  1005. aZone, via, aLayer ) );
  1006. if( !sameNet )
  1007. {
  1008. gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
  1009. aZone, via, aLayer ) );
  1010. }
  1011. if( gap >= 0 )
  1012. {
  1013. int radius = via->GetDrillValue() / 2;
  1014. TransformCircleToPolygon( aHoles, via->GetPosition(),
  1015. radius + gap + extra_margin,
  1016. m_maxError, ERROR_OUTSIDE );
  1017. }
  1018. }
  1019. else
  1020. {
  1021. if( gap >= 0 )
  1022. {
  1023. aTrack->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
  1024. m_maxError, ERROR_OUTSIDE );
  1025. }
  1026. }
  1027. }
  1028. };
  1029. for( PCB_TRACK* track : m_board->Tracks() )
  1030. {
  1031. if( !track->IsOnLayer( aLayer ) )
  1032. continue;
  1033. if( checkForCancel( m_progressReporter ) )
  1034. return;
  1035. knockoutTrackClearance( track );
  1036. }
  1037. // Add graphic item clearances.
  1038. //
  1039. auto knockoutGraphicClearance =
  1040. [&]( BOARD_ITEM* aItem )
  1041. {
  1042. int shapeNet = -1;
  1043. if( aItem->Type() == PCB_SHAPE_T )
  1044. shapeNet = static_cast<PCB_SHAPE*>( aItem )->GetNetCode();
  1045. bool sameNet = shapeNet == aZone->GetNetCode();
  1046. if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
  1047. sameNet = false;
  1048. // A item on the Edge_Cuts or Margin is always seen as on any layer:
  1049. if( aItem->IsOnLayer( aLayer )
  1050. || aItem->IsOnLayer( Edge_Cuts )
  1051. || aItem->IsOnLayer( Margin ) )
  1052. {
  1053. if( aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
  1054. {
  1055. bool ignoreLineWidths = false;
  1056. int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
  1057. aZone, aItem, aLayer );
  1058. if( aItem->IsOnLayer( aLayer ) && !sameNet )
  1059. {
  1060. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
  1061. aZone, aItem, aLayer ) );
  1062. }
  1063. else if( aItem->IsOnLayer( Edge_Cuts ) )
  1064. {
  1065. gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
  1066. aZone, aItem, aLayer ) );
  1067. ignoreLineWidths = true;
  1068. }
  1069. else if( aItem->IsOnLayer( Margin ) )
  1070. {
  1071. gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
  1072. aZone, aItem, aLayer ) );
  1073. }
  1074. if( gap >= 0 )
  1075. {
  1076. gap += extra_margin;
  1077. addKnockout( aItem, aLayer, gap, ignoreLineWidths, aHoles );
  1078. }
  1079. }
  1080. }
  1081. };
  1082. auto knockoutCourtyardClearance =
  1083. [&]( FOOTPRINT* aFootprint )
  1084. {
  1085. if( aFootprint->GetBoundingBox().Intersects( zone_boundingbox ) )
  1086. {
  1087. int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone,
  1088. aFootprint, aLayer );
  1089. if( gap == 0 )
  1090. {
  1091. aHoles.Append( aFootprint->GetCourtyard( aLayer ) );
  1092. }
  1093. else if( gap > 0 )
  1094. {
  1095. SHAPE_POLY_SET hole = aFootprint->GetCourtyard( aLayer );
  1096. hole.Inflate( gap, CORNER_STRATEGY::ROUND_ALL_CORNERS, m_maxError );
  1097. aHoles.Append( hole );
  1098. }
  1099. }
  1100. };
  1101. for( FOOTPRINT* footprint : m_board->Footprints() )
  1102. {
  1103. knockoutCourtyardClearance( footprint );
  1104. knockoutGraphicClearance( &footprint->Reference() );
  1105. knockoutGraphicClearance( &footprint->Value() );
  1106. std::set<PAD*> allowedNetTiePads;
  1107. // Don't knock out holes for graphic items which implement a net-tie to the zone's net
  1108. // on the layer being filled.
  1109. if( footprint->IsNetTie() )
  1110. {
  1111. for( PAD* pad : footprint->Pads() )
  1112. {
  1113. bool sameNet = pad->GetNetCode() == aZone->GetNetCode();
  1114. if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
  1115. sameNet = false;
  1116. if( sameNet )
  1117. {
  1118. if( pad->IsOnLayer( aLayer ) )
  1119. allowedNetTiePads.insert( pad );
  1120. for( PAD* other : footprint->GetNetTiePads( pad ) )
  1121. {
  1122. if( other->IsOnLayer( aLayer ) )
  1123. allowedNetTiePads.insert( other );
  1124. }
  1125. }
  1126. }
  1127. }
  1128. for( BOARD_ITEM* item : footprint->GraphicalItems() )
  1129. {
  1130. if( checkForCancel( m_progressReporter ) )
  1131. return;
  1132. BOX2I itemBBox = item->GetBoundingBox();
  1133. if( !zone_boundingbox.Intersects( itemBBox ) )
  1134. continue;
  1135. bool skipItem = false;
  1136. if( item->IsOnLayer( aLayer ) )
  1137. {
  1138. std::shared_ptr<SHAPE> itemShape = item->GetEffectiveShape();
  1139. for( PAD* pad : allowedNetTiePads )
  1140. {
  1141. if( pad->GetBoundingBox().Intersects( itemBBox )
  1142. && pad->GetEffectiveShape( aLayer )->Collide( itemShape.get() ) )
  1143. {
  1144. skipItem = true;
  1145. break;
  1146. }
  1147. }
  1148. }
  1149. if( !skipItem )
  1150. knockoutGraphicClearance( item );
  1151. }
  1152. }
  1153. for( BOARD_ITEM* item : m_board->Drawings() )
  1154. {
  1155. if( checkForCancel( m_progressReporter ) )
  1156. return;
  1157. knockoutGraphicClearance( item );
  1158. }
  1159. // Add non-connected zone clearances
  1160. //
  1161. auto knockoutZoneClearance =
  1162. [&]( ZONE* aKnockout )
  1163. {
  1164. // If the zones share no common layers
  1165. if( !aKnockout->GetLayerSet().test( aLayer ) )
  1166. return;
  1167. if( aKnockout->GetBoundingBox().Intersects( zone_boundingbox ) )
  1168. {
  1169. if( aKnockout->GetIsRuleArea() )
  1170. {
  1171. // Keepouts use outline with no clearance
  1172. aKnockout->TransformSmoothedOutlineToPolygon( aHoles, 0, m_maxError,
  1173. ERROR_OUTSIDE, nullptr );
  1174. }
  1175. else
  1176. {
  1177. int gap = std::max( 0, evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
  1178. aZone, aKnockout, aLayer ) );
  1179. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
  1180. aZone, aKnockout, aLayer ) );
  1181. SHAPE_POLY_SET poly;
  1182. aKnockout->TransformShapeToPolygon( poly, aLayer, gap + extra_margin,
  1183. m_maxError, ERROR_OUTSIDE );
  1184. aHoles.Append( poly );
  1185. }
  1186. }
  1187. };
  1188. for( ZONE* otherZone : m_board->Zones() )
  1189. {
  1190. if( checkForCancel( m_progressReporter ) )
  1191. return;
  1192. // Negative clearance permits zones to short
  1193. if( evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, otherZone, aLayer ) < 0 )
  1194. continue;
  1195. if( otherZone->GetIsRuleArea() )
  1196. {
  1197. if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
  1198. knockoutZoneClearance( otherZone );
  1199. }
  1200. else if( otherZone->HigherPriority( aZone ) )
  1201. {
  1202. if( !otherZone->SameNet( aZone ) )
  1203. knockoutZoneClearance( otherZone );
  1204. }
  1205. }
  1206. for( FOOTPRINT* footprint : m_board->Footprints() )
  1207. {
  1208. for( ZONE* otherZone : footprint->Zones() )
  1209. {
  1210. if( checkForCancel( m_progressReporter ) )
  1211. return;
  1212. if( otherZone->GetIsRuleArea() )
  1213. {
  1214. if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
  1215. knockoutZoneClearance( otherZone );
  1216. }
  1217. else if( otherZone->HigherPriority( aZone ) )
  1218. {
  1219. if( !otherZone->SameNet( aZone ) )
  1220. knockoutZoneClearance( otherZone );
  1221. }
  1222. }
  1223. }
  1224. aHoles.Simplify( SHAPE_POLY_SET::PM_FAST );
  1225. }
  1226. /**
  1227. * Removes the outlines of higher-proirity zones with the same net. These zones should be
  1228. * in charge of the fill parameters within their own outlines.
  1229. */
  1230. void ZONE_FILLER::subtractHigherPriorityZones( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1231. SHAPE_POLY_SET& aRawFill )
  1232. {
  1233. BOX2I zoneBBox = aZone->GetBoundingBox();
  1234. auto knockoutZoneOutline =
  1235. [&]( ZONE* aKnockout )
  1236. {
  1237. // If the zones share no common layers
  1238. if( !aKnockout->GetLayerSet().test( aLayer ) )
  1239. return;
  1240. if( aKnockout->GetBoundingBox().Intersects( zoneBBox ) )
  1241. {
  1242. // Processing of arc shapes in zones is not yet supported because Clipper
  1243. // can't do boolean operations on them. The poly outline must be converted to
  1244. // segments first.
  1245. SHAPE_POLY_SET outline = aKnockout->Outline()->CloneDropTriangulation();
  1246. outline.ClearArcs();
  1247. aRawFill.BooleanSubtract( outline, SHAPE_POLY_SET::PM_FAST );
  1248. }
  1249. };
  1250. for( ZONE* otherZone : m_board->Zones() )
  1251. {
  1252. // Don't use the `HigherPriority()` check here because we _only_ want to knock out zones
  1253. // with explicitly higher priorities, not those with equal priorities
  1254. if( otherZone->SameNet( aZone )
  1255. && otherZone->GetAssignedPriority() > aZone->GetAssignedPriority() )
  1256. {
  1257. // Do not remove teardrop area: it is not useful and not good
  1258. if( !otherZone->IsTeardropArea() )
  1259. knockoutZoneOutline( otherZone );
  1260. }
  1261. }
  1262. for( FOOTPRINT* footprint : m_board->Footprints() )
  1263. {
  1264. for( ZONE* otherZone : footprint->Zones() )
  1265. {
  1266. if( otherZone->SameNet( aZone ) && otherZone->HigherPriority( aZone ) )
  1267. {
  1268. // Do not remove teardrop area: it is not useful and not good
  1269. if( !otherZone->IsTeardropArea() )
  1270. knockoutZoneOutline( otherZone );
  1271. }
  1272. }
  1273. }
  1274. }
  1275. void ZONE_FILLER::connect_nearby_polys( SHAPE_POLY_SET& aPolys, double aDistance )
  1276. {
  1277. if( aPolys.OutlineCount() < 1 )
  1278. return;
  1279. VERTEX_CONNECTOR vs( aPolys.BBoxFromCaches(), aPolys, aDistance );
  1280. vs.FindResults();
  1281. // This cannot be a reference because we need to do the comparison below while
  1282. // changing the values
  1283. std::map<int, std::vector<std::pair<int, VECTOR2I>>> insertion_points;
  1284. for( const RESULTS& result : vs.GetResults() )
  1285. {
  1286. SHAPE_LINE_CHAIN& line1 = aPolys.Outline( result.m_outline1 );
  1287. SHAPE_LINE_CHAIN& line2 = aPolys.Outline( result.m_outline2 );
  1288. VECTOR2I pt1 = line1.CPoint( result.m_vertex1 );
  1289. VECTOR2I pt2 = line2.CPoint( result.m_vertex2 );
  1290. // We want to insert the existing point first so that we can place the new point
  1291. // between the two points at the same location.
  1292. insertion_points[result.m_outline1].push_back( { result.m_vertex1, pt1 } );
  1293. insertion_points[result.m_outline1].push_back( { result.m_vertex1, pt2 } );
  1294. }
  1295. for( auto& [outline, vertices] : insertion_points )
  1296. {
  1297. SHAPE_LINE_CHAIN& line = aPolys.Outline( outline );
  1298. // Stable sort here because we want to make sure that we are inserting pt1 first and
  1299. // pt2 second but still sorting the rest of the indices from highest to lowest.
  1300. // This allows us to insert into the existing polygon without modifying the future
  1301. // insertion points.
  1302. std::stable_sort( vertices.begin(), vertices.end(),
  1303. []( const std::pair<int, VECTOR2I>& a, const std::pair<int, VECTOR2I>& b )
  1304. { return a.first > b.first; } );
  1305. for( const auto& [vertex, pt] : vertices )
  1306. line.Insert( vertex + 1, pt ); // +1 here because we want to insert after the existing point
  1307. }
  1308. }
  1309. #define DUMP_POLYS_TO_COPPER_LAYER( a, b, c ) \
  1310. { if( m_debugZoneFiller && aDebugLayer == b ) \
  1311. { \
  1312. m_board->SetLayerName( b, c ); \
  1313. SHAPE_POLY_SET d = a; \
  1314. d.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE ); \
  1315. aFillPolys = d; \
  1316. return false; \
  1317. } \
  1318. }
  1319. /**
  1320. * 1 - Creates the main zone outline using a correction to shrink the resulting area by
  1321. * m_ZoneMinThickness / 2. The result is areas with a margin of m_ZoneMinThickness / 2
  1322. * so that when drawing outline with segments having a thickness of m_ZoneMinThickness the
  1323. * outlines will match exactly the initial outlines
  1324. * 2 - Knocks out thermal reliefs around thermally-connected pads
  1325. * 3 - Builds a set of thermal spoke for the whole zone
  1326. * 4 - Knocks out unconnected copper items, deleting any affected spokes
  1327. * 5 - Removes unconnected copper islands, deleting any affected spokes
  1328. * 6 - Adds in the remaining spokes
  1329. */
  1330. bool ZONE_FILLER::fillCopperZone( const ZONE* aZone, PCB_LAYER_ID aLayer, PCB_LAYER_ID aDebugLayer,
  1331. const SHAPE_POLY_SET& aSmoothedOutline,
  1332. const SHAPE_POLY_SET& aMaxExtents, SHAPE_POLY_SET& aFillPolys )
  1333. {
  1334. m_maxError = m_board->GetDesignSettings().m_MaxError;
  1335. // Features which are min_width should survive pruning; features that are *less* than
  1336. // min_width should not. Therefore we subtract epsilon from the min_width when
  1337. // deflating/inflating.
  1338. int half_min_width = aZone->GetMinThickness() / 2;
  1339. int epsilon = pcbIUScale.mmToIU( 0.001 );
  1340. // Solid polygons are deflated and inflated during calculations. Deflating doesn't cause
  1341. // issues, but inflate is tricky as it can create excessively long and narrow spikes for
  1342. // acute angles.
  1343. // ALLOW_ACUTE_CORNERS cannot be used due to the spike problem.
  1344. // CHAMFER_ACUTE_CORNERS is tempting, but can still produce spikes in some unusual
  1345. // circumstances (https://gitlab.com/kicad/code/kicad/-/issues/5581).
  1346. // It's unclear if ROUND_ACUTE_CORNERS would have the same issues, but is currently avoided
  1347. // as a "less-safe" option.
  1348. // ROUND_ALL_CORNERS produces the uniformly nicest shapes, but also a lot of segments.
  1349. // CHAMFER_ALL_CORNERS improves the segment count.
  1350. CORNER_STRATEGY fastCornerStrategy = CORNER_STRATEGY::CHAMFER_ALL_CORNERS;
  1351. CORNER_STRATEGY cornerStrategy = CORNER_STRATEGY::ROUND_ALL_CORNERS;
  1352. std::vector<PAD*> thermalConnectionPads;
  1353. std::vector<PAD*> noConnectionPads;
  1354. std::deque<SHAPE_LINE_CHAIN> thermalSpokes;
  1355. SHAPE_POLY_SET clearanceHoles;
  1356. aFillPolys = aSmoothedOutline;
  1357. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In1_Cu, wxT( "smoothed-outline" ) );
  1358. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1359. return false;
  1360. /* -------------------------------------------------------------------------------------
  1361. * Knockout thermal reliefs.
  1362. */
  1363. knockoutThermalReliefs( aZone, aLayer, aFillPolys, thermalConnectionPads, noConnectionPads );
  1364. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In2_Cu, wxT( "minus-thermal-reliefs" ) );
  1365. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1366. return false;
  1367. /* -------------------------------------------------------------------------------------
  1368. * Knockout electrical clearances.
  1369. */
  1370. buildCopperItemClearances( aZone, aLayer, noConnectionPads, clearanceHoles );
  1371. DUMP_POLYS_TO_COPPER_LAYER( clearanceHoles, In3_Cu, wxT( "clearance-holes" ) );
  1372. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1373. return false;
  1374. /* -------------------------------------------------------------------------------------
  1375. * Add thermal relief spokes.
  1376. */
  1377. buildThermalSpokes( aZone, aLayer, thermalConnectionPads, thermalSpokes );
  1378. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1379. return false;
  1380. // Create a temporary zone that we can hit-test spoke-ends against. It's only temporary
  1381. // because the "real" subtract-clearance-holes has to be done after the spokes are added.
  1382. static const bool USE_BBOX_CACHES = true;
  1383. SHAPE_POLY_SET testAreas = aFillPolys.CloneDropTriangulation();
  1384. testAreas.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1385. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In4_Cu, wxT( "minus-clearance-holes" ) );
  1386. // Prune features that don't meet minimum-width criteria
  1387. if( half_min_width - epsilon > epsilon )
  1388. {
  1389. testAreas.Deflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
  1390. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In5_Cu, wxT( "spoke-test-deflated" ) );
  1391. testAreas.Inflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
  1392. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In6_Cu, wxT( "spoke-test-reinflated" ) );
  1393. }
  1394. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1395. return false;
  1396. // Spoke-end-testing is hugely expensive so we generate cached bounding-boxes to speed
  1397. // things up a bit.
  1398. testAreas.BuildBBoxCaches();
  1399. int interval = 0;
  1400. SHAPE_POLY_SET debugSpokes;
  1401. for( const SHAPE_LINE_CHAIN& spoke : thermalSpokes )
  1402. {
  1403. const VECTOR2I& testPt = spoke.CPoint( 3 );
  1404. // Hit-test against zone body
  1405. if( testAreas.Contains( testPt, -1, 1, USE_BBOX_CACHES ) )
  1406. {
  1407. if( m_debugZoneFiller )
  1408. debugSpokes.AddOutline( spoke );
  1409. aFillPolys.AddOutline( spoke );
  1410. continue;
  1411. }
  1412. if( interval++ > 400 )
  1413. {
  1414. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1415. return false;
  1416. interval = 0;
  1417. }
  1418. // Hit-test against other spokes
  1419. for( const SHAPE_LINE_CHAIN& other : thermalSpokes )
  1420. {
  1421. // Hit test in both directions to avoid interactions with round-off errors.
  1422. // (See https://gitlab.com/kicad/code/kicad/-/issues/13316.)
  1423. if( &other != &spoke
  1424. && other.PointInside( testPt, 1, USE_BBOX_CACHES )
  1425. && spoke.PointInside( other.CPoint( 3 ), 1, USE_BBOX_CACHES ) )
  1426. {
  1427. if( m_debugZoneFiller )
  1428. debugSpokes.AddOutline( spoke );
  1429. aFillPolys.AddOutline( spoke );
  1430. break;
  1431. }
  1432. }
  1433. }
  1434. DUMP_POLYS_TO_COPPER_LAYER( debugSpokes, In7_Cu, wxT( "spokes" ) );
  1435. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1436. return false;
  1437. aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1438. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In8_Cu, wxT( "after-spoke-trimming" ) );
  1439. /* -------------------------------------------------------------------------------------
  1440. * Prune features that don't meet minimum-width criteria
  1441. */
  1442. if( half_min_width - epsilon > epsilon )
  1443. aFillPolys.Deflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
  1444. // Min-thickness is the web thickness. On the other hand, a blob min-thickness by
  1445. // min-thickness is not useful. Since there's no obvious definition of web vs. blob, we
  1446. // arbitrarily choose "at least 2X min-thickness on one axis". (Since we're doing this
  1447. // during the deflated state, that means we test for "at least min-thickness".)
  1448. for( int ii = aFillPolys.OutlineCount() - 1; ii >= 0; ii-- )
  1449. {
  1450. std::vector<SHAPE_LINE_CHAIN>& island = aFillPolys.Polygon( ii );
  1451. BOX2I islandExtents;
  1452. for( const VECTOR2I& pt : island.front().CPoints() )
  1453. {
  1454. islandExtents.Merge( pt );
  1455. if( islandExtents.GetSizeMax() > aZone->GetMinThickness() )
  1456. break;
  1457. }
  1458. if( islandExtents.GetSizeMax() < aZone->GetMinThickness() )
  1459. aFillPolys.DeletePolygon( ii );
  1460. }
  1461. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In9_Cu, wxT( "deflated" ) );
  1462. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1463. return false;
  1464. /* -------------------------------------------------------------------------------------
  1465. * Process the hatch pattern (note that we do this while deflated)
  1466. */
  1467. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  1468. {
  1469. if( !addHatchFillTypeOnZone( aZone, aLayer, aDebugLayer, aFillPolys ) )
  1470. return false;
  1471. }
  1472. else
  1473. {
  1474. /* -------------------------------------------------------------------------------------
  1475. * Connect nearby polygons
  1476. */
  1477. aFillPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
  1478. connect_nearby_polys( aFillPolys, aZone->GetMinThickness() );
  1479. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In10_Cu, wxT( "connected-nearby-polys" ) );
  1480. }
  1481. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1482. return false;
  1483. /* -------------------------------------------------------------------------------------
  1484. * Finish minimum-width pruning by re-inflating
  1485. */
  1486. if( half_min_width - epsilon > epsilon )
  1487. aFillPolys.Inflate( half_min_width - epsilon, cornerStrategy, m_maxError, true );
  1488. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In15_Cu, wxT( "after-reinflating" ) );
  1489. /* -------------------------------------------------------------------------------------
  1490. * Ensure additive changes (thermal stubs and inflating acute corners) do not add copper
  1491. * outside the zone boundary, inside the clearance holes, or between otherwise isolated
  1492. * islands
  1493. */
  1494. for( PAD* pad : thermalConnectionPads )
  1495. addHoleKnockout( pad, 0, clearanceHoles );
  1496. aFillPolys.BooleanIntersection( aMaxExtents, SHAPE_POLY_SET::PM_FAST );
  1497. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In16_Cu, wxT( "after-trim-to-outline" ) );
  1498. aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1499. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In17_Cu, wxT( "after-trim-to-clearance-holes" ) );
  1500. /* -------------------------------------------------------------------------------------
  1501. * Lastly give any same-net but higher-priority zones control over their own area.
  1502. */
  1503. subtractHigherPriorityZones( aZone, aLayer, aFillPolys );
  1504. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In18_Cu, wxT( "minus-higher-priority-zones" ) );
  1505. aFillPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
  1506. return true;
  1507. }
  1508. bool ZONE_FILLER::fillNonCopperZone( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1509. const SHAPE_POLY_SET& aSmoothedOutline,
  1510. SHAPE_POLY_SET& aFillPolys )
  1511. {
  1512. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  1513. BOX2I zone_boundingbox = aZone->GetBoundingBox();
  1514. SHAPE_POLY_SET clearanceHoles;
  1515. long ticker = 0;
  1516. auto checkForCancel =
  1517. [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
  1518. {
  1519. return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
  1520. };
  1521. auto knockoutGraphicClearance =
  1522. [&]( BOARD_ITEM* aItem )
  1523. {
  1524. if( aItem->IsKnockout() && aItem->IsOnLayer( aLayer )
  1525. && aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
  1526. {
  1527. DRC_CONSTRAINT cc = bds.m_DRCEngine->EvalRules( PHYSICAL_CLEARANCE_CONSTRAINT,
  1528. aZone, aItem, aLayer );
  1529. addKnockout( aItem, aLayer, cc.GetValue().Min(), false, clearanceHoles );
  1530. }
  1531. };
  1532. for( FOOTPRINT* footprint : m_board->Footprints() )
  1533. {
  1534. if( checkForCancel( m_progressReporter ) )
  1535. return false;
  1536. knockoutGraphicClearance( &footprint->Reference() );
  1537. knockoutGraphicClearance( &footprint->Value() );
  1538. for( BOARD_ITEM* item : footprint->GraphicalItems() )
  1539. knockoutGraphicClearance( item );
  1540. }
  1541. for( BOARD_ITEM* item : m_board->Drawings() )
  1542. {
  1543. if( checkForCancel( m_progressReporter ) )
  1544. return false;
  1545. knockoutGraphicClearance( item );
  1546. }
  1547. aFillPolys = aSmoothedOutline;
  1548. aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1549. for( ZONE* keepout : m_board->Zones() )
  1550. {
  1551. if( !keepout->GetIsRuleArea() )
  1552. continue;
  1553. if( !keepout->HasKeepoutParametersSet() )
  1554. continue;
  1555. if( keepout->GetDoNotAllowCopperPour() && keepout->IsOnLayer( aLayer ) )
  1556. {
  1557. if( keepout->GetBoundingBox().Intersects( zone_boundingbox ) )
  1558. aFillPolys.BooleanSubtract( *keepout->Outline(), SHAPE_POLY_SET::PM_FAST );
  1559. }
  1560. }
  1561. // Features which are min_width should survive pruning; features that are *less* than
  1562. // min_width should not. Therefore we subtract epsilon from the min_width when
  1563. // deflating/inflating.
  1564. int half_min_width = aZone->GetMinThickness() / 2;
  1565. int epsilon = pcbIUScale.mmToIU( 0.001 );
  1566. aFillPolys.Deflate( half_min_width - epsilon, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, m_maxError );
  1567. // Remove the non filled areas due to the hatch pattern
  1568. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  1569. {
  1570. if( !addHatchFillTypeOnZone( aZone, aLayer, aLayer, aFillPolys ) )
  1571. return false;
  1572. }
  1573. // Re-inflate after pruning of areas that don't meet minimum-width criteria
  1574. if( half_min_width - epsilon > epsilon )
  1575. aFillPolys.Inflate( half_min_width - epsilon, CORNER_STRATEGY::ROUND_ALL_CORNERS, m_maxError );
  1576. aFillPolys.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
  1577. return true;
  1578. }
  1579. /*
  1580. * Build the filled solid areas data from real outlines (stored in m_Poly)
  1581. * The solid areas can be more than one on copper layers, and do not have holes
  1582. * ( holes are linked by overlapping segments to the main outline)
  1583. */
  1584. bool ZONE_FILLER::fillSingleZone( ZONE* aZone, PCB_LAYER_ID aLayer, SHAPE_POLY_SET& aFillPolys )
  1585. {
  1586. SHAPE_POLY_SET* boardOutline = m_brdOutlinesValid ? &m_boardOutline : nullptr;
  1587. SHAPE_POLY_SET maxExtents;
  1588. SHAPE_POLY_SET smoothedPoly;
  1589. PCB_LAYER_ID debugLayer = UNDEFINED_LAYER;
  1590. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( aLayer ) )
  1591. {
  1592. debugLayer = aLayer;
  1593. aLayer = F_Cu;
  1594. }
  1595. if( !aZone->BuildSmoothedPoly( maxExtents, aLayer, boardOutline, &smoothedPoly ) )
  1596. return false;
  1597. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1598. return false;
  1599. if( aZone->IsOnCopperLayer() )
  1600. {
  1601. if( fillCopperZone( aZone, aLayer, debugLayer, smoothedPoly, maxExtents, aFillPolys ) )
  1602. aZone->SetNeedRefill( false );
  1603. }
  1604. else
  1605. {
  1606. if( fillNonCopperZone( aZone, aLayer, smoothedPoly, aFillPolys ) )
  1607. aZone->SetNeedRefill( false );
  1608. }
  1609. return true;
  1610. }
  1611. /**
  1612. * Function buildThermalSpokes
  1613. */
  1614. void ZONE_FILLER::buildThermalSpokes( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1615. const std::vector<PAD*>& aSpokedPadsList,
  1616. std::deque<SHAPE_LINE_CHAIN>& aSpokesList )
  1617. {
  1618. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  1619. BOX2I zoneBB = aZone->GetBoundingBox();
  1620. DRC_CONSTRAINT constraint;
  1621. int zone_half_width = aZone->GetMinThickness() / 2;
  1622. zoneBB.Inflate( std::max( bds.GetBiggestClearanceValue(), aZone->GetLocalClearance().value() ) );
  1623. // Is a point on the boundary of the polygon inside or outside?
  1624. // The boundary may be off by MaxError
  1625. int epsilon = bds.m_MaxError;
  1626. for( PAD* pad : aSpokedPadsList )
  1627. {
  1628. // We currently only connect to pads, not pad holes
  1629. if( !pad->IsOnLayer( aLayer ) )
  1630. continue;
  1631. constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad, aZone, aLayer );
  1632. int thermalReliefGap = constraint.GetValue().Min();
  1633. constraint = bds.m_DRCEngine->EvalRules( THERMAL_SPOKE_WIDTH_CONSTRAINT, pad, aZone, aLayer );
  1634. int spoke_w = constraint.GetValue().Opt();
  1635. // Spoke width should ideally be smaller than the pad minor axis.
  1636. // Otherwise the thermal shape is not really a thermal relief,
  1637. // and the algo to count the actual number of spokes can fail
  1638. int spoke_max_allowed_w = std::min( pad->GetSize( aLayer ).x, pad->GetSize( aLayer ).y );
  1639. spoke_w = std::clamp( spoke_w, constraint.Value().Min(), constraint.Value().Max() );
  1640. // ensure the spoke width is smaller than the pad minor size
  1641. spoke_w = std::min( spoke_w, spoke_max_allowed_w );
  1642. // Cannot create stubs having a width < zone min thickness
  1643. if( spoke_w < aZone->GetMinThickness() )
  1644. continue;
  1645. int spoke_half_w = spoke_w / 2;
  1646. // Quick test here to possibly save us some work
  1647. BOX2I itemBB = pad->GetBoundingBox();
  1648. itemBB.Inflate( thermalReliefGap + epsilon );
  1649. if( !( itemBB.Intersects( zoneBB ) ) )
  1650. continue;
  1651. bool customSpokes = false;
  1652. if( pad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
  1653. {
  1654. for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives( aLayer ) )
  1655. {
  1656. if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
  1657. {
  1658. customSpokes = true;
  1659. break;
  1660. }
  1661. }
  1662. }
  1663. // Thermal spokes consist of square-ended segments from the pad center to points just
  1664. // outside the thermal relief. The outside end has an extra center point (which must be
  1665. // at idx 3) which is used for testing whether or not the spoke connects to copper in the
  1666. // parent zone.
  1667. auto buildSpokesFromOrigin =
  1668. [&]( const BOX2I& box, EDA_ANGLE angle )
  1669. {
  1670. VECTOR2I center = box.GetCenter();
  1671. VECTOR2I half_size( box.GetWidth() / 2, box.GetHeight() / 2 );
  1672. // Function to find intersection of line with box edge
  1673. auto intersectLineBox = [&](const VECTOR2D& direction) -> VECTOR2I {
  1674. double dx = direction.x;
  1675. double dy = direction.y;
  1676. // Shortcircuit the axis cases because they will be degenerate in the
  1677. // intersection test
  1678. if( direction.x == 0 )
  1679. {
  1680. return VECTOR2I(0, dy * half_size.y );
  1681. }
  1682. else if( direction.y == 0 )
  1683. {
  1684. return VECTOR2I(dx * half_size.x, 0);
  1685. }
  1686. // We are going to intersect with one side or the other. Whichever
  1687. // we hit first is the fraction of the spoke length we keep
  1688. double tx = std::min( half_size.x / std::abs( dx ),
  1689. half_size.y / std::abs( dy ) );
  1690. return VECTOR2I( dx * tx, dy * tx );
  1691. };
  1692. // Precalculate angles for four cardinal directions
  1693. const EDA_ANGLE angles[4] = {
  1694. EDA_ANGLE( 0.0, DEGREES_T ) + angle, // Right
  1695. EDA_ANGLE( 90.0, DEGREES_T ) + angle, // Up
  1696. EDA_ANGLE( 180.0, DEGREES_T ) + angle, // Left
  1697. EDA_ANGLE( 270.0, DEGREES_T ) + angle // Down
  1698. };
  1699. // Generate four spokes in cardinal directions
  1700. for( const EDA_ANGLE& spokeAngle : angles )
  1701. {
  1702. VECTOR2D direction( spokeAngle.Cos(), spokeAngle.Sin() );
  1703. VECTOR2D perpendicular = direction.Perpendicular();
  1704. VECTOR2I intersection = intersectLineBox( direction );
  1705. VECTOR2I spoke_side = perpendicular.Resize( spoke_half_w );
  1706. SHAPE_LINE_CHAIN spoke;
  1707. spoke.Append( center + spoke_side );
  1708. spoke.Append( center - spoke_side );
  1709. spoke.Append( center + intersection - spoke_side );
  1710. spoke.Append( center + intersection ); // test pt
  1711. spoke.Append( center + intersection + spoke_side );
  1712. spoke.SetClosed( true );
  1713. aSpokesList.push_back( std::move( spoke ) );
  1714. }
  1715. };
  1716. if( customSpokes )
  1717. {
  1718. SHAPE_POLY_SET thermalPoly;
  1719. SHAPE_LINE_CHAIN thermalOutline;
  1720. pad->TransformShapeToPolygon( thermalPoly, aLayer, thermalReliefGap + epsilon,
  1721. m_maxError, ERROR_OUTSIDE );
  1722. if( thermalPoly.OutlineCount() )
  1723. thermalOutline = thermalPoly.Outline( 0 );
  1724. for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives( aLayer ) )
  1725. {
  1726. if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
  1727. {
  1728. SEG seg( primitive->GetStart(), primitive->GetEnd() );
  1729. SHAPE_LINE_CHAIN::INTERSECTIONS intersections;
  1730. RotatePoint( seg.A, pad->GetOrientation() );
  1731. RotatePoint( seg.B, pad->GetOrientation() );
  1732. seg.A += pad->ShapePos( aLayer );
  1733. seg.B += pad->ShapePos( aLayer );
  1734. // Make sure seg.A is the origin
  1735. if( !pad->GetEffectivePolygon( aLayer, ERROR_OUTSIDE )->Contains( seg.A ) )
  1736. seg.Reverse();
  1737. // Trim seg.B to the thermal outline
  1738. if( thermalOutline.Intersect( seg, intersections ) )
  1739. {
  1740. seg.B = intersections.front().p;
  1741. VECTOR2I offset = ( seg.B - seg.A ).Perpendicular().Resize( spoke_half_w );
  1742. SHAPE_LINE_CHAIN spoke;
  1743. spoke.Append( seg.A + offset );
  1744. spoke.Append( seg.A - offset );
  1745. spoke.Append( seg.B - offset );
  1746. spoke.Append( seg.B ); // test pt
  1747. spoke.Append( seg.B + offset );
  1748. spoke.SetClosed( true );
  1749. aSpokesList.push_back( std::move( spoke ) );
  1750. }
  1751. }
  1752. }
  1753. }
  1754. else
  1755. {
  1756. // Since the bounding-box needs to be correclty rotated we use a dummy pad to keep
  1757. // from dirtying the real pad's cached shapes.
  1758. PAD dummy_pad( *pad );
  1759. dummy_pad.SetOrientation( ANGLE_0 );
  1760. // Spokes are from center of pad shape, not from hole. So the dummy pad has no shape
  1761. // offset and is at position 0,0
  1762. dummy_pad.SetPosition( VECTOR2I( 0, 0 ) );
  1763. dummy_pad.SetOffset( aLayer, VECTOR2I( 0, 0 ) );
  1764. BOX2I spokesBox = dummy_pad.GetBoundingBox();
  1765. //Add the half width of the zone mininum width to the inflate amount to account for the fact that
  1766. //the deflation procedure will shrink the results by half the half the zone min width
  1767. spokesBox.Inflate( thermalReliefGap + epsilon + zone_half_width );
  1768. // This is a touchy case because the bounding box for circles overshoots the mark
  1769. // when rotated at 45 degrees. So we just build spokes at 0 degrees and rotate
  1770. // them later.
  1771. if( pad->GetShape( aLayer ) == PAD_SHAPE::CIRCLE
  1772. || ( pad->GetShape( aLayer ) == PAD_SHAPE::OVAL
  1773. && pad->GetSizeX() == pad->GetSizeY() ) )
  1774. {
  1775. buildSpokesFromOrigin( spokesBox, ANGLE_0 );
  1776. if( pad->GetThermalSpokeAngle() != ANGLE_0 )
  1777. {
  1778. //Rotate the last four elements of aspokeslist
  1779. for( auto it = aSpokesList.rbegin(); it != aSpokesList.rbegin() + 4; ++it )
  1780. it->Rotate( pad->GetThermalSpokeAngle() );
  1781. }
  1782. }
  1783. else
  1784. {
  1785. buildSpokesFromOrigin( spokesBox, pad->GetThermalSpokeAngle() );
  1786. }
  1787. auto spokeIter = aSpokesList.rbegin();
  1788. for( int ii = 0; ii < 4; ++ii, ++spokeIter )
  1789. {
  1790. spokeIter->Rotate( pad->GetOrientation() );
  1791. spokeIter->Move( pad->ShapePos( aLayer ) );
  1792. }
  1793. // Remove group membership from dummy item before deleting
  1794. dummy_pad.SetParentGroup( nullptr );
  1795. }
  1796. }
  1797. for( size_t ii = 0; ii < aSpokesList.size(); ++ii )
  1798. aSpokesList[ii].GenerateBBoxCache();
  1799. }
  1800. bool ZONE_FILLER::addHatchFillTypeOnZone( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1801. PCB_LAYER_ID aDebugLayer, SHAPE_POLY_SET& aFillPolys )
  1802. {
  1803. // Build grid:
  1804. // obviously line thickness must be > zone min thickness.
  1805. // It can happens if a board file was edited by hand by a python script
  1806. // Use 1 micron margin to be *sure* there is no issue in Gerber files
  1807. // (Gbr file unit = 1 or 10 nm) due to some truncation in coordinates or calculations
  1808. // This margin also avoid problems due to rounding coordinates in next calculations
  1809. // that can create incorrect polygons
  1810. int thickness = std::max( aZone->GetHatchThickness(),
  1811. aZone->GetMinThickness() + pcbIUScale.mmToIU( 0.001 ) );
  1812. int linethickness = thickness - aZone->GetMinThickness();
  1813. int gridsize = thickness + aZone->GetHatchGap();
  1814. int maxError = m_board->GetDesignSettings().m_MaxError;
  1815. SHAPE_POLY_SET filledPolys = aFillPolys.CloneDropTriangulation();
  1816. // Use a area that contains the rotated bbox by orientation, and after rotate the result
  1817. // by -orientation.
  1818. if( !aZone->GetHatchOrientation().IsZero() )
  1819. filledPolys.Rotate( - aZone->GetHatchOrientation() );
  1820. BOX2I bbox = filledPolys.BBox( 0 );
  1821. // Build hole shape
  1822. // the hole size is aZone->GetHatchGap(), but because the outline thickness
  1823. // is aZone->GetMinThickness(), the hole shape size must be larger
  1824. SHAPE_LINE_CHAIN hole_base;
  1825. int hole_size = aZone->GetHatchGap() + aZone->GetMinThickness();
  1826. VECTOR2I corner( 0, 0 );;
  1827. hole_base.Append( corner );
  1828. corner.x += hole_size;
  1829. hole_base.Append( corner );
  1830. corner.y += hole_size;
  1831. hole_base.Append( corner );
  1832. corner.x = 0;
  1833. hole_base.Append( corner );
  1834. hole_base.SetClosed( true );
  1835. // Calculate minimal area of a grid hole.
  1836. // All holes smaller than a threshold will be removed
  1837. double minimal_hole_area = hole_base.Area() * aZone->GetHatchHoleMinArea();
  1838. // Now convert this hole to a smoothed shape:
  1839. if( aZone->GetHatchSmoothingLevel() > 0 )
  1840. {
  1841. // the actual size of chamfer, or rounded corner radius is the half size
  1842. // of the HatchFillTypeGap scaled by aZone->GetHatchSmoothingValue()
  1843. // aZone->GetHatchSmoothingValue() = 1.0 is the max value for the chamfer or the
  1844. // radius of corner (radius = half size of the hole)
  1845. int smooth_value = KiROUND( aZone->GetHatchGap()
  1846. * aZone->GetHatchSmoothingValue() / 2 );
  1847. // Minimal optimization:
  1848. // make smoothing only for reasonable smooth values, to avoid a lot of useless segments
  1849. // and if the smooth value is small, use chamfer even if fillet is requested
  1850. #define SMOOTH_MIN_VAL_MM 0.02
  1851. #define SMOOTH_SMALL_VAL_MM 0.04
  1852. if( smooth_value > pcbIUScale.mmToIU( SMOOTH_MIN_VAL_MM ) )
  1853. {
  1854. SHAPE_POLY_SET smooth_hole;
  1855. smooth_hole.AddOutline( hole_base );
  1856. int smooth_level = aZone->GetHatchSmoothingLevel();
  1857. if( smooth_value < pcbIUScale.mmToIU( SMOOTH_SMALL_VAL_MM ) && smooth_level > 1 )
  1858. smooth_level = 1;
  1859. // Use a larger smooth_value to compensate the outline tickness
  1860. // (chamfer is not visible is smooth value < outline thickess)
  1861. smooth_value += aZone->GetMinThickness() / 2;
  1862. // smooth_value cannot be bigger than the half size oh the hole:
  1863. smooth_value = std::min( smooth_value, aZone->GetHatchGap() / 2 );
  1864. // the error to approximate a circle by segments when smoothing corners by a arc
  1865. maxError = std::max( maxError * 2, smooth_value / 20 );
  1866. switch( smooth_level )
  1867. {
  1868. case 1:
  1869. // Chamfer() uses the distance from a corner to create a end point
  1870. // for the chamfer.
  1871. hole_base = smooth_hole.Chamfer( smooth_value ).Outline( 0 );
  1872. break;
  1873. default:
  1874. if( aZone->GetHatchSmoothingLevel() > 2 )
  1875. maxError /= 2; // Force better smoothing
  1876. hole_base = smooth_hole.Fillet( smooth_value, maxError ).Outline( 0 );
  1877. break;
  1878. case 0:
  1879. break;
  1880. };
  1881. }
  1882. }
  1883. // Build holes
  1884. SHAPE_POLY_SET holes;
  1885. for( int xx = 0; ; xx++ )
  1886. {
  1887. int xpos = xx * gridsize;
  1888. if( xpos > bbox.GetWidth() )
  1889. break;
  1890. for( int yy = 0; ; yy++ )
  1891. {
  1892. int ypos = yy * gridsize;
  1893. if( ypos > bbox.GetHeight() )
  1894. break;
  1895. // Generate hole
  1896. SHAPE_LINE_CHAIN hole( hole_base );
  1897. hole.Move( VECTOR2I( xpos, ypos ) );
  1898. holes.AddOutline( hole );
  1899. }
  1900. }
  1901. holes.Move( bbox.GetPosition() );
  1902. if( !aZone->GetHatchOrientation().IsZero() )
  1903. holes.Rotate( aZone->GetHatchOrientation() );
  1904. DUMP_POLYS_TO_COPPER_LAYER( holes, In10_Cu, wxT( "hatch-holes" ) );
  1905. int outline_margin = aZone->GetMinThickness() * 1.1;
  1906. // Using GetHatchThickness() can look more consistent than GetMinThickness().
  1907. if( aZone->GetHatchBorderAlgorithm() && aZone->GetHatchThickness() > outline_margin )
  1908. outline_margin = aZone->GetHatchThickness();
  1909. // The fill has already been deflated to ensure GetMinThickness() so we just have to
  1910. // account for anything beyond that.
  1911. SHAPE_POLY_SET deflatedFilledPolys = aFillPolys.CloneDropTriangulation();
  1912. deflatedFilledPolys.Deflate( outline_margin - aZone->GetMinThickness(),
  1913. CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
  1914. holes.BooleanIntersection( deflatedFilledPolys, SHAPE_POLY_SET::PM_FAST );
  1915. DUMP_POLYS_TO_COPPER_LAYER( holes, In11_Cu, wxT( "fill-clipped-hatch-holes" ) );
  1916. SHAPE_POLY_SET deflatedOutline = aZone->Outline()->CloneDropTriangulation();
  1917. deflatedOutline.Deflate( outline_margin, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
  1918. holes.BooleanIntersection( deflatedOutline, SHAPE_POLY_SET::PM_FAST );
  1919. DUMP_POLYS_TO_COPPER_LAYER( holes, In12_Cu, wxT( "outline-clipped-hatch-holes" ) );
  1920. if( aZone->GetNetCode() != 0 )
  1921. {
  1922. // Vias and pads connected to the zone must not be allowed to become isolated inside
  1923. // one of the holes. Effectively this means their copper outline needs to be expanded
  1924. // to be at least as wide as the gap so that it is guaranteed to touch at least one
  1925. // edge.
  1926. BOX2I zone_boundingbox = aZone->GetBoundingBox();
  1927. SHAPE_POLY_SET aprons;
  1928. int min_apron_radius = ( aZone->GetHatchGap() * 10 ) / 19;
  1929. for( PCB_TRACK* track : m_board->Tracks() )
  1930. {
  1931. if( track->Type() == PCB_VIA_T )
  1932. {
  1933. PCB_VIA* via = static_cast<PCB_VIA*>( track );
  1934. if( via->GetNetCode() == aZone->GetNetCode()
  1935. && via->IsOnLayer( aLayer )
  1936. && via->GetBoundingBox().Intersects( zone_boundingbox ) )
  1937. {
  1938. int r = std::max( min_apron_radius,
  1939. via->GetDrillValue() / 2 + outline_margin );
  1940. TransformCircleToPolygon( aprons, via->GetPosition(), r, maxError,
  1941. ERROR_OUTSIDE );
  1942. }
  1943. }
  1944. }
  1945. for( FOOTPRINT* footprint : m_board->Footprints() )
  1946. {
  1947. for( PAD* pad : footprint->Pads() )
  1948. {
  1949. if( pad->GetNetCode() == aZone->GetNetCode()
  1950. && pad->IsOnLayer( aLayer )
  1951. && pad->GetBoundingBox().Intersects( zone_boundingbox ) )
  1952. {
  1953. // What we want is to bulk up the pad shape so that the narrowest bit of
  1954. // copper between the hole and the apron edge is at least outline_margin
  1955. // wide (and that the apron itself meets min_apron_radius. But that would
  1956. // take a lot of code and math, and the following approximation is close
  1957. // enough.
  1958. int pad_width = std::min( pad->GetSize( aLayer ).x, pad->GetSize( aLayer ).y );
  1959. int slot_width = std::min( pad->GetDrillSize().x, pad->GetDrillSize().y );
  1960. int min_annular_ring_width = ( pad_width - slot_width ) / 2;
  1961. int clearance = std::max( min_apron_radius - pad_width / 2,
  1962. outline_margin - min_annular_ring_width );
  1963. clearance = std::max( 0, clearance - linethickness / 2 );
  1964. pad->TransformShapeToPolygon( aprons, aLayer, clearance, maxError,
  1965. ERROR_OUTSIDE );
  1966. }
  1967. }
  1968. }
  1969. holes.BooleanSubtract( aprons, SHAPE_POLY_SET::PM_FAST );
  1970. }
  1971. DUMP_POLYS_TO_COPPER_LAYER( holes, In13_Cu, wxT( "pad-via-clipped-hatch-holes" ) );
  1972. // Now filter truncated holes to avoid small holes in pattern
  1973. // It happens for holes near the zone outline
  1974. for( int ii = 0; ii < holes.OutlineCount(); )
  1975. {
  1976. double area = holes.Outline( ii ).Area();
  1977. if( area < minimal_hole_area ) // The current hole is too small: remove it
  1978. holes.DeletePolygon( ii );
  1979. else
  1980. ++ii;
  1981. }
  1982. // create grid. Use SHAPE_POLY_SET::PM_STRICTLY_SIMPLE to
  1983. // generate strictly simple polygons needed by Gerber files and Fracture()
  1984. aFillPolys.BooleanSubtract( aFillPolys, holes, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
  1985. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In14_Cu, wxT( "after-hatching" ) );
  1986. return true;
  1987. }