aboutsummaryrefslogtreecommitdiff
path: root/tools/placer/src/model.rs
blob: c8e978b69adc1c39d181c3ee0a7b650ed6ddd05e (plain) (blame)
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! The placement problem: parts, pads, nets from export.py's JSON, plus the sidecar config
//! (placement.toml) and what can be inferred from the netlist (decoupling caps, pin normals,
//! fine-pitch fan-out bands, fixed parts).
//!
//! Labels beyond the netlist: `[[link]]` keeps two pads within a distance (a net tie on a
//! Kelvin pad), `[[pull]]` draws the pads of interface nets towards a board side (where the
//! host connects), `[[replicate]]` makes repeated channels copies of the first one at a fixed
//! pitch (followers move with their master and are never moved on their own).

use crate::geom::{poly_rects, Pt, Rect};
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use std::collections::HashMap;

// ---------- export.py JSON ----------

#[derive(Deserialize)]
struct JPad {
    num: String,
    net: String,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    tht: bool,
}

#[derive(Deserialize)]
struct JPart {
    #[serde(rename = "ref")]
    reference: String,
    value: String,
    fpid: String,
    x: f64,
    y: f64,
    rot: f64,
    locked: bool,
    board_only: bool,
    fields: HashMap<String, String>,
    court: Vec<Vec<[f64; 2]>>,
    pads: Vec<JPad>,
}

#[derive(Deserialize)]
struct JKeepout {
    poly: Vec<[f64; 2]>,
    footprints: bool,
    pads: bool,
    #[serde(default)]
    tracks: bool,
}

#[derive(Deserialize)]
struct JClass {
    track: f64,
    clearance: f64,
}

#[derive(Deserialize)]
struct JProblem {
    bounds: [f64; 4],
    parts: Vec<JPart>,
    netclass: HashMap<String, String>,
    #[serde(default)]
    classes: HashMap<String, JClass>,
    fill: Vec<String>,
    keepouts: Vec<JKeepout>,
}

// ---------- placement.toml ----------

/// Cost weights. Lengths are in mm, areas in mm^2.
#[derive(Deserialize, Clone, Debug)]
#[serde(default, deny_unknown_fields)]
pub struct Weights {
    /// per mm of ratsnest (MST) length, times the net weight
    pub length: f64,
    /// per crossing of two ratsnest lines, times the mean weight of both nets
    pub crossing: f64,
    /// per line that leaves a pin backwards, times the detour (part size); not scaled by net weight
    pub escape: f64,
    /// per ratsnest line over another net's pad, times the net weight
    pub block: f64,
    /// per mm from a decoupling cap to its pin (ground pad counts half)
    pub decap: f64,
    /// beyond the decap limit (3 mm, 8 mm for bulk caps): per mm^2 for the first 2 mm, then 4 per mm
    pub decap_limit: f64,
    /// per mm that a decoupled IC pin is farther than 3 mm from its nearest cap
    pub cover: f64,
    /// per mm^2 of courtyard overlap, outside the board, in a keep-out or outside a group bbox
    pub overlap: f64,
    /// per mm^2 of another part's pad in a fine-pitch IC's fan-out band
    pub band: f64,
    /// fan-out band width in front of fine-pitch pin rows (mm)
    pub fanout: f64,
    /// copper-to-edge clearance for pads (mm)
    pub edge: f64,
    /// [[link]] past its distance: per mm^2 for the first 2 mm, then 4 per mm (times its weight)
    pub link: f64,
    /// [[pull]]: per mm from a pad to its side of the part's group bbox, else of the board
    /// (times its weight)
    pub pull: f64,
}

impl Default for Weights {
    fn default() -> Self {
        Weights {
            length: 1.0,
            crossing: 4.0,
            escape: 3.0,
            block: 3.0,
            decap: 3.0,
            decap_limit: 20.0,
            cover: 4.0,
            overlap: 100.0,
            band: 40.0,
            fanout: 1.0,
            edge: 0.5,
            link: 20.0,
            pull: 1.0,
        }
    }
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct CNet {
    #[serde(rename = "match")]
    pattern: String,
    weight: f64,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct CGroup {
    name: String,
    #[serde(default)]
    parts: Vec<String>,
    bbox: Option<[f64; 4]>,
}

#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct CAttach {
    part: String,
    /// "U2.21"
    pin: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CLink {
    /// "NT1.2"
    a: String,
    b: String,
    /// pad centre distance (mm) allowed without cost
    max: f64,
    #[serde(default = "one")]
    weight: f64,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CPull {
    /// net name globs
    nets: Vec<String>,
    /// "N", "S", "E" or "W"
    side: String,
    #[serde(default = "one")]
    weight: f64,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CReplicate {
    /// channels, each a list of parts; channel k's part i follows channel 0's part i
    parts: Vec<Vec<String>>,
    /// offset (mm) from one channel to the next, in board axes
    pitch: [f64; 2],
}

fn one() -> f64 {
    1.0
}

#[derive(Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
struct Config {
    fixed: Vec<String>,
    /// net-class name -> weight; classes not listed weigh 1
    class: HashMap<String, f64>,
    net: Vec<CNet>,
    group: Vec<CGroup>,
    attach: Vec<CAttach>,
    link: Vec<CLink>,
    pull: Vec<CPull>,
    replicate: Vec<CReplicate>,
    weights: Weights,
}

// ---------- model ----------

pub struct Pad {
    pub part: usize,
    pub num: String,
    /// None for unconnected pads and fill nets
    pub net: Option<usize>,
    pub fill: bool,
    pub local: Pt,
    pub half: Pt,
    /// outward direction a track leaves the pin in, footprint-local
    pub normal: Option<Pt>,
    /// through-hole (blocks both layers)
    pub tht: bool,
}

pub struct Part {
    pub reference: String,
    pub fpid: String,
    pub fixed: bool,
    pub at0: Pt,
    pub rot0: u8,
    pub pads: Vec<usize>,
    pub court: Vec<Rect>,
    /// bounding box of the courtyard (local)
    pub hull: Rect,
    /// fine-pitch ICs: pad envelope grown by the fan-out width (local)
    pub band: Option<Rect>,
    /// detour length when a line leaves a pin backwards
    pub detour: f64,
    /// non-fill nets on this part
    pub nets: Vec<usize>,
    /// all groups this part belongs to, innermost first
    pub groups: Vec<usize>,
    /// links this part has a pad in
    pub links: Vec<usize>,
    /// [[pull]] pads: (pad, outward unit vector of the side, weight)
    pub pulls: Vec<(usize, Pt, f64)>,
    /// replicated channel: (master part, offset from it); moves only with the master
    pub follow: Option<(usize, Pt)>,
    /// parts that follow this one
    pub followers: Vec<usize>,
}

pub struct Link {
    pub a: usize,
    pub b: usize,
    pub max: f64,
    pub weight: f64,
}

pub struct Decap {
    pub part: usize,
    pub sig: usize,
    pub gnd: usize,
    pub bulk: bool,
    /// candidate pins (pad) with the ground pins of the same part
    pub cands: Vec<(usize, Vec<usize>)>,
}

pub struct Net {
    pub name: String,
    pub pads: Vec<usize>,
    pub weight: f64,
    /// track width + clearance of the net's class (mm): the room one track takes
    pub pitch: f64,
    pub decaps: Vec<usize>,
    /// IC pins that need a cap within 3 mm
    pub cover: Vec<usize>,
}

pub struct Group {
    pub name: String,
    pub bbox: Option<Rect>,
    /// movable members, including those of subgroups
    pub parts: Vec<usize>,
}

pub struct Model {
    pub parts: Vec<Part>,
    pub pads: Vec<Pad>,
    pub nets: Vec<Net>,
    pub decaps: Vec<Decap>,
    pub groups: Vec<Group>,
    pub links: Vec<Link>,
    pub bounds: Rect,
    /// rule areas no courtyard may enter
    pub keepouts: Vec<Rect>,
    /// rule areas no pad may enter
    pub pad_keepouts: Vec<Rect>,
    /// rule areas no track may enter
    pub track_keepouts: Vec<Rect>,
    pub w: Weights,
    pub movable: Vec<usize>,
}

const COURT_MARGIN: f64 = 0.03;

fn glob(pat: &str, s: &str) -> bool {
    // '*' only
    let parts: Vec<&str> = pat.split('*').collect();
    if parts.len() == 1 {
        return pat == s;
    }
    let mut rest = s;
    for (i, p) in parts.iter().enumerate() {
        if i == 0 {
            if !rest.starts_with(p) {
                return false;
            }
            rest = &rest[p.len()..];
        } else if i == parts.len() - 1 {
            return rest.ends_with(p);
        } else if let Some(k) = rest.find(p) {
            rest = &rest[k + p.len()..];
        } else {
            return false;
        }
    }
    true
}

fn cap_uf(v: &str) -> f64 {
    let v = v.trim();
    let k = v.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(v.len());
    let n: f64 = v[..k].parse().unwrap_or(0.0);
    let f = match v[k..].chars().next() {
        Some('p') => 1e-6,
        Some('n') => 1e-3,
        Some('u') | Some('µ') => 1.0,
        Some('m') => 1e3,
        _ => 1.0,
    };
    n * f
}

fn is_ic(reference: &str, npads: usize) -> bool {
    npads >= 4 && !reference.starts_with(['J', 'P']) && !reference.starts_with("TP")
}

/// Outward direction of each pad: 2-pad parts along their axis, ICs and connectors from the
/// side of the pad envelope the pad sits on (pads elongated along it decide first); centre
/// pads (exposed pads, module ground pads) and THT pads have none.
fn normals(pads: &[JPad]) -> Vec<Option<Pt>> {
    let smd: Vec<&JPad> = pads.iter().filter(|p| !p.tht).collect();
    if smd.len() == 2 && pads.len() == 2 {
        let c = ((smd[0].x + smd[1].x) / 2.0, (smd[0].y + smd[1].y) / 2.0);
        return pads
            .iter()
            .map(|p| {
                let (dx, dy) = (p.x - c.0, p.y - c.1);
                let l = (dx * dx + dy * dy).sqrt();
                (l > 1e-6).then(|| (dx / l, dy / l))
            })
            .collect();
    }
    if smd.len() < 3 {
        return pads.iter().map(|_| None).collect();
    }
    let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
    for p in &smd {
        x0 = x0.min(p.x);
        y0 = y0.min(p.y);
        x1 = x1.max(p.x);
        y1 = y1.max(p.y);
    }
    let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
    pads.iter()
        .map(|p| {
            if p.tht {
                return None;
            }
            let d = [p.x - x0, x1 - p.x, p.y - y0, y1 - p.y];
            let m = d.iter().cloned().fold(f64::MAX, f64::min);
            if m > 0.3 {
                return None; // not on the perimeter
            }
            if p.w > 1.3 * p.h {
                return Some((if p.x < cx { -1.0 } else { 1.0 }, 0.0));
            }
            if p.h > 1.3 * p.w {
                return Some((0.0, if p.y < cy { -1.0 } else { 1.0 }));
            }
            let dirs = [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0)];
            let (mut nx, mut ny) = (0.0, 0.0);
            for (k, dir) in dirs.iter().enumerate() {
                if d[k] < m + 0.2 {
                    nx += dir.0;
                    ny += dir.1;
                }
            }
            let l = ((nx * nx + ny * ny) as f64).sqrt();
            (l > 1e-6).then(|| (nx / l, ny / l))
        })
        .collect()
}

fn rot_steps(deg: f64) -> u8 {
    (((deg / 90.0).round() as i64).rem_euclid(4)) as u8
}

impl Model {
    pub fn load(problem: &str, config: &str) -> Result<Model> {
        let jp: JProblem = serde_json::from_str(&std::fs::read_to_string(problem).with_context(|| problem.to_string())?)?;
        let cfg: Config = toml::from_str(&std::fs::read_to_string(config).with_context(|| config.to_string())?)
            .with_context(|| format!("parsing {config}"))?;
        let w = cfg.weights.clone();
        let fillset: std::collections::HashSet<&str> = jp.fill.iter().map(|s| s.as_str()).collect();
        let is_fill = |n: &str| {
            fillset.contains(n) || {
                let base = n.rsplit('/').next().unwrap_or(n);
                matches!(base, "GND" | "GNDA" | "GNDD" | "AGND" | "DGND" | "VSS" | "PGND")
            }
        };

        // nets
        let mut netid: HashMap<String, usize> = HashMap::new();
        let mut nets: Vec<Net> = Vec::new();
        let mut names: Vec<&String> = jp.netclass.keys().collect();
        names.sort();
        for n in names {
            if is_fill(n) {
                continue;
            }
            let cls = &jp.netclass[n];
            let mut weight = *cfg.class.get(cls).unwrap_or(&1.0);
            for o in &cfg.net {
                if glob(&o.pattern, n) {
                    weight = o.weight;
                }
            }
            let pitch = jp.classes.get(cls).map(|c| c.track + c.clearance).unwrap_or(0.4);
            netid.insert(n.clone(), nets.len());
            nets.push(Net { name: n.clone(), pads: vec![], weight, pitch, decaps: vec![], cover: vec![] });
        }

        // parts and pads
        let mut parts = Vec::new();
        let mut pads = Vec::new();
        let fixed_cfg: std::collections::HashSet<&str> = cfg.fixed.iter().map(|s| s.as_str()).collect();
        for (pi, p) in jp.parts.iter().enumerate() {
            // grown by a bit more than half the courtyard line: KiCad's DRC flags courtyards
            // that touch, so parts must keep at least one grid step apart
            let mut court: Vec<Rect> = p.court.iter().flat_map(|poly| poly_rects(poly)).map(|r| r.grow(COURT_MARGIN)).collect();
            if court.is_empty() {
                for q in &p.pads {
                    court.push(Rect::around((q.x, q.y), q.w / 2.0 + 0.25, q.h / 2.0 + 0.25));
                }
            }
            let hull = court.iter().skip(1).fold(court[0], |a, r| a.union(r));
            let field_fixed = p.fields.get("Place_Fixed").map(|v| !v.is_empty() && v != "0" && v != "no").unwrap_or(false);
            let hole = p.fpid.contains("MountingHole") || p.fpid.contains("DIN_Post") || p.fpid.contains("DIN_Housing");
            let fixed = p.locked || p.board_only || hole || field_fixed || fixed_cfg.contains(p.reference.as_str());
            let ns = normals(&p.pads);
            let mut ids = vec![];
            for (q, n) in p.pads.iter().zip(ns) {
                let net = netid.get(&q.net).copied();
                if let Some(k) = net {
                    nets[k].pads.push(pads.len());
                }
                ids.push(pads.len());
                pads.push(Pad {
                    part: pi,
                    num: q.num.clone(),
                    net,
                    fill: is_fill(&q.net),
                    local: (q.x, q.y),
                    half: (q.w / 2.0, q.h / 2.0),
                    normal: n,
                    tht: q.tht,
                });
            }
            // fine-pitch: >= 8 SMD pads with neighbours closer than 0.7 mm
            let smd: Vec<&JPad> = p.pads.iter().filter(|q| !q.tht).collect();
            let pitch = smd
                .iter()
                .enumerate()
                .flat_map(|(i, a)| smd[i + 1..].iter().map(move |b| ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt()))
                .fold(f64::MAX, f64::min);
            let band = (smd.len() >= 8 && pitch < 0.7).then(|| {
                smd.iter()
                    .map(|q| Rect::around((q.x, q.y), q.w / 2.0, q.h / 2.0))
                    .reduce(|a, b| a.union(&b))
                    .unwrap()
                    .grow(w.fanout)
            });
            let mut pn: Vec<usize> = ids.iter().filter_map(|&k| pads[k].net).collect();
            pn.sort();
            pn.dedup();
            parts.push(Part {
                reference: p.reference.clone(),
                fpid: p.fpid.clone(),
                fixed,
                at0: (p.x, p.y),
                rot0: rot_steps(p.rot),
                pads: ids,
                court,
                hull,
                band,
                detour: ((hull.x1 - hull.x0) + (hull.y1 - hull.y0)) / 2.0,
                nets: pn,
                groups: vec![],
                links: vec![],
                pulls: vec![],
                follow: None,
                followers: vec![],
            });
        }
        let pref: HashMap<String, usize> = parts.iter().enumerate().map(|(i, p)| (p.reference.clone(), i)).collect();

        // decoupling caps: C with one pad on a fill net, the other on a net with IC pins
        let mut decaps = Vec::new();
        let xtal_nets: std::collections::HashSet<usize> = parts
            .iter()
            .filter(|p| p.reference.starts_with('Y'))
            .flat_map(|p| p.nets.clone())
            .collect();
        let attach: HashMap<&str, &str> = cfg.attach.iter().map(|a| (a.part.as_str(), a.pin.as_str())).collect();
        for (pi, (p, jpart)) in parts.iter().zip(&jp.parts).enumerate() {
            if !p.reference.starts_with('C') || p.pads.len() != 2 {
                continue;
            }
            let (a, b) = (p.pads[0], p.pads[1]);
            let (sig, gnd) = match (pads[a].fill, pads[b].fill) {
                (false, true) => (a, b),
                (true, false) => (b, a),
                _ => continue,
            };
            let Some(net) = pads[sig].net else { continue };
            let bulk = cap_uf(&jpart.value) >= 4.7;
            let mut cands = vec![];
            if let Some(pin) = attach.get(p.reference.as_str()) {
                let (r, num) = pin.split_once('.').context("attach pin must be REF.PIN")?;
                let Some(&ic) = pref.get(r) else { bail!("attach {}: no part {r}", p.reference) };
                let Some(&k) = parts[ic].pads.iter().find(|&&k| pads[k].num == num) else {
                    bail!("attach {}: no pin {pin}", p.reference)
                };
                cands.push(k);
            } else {
                for &k in &nets[net].pads {
                    let q = &parts[pads[k].part];
                    let ok = is_ic(&q.reference, q.pads.len()) || (bulk && q.reference.starts_with(['L', 'F']));
                    if pads[k].part != pi && ok {
                        cands.push(k);
                    }
                }
            }
            if cands.is_empty() {
                continue;
            }
            let cands = cands
                .into_iter()
                .map(|k| {
                    let g = parts[pads[k].part].pads.iter().copied().filter(|&j| pads[j].fill).collect();
                    (k, g)
                })
                .collect();
            nets[net].decaps.push(decaps.len());
            decaps.push(Decap { part: pi, sig, gnd, bulk, cands });
        }
        // IC pins on nets with a small cap need a cap within 3 mm (crystal nets excluded)
        for (ni, net) in nets.iter_mut().enumerate() {
            if xtal_nets.contains(&ni) || !net.decaps.iter().any(|&d| !decaps[d].bulk) {
                continue;
            }
            net.cover = net
                .pads
                .iter()
                .copied()
                .filter(|&k| {
                    let q = &parts[pads[k].part];
                    is_ic(&q.reference, q.pads.len()) && !q.reference.starts_with(['Y', 'L', 'F'])
                })
                .collect();
        }

        // links, pulls and replicated channels
        let pad_of = |parts: &[Part], s: &str, what: &str| -> Result<usize> {
            let (r, num) = s.split_once('.').with_context(|| format!("{what} {s}: write REF.PIN"))?;
            let Some(&pi) = pref.get(r) else { bail!("{what} {s}: no part {r}") };
            parts[pi].pads.iter().copied().find(|&k| pads[k].num == num).with_context(|| format!("{what} {s}: no pin {num}"))
        };
        let mut links = Vec::new();
        for l in &cfg.link {
            let (a, b) = (pad_of(&parts, &l.a, "link")?, pad_of(&parts, &l.b, "link")?);
            for k in [a, b] {
                let pi = pads[k].part;
                if !parts[pi].links.contains(&links.len()) {
                    parts[pi].links.push(links.len());
                }
            }
            links.push(Link { a, b, max: l.max, weight: l.weight });
        }
        for pl in &cfg.pull {
            let dir = match pl.side.as_str() {
                "N" => (0.0, -1.0),
                "S" => (0.0, 1.0),
                "W" => (-1.0, 0.0),
                "E" => (1.0, 0.0),
                o => bail!("pull: side {o:?} is not N, S, E or W"),
            };
            for (pi, jpart) in jp.parts.iter().enumerate() {
                for (q, &k) in jpart.pads.iter().zip(&parts[pi].pads.clone()) {
                    if pl.nets.iter().any(|g| glob(g, &q.net)) {
                        parts[pi].pulls.push((k, dir, pl.weight));
                    }
                }
            }
        }
        for rp in &cfg.replicate {
            let Some(first) = rp.parts.first() else { continue };
            for (c, chan) in rp.parts.iter().enumerate().skip(1) {
                if chan.len() != first.len() {
                    bail!("replicate: channel {c} has {} parts, channel 0 has {}", chan.len(), first.len());
                }
                for (r0, r) in first.iter().zip(chan) {
                    let (Some(&m0), Some(&f)) = (pref.get(r0.as_str()), pref.get(r.as_str())) else { bail!("replicate: no part {r0} or {r}") };
                    if parts[m0].fpid != parts[f].fpid {
                        bail!("replicate: {r} ({}) is not the footprint of {r0} ({})", parts[f].fpid, parts[m0].fpid);
                    }
                    if parts[m0].fixed || parts[f].fixed {
                        bail!("replicate: {r0} and {r} must both be movable");
                    }
                    parts[f].follow = Some((m0, (rp.pitch[0] * c as f64, rp.pitch[1] * c as f64)));
                    parts[m0].followers.push(f);
                }
            }
        }

        // groups: from the config and from Place_Group fields ("eth/xtal" is a subgroup of "eth")
        let mut groups: Vec<Group> = Vec::new();
        let mut gid: HashMap<String, usize> = HashMap::new();
        let mut member: Vec<(usize, String)> = vec![];
        for (pi, p) in jp.parts.iter().enumerate() {
            if let Some(g) = p.fields.get("Place_Group").filter(|g| !g.is_empty()) {
                member.push((pi, g.clone()));
            }
        }
        for g in &cfg.group {
            gid.insert(g.name.clone(), groups.len());
            groups.push(Group { name: g.name.clone(), bbox: g.bbox.map(|b| Rect::new(b[0], b[1], b[2], b[3])), parts: vec![] });
            for r in &g.parts {
                let Some(&pi) = pref.get(r.as_str()) else { bail!("group {}: no part {r}", g.name) };
                member.retain(|(q, _)| *q != pi); // the config overrides the field
                member.push((pi, g.name.clone()));
            }
        }
        for (pi, g) in member {
            // the group and every parent group
            let segs: Vec<&str> = g.split('/').collect();
            for k in (1..=segs.len()).rev() {
                let name = segs[..k].join("/");
                let id = *gid.entry(name.clone()).or_insert_with(|| {
                    groups.push(Group { name: name.clone(), bbox: None, parts: vec![] });
                    groups.len() - 1
                });
                if !parts[pi].fixed && parts[pi].follow.is_none() && !groups[id].parts.contains(&pi) {
                    groups[id].parts.push(pi);
                }
                if !parts[pi].groups.contains(&id) {
                    parts[pi].groups.push(id);
                }
            }
        }

        let keepouts = jp.keepouts.iter().filter(|k| k.footprints).flat_map(|k| poly_rects(&k.poly)).collect();
        let pad_keepouts = jp.keepouts.iter().filter(|k| k.pads).flat_map(|k| poly_rects(&k.poly)).collect();
        let track_keepouts = jp.keepouts.iter().filter(|k| k.tracks).flat_map(|k| poly_rects(&k.poly)).collect();
        let movable = (0..parts.len()).filter(|&i| !parts[i].fixed && parts[i].follow.is_none()).collect();
        let b = jp.bounds;
        Ok(Model {
            parts,
            pads,
            nets,
            decaps,
            groups,
            links,
            bounds: Rect::new(b[0], b[1], b[2], b[3]),
            keepouts,
            pad_keepouts,
            track_keepouts,
            w,
            movable,
        })
    }

    /// Put every follower at its master's pose plus its offset.
    pub fn sync(&self, at: &mut [Pt], rot: &mut [u8]) {
        for (i, p) in self.parts.iter().enumerate() {
            if let Some((m0, off)) = p.follow {
                at[i] = (at[m0].0 + off.0, at[m0].1 + off.1);
                rot[i] = rot[m0];
            }
        }
    }

    pub fn part(&self, r: &str) -> Option<usize> {
        self.parts.iter().position(|p| p.reference == r)
    }
}