by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
main
Colby Knox
update_footprints_from_library (KiCad's verb, plan then apply); one Altium document per file whatever the path spelling
04d4256
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
//! update_footprints_from_library: compare each placed footprint with its library's current one (pads by number:
//! added, removed, moved, resized, reshaped, redrilled, relayered; 3D bodies) and, with apply:true, put the library's
//! footprint in place of each one that differs, keeping where the part sits, its designator and comment, its pad nets
//! and its schematic link. KiCad's verb of the same name, the same arguments and the same answer.
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }
fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }
/// The PcbLibs a project lists, as full paths. Pure apart from reading the project file.
fn project_libraries(board: &Path) -> Vec<PathBuf> {
let dir = board.parent().unwrap_or(Path::new("."));
let mut out = Vec::new();
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let p = e.path();
if !p.extension().map(|x| x.eq_ignore_ascii_case("PrjPcb")).unwrap_or(false) { continue; }
let text = std::fs::read_to_string(&p).unwrap_or_default();
let name = board.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
if !text.to_lowercase().contains(&name) { continue; }
for l in text.lines() {
if let Some(d) = l.trim().strip_prefix("DocumentPath=") {
if d.to_lowercase().ends_with(".pcblib") { out.push(dir.join(d.replace('\\', "/"))); }
}
}
}
out
}
/// One pad as the comparison sees it: number, position in the footprint's frame, size, rotation, drill, shape, side.
#[derive(Debug, Clone)]
pub struct P { pub num: String, pub x: f64, pub y: f64, pub w: f64, pub h: f64, pub rot: f64, pub drill: f64, pub shape: String, pub smd: bool }
/// A placed part's pads in its footprint's own frame, for each way the part might be turned and mirrored: rotation
/// undone, and for a bottom part the mirror undone in x or in y (the comparison keeps whichever fits). Pure.
pub fn placed_frames(comp: &Value, pads: &[&Value]) -> Vec<Vec<P>> {
let (cx, cy, rot) = (f(&comp["x"]), f(&comp["y"]), f(&comp["rotation"]));
let bottom = comp["side"] == "bottom";
let mirrors: &[(f64, f64, f64)] = if bottom { &[(-1.0, 1.0, 1.0), (1.0, -1.0, 1.0), (-1.0, 1.0, -1.0), (1.0, -1.0, -1.0)] } else { &[(1.0, 1.0, 1.0)] };
mirrors.iter().map(|(mx, my, sense)| {
let a = (-rot * sense).to_radians();
let (c, s) = (a.cos(), a.sin());
pads.iter().map(|p| {
let (dx, dy) = (f(&p["x"]) - cx, f(&p["y"]) - cy);
let (lx, ly) = (dx * c - dy * s, dx * s + dy * c);
P { num: p["name"].as_str().unwrap_or("").to_string(), x: lx * mx, y: ly * my, w: f(&p["sizeX"]), h: f(&p["sizeY"]),
rot: (f(&p["rotation"]) - rot * sense).rem_euclid(180.0), drill: f(&p["drill"]), shape: p["shape"].as_str().unwrap_or("").to_string(),
smd: f(&p["drill"]) == 0.0 }
}).collect()
}).collect()
}
/// The library footprint's pads (read_footprint's pads). Pure.
pub fn library_pads(fp: &Value) -> Vec<P> {
fp["pads"].as_array().cloned().unwrap_or_default().iter().map(|p| P {
num: p["number"].as_str().map(String::from).unwrap_or_else(|| p["number"].to_string()), x: f(&p["at"][0]), y: f(&p["at"][1]),
w: f(&p["sizeMm"][0]), h: f(&p["sizeMm"][1]), rot: f(&p["rotation"]).rem_euclid(180.0), drill: f(&p["drillMm"]),
shape: p["shape"].as_str().unwrap_or("").to_string(), smd: p["type"] == "smd",
}).collect()
}
/// What differs between a placed footprint (in one of its frames) and the library's: pads added and removed by number,
/// and per pad what changed. Tolerance 0.002 mm and 0.1 degree. Pure.
pub fn diff(placed: &[P], lib: &[P]) -> (Vec<String>, Vec<String>, Vec<Value>) {
let near = |a: f64, b: f64, t: f64| (a - b).abs() <= t;
let mut added: Vec<String> = lib.iter().filter(|l| !placed.iter().any(|p| p.num == l.num)).map(|l| l.num.clone()).collect();
let mut removed: Vec<String> = placed.iter().filter(|p| !lib.iter().any(|l| l.num == p.num)).map(|p| p.num.clone()).collect();
added.sort(); added.dedup(); removed.sort(); removed.dedup();
let mut changed = Vec::new();
let mut used = vec![false; lib.len()];
for p in placed {
// a number can be on several pads (a thermal pad's vias): match each placed pad to the nearest unused one
let Some(i) = (0..lib.len()).filter(|i| !used[*i] && lib[*i].num == p.num)
.min_by(|a, b| ((lib[*a].x - p.x).hypot(lib[*a].y - p.y)).partial_cmp(&(lib[*b].x - p.x).hypot(lib[*b].y - p.y)).unwrap()) else { continue };
used[i] = true;
let l = &lib[i];
let mut what = Vec::new();
if !near(p.x, l.x, 0.002) || !near(p.y, l.y, 0.002) { what.push(format!("moved from ({}, {}) to ({}, {})", r3(p.x), r3(p.y), r3(l.x), r3(l.y))); }
// a pad turned a quarter is the same copper with its sizes swapped
let quarter = (((p.rot - l.rot).rem_euclid(180.0)) - 90.0).abs() < 0.1;
let (lw, lh) = if quarter { (l.h, l.w) } else { (l.w, l.h) };
if !near(p.w, lw, 0.002) || !near(p.h, lh, 0.002) { what.push(format!("size {} x {} to {} x {}", r3(p.w), r3(p.h), r3(l.w), r3(l.h))); }
if !near(p.drill, l.drill, 0.002) { what.push(format!("drill {} to {}", r3(p.drill), r3(l.drill))); }
if p.smd != l.smd { what.push(if l.smd { "through-hole to surface".into() } else { "surface to through-hole".into() }); }
if !p.shape.is_empty() && !l.shape.is_empty() && p.shape != l.shape && !(p.shape.contains("rect") && l.shape.contains("rect") && p.shape != "roundrect" && l.shape != "roundrect") {
what.push(format!("shape {} to {}", p.shape, l.shape));
}
if !what.is_empty() { changed.push(json!({"pad": p.num, "changes": what})); }
}
(added, removed, changed)
}
/// The best fit over a part's frames: the one with the fewest differences.
pub fn best_diff(frames: &[Vec<P>], lib: &[P]) -> (Vec<String>, Vec<String>, Vec<Value>) {
frames.iter().map(|fr| diff(fr, lib)).min_by_key(|(a, r, c)| a.len() + r.len() + c.len()).unwrap_or_default()
}
/// altium_update_footprints_from_library {filePath, refs?, apply?, libraryPath? | libraries?}
pub fn update_footprints_from_library(args: &Value) -> Value {
if let Some(g) = crate::support::need_licensed() { return g; }
let Some(board) = crate::support::s(args, "filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) else {
return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .PcbDoc) is required"});
};
if let Some(e) = crate::support::must_open(&board, 60) { return e; }
let st = crate::routing::routing_state(&json!({}));
if st.get("success").and_then(|v| v.as_bool()) != Some(true) { return st; }
let revision = st["revision"].clone();
// the libraries: those named, else the project's
let mut libs: Vec<PathBuf> = args.get("libraries").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).map(PathBuf::from).collect()).unwrap_or_default();
if let Some(l) = crate::support::s(args, "libraryPath") { libs.push(PathBuf::from(l)); }
if libs.is_empty() { libs = project_libraries(Path::new(&board.replace('\\', "/"))); }
let refs: Vec<String> = args.get("refs").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.to_ascii_uppercase())).collect()).unwrap_or_default();
let comps: Vec<Value> = st["components"].as_array().cloned().unwrap_or_default().into_iter()
.filter(|c| refs.is_empty() || refs.contains(&c["ref"].as_str().unwrap_or("").to_ascii_uppercase())).collect();
if comps.is_empty() { return json!({"success": false, "errorCode": "no_such_part", "error": format!("none of {refs:?} is on the board")}); }
let all_pads: Vec<Value> = st["pads"].as_array().cloned().unwrap_or_default();
// each footprint read once from the library it is in (its source library first, by file name)
let mut cache: std::collections::HashMap<(String, String), Option<(PathBuf, Value)>> = std::collections::HashMap::new();
let mut misses: std::collections::HashMap<(String, String), String> = std::collections::HashMap::new();
let mut rows = Vec::new();
for c in &comps {
let r = c["ref"].as_str().unwrap_or("").to_string();
let pattern = c["pattern"].as_str().unwrap_or("").to_string();
let src = c["library"].as_str().unwrap_or("").to_lowercase();
let key = (pattern.to_lowercase(), src.clone());
if !cache.contains_key(&key) {
let mut order: Vec<&PathBuf> = libs.iter().filter(|l| l.file_name().map(|n| n.to_string_lossy().to_lowercase() == src).unwrap_or(false)).collect();
order.extend(libs.iter().filter(|l| l.file_name().map(|n| n.to_string_lossy().to_lowercase() != src).unwrap_or(true)));
let mut hit = None;
for l in order {
let fp = crate::project::read_footprint(&json!({"libraryPath": l.to_string_lossy().replace('\\', "/"), "name": pattern}));
if fp.get("success").and_then(|v| v.as_bool()) == Some(true) { hit = Some((l.clone(), fp)); break; }
misses.insert(key.clone(), format!("{}: {}", l.display(), fp.get("error").and_then(|e| e.as_str()).unwrap_or("not read")));
}
cache.insert(key.clone(), hit);
}
let Some((lib, fp)) = cache.get(&key).cloned().flatten() else {
rows.push(json!({"ref": r, "footprint": pattern, "status": "library_not_found",
"why": if libs.is_empty() { "no library given, and the board's project lists no .PcbLib".to_string() } else { format!("{pattern} is in none of {} libraries", libs.len()) },
"lastError": misses.get(&key)}));
continue;
};
let pads: Vec<&Value> = all_pads.iter().filter(|p| p["ref"].as_str() == Some(r.as_str())).collect();
let (added, removed, changed) = best_diff(&placed_frames(c, &pads), &library_pads(&fp));
let lib_bodies = fp["models"].as_array().map(|a| a.len()).unwrap_or(0) as i64;
let board_bodies = c["bodies"].as_i64().unwrap_or(0);
let bodies_differ = lib_bodies != board_bodies;
let differs = !added.is_empty() || !removed.is_empty() || !changed.is_empty() || bodies_differ;
let mut row = json!({"ref": r, "footprint": pattern, "library": lib.to_string_lossy(), "status": if differs { "differs" } else { "up_to_date" },
"padsCompared": {"board": pads.len(), "library": library_pads(&fp).len()}});
if differs {
row["diff"] = json!({"padsAdded": added, "padsRemoved": removed, "padsChanged": changed});
if bodies_differ { row["diff"]["bodies3d"] = json!({"board": board_bodies, "library": lib_bodies}); }
}
rows.push(row);
}
let differing: Vec<Value> = rows.iter().filter(|r| r["status"] == "differs").cloned().collect();
if args.get("apply").and_then(|v| v.as_bool()) != Some(true) || differing.is_empty() {
return json!({"success": true, "plan": true, "mutated": false, "footprints": rows, "differs": differing.len(), "revision": revision,
"_hint": if differing.is_empty() { "Every footprint matches its library." } else { "A plan: nothing changed. Read each diff (a pad new in the library gets no net; a removed pad's net goes with it), then call again with apply:true to replace the differing ones." }});
}
if let Some(rev) = args.get("expectedRevision").and_then(|v| v.as_str()) {
if revision.as_str() != Some(rev) { return json!({"success": false, "errorCode": "stale_board", "error": format!("the board changed since revision {rev}")}); }
}
// reading the libraries made them the current documents: the board comes back to the front first
if let Some(e) = crate::support::must_open(&board, 60) { return e; }
let mut done = Vec::new();
for row in &differing {
let a = crate::agent::call("replace_fp", &[("ref", row["ref"].as_str().unwrap_or("").to_string()), ("libraryPath", row["library"].as_str().unwrap_or("").replace('/', "\\")),
("footprint", row["footprint"].as_str().unwrap_or("").to_string())], None, std::time::Duration::from_secs(120));
let d = a.get("data").cloned().unwrap_or(Value::Null);
done.push(json!({"ref": row["ref"], "replaced": d["ok"] == json!(true), "netsKept": d["netsKept"], "netsBefore": d["netsBefore"], "error": d["error"]}));
}
// read back: every replaced part where it was, and now matching its library
let after = crate::routing::routing_state(&json!({}));
let mut problems = Vec::new();
for row in &differing {
let r = row["ref"].as_str().unwrap_or("");
let before = comps.iter().find(|c| c["ref"].as_str() == Some(r));
let now = after["components"].as_array().and_then(|a| a.iter().find(|c| c["ref"].as_str() == Some(r)).cloned());
match (before, now) {
(Some(b), Some(n)) => {
if (f(&b["x"]) - f(&n["x"])).abs() > 0.001 || (f(&b["y"]) - f(&n["y"])).abs() > 0.001 || b["side"] != n["side"]
|| ((f(&b["rotation"]) - f(&n["rotation"])).rem_euclid(360.0)).min((f(&n["rotation"]) - f(&b["rotation"])).rem_euclid(360.0)) > 0.01 {
problems.push(json!({"ref": r, "problem": "moved", "before": [b["x"], b["y"], b["rotation"], b["side"]], "after": [n["x"], n["y"], n["rotation"], n["side"]]}));
}
let pads: Vec<&Value> = after["pads"].as_array().map(|a| a.iter().filter(|p| p["ref"].as_str() == Some(r)).collect()).unwrap_or_default();
let key = (row["footprint"].as_str().unwrap_or("").to_lowercase(), b["library"].as_str().unwrap_or("").to_lowercase());
if let Some(Some((_, fp))) = cache.get(&key) {
let (ad, rm, ch) = best_diff(&placed_frames(&n, &pads), &library_pads(fp));
if !ad.is_empty() || !rm.is_empty() || !ch.is_empty() { problems.push(json!({"ref": r, "problem": "still differs", "padsAdded": ad, "padsRemoved": rm, "padsChanged": ch})); }
}
}
_ => problems.push(json!({"ref": r, "problem": "not on the board after the replace"})),
}
}
json!({"success": problems.is_empty() && done.iter().all(|d| d["replaced"] == json!(true)), "plan": false, "mutated": true, "footprints": rows, "replaced": done,
"problems": problems, "revision": after["revision"], "unconnected": after["unconnected"],
"_hint": "Each part was replaced by its library's footprint where it sat, with its designator, comment, nets (by pad number) and schematic link. Tracks were not moved to follow pads that moved: run altium_routing_drc. Save with altium_save."})
}
#[cfg(test)]
mod tests {
use super::*;
fn pad(r: &str, n: &str, x: f64, y: f64, w: f64, h: f64, rot: f64) -> Value {
json!({"ref": r, "name": n, "x": x, "y": y, "sizeX": w, "sizeY": h, "rotation": rot, "drill": 0.0, "shape": "rect"})
}
#[test]
fn a_turned_part_matches_its_library_and_a_changed_pad_is_named() {
// a two-pad part at (10, 20) turned 90: library pads at (-1, 0) and (1, 0), 0.6 x 0.5
let comp = json!({"ref": "R1", "x": 10.0, "y": 20.0, "rotation": 90.0, "side": "top"});
let p1 = pad("R1", "1", 10.0, 19.0, 0.6, 0.5, 90.0);
let p2 = pad("R1", "2", 10.0, 21.0, 0.6, 0.5, 90.0);
let lib = vec![P { num: "1".into(), x: -1.0, y: 0.0, w: 0.6, h: 0.5, rot: 0.0, drill: 0.0, shape: "rect".into(), smd: true },
P { num: "2".into(), x: 1.0, y: 0.0, w: 0.6, h: 0.5, rot: 0.0, drill: 0.0, shape: "rect".into(), smd: true }];
let (a, r, c) = best_diff(&placed_frames(&comp, &[&p1, &p2]), &lib);
assert!(a.is_empty() && r.is_empty() && c.is_empty(), "{a:?} {r:?} {c:?}");
let mut lib2 = lib.clone();
lib2[1].w = 0.8;
lib2.push(P { num: "3".into(), x: 0.0, y: 1.0, w: 0.3, h: 0.3, rot: 0.0, drill: 0.0, shape: "rect".into(), smd: true });
let (a, _, c) = best_diff(&placed_frames(&comp, &[&p1, &p2]), &lib2);
assert_eq!(a, vec!["3".to_string()]);
assert_eq!(c.len(), 1);
assert_eq!(c[0]["pad"], "2");
}
#[test]
fn a_bottom_part_is_seen_through_its_mirror() {
let comp = json!({"ref": "U1", "x": 0.0, "y": 0.0, "rotation": 0.0, "side": "bottom"});
// library pad 1 at (-1, 0.5); on the bottom it shows at (1, 0.5)
let p1 = pad("U1", "1", 1.0, 0.5, 0.4, 0.4, 0.0);
let lib = vec![P { num: "1".into(), x: -1.0, y: 0.5, w: 0.4, h: 0.4, rot: 0.0, drill: 0.0, shape: "rect".into(), smd: true }];
let (a, r, c) = best_diff(&placed_frames(&comp, &[&p1]), &lib);
assert!(a.is_empty() && r.is_empty() && c.is_empty(), "{c:?}");
}
}