1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
//! Grid A* core, 2 layers (port of tools/router/astar.c with the same arithmetic in f32;
//! a radix heap replaces the binary heap, so ties break differently).
//!
//! States are cell * 2 + layer, so both layers of a cell share a cache line. Foreign distance for net X: n1 == X ? d2 : d1.
use crate::board::Field;
/// A step "runs alongside" copper within this distance (mm) beyond its clearance.
const HUG_BAND: f32 = 0.15;
/// A via's conflicts and history weigh like this many track steps.
const VIA_SOFT: f32 = 8.0;
const DX: [i32; 8] = [1, 1, 0, -1, -1, -1, 0, 1];
const DY: [i32; 8] = [0, 1, 1, 1, 0, -1, -1, -1];
pub struct SearchArgs<'a> {
pub nx: usize,
pub n: usize,
pub f: &'a [Field],
pub padd: &'a [f32],
/// per cell distance to the nearest drill edge; a via needs r_hole
pub hole: &'a [f32],
pub r_hole: f32,
/// steps a path needs between two of its own vias
pub via_gap: u16,
pub cost: &'a [f32],
/// negotiation: a step onto other nets' soft copper costs (base + hist) * (1 + pres)
/// (INFINITY: not allowed); elsewhere base + hist
pub soft: Option<&'a [Field]>,
pub hist: &'a [f32],
pub pres: f32,
pub net: i32,
pub src: &'a [i32],
pub tgt: &'a [u8],
pub goal_layer1: bool,
pub hx: i32,
pub hy: i32,
pub r_nom: f32,
pub r_neck: f32,
pub r_via: f32,
pub r_vpad: f32,
pub r_diag: f32,
pub neckbox: &'a [[i32; 4]],
pub via_cost: f32,
pub via_cmult: f32,
pub bmult: f32,
pub turn_cost: f32,
pub allow_via: bool,
pub max_expand: i64,
pub layer_mask: u8,
/// heuristic weight: 1 is exact A*, more trades path cost for fewer expansions
pub hweight: f32,
/// extra cost per step farther than HUG_BAND from other copper
pub hug: f32,
/// per state distance to the copper of the net's bundle partners (pair, bus), and the
/// extra cost per step farther than HUG_BAND from it
pub attract: Option<&'a [f32]>,
pub attract_cost: f32,
/// a necked step costs 0.3 plus this much per mm of width given up
pub neck: f32,
/// cell window [x0, y0, x1, y1] (inclusive) the search stays in
pub window: [i32; 4],
}
/// Per-state search data, packed so that one state is one cache access.
#[derive(Clone, Copy, Default)]
struct Node {
g: f32,
par: i32,
stamp: u32,
dir: u8,
closed: bool,
/// steps since the path's last via (its own vias are not in the hole field yet)
since: u16,
}
/// Radix heap on the f32 bit patterns of non-negative keys. A* pops keys in non-decreasing
/// order (the octile heuristic is consistent: every step costs at least its length), which
/// is all a radix heap needs; push and pop are O(1) amortised instead of a binary heap's
/// cache-missing O(log n).
struct RadixHeap {
last: u32,
len: usize,
buckets: Vec<Vec<(u32, i32)>>,
}
impl RadixHeap {
fn new() -> RadixHeap {
RadixHeap { last: 0, len: 0, buckets: (0..33).map(|_| Vec::new()).collect() }
}
fn clear(&mut self) {
self.buckets.iter_mut().for_each(Vec::clear);
self.last = 0;
self.len = 0;
}
fn bucket(&self, k: u32) -> usize {
(32 - (k ^ self.last).leading_zeros()) as usize
}
fn push(&mut self, f: f32, i: i32) {
let k = f.max(0.0).to_bits().max(self.last); // a key below the last pop would break the order
let b = self.bucket(k);
self.buckets[b].push((k, i));
self.len += 1;
}
fn pop(&mut self) -> i32 {
if self.buckets[0].is_empty() {
let b = (1..33).find(|&b| !self.buckets[b].is_empty()).unwrap();
let items = std::mem::take(&mut self.buckets[b]);
self.last = items.iter().map(|e| e.0).min().unwrap();
for &(k, i) in &items {
let nb = self.bucket(k);
self.buckets[nb].push((k, i));
}
let mut v = items;
v.clear();
self.buckets[b] = v;
}
self.len -= 1;
self.buckets[0].pop().unwrap().1
}
fn is_empty(&self) -> bool {
self.len == 0
}
}
pub struct Search {
node: Vec<Node>,
call: u32,
heap: RadixHeap,
}
#[inline]
fn heur(x: i32, y: i32, hx: i32, hy: i32) -> f32 {
let (ax, ay) = ((x - hx).abs(), (y - hy).abs());
ax.max(ay) as f32 + 0.414_213_56f32 * ax.min(ay) as f32
}
impl Search {
pub fn new(states: usize) -> Search {
Search { node: vec![Node::default(); states], call: 0, heap: RadixHeap::new() }
}
fn push(&mut self, f: f32, i: i32) {
self.heap.push(f, i);
}
fn pop(&mut self) -> i32 {
self.heap.pop()
}
/// Path (target back to source) with neck flags, or None.
pub fn route(&mut self, a: &SearchArgs) -> Option<(Vec<i32>, Vec<u8>)> {
let nx = a.nx as i32;
let fdist = |s: usize| a.f[s].fdist(a.net);
self.call = self.call.wrapping_add(1);
if self.call == 0 {
self.node.iter_mut().for_each(|v| v.stamp = 0);
self.call = 1;
}
let call = self.call;
self.heap.clear();
let neck_cost = 0.3 + a.neck * 2.0 * (a.r_nom - a.r_neck).max(0.0);
for &s in a.src {
let s = s as usize;
let l = s & 1;
if (a.layer_mask >> l) & 1 == 0 {
continue;
}
if fdist(s) < if a.r_neck > 0.0 { a.r_neck } else { a.r_nom } {
continue; // a track must fit at its start cell
}
self.node[s] = Node { g: 0.0, par: -1, stamp: call, dir: 255, closed: false, since: u16::MAX };
let c = (s >> 1) as i32;
self.push(if a.goal_layer1 { 0.0 } else { a.hweight * heur(c % nx, c / nx, a.hx, a.hy) }, s as i32);
}
let mut expanded: i64 = 0;
let mut found: i64 = -1;
while !self.heap.is_empty() {
let s = self.pop() as usize;
if self.node[s].closed {
continue;
}
self.node[s].closed = true;
let l = s & 1;
let c = s >> 1;
let (x, y) = ((c % a.nx) as i32, (c / a.nx) as i32);
if a.tgt[s] != 0 || (a.goal_layer1 && l == 1) {
found = s as i64;
break;
}
expanded += 1;
if expanded > a.max_expand {
break;
}
let gcur = self.node[s].g;
let pd = self.node[s].dir;
let since = self.node[s].since;
for d in 0..8usize {
// cheap rejections first: reversals and sharp turns, closed states
let mut turn = 0.0f32;
if pd != 255 && pd as usize != d {
let mut t = (pd as i32 - d as i32).abs();
if t > 4 {
t = 8 - t;
}
if t >= 3 {
continue;
}
turn = a.turn_cost * t as f32;
}
let (qx, qy) = (x + DX[d], y + DY[d]);
if qx < a.window[0] || qy < a.window[1] || qx > a.window[2] || qy > a.window[3] {
continue;
}
let nc = (qy * nx + qx) as usize;
let ns = nc * 2 + l;
let q = self.node[ns];
if q.stamp == call && q.closed {
continue;
}
let fd = fdist(ns);
let odd = d & 1 == 1;
let need = a.r_nom + if odd { a.r_diag } else { 0.0 };
let mut neck = false;
let mut r = need;
if fd < need {
if a.r_neck <= 0.0 {
continue;
}
let needn = a.r_neck + if odd { a.r_diag } else { 0.0 };
if fd < needn {
continue;
}
if !a.neckbox.iter().any(|b| qx >= b[0] && qx <= b[2] && qy >= b[1] && qy <= b[3]) {
continue;
}
neck = true;
r = needn;
}
let step = if odd { 1.414_213_56f32 } else { 1.0f32 };
let mut cst = step * if l == 1 { a.bmult } else { 1.0 } + a.cost[ns] * step;
if neck {
cst += neck_cost * step;
}
if a.hug > 0.0 && fd > r + HUG_BAND {
cst += a.hug * step;
}
if let Some(at) = a.attract {
if at[ns] > r + HUG_BAND {
cst += a.attract_cost * step;
}
}
if let Some(sf) = a.soft {
// PathFinder: (base + history) * (1 + present factor on conflict)
cst += a.hist[ns] * step;
if sf[ns].fdist(a.net) < r {
if a.pres == f32::INFINITY {
continue;
}
cst *= 1.0 + a.pres;
}
}
cst += turn;
let ng = gcur + cst;
if q.stamp == call && q.g <= ng {
continue;
}
self.node[ns] = Node { g: ng, par: s as i32, stamp: call, dir: d as u8, closed: false, since: since.saturating_add(1) };
self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(qx, qy, a.hx, a.hy) }, ns as i32);
}
if a.allow_via && a.layer_mask & 3 == 3 {
let (s0, s1) = (c * 2, c * 2 + 1);
let mut soft_ok = true;
let mut vc = a.via_cost + a.via_cmult * (a.cost[s0] + a.cost[s1]);
if let Some(sf) = a.soft {
let n = (sf[s0].fdist(a.net) < a.r_via) as u32 + (sf[s1].fdist(a.net) < a.r_via) as u32;
soft_ok = n == 0 || a.pres != f32::INFINITY;
vc += VIA_SOFT * (a.hist[s0] + a.hist[s1]);
if n > 0 {
vc *= 1.0 + a.pres * n as f32;
}
}
if soft_ok && since >= a.via_gap && a.hole[c] >= a.r_hole && fdist(s0) >= a.r_via && fdist(s1) >= a.r_via && a.padd[s0] >= a.r_vpad && a.padd[s1] >= a.r_vpad {
let ns = c * 2 + 1 - l;
let ng = gcur + vc;
let q = &mut self.node[ns];
if !(q.stamp == call && (q.closed || q.g <= ng)) {
*q = Node { g: ng, par: s as i32, stamp: call, dir: 255, closed: false, since: 0 };
self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(x, y, a.hx, a.hy) }, ns as i32);
}
}
}
}
if std::env::var("ROUTER_TRACE").is_ok() {
eprintln!("EXP {} {}", expanded, found >= 0);
}
if found < 0 {
return None;
}
let (mut out, mut neck) = (Vec::new(), Vec::new());
let mut s = found as i32;
while s >= 0 && out.len() < 400_000 {
let su = s as usize;
// the same test the search used to enter the cell: a full-width track that
// barely fits must not be drawn necked all along its run
let dd = self.node[su].dir;
let odd = dd != 255 && dd & 1 == 1;
neck.push((fdist(su) < a.r_nom + if odd { a.r_diag } else { 0.0 }) as u8);
out.push(s);
s = self.node[su].par;
}
Some((out, neck))
}
}
|