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.

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