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 <advanced_config.h>
24#include <optional>
25
27
28#include "pns_walkaround.h"
29#include "pns_optimizer.h"
30#include "pns_router.h"
31#include "pns_debug_decorator.h"
32#include "pns_solid.h"
33
34
35namespace PNS {
36
37void WALKAROUND::start( const LINE& aInitialPath )
38{
39 m_iteration = 0;
40 for( int pol = 0 ; pol < MaxWalkPolicies; pol++)
41 {
42 m_currentResult.status[ pol ] = ST_IN_PROGRESS;
43 m_currentResult.lines[ pol ] = aInitialPath;
44 m_currentResult.lines[ pol ].ClearLinks();
45 }
46}
47
48
50{
52
54
55 if( ! m_restrictedSet.empty() )
56 {
57 opts.m_filter = [ this ] ( const ITEM* item ) -> bool
58 {
59 if( m_restrictedSet.find( item ) != m_restrictedSet.end() )
60 return true;
61 return false;
62 };
63 }
64
65 opts.m_useClearanceEpsilon = false;
66 return m_world->NearestObstacle( &aPath, opts );
67}
68
69
70void WALKAROUND::RestrictToCluster( bool aEnabled, const TOPOLOGY::CLUSTER& aCluster )
71{
73 m_restrictedSet.clear();
74
75 if( aEnabled )
76 {
77 for( ITEM* item : aCluster.m_items )
78 {
79 m_restrictedSet.insert( item );
80
81 if ( item->HasHole() )
82 m_restrictedSet.insert( item->Hole() );
83 }
84 }
85
86 for( ITEM* item : aCluster.m_items )
87 {
88 if( SOLID* solid = dyn_cast<SOLID*>( item ) )
89 m_restrictedVertices.push_back( solid->Anchor( 0 ) );
90 }
91}
92
93static wxString policy2string ( WALKAROUND::WALK_POLICY policy )
94{
95 switch(policy)
96 {
97 case WALKAROUND::WP_CCW: return wxT("ccw");
98 case WALKAROUND::WP_CW: return wxT("cw");
99 case WALKAROUND::WP_SHORTEST: return wxT("shortest");
100 }
101 return wxT("?");
102}
103
105{
106 TOPOLOGY topo( m_world );
107 TOPOLOGY::CLUSTER pendingClusters[MaxWalkPolicies];
108
109 for( int i = 0; i < MaxWalkPolicies; i++ )
110 {
111 if( !m_enabledPolicies[i] )
112 continue;
113
114 auto& line = m_currentResult.lines[ i ];
115 auto& status = m_currentResult.status[ i ];
116
117 PNS_DBG( Dbg(), AddItem, &line, WHITE, 10000, wxString::Format( "current (policy %d, stat %d)", i, status ) );
118
119 if( status != ST_IN_PROGRESS )
120 continue;
121
122 auto obstacle = nearestObstacle( line );
123
124 if( !obstacle )
125 {
126
127 m_currentResult.status[ i ] = ST_DONE;
128 PNS_DBG( Dbg(), Message, wxString::Format( "no-more-colls pol %d st %d", i, status ) );
129
130 continue;
131 }
132
133
134 pendingClusters[ i ] = topo.AssembleCluster( obstacle->m_item, line.Layer(), 0.0, line.Net() );
135 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() ) );
136
137 }
138
140
141 auto processCluster = [ & ] ( TOPOLOGY::CLUSTER& aCluster, LINE& aLine, bool aCw ) -> bool
142 {
143 using namespace std::chrono;
144 auto start_time = steady_clock::now();
145
147
148 PNS_DBG( Dbg(), BeginGroup, wxString::Format( "cluster-details [cw %d]", aCw?1:0 ), 1 );
149
150 for( auto& clItem : aCluster.m_items )
151 {
152 // Check for wallclock timeout
153 // Emprically, 100ms seems to be about where you're not going to find a valid path
154 // if you haven't found it by then. This allows the user to adjust their mouse position
155 // to get a better path without waiting too long.
156 auto now = steady_clock::now();
157 auto elapsed = duration_cast<milliseconds>( now - start_time ).count();
158
159 if( elapsed > timeout_ms )
160 {
161 PNS_DBG( Dbg(), Message, wxString::Format( "processCluster timeout after %d ms", timeout_ms ) );
162 PNS_DBGN( Dbg(), EndGroup );
163 return false;
164 }
165
166 int clearance = m_world->GetClearance( clItem, &aLine, false );
167 const SHAPE_LINE_CHAIN& cachedHull = m_world->GetRuleResolver()->HullCache(
168 clItem, clearance, aLine.Width(), aLine.Layer() );
169
170 SHAPE_LINE_CHAIN hull;
171
172 if( cornerMode == DIRECTION_45::MITERED_90 || cornerMode == DIRECTION_45::ROUNDED_90 )
173 {
174 BOX2I bbox = cachedHull.BBox();
175 hull.Append( bbox.GetLeft(), bbox.GetTop() );
176 hull.Append( bbox.GetRight(), bbox.GetTop() );
177 hull.Append( bbox.GetRight(), bbox.GetBottom() );
178 hull.Append( bbox.GetLeft(), bbox.GetBottom() );
179 }
180 else
181 {
182 hull = cachedHull;
183 }
184
185 LINE tmp( aLine );
186
187 bool stat = aLine.Walkaround( hull, tmp.Line(), aCw );
188
189 PNS_DBG( Dbg(), AddShape, &hull, YELLOW, 10000, wxString::Format( "hull stat %d", stat?1:0 ) );
190 PNS_DBG( Dbg(), AddItem, &tmp, RED, 10000, wxString::Format( "walk stat %d", stat?1:0 ) );
191 PNS_DBG( Dbg(), AddItem, clItem, WHITE, 10000, wxString::Format( "item stat %d", stat?1:0 ) );
192
193 if( !stat )
194 {
195 PNS_DBGN( Dbg(), EndGroup );
196 return false;
197 }
198
199 aLine.SetShape( tmp.CLine() );
200 }
201
202 PNS_DBGN( Dbg(), EndGroup );
203
204 return true;
205 };
206
208 {
209 bool stat = processCluster( pendingClusters[ WP_CW ], m_currentResult.lines[ WP_CW ], true );
210 if( !stat )
211 m_currentResult.status[ WP_CW ] = ST_STUCK;
212 }
213
215 {
216 bool stat = processCluster( pendingClusters[ WP_CCW ], m_currentResult.lines[ WP_CCW ], false );
217 if( !stat )
218 m_currentResult.status[ WP_CCW ] = ST_STUCK;
219 }
220
222 {
223 LINE& line = m_currentResult.lines[WP_SHORTEST];
224 LINE path_cw( line ), path_ccw( line );
225
226 auto st_cw = processCluster( pendingClusters[WP_SHORTEST], path_cw, true );
227 auto st_ccw = processCluster( pendingClusters[WP_SHORTEST], path_ccw, false );
228
229 bool cw_coll = st_cw ? m_world->CheckColliding( &path_cw ).has_value() : false;
230 bool ccw_coll = st_ccw ? m_world->CheckColliding( &path_ccw ).has_value() : false;
231
232 double lengthFactorCw = (double) path_cw.CLine().Length() / (double) m_initialLength;
233 double lengthFactorCcw = (double) path_ccw.CLine().Length() / (double) m_initialLength;
234
235 PNS_DBG( Dbg(), AddItem, &path_cw, RED, 10000, wxString::Format( "shortest-cw stat %d lf %.1f", st_cw?1:0, lengthFactorCw ) );
236 PNS_DBG( Dbg(), AddItem, &path_ccw, BLUE, 10000, wxString::Format( "shortest-ccw stat %d lf %.1f", st_ccw?1:0, lengthFactorCcw ) );
237
238
239 std::optional<LINE> shortest;
240 std::optional<LINE> shortest_alt;
241
242
243 if( st_cw && st_ccw )
244 {
245 if( !cw_coll && !ccw_coll || ( cw_coll && ccw_coll) )
246 {
247 if( path_cw.CLine().Length() > path_ccw.CLine().Length() )
248 {
249 shortest = path_ccw;
250 shortest_alt = path_cw;
251 }
252 else
253 {
254 shortest = path_cw;
255 shortest_alt = path_ccw;
256 }
257 }
258 else if( !cw_coll )
259 shortest = path_cw;
260 else if( !ccw_coll )
261 shortest = path_ccw;
262
263 }
264 else if( st_ccw )
265 shortest = path_ccw;
266 else if( st_cw )
267 shortest = path_cw;
268
269 bool anyColliding = false;
270
271 if( m_lastShortestCluster && shortest.has_value() )
272 {
273 for( auto& item : m_lastShortestCluster->m_items )
274 {
275 if( shortest->Collide( item, m_world, shortest->Layer() ) )
276 {
277 anyColliding = true;
278 break;
279 }
280 }
281
282 PNS_DBG( Dbg(), Message, wxString::Format("check-back cc %d items %d coll %d", (int) pendingClusters[ WP_SHORTEST ].m_items.size(), (int) m_lastShortestCluster->m_items.size(), anyColliding ? 1: 0 ) );
283 }
284
285 if ( anyColliding )
286 {
287 shortest = std::move( shortest_alt );
288 }
289
290 if( !shortest )
291 {
293 }
294 else
295 {
296 m_currentResult.lines[WP_SHORTEST] = *shortest;
297 }
298
299 m_lastShortestCluster = pendingClusters[ WP_SHORTEST ];
300 }
301
302 return ST_IN_PROGRESS;
303}
304
305
306const WALKAROUND::RESULT WALKAROUND::Route( const LINE& aInitialPath )
307{
309
310 m_initialLength = aInitialPath.CLine().Length();
311
312 // special case for via-in-the-middle-of-track placement
313
314#if 0
315 if( aInitialPath.PointCount() <= 1 )
316 {
317 if( aInitialPath.EndsWithVia() && m_world->CheckColliding( &aInitialPath.Via(),
318 m_itemMask ) )
319 {
320 // fixme restult
321 }
322 //return RESULT( STUCK, STUCK );
323
324 return RESULT(); //( DONE, DONE, aInitialPath, aInitialPath );
325 }
326#endif
327
328 start( aInitialPath );
329
330 PNS_DBG( Dbg(), AddItem, &aInitialPath, WHITE, 10000, wxT( "initial-path" ) );
331
333 {
334 singleStep();
335
336 bool stillInProgress = false;
337
338 for( int pol = 0; pol < MaxWalkPolicies; pol++ )
339 {
340 if (!m_enabledPolicies[pol])
341 continue;
342
343 auto& st = m_currentResult.status[pol];
344 auto& ln = m_currentResult.lines[pol];
345 double lengthFactor = (double) ln.CLine().Length() / (double) aInitialPath.CLine().Length();
346 // In some situations, there isn't a trivial path (or even a path at all). Hitting the
347 // iteration limit causes lag, so we can exit out early if the walkaround path gets very long
348 // compared with the initial path. If the length exceeds the initial length times this factor,
349 // fail out.
350 if( m_lengthLimitOn )
351 {
352 if( st != ST_DONE && lengthFactor > m_lengthExpansionFactor )
353 st = ST_ALMOST_DONE;
354 }
355
356 PNS_DBG( Dbg(), Message, wxString::Format( "check-wp iter %d st %d i %d lf %.1f", m_iteration, st, pol, lengthFactor ) );
357
358 if ( st == ST_IN_PROGRESS )
359 stillInProgress = true;
360 }
361
362
363 if( !stillInProgress )
364 break;
365
366 m_iteration++;
367 }
368
369
370 for( int pol = 0; pol < MaxWalkPolicies; pol++ )
371 {
372 auto& st = m_currentResult.status[pol];
373 const auto& ln = m_currentResult.lines[pol].CLine();
374
375 m_currentResult.lines[pol].ClearLinks();
376 if( st == ST_IN_PROGRESS )
377 st = ST_ALMOST_DONE;
378
379 if( ln.SegmentCount() < 1 || ln.CPoint( 0 ) != aInitialPath.CPoint( 0 ) )
380 {
381 st = ST_STUCK;
382 }
383
384 if( ln.PointCount() > 0 && ln.CLastPoint() != aInitialPath.CLastPoint() )
385 {
386 st = ST_ALMOST_DONE;
387
388 }
389 PNS_DBG( Dbg(), Message, wxString::Format( "stat=%d", st ) );
390
391 }
392
393
394 return m_currentResult;
395}
396
397void WALKAROUND::SetAllowedPolicies( std::vector<WALK_POLICY> aPolicies)
398{
399 for( int i = 0; i < MaxWalkPolicies; i++ )
400 m_enabledPolicies[i] = false;
401
402 for ( auto p : aPolicies )
403 m_enabledPolicies[p] = true;
404}
405
406}
407
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::optional< TOPOLOGY::CLUSTER > m_lastShortestCluster
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.
static wxString policy2string(WALKAROUND::WALK_POLICY policy)
#define PNS_DBG(dbg, method,...)
#define PNS_DBGN(dbg, method)
std::function< bool(const ITEM *)> m_filter
Definition pns_node.h:120
std::set< 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