KiCad PCB EDA Suite
Loading...
Searching...
No Matches
drc_test_provider_disallow.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include <atomic>
21#include <common.h>
23#include <drc/drc_rtree.h>
24#include <drc/drc_engine.h>
25#include <drc/drc_item.h>
26#include <drc/drc_rule.h>
28#include <pad.h>
29#include <progress_reporter.h>
30#include <thread_pool.h>
31#include <zone.h>
32#include <pcb_track.h>
33#include <mutex>
34
35
36/*
37 "Disallow" test. Goes through all items, matching types/conditions drop errors.
38 Errors generated:
39 - DRCE_ALLOWED_ITEMS
40 - DRCE_TEXT_ON_EDGECUTS
41*/
42
44{
45public:
48
49 virtual ~DRC_TEST_PROVIDER_DISALLOW() = default;
50
51 virtual bool Run() override;
52
53 virtual const wxString GetName() const override { return wxT( "disallow" ); };
54};
55
56
58{
59 if( !reportPhase( _( "Checking keepouts & disallow constraints..." ) ) )
60 return false; // DRC cancelled
61
62 BOARD* board = m_drcEngine->GetBoard();
64
65 // First build out the board's cache of copper-keepout to copper-zone caches. This is where
66 // the bulk of the time is spent, and we can do this in parallel.
67 //
68 std::vector<ZONE*> antiCopperKeepouts;
69 std::vector<ZONE*> copperZones;
70 std::vector<std::pair<ZONE*, ZONE*>> toCache;
71 std::atomic<size_t> done( 1 );
72 int totalCount = 0;
73 std::unique_ptr<DRC_RTREE> antiTrackKeepouts = std::make_unique<DRC_RTREE>();
74
76 [&]( BOARD_ITEM* item ) -> bool
77 {
78 ZONE* zone = static_cast<ZONE*>( item );
79
80 if( zone->GetIsRuleArea() )
81 {
82 if( zone->GetDoNotAllowZoneFills() )
83 antiCopperKeepouts.push_back( zone );
84
85 if( zone->GetDoNotAllowTracks() )
86 {
87 for( PCB_LAYER_ID layer : zone->GetLayerSet() )
88 antiTrackKeepouts->Insert( zone, layer );
89 }
90 }
91 else if( zone->IsOnCopperLayer() )
92 {
93 copperZones.push_back( zone );
94 }
95
96 totalCount++;
97
98 return true;
99 } );
100
101 antiTrackKeepouts->Build();
102
103 for( ZONE* ruleArea : antiCopperKeepouts )
104 {
105 for( ZONE* copperZone : copperZones )
106 {
107 toCache.push_back( { ruleArea, copperZone } );
108 totalCount++;
109 }
110 }
111
112 auto query_areas =
113 [&]( const int idx ) -> size_t
114 {
115 if( m_drcEngine->IsCancelled() )
116 return 0;
117 const auto& areaZonePair = toCache[idx];
118 ZONE* ruleArea = areaZonePair.first;
119 ZONE* copperZone = areaZonePair.second;
120 BOX2I areaBBox = ruleArea->GetBoundingBox();
121 BOX2I copperBBox = copperZone->GetBoundingBox();
122 bool isInside = false;
123
124 if( copperZone->IsFilled() && areaBBox.Intersects( copperBBox ) )
125 {
126 // Collisions include touching, so we need to deflate outline by enough to
127 // exclude it. This is particularly important for detecting copper fills as
128 // they will be exactly touching along the entire exclusion border.
129 SHAPE_POLY_SET areaPoly = ruleArea->GetBoardOutline();
130 areaPoly.Fracture();
132
133 DRC_RTREE* zoneRTree = board->m_CopperZoneRTreeCache[ copperZone ].get();
134
135 if( zoneRTree )
136 {
137 for( size_t ii = 0; ii < ruleArea->GetLayerSet().size(); ++ii )
138 {
139 if( ruleArea->GetLayerSet().test( ii ) )
140 {
141 PCB_LAYER_ID layer = PCB_LAYER_ID( ii );
142
143 if( zoneRTree->QueryColliding( areaBBox, &areaPoly, layer ) )
144 {
145 isInside = true;
146 break;
147 }
148
149 if( m_drcEngine->IsCancelled() )
150 return 0;
151 }
152 }
153 }
154 }
155
156 if( m_drcEngine->IsCancelled() )
157 return 0;
158
159 PTR_PTR_LAYER_CACHE_KEY key = { ruleArea, copperZone, UNDEFINED_LAYER };
160 board->m_IntersectsAreaCache.Set( key, isInside );
161
162 done.fetch_add( 1 );
163
164 return 1;
165 };
166
168 auto futures = tp.submit_loop( 0, toCache.size(), query_areas, toCache.size() );
169
170 for( auto& ret : futures )
171 {
172 std::future_status status = ret.wait_for( std::chrono::milliseconds( 250 ) );
173
174 while( status != std::future_status::ready )
175 {
176 reportProgress( done, toCache.size() );
177 status = ret.wait_for( std::chrono::milliseconds( 250 ) );
178 }
179 }
180
181 if( m_drcEngine->IsCancelled() )
182 return false;
183
184 // Now go through all the board objects calling the DRC_ENGINE to run the actual disallow
185 // tests. These should be reasonably quick using the caches generated above.
186 //
187 // Collect items first, then process in parallel.
188 std::vector<BOARD_ITEM*> allItems;
189
191 [&]( BOARD_ITEM* item ) -> bool
192 {
193 allItems.push_back( item );
194 return true;
195 } );
196
197 std::atomic<size_t> itemsDone( 0 );
198 size_t itemCount = allItems.size();
199
200 auto checkTextOnEdgeCuts = []( BOARD_ITEM* item ) -> bool
201 {
202 // Items that plot geometry onto Edge.Cuts corrupt the board outline.
203 // Reference images are excluded on purpose because they are never plotted.
204 if( item->Type() == PCB_FIELD_T || item->Type() == PCB_TEXT_T || item->Type() == PCB_TEXTBOX_T
205 || item->Type() == PCB_TABLE_T || item->Type() == PCB_BARCODE_T
206 || BaseType( item->Type() ) == PCB_DIMENSION_T )
207 {
208 return item->GetLayer() == Edge_Cuts;
209 }
210
211 return false;
212 };
213
214 auto processItem =
215 [&]( const int idx ) -> size_t
216 {
217 if( m_drcEngine->IsCancelled() )
218 {
219 itemsDone.fetch_add( 1 );
220 return 0;
221 }
222
223 bool testTextOnEdge = !m_drcEngine->IsErrorLimitExceeded( DRCE_TEXT_ON_EDGECUTS );
224 bool testDisallow = !m_drcEngine->IsErrorLimitExceeded( DRCE_ALLOWED_ITEMS );
225
226 if( !testTextOnEdge && !testDisallow )
227 {
228 itemsDone.fetch_add( 1 );
229 return 0;
230 }
231
232 BOARD_ITEM* item = allItems[idx];
233
234 if( testTextOnEdge && checkTextOnEdgeCuts( item ) )
235 {
236 std::shared_ptr<DRC_ITEM> drc = DRC_ITEM::Create( DRCE_TEXT_ON_EDGECUTS );
237 drc->SetItems( item );
239 }
240
241 if( testDisallow )
242 {
243 if( item->Type() == PCB_ZONE_T )
244 {
245 ZONE* zone = static_cast<ZONE*>( item );
246
247 if( zone->GetIsRuleArea() && zone->HasKeepoutParametersSet() )
248 {
249 itemsDone.fetch_add( 1 );
250 return 1;
251 }
252 }
253
254 item->ClearFlags( HOLE_PROXY );
255
256 if( item->Type() == PCB_TRACE_T || item->Type() == PCB_ARC_T )
257 {
258 PCB_TRACK* track = static_cast<PCB_TRACK*>( item );
259 PCB_LAYER_ID layer = track->GetLayer();
260
261 antiTrackKeepouts->QueryColliding( track, layer, layer,
262 [&]( BOARD_ITEM* other ) -> bool
263 {
264 return true;
265 },
266 [&]( BOARD_ITEM* other ) -> bool
267 {
268 std::shared_ptr<SHAPE> shape = track->GetEffectiveShape();
269 int dummyActual;
270 VECTOR2I pos;
271
272 SHAPE_POLY_SET zoneOutline = static_cast<ZONE*>( other )->GetBoardOutline();
273
274 if( zoneOutline.Collide( shape.get(), 0, &dummyActual, &pos ) )
275 {
276 std::shared_ptr<DRC_ITEM> drcItem =
278 drcItem->SetItems( track );
279 reportViolation( drcItem, pos,
280 track->GetLayerSet().ExtractLayer() );
281 }
282
283 return !m_drcEngine->IsCancelled();
284 },
286 }
287
288 // Tracks and arcs against keepout areas that disallow tracks are already
289 // reported above via antiTrackKeepouts (which collides every crossing, not
290 // just one per rule match). Skip the track/arc case for implicit keepout
291 // rules here to avoid duplicate markers, but still let EvalRules produce
292 // markers for all other item types against implicit keepout rules.
293 bool isTrackOrArc = ( item->Type() == PCB_TRACE_T || item->Type() == PCB_ARC_T );
294
295 auto reportDisallow =
296 [&]( const DRC_CONSTRAINT& aConstraint )
297 {
298 DRC_RULE* rule = aConstraint.GetParentRule();
299
300 if( !rule )
301 return;
302
303 if( isTrackOrArc && rule->IsImplicit() )
304 return;
305
306 std::shared_ptr<DRC_ITEM> drcItem =
308 PCB_LAYER_ID layer = item->GetLayerSet().ExtractLayer();
309 VECTOR2I pos = item->GetPosition();
310
311 // Provide a better location for keepout area collisions by
312 // snapping to where the item actually crosses the keepout outline.
313 // Use the cached BOARD_ITEM* rather than a UUID lookup, since
314 // ResolveItem mutates an unsynchronized cache and this lambda
315 // runs inside the parallel DRC worker pool.
316 if( rule->IsImplicit() )
317 {
318 if( ZONE* keepout = dynamic_cast<ZONE*>( rule->m_ImplicitItem ) )
319 {
320 std::shared_ptr<SHAPE> shape =
321 item->GetEffectiveShape( layer );
322 int dummyActual;
323
324 SHAPE_POLY_SET keepoutOutline = keepout->GetBoardOutline();
325 keepoutOutline.Collide( shape.get(), 0, &dummyActual, &pos );
326 }
327 }
328
329 drcItem->SetErrorDetail(
330 wxString::Format( wxS( "(%s)" ), aConstraint.GetName() ) );
331 drcItem->SetItems( item );
332 drcItem->SetViolatingRule( rule );
333 reportViolation( drcItem, pos, layer );
334 };
335
336 DRC_CONSTRAINT constraint = m_drcEngine->EvalRules( DISALLOW_CONSTRAINT,
337 item, nullptr,
339
340 if( constraint.m_DisallowFlags
341 && constraint.GetSeverity() != RPT_SEVERITY_IGNORE )
342 {
343 reportDisallow( constraint );
344 }
345
346 // N.B. HOLE_PROXY is set/cleared on the item's flags for
347 // EvalRules to distinguish hole-specific disallow constraints.
348 // This is a non-atomic read-modify-write on m_flags, so this
349 // provider must run with each item processed by only one thread
350 // at a time (guaranteed by submit_loop's work partitioning).
351 if( item->HasHole() )
352 {
353 item->SetFlags( HOLE_PROXY );
354
355 constraint = m_drcEngine->EvalRules( DISALLOW_CONSTRAINT, item,
356 nullptr, UNDEFINED_LAYER );
357
358 if( constraint.m_DisallowFlags
359 && constraint.GetSeverity() != RPT_SEVERITY_IGNORE )
360 {
361 reportDisallow( constraint );
362 }
363
364 item->ClearFlags( HOLE_PROXY );
365 }
366 }
367
368 itemsDone.fetch_add( 1 );
369 return 1;
370 };
371
372 auto itemFutures = tp.submit_loop( 0, itemCount, processItem, itemCount );
373
374 while( itemsDone < itemCount )
375 {
376 reportProgress( itemsDone, itemCount );
377
378 if( m_drcEngine->IsCancelled() )
379 {
380 for( auto& f : itemFutures )
381 f.wait();
382
383 break;
384 }
385
386 itemFutures.wait_for( std::chrono::milliseconds( 250 ) );
387 }
388
389 return !m_drcEngine->IsCancelled();
390}
391
392
393namespace detail
394{
396}
constexpr int ARC_LOW_DEF
Definition base_units.h:136
BOX2< VECTOR2I > BOX2I
Definition box2.h:918
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
int GetDRCEpsilon() const
Return an epsilon which accounts for rounding errors, etc.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:81
virtual std::shared_ptr< SHAPE > GetEffectiveShape(PCB_LAYER_ID aLayer=UNDEFINED_LAYER, FLASHING aFlash=FLASHING::DEFAULT) const
Some pad shapes can be complex (rounded/chamfered rectangle), even without considering custom shapes.
virtual LSET GetLayerSet() const
Return a std::bitset of all layers on which the item physically resides.
Definition board_item.h:285
virtual bool HasHole() const
Definition board_item.h:177
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:372
SHARDED_CACHE< PTR_PTR_LAYER_CACHE_KEY, bool > m_IntersectsAreaCache
Definition board.h:1666
int m_DRCMaxPhysicalClearance
Definition board.h:1698
std::unordered_map< ZONE *, std::unique_ptr< DRC_RTREE > > m_CopperZoneRTreeCache
Definition board.h:1675
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition board.cpp:1149
constexpr bool Intersects(const BOX2< Vec > &aRect) const
Definition box2.h:307
int m_DisallowFlags
Definition drc_rule.h:241
SEVERITY GetSeverity() const
Definition drc_rule.h:217
static std::shared_ptr< DRC_ITEM > Create(int aErrorCode)
Constructs a DRC_ITEM for the given error code.
Definition drc_item.cpp:417
Implement an R-tree for fast spatial and layer indexing of connectable items.
Definition drc_rtree.h:45
int QueryColliding(BOARD_ITEM *aRefItem, PCB_LAYER_ID aRefLayer, PCB_LAYER_ID aTargetLayer, std::function< bool(BOARD_ITEM *)> aFilter=nullptr, std::function< bool(BOARD_ITEM *)> aVisitor=nullptr, int aClearance=0) const
This is a fast test which essentially does bounding-box overlap given a worst-case clearance.
Definition drc_rtree.h:225
bool IsImplicit() const
Definition drc_rule.h:143
BOARD_ITEM * m_ImplicitItem
Definition drc_rule.h:152
virtual ~DRC_TEST_PROVIDER_DISALLOW()=default
virtual const wxString GetName() const override
virtual bool Run() override
Run this provider against the given PCB with configured options (if any).
virtual bool reportPhase(const wxString &aStageName)
int forEachGeometryItem(const std::vector< KICAD_T > &aTypes, const LSET &aLayers, const std::function< bool(BOARD_ITEM *)> &aFunc)
void reportViolation(std::shared_ptr< DRC_ITEM > &item, const VECTOR2I &aMarkerPos, int aMarkerLayer, const std::function< void(PCB_MARKER *)> &aPathGenerator=[](PCB_MARKER *){})
virtual bool reportProgress(size_t aCount, size_t aSize, size_t aDelta=1)
virtual VECTOR2I GetPosition() const
Definition eda_item.h:282
void SetFlags(EDA_ITEM_FLAGS aMask)
Definition eda_item.h:152
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:108
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:154
PCB_LAYER_ID ExtractLayer() const
Find the first set PCB_LAYER_ID.
Definition lset.cpp:538
static const LSET & AllLayersMask()
Definition lset.cpp:637
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
std::shared_ptr< SHAPE > GetEffectiveShape(PCB_LAYER_ID aLayer=UNDEFINED_LAYER, FLASHING aFlash=FLASHING::DEFAULT) const override
Some pad shapes can be complex (rounded/chamfered rectangle), even without considering custom shapes.
Represent a set of closed polygons.
bool Collide(const SHAPE *aShape, int aClearance=0, int *aActual=nullptr, VECTOR2I *aLocation=nullptr) const override
Check if the boundary of shape (this) lies closer to the shape aShape than aClearance,...
void Deflate(int aAmount, CORNER_STRATEGY aCornerStrategy, int aMaxError)
void Fracture(bool aSimplify=true)
Convert a set of polygons with holes to a single outline with "slits"/"fractures" connecting the oute...
void Set(const KEY &aKey, const VALUE &aValue)
Handle a list of polygons defining a copper zone.
Definition zone.h:70
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:811
const BOX2I GetBoundingBox() const override
Definition zone.cpp:737
bool GetDoNotAllowTracks() const
Definition zone.h:823
bool IsFilled() const
Definition zone.h:306
SHAPE_POLY_SET GetBoardOutline() const
Definition zone.cpp:835
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
bool HasKeepoutParametersSet() const
Accessor to determine if any keepout parameters are set.
Definition zone.h:802
bool GetDoNotAllowZoneFills() const
Definition zone.h:821
bool IsOnCopperLayer() const override
Definition zone.cpp:574
The common library.
@ ALLOW_ACUTE_CORNERS
just inflate the polygon. Acute angles create spikes
@ DRCE_TEXT_ON_EDGECUTS
Definition drc_item.h:39
@ DRCE_ALLOWED_ITEMS
Definition drc_item.h:38
@ DISALLOW_CONSTRAINT
Definition drc_rule.h:71
#define _(s)
#define HOLE_PROXY
Indicates the BOARD_ITEM is a proxy for its hole.
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ Edge_Cuts
Definition layer_ids.h:108
@ UNDEFINED_LAYER
Definition layer_ids.h:57
static DRC_REGISTER_TEST_PROVIDER< DRC_TEST_PROVIDER_ANNULAR_WIDTH > dummy
@ RPT_SEVERITY_IGNORE
const double epsilon
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
static thread_pool * tp
BS::priority_thread_pool thread_pool
Definition thread_pool.h:27
constexpr KICAD_T BaseType(const KICAD_T aType)
Return the underlying type of the given type.
Definition typeinfo.h:256
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
Definition typeinfo.h:86
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:101
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:85
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition typeinfo.h:83
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
Definition typeinfo.h:94
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:91
@ PCB_DIMENSION_T
class PCB_DIMENSION_BASE: abstract dimension meta-type
Definition typeinfo.h:93
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition typeinfo.h:87
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:89
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683