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.

1488 lines
54 KiB

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