aboutsummaryrefslogtreecommitdiff
path: root/tools/router/src/main.rs
blob: 85802ce8eee6bda5d4d6444296438d2de97d6455 (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
//! router: grid maze router for 2-layer KiCad boards.
//!
//!   router route BOARD.json ROUTE.toml OUT.json [--fixed NAME=FILE]... [--stop LABEL]
//!   router place BOARD.json PLACEMENT.json OUT.json
//!
//! `place` writes BOARD.json with the footprints moved to a placer result (ref -> [x, y, rot]),
//! so a placement can be routed without KiCad; existing tracks and vias are left as they are.
//! BOARD.json comes from tools/router/dump_board.py, OUT.json goes to
//! tools/router/write_board.py. `--stop` ends after the step with that label (to look at
//! partial results). Prints one summary line:
//! "RESULT split=<nets in pieces> failed=<connections; a poured plane net's failed drops count
//! only through islands> islands=<plane pad groups apart>
//! vias=<n> length=<mm> bcu=<mm> neck=<mm narrower than the net width> score=<[rank]> time=<s>".

use anyhow::{bail, Context, Result};
use router::config::Config;
use router::io::BoardJson;
use router::placement;
use router::run::Run;
use std::collections::HashMap;
use std::path::Path;
use std::time::Instant;

fn main() -> Result<()> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.len() == 4 && args[0] == "place" {
        let mut d = BoardJson::load(&args[1])?;
        placement::apply(&mut d, &placement::load(&args[2])?)?;
        std::fs::write(&args[3], serde_json::to_string(&d)?).with_context(|| args[3].to_string())?;
        return Ok(());
    }
    if args.len() < 4 || args[0] != "route" {
        bail!("usage: router route BOARD.json ROUTE.toml OUT.json [--fixed NAME=FILE]... [--stop LABEL]\n       router place BOARD.json PLACEMENT.json OUT.json");
    }
    let t0 = Instant::now();
    let (board, toml, out) = (&args[1], &args[2], &args[3]);
    let mut fixed = HashMap::new();
    let mut stop = None;
    let mut k = 4;
    while k < args.len() {
        match args[k].as_str() {
            "--fixed" => {
                let (n, f) = args.get(k + 1).and_then(|a| a.split_once('=')).context("--fixed NAME=FILE")?;
                fixed.insert(n.to_string(), f.to_string());
                k += 2;
            }
            "--stop" => {
                stop = Some(args.get(k + 1).context("--stop LABEL")?.clone());
                k += 2;
            }
            a => bail!("unknown argument {a}"),
        }
    }
    let d = BoardJson::load(board)?;
    let cfg = Config::load(toml)?;
    let base = Path::new(toml).parent().unwrap_or(Path::new("."));
    let mut run = Run::new(&d, &cfg, base, &fixed, true)?;
    let t_setup = t0.elapsed().as_secs_f64();
    for s in &cfg.step {
        let t = Instant::now();
        run.step(&cfg, s)?;
        if std::env::var("ROUTER_TIMES").is_ok() {
            eprintln!("{:>7.3} s  {} {}", t.elapsed().as_secs_f64(), s.kind, s.nets.as_ref().map(|n| n.join(",")).or(s.net.clone()).unwrap_or_default());
        }
        if stop.is_some() && s.label == stop {
            println!("stopped after {}", s.label.as_deref().unwrap_or(""));
            break;
        }
    }
    let sum = run.summary(&cfg, t0.elapsed().as_secs_f64());
    let r = &run.r;
    let incomplete: Vec<_> = r
        .log
        .iter()
        .filter(|l| {
            let a = l.as_array().unwrap();
            (a.len() > 4 && a[1] == "pads" && a[4].as_i64() > Some(0)) || (a.len() > 2 && a[1] == "components" && a[2].as_i64() > Some(1))
        })
        .collect();
    println!("incomplete: {incomplete:?}");
    println!("failed: {:?}", r.failed);
    let res = r.result();
    std::fs::write(out, serde_json::to_string(&res)?).with_context(|| out.to_string())?;
    let len = |l: Option<&str>| -> f64 { res.segs.iter().filter(|s| l.is_none_or(|l| s.layer == l)).map(|s| (s.x2 - s.x1).hypot(s.y2 - s.y1)).sum() };
    let split = r.split_nets(&r.plane_nets);
    println!(
        "segs {} vias {} B.Cu {:.1} mm, setup {:.2} s, total {:.2} s",
        res.segs.len(),
        res.vias.len(),
        len(Some("B.Cu")),
        t_setup,
        t0.elapsed().as_secs_f64()
    );
    println!(
        "RESULT split={} failed={} islands={} vias={} length={:.1} bcu={:.1} neck={:.1} score={:.1} time={:.1}",
        split.len(),
        sum.failed,
        sum.islands,
        res.vias.len(),
        len(None),
        len(Some("B.Cu")),
        sum.neck,
        sum.score,
        t0.elapsed().as_secs_f64()
    );
    Ok(())
}