KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pns_walkaround.cpp
Go to the documentation of this file.
1/*
2 * KiRouter - a push-and-(sometimes-)shove PCB router
3 *
4 * Copyright (C) 2013-2014 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 * Author: Tomasz Wlostowski <[email protected]>
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, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include <chrono>
23#include <optional>
24
25#include <advanced_config.h>
26#include <core/typeinfo.h>
28
29#include "pns_walkaround.h"
30#include "pns_optimizer.h"
31#include "pns_router.h"
32#include "pns_debug_decorator.h"
33#include "pns_solid.h"
34
35
36namespace PNS {
37
38void WALKAROUND::start( const LINE& aInitialPath )
39{
40 m_iteration = 0;
41 for( int pol = 0 ; pol < MaxWalkPolicies; pol++)
42 {
43 m_currentResult.status[ pol ] = ST_IN_PROGRESS;
44 m_currentResult.lines[ pol ] = aInitialPath;
45 m_currentResult.lines[ pol ].ClearLinks();
46 }
47}
48
49
51{
53
55
56 if( ! m_restrictedSet.empty() )
57 {
58 opts.m_filter = [ this ] ( const ITEM* item ) -> bool
59 {
60 if( m_restrictedSet.find( item ) != m_restrictedSet.end() )
61 return true;
62 return false;
63 };
64 }
65
66 opts.m_useClearanceEpsilon = true;
67 return m_world->NearestObstacle( &aPath, opts );
68}
69
70
71void WALKAROUND::RestrictToCluster( bool aEnabled, const TOPOLOGY::CLUSTER& aCluster )
72{
74 m_restrictedSet.clear();
75
76 if( aEnabled )
77 {
78 for( ITEM* item : aCluster.m_items )
79 {
80 m_restrictedSet.insert( item );
81
82 if ( item->HasHole() )
83 m_restrictedSet.insert( item->Hole() );
84 }
85 }
86
87 for( ITEM* item : aCluster.m_items )
88 {
89 if( SOLID* solid = dyn_cast<SOLID*>( item ) )
90 m_restrictedVertices.push_back( solid->Anchor( 0 ) );
91 }
92}
93
95{
96 TOPOLOGY topo( m_world );
97 TOPOLOGY::CLUSTER pendingClusters[MaxWalkPolicies];
98
99 for( int i = 0; i < MaxWalkPolicies; i++ )
100 {
101 if( !m_enabledPolicies[i] )
102 continue;
103
104 auto& line = m_currentResult.lines[ i ];
105 auto& status = m_currentResult.status[ i ];
106
107 PNS_DBG( Dbg(), AddItem, &line, WHITE, 10000, wxString::Format( "current (policy %d, stat %d)", i, status ) );
108
109 if( status != ST_IN_PROGRESS )
110 continue;
111
112 auto obstacle = nearestObstacle( line );
113
114 if( !obstacle )
115 {
116
117 m_currentResult.status[ i ] = ST_DONE;
118 PNS_DBG( Dbg(), Message, wxString::Format( "no-more-colls pol %d st %d", i, status ) );
119
120 continue;
121 }
122
123
124 pendingClusters[ i ] = topo.AssembleCluster( obstacle->m_item, line.Layer(), 0.0, line.Net() );
125 PNS_DBG( Dbg(), AddItem, obstacle->m_item, BLUE, 10000, wxString::Format( "col-item owner-depth %d cl-items=%d", static_cast<const NODE*>( obstacle->m_item->Owner() )->Depth(), (int) pendingClusters[i].m_items.size() ) );
126
127 }
128
130
131 auto processCluster = [ & ] ( TOPOLOGY::CLUSTER& aCluster, LINE& aLine, bool aCw ) -> bool
132 {
133 using namespace std::chrono;
134 auto start_time = steady_clock::now();
135
137
138 PNS_DBG( Dbg(), BeginGroup, wxString::Format( "cluster-details [cw %d]", aCw?1:0 ), 1 );
139
140 for( auto& clItem : aCluster.m_items )
141 {
142 // Check for wallclock timeout
143 // Emprically, 100ms seems to be about where you're not going to find a valid path
144 // if you haven't found it by then. This allows the user to adjust their mouse position
145 // to get a better path without waiting too long.
146 auto now = steady_clock::now();
147 auto elapsed = duration_cast<milliseconds>( now - start_time ).count();
148
149 if( elapsed > timeout_ms )
150 {
151 PNS_DBG( Dbg(), Message, wxString::Format( "processCluster timeout after %d ms", timeout_ms ) );
152 PNS_DBGN( Dbg(), EndGroup );
153 return false;
154 }
155
156 int clearance = m_world->GetClearance( clItem, &aLine, false );
157 const SHAPE_LINE_CHAIN& cachedHull = m_world->GetRuleResolver()->HullCache(
158 clItem, clearance, aLine.Width(), aLine.Layer() );
159
160 SHAPE_LINE_CHAIN hull;
161
162 if( cornerMode == DIRECTION_45::MITERED_90 || cornerMode == DIRECTION_45::ROUNDED_90 )
163 {
164 BOX2I bbox = cachedHull.BBox();
165 hull.Append( bbox.GetLeft(), bbox.GetTop() );
166 hull.Append( bbox.GetRight(), bbox.GetTop() );
167 hull.Append( bbox.GetRight(), bbox.GetBottom() );
168 hull.Append( bbox.GetLeft(), bbox.GetBottom() );
169 }
170 else
171 {
172 hull = cachedHull;
173 }
174
175 LINE tmp( aLine );
176
177 aLine.Line().Simplify2();
178
179 bool stat = aLine.Walkaround( hull, tmp.Line(), aCw );
180
181 PNS_DBG( Dbg(), AddShape, &hull, YELLOW, 10000, wxString::Format( "hull stat %d", stat?1:0 ) );
182 PNS_DBG( Dbg(), AddItem, &tmp, RED, 10000, wxString::Format( "walk stat %d", stat?1:0 ) );
183 PNS_DBG( Dbg(), AddItem, clItem, WHITE, 10000, wxString::Format( "item stat %d", stat?1:0 ) );
184
185 if( !stat )
186 {
187 PNS_DBGN( Dbg(), EndGroup );
188 return false;
189 }
190
191 aLine.SetShape( tmp.CLine() );
192 }
193
194 PNS_DBGN( Dbg(), EndGroup );
195
196 return true;
197 };
198
200 {
201 bool stat = processCluster( pendingClusters[ WP_CW ], m_currentResult.lines[ WP_CW ], true );
202 if( !stat )
203 m_currentResult.status[ WP_CW ] = ST_STUCK;
204 }
205
207 {
208 bool stat = processCluster( pendingClusters[ WP_CCW ], m_currentResult.lines[ WP_CCW ], false );
209 if( !stat )
210 m_currentResult.status[ WP_CCW ] = ST_STUCK;
211 }
212
214 {
215 LINE& line = m_currentResult.lines[WP_SHORTEST];
216 LINE path_cw( line ), path_ccw( line );
217
218 auto st_cw = processCluster( pendingClusters[WP_SHORTEST], path_cw, true );
219 auto st_ccw = processCluster( pendingClusters[WP_SHORTEST], path_ccw, false );
220
221 bool cw_coll = st_cw ? m_world->CheckColliding( &path_cw ).has_value() : false;
222 bool ccw_coll = st_ccw ? m_world->CheckColliding( &path_ccw ).has_value() : false;
223
224 double lengthFactorCw = (double) path_cw.CLine().Length() / (double) m_initialLength;
225 double lengthFactorCcw = (double) path_ccw.CLine().Length() / (double) m_initialLength;
226
227 PNS_DBG( Dbg(), AddItem, &path_cw, RED, 10000, wxString::Format( "shortest-cw stat %d lf %.1f", st_cw?1:0, lengthFactorCw ) );
228 PNS_DBG( Dbg(), AddItem, &path_ccw, BLUE, 10000, wxString::Format( "shortest-ccw stat %d lf %.1f", st_ccw?1:0, lengthFactorCcw ) );
229
230
231 std::optional<LINE> shortest;
232 std::optional<LINE> shortest_alt;
233
234
235 if( st_cw && st_ccw )
236 {
237 if( ( !cw_coll && !ccw_coll ) || ( cw_coll && ccw_coll ) )
238 {
239 if( path_cw.CLine().Length() > path_ccw.CLine().Length() )
240 {
241 shortest = path_ccw;
242 shortest_alt = path_cw;
243 }
244 else
245 {
246 shortest = path_cw;
247 shortest_alt = path_ccw;
248 }
249 }
250 else if( !cw_coll )
251 shortest = path_cw;
252 else if( !ccw_coll )
253 shortest = path_ccw;
254
255 }
256 else if( st_ccw )
257 shortest = path_ccw;
258 else if( st_cw )
259 shortest = path_cw;
260
261 bool anyColliding = false;
262
263 if( shortest.has_value() )
264 {
265 PNS_DBG( Dbg(), AddItem, &shortest.value(), RED, 10000, wxString::Format( "shortest-l" ) );
266
267 for( auto& item : m_processedItems )
268 {
269 std::set<PNS::OBSTACLE> obstacles;
270 PNS::COLLISION_SEARCH_CONTEXT ctx( obstacles );
271 if( shortest->Collide( item, m_world, shortest->Layer(), &ctx ) )
272 {
273 anyColliding = true;
274 break;
275 }
276 }
277
278 PNS_DBG( Dbg(), Message, wxString::Format("check-back cc %d items %d coll %d", (int) pendingClusters[ WP_SHORTEST ].m_items.size(), (int) m_processedItems.size(), anyColliding ? 1: 0 ) );
279 }
280
281 if ( anyColliding )
282 {
283 shortest = std::move( shortest_alt );
284 }
285
286 if( !shortest )
287 {
289 }
290 else
291 {
292 m_currentResult.lines[WP_SHORTEST] = *shortest;
293 }
294
295 for( auto item : pendingClusters[ WP_SHORTEST ].m_items )
296 m_processedItems.insert( item );
297 }
298
299 return ST_IN_PROGRESS;
300}
301
302
303const WALKAROUND::RESULT WALKAROUND::Route( const LINE& aInitialPath )
304{
306
307 m_initialLength = aInitialPath.CLine().Length();
308
309 // special case for via-in-the-middle-of-track placement
310
311#if 0
312 if( aInitialPath.PointCount() <= 1 )
313 {
314 if( aInitialPath.EndsWithVia() && m_world->CheckColliding( &aInitialPath.Via(),
315 m_itemMask ) )
316 {
317 // fixme restult
318 }
319 //return RESULT( STUCK, STUCK );
320
321 return RESULT(); //( DONE, DONE, aInitialPath, aInitialPath );
322 }
323#endif
324
325 start( aInitialPath );
326
327 m_processedItems.clear();
328
329 PNS_DBG( Dbg(), AddItem, &aInitialPath, WHITE, 10000, wxT( "initial-path" ) );
330
332 {
333 singleStep();
334
335 bool stillInProgress = false;
336
337 for( int pol = 0; pol < MaxWalkPolicies; pol++ )
338 {
339 if (!m_enabledPolicies[pol])
340 continue;
341
342 auto& st = m_currentResult.status[pol];
343 auto& ln = m_currentResult.lines[pol];
344 double lengthFactor = (double) ln.CLine().Length() / (double) aInitialPath.CLine().Length();
345 // In some situations, there isn't a trivial path (or even a path at all). Hitting the
346 // iteration limit causes lag, so we can exit out early if the walkaround path gets very long
347 // compared with the initial path. If the length exceeds the initial length times this factor,
348 // fail out.
349 if( m_lengthLimitOn )
350 {
351 if( st != ST_DONE && lengthFactor > m_lengthExpansionFactor )
352 st = ST_ALMOST_DONE;
353 }
354
355 PNS_DBG( Dbg(), Message, wxString::Format( "check-wp iter %d st %d i %d lf %.1f", m_iteration, st, pol, lengthFactor ) );
356
357 if ( st == ST_IN_PROGRESS )
358 stillInProgress = true;
359 }
360
361
362 if( !stillInProgress )
363 break;
364
365 m_iteration++;
366 }
367
368
369 for( int pol = 0; pol < MaxWalkPolicies; pol++ )
370 {
371 auto& st = m_currentResult.status[pol];
372 const auto& ln = m_currentResult.lines[pol].CLine();
373
374 m_currentResult.lines[pol].ClearLinks();
375 if( st == ST_IN_PROGRESS )
376 st = ST_ALMOST_DONE;
377
378 if( ln.SegmentCount() < 1 || ln.CPoint( 0 ) != aInitialPath.CPoint( 0 ) )
379 {
380 st = ST_STUCK;
381 }
382
383 if( ln.PointCount() > 0 && ln.CLastPoint() != aInitialPath.CLastPoint() )
384 {
385 st = ST_ALMOST_DONE;
386
387 }
388 PNS_DBG( Dbg(), Message, wxString::Format( "stat=%d", st ) );
389
390 }
391
392
393 return m_currentResult;
394}
395
396void WALKAROUND::SetAllowedPolicies( std::vector<WALK_POLICY> aPolicies)
397{
398 for( int i = 0; i < MaxWalkPolicies; i++ )
399 m_enabledPolicies[i] = false;
400
401 for ( auto p : aPolicies )
402 m_enabledPolicies[p] = true;
403}
404
405}
BOX2< VECTOR2I > BOX2I
Definition box2.h:922
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
constexpr coord_type GetLeft() const
Definition box2.h:228
constexpr coord_type GetRight() const
Definition box2.h:217
constexpr coord_type GetTop() const
Definition box2.h:229
constexpr coord_type GetBottom() const
Definition box2.h:222
CORNER_MODE
Corner modes.
Definition direction45.h:67
@ ROUNDED_90
H/V with filleted corners.
Definition direction45.h:71
@ MITERED_90
H/V only (90-degree corners)
Definition direction45.h:70
ROUTING_SETTINGS & Settings() const
Return the logger object, allowing to dump geometry to a file.
DEBUG_DECORATOR * Dbg() const
Base class for PNS router board items.
Definition pns_item.h:98
virtual HOLE * Hole() const
Definition pns_item.h:304
virtual bool HasHole() const
Definition pns_item.h:303
Represents a track on a PCB, connecting two non-trivial joints (that is, vias, pads,...
Definition pns_line.h:62
const VECTOR2I & CPoint(int aIdx) const
Definition pns_line.h:150
const SHAPE_LINE_CHAIN & CLine() const
Definition pns_line.h:142
const VECTOR2I & CLastPoint() const
Definition pns_line.h:151
SHAPE_LINE_CHAIN & Line()
Definition pns_line.h:141
VIA & Via()
Definition pns_line.h:203
int PointCount() const
Definition pns_line.h:145
bool EndsWithVia() const
Definition pns_line.h:195
Keep the router "world" - i.e.
Definition pns_node.h:240
std::optional< OBSTACLE > OPT_OBSTACLE
Definition pns_node.h:250
int Depth() const
Definition pns_node.h:290
DIRECTION_45::CORNER_MODE GetCornerMode() const
const CLUSTER AssembleCluster(ITEM *aStart, int aLayer, double aAreaExpansionLimit=0.0, NET_HANDLE aExcludedNet=nullptr)
void RestrictToCluster(bool aEnabled, const TOPOLOGY::CLUSTER &aCluster)
STATUS Route(const LINE &aInitialPath, LINE &aWalkPath, bool aOptimize=true)
bool m_enabledPolicies[MaxWalkPolicies]
NODE::OPT_OBSTACLE nearestObstacle(const LINE &aPath)
std::vector< VECTOR2I > m_restrictedVertices
void SetAllowedPolicies(std::vector< WALK_POLICY > aPolicies)
void start(const LINE &aInitialPath)
static constexpr int MaxWalkPolicies
std::set< ITEM * > m_processedItems
double m_lengthExpansionFactor
std::set< const ITEM * > m_restrictedSet
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
long long int Length() const
Return length of the line chain in Euclidean metric.
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
@ WHITE
Definition color4d.h:48
@ BLUE
Definition color4d.h:56
@ YELLOW
Definition color4d.h:67
@ RED
Definition color4d.h:59
int m_PNSProcessClusterTimeout
Timeout for the PNS router's processCluster wallclock timeout, in milliseconds.
Push and Shove diff pair dimensions (gap) settings dialog.
#define PNS_DBG(dbg, method,...)
#define PNS_DBGN(dbg, method)
std::function< bool(const ITEM *)> m_filter
Definition pns_node.h:120
std::vector< ITEM * > m_items
int clearance
wxString result
Test unit parsing edge cases and error handling.
Casted dyn_cast(From aObject)
A lightweight dynamic downcast.
Definition typeinfo.h:61