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
0.2.88: export_3d, edit_pours, import_step, tool_update, import_design (kicad); engine 0.24.0 (bom, cross_check); pour…
58902e4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
//! edit_pours: change existing pours in place (EDA Bridge Standard #29): net, layer, hatching, minimum width, grid,
//! dead copper, islands, necks, pouring over same-net objects, pour order; and clearance and thermals. In Altium the
//! last two are not the polygon's own: they come from design rules, so they are written as rules scoped to the
//! polygon (IsNamedPolygon, as apply_pours' connect rules) and named in rulesWritten. Pours are named by pour_state's
//! name, or by net and layer.
use serde_json::{json, Value};
use std::time::Duration;
const PER_MM: f64 = 10000.0 / 0.0254;
/// The agent's lines ("name|key|value") for one pour's changes, and the clearance it wants as a rule. Pure.
pub fn ops_for(name: &str, set: &Value) -> Result<(Vec<String>, Option<f64>), String> {
let mut out = Vec::new();
let raw = |mm: f64| ((mm * PER_MM).round() as i64).to_string();
let push = |out: &mut Vec<String>, k: &str, v: String| out.push(format!("{name}|{k}|{v}"));
let Some(m) = set.as_object() else { return Err("set is an object of the properties to change".into()) };
let mut clearance = None;
for (k, v) in m {
match k.as_str() {
"net" => push(&mut out, "net", v.as_str().ok_or("net is a name")?.to_string()),
"layer" => push(&mut out, "layer", crate::routing::layer_id(v).ok_or(format!("unknown layer {v}"))?.to_string()),
"hatch" => { let h = v.as_str().unwrap_or(""); if !["solid", "45", "90", "none"].contains(&h) { return Err("hatch is solid, 45, 90 or none".into()); } push(&mut out, "hatch", h.into()) }
"minWidthMm" => push(&mut out, "track", raw(v.as_f64().ok_or("minWidthMm is mm")?)),
"gridMm" => push(&mut out, "grid", raw(v.as_f64().ok_or("gridMm is mm")?)),
"removeDead" => push(&mut out, "dead", if v.as_bool() == Some(true) { "1" } else { "0" }.into()),
"removeIslands" => push(&mut out, "islands", if v.as_bool() == Some(true) { "1" } else { "0" }.into()),
"neckMm" => push(&mut out, "neck", raw(v.as_f64().unwrap_or(0.0))),
"pourOverSameNet" => push(&mut out, "over", if v.as_bool() == Some(false) { "none" } else { "same" }.into()),
"pourIndex" | "priority" => push(&mut out, "index", v.as_i64().ok_or("pourIndex is an integer")?.to_string()),
"clearanceMm" => clearance = Some(v.as_f64().ok_or("clearanceMm is mm")?),
"connect" => {
let style = match v.as_str().unwrap_or("").to_ascii_lowercase().as_str() { "direct" | "solid" => "D", "relief" | "thermal" => "R", "none" => "N", o => return Err(format!("connect is direct, relief or none (got {o})")) };
let w = m.get("reliefWidthMm").and_then(|x| x.as_f64()).unwrap_or(0.254);
let g = m.get("reliefGapMm").and_then(|x| x.as_f64()).unwrap_or(0.254);
let e = m.get("reliefEntries").and_then(|x| x.as_i64()).unwrap_or(4);
if e != 2 && e != 4 { return Err("reliefEntries is 2 or 4".into()); }
push(&mut out, "connect", format!("{style},{},{},{e}", raw(w), raw(g)));
}
"reliefWidthMm" | "reliefGapMm" | "reliefEntries" => { if !m.contains_key("connect") { return Err(format!("{k} goes with connect")); } }
o => return Err(format!("{o} is not a pour property this verb changes")),
}
}
Ok((out, clearance))
}
/// The pours a target names: by name, or every pour on a net (and layer). Pure.
pub fn targets(t: &Value, zones: &[Value]) -> Vec<String> {
// pour_state's id first (the standard's handle: Altium's name, #n when two pours share one), then its name
if let Some(id) = t["id"].as_str() {
return zones.iter().filter(|z| z["id"].as_str() == Some(id)).filter_map(|z| z["name"].as_str().map(str::to_string)).take(1).collect();
}
if let Some(n) = t["name"].as_str() {
return zones.iter().filter(|z| z["name"].as_str() == Some(n)).filter_map(|z| z["name"].as_str().map(str::to_string)).collect();
}
let net = t["net"].as_str();
let layer = t.get("layer").and_then(crate::routing::layer_id);
zones.iter().filter(|z| net.map(|n| z["net"].as_str() == Some(n)).unwrap_or(false) && layer.map(|l| z["layerId"].as_i64() == Some(l)).unwrap_or(true))
.filter_map(|z| z["name"].as_str().map(str::to_string)).collect()
}
fn zones(ps: &Value) -> Vec<Value> { ["zones", "unfilled"].iter().flat_map(|k| ps[*k].as_array().cloned().unwrap_or_default()).collect() }
/// altium_edit_pours {filePath, pours: [{name | net + layer?, set: {...}}], repour?, expectedRevision?}
pub fn edit_pours(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"});
};
let Some(want) = args.get("pours").and_then(|v| v.as_array()).filter(|a| !a.is_empty()).cloned() else {
return json!({"success": false, "errorCode": "bad_args", "error": "pours: [{name (from pour_state) | net + layer?, set: {...}}] is required"});
};
if let Some(e) = crate::support::must_open(&board, 60) { return e; }
if let Err(e) = crate::routing::guarded(args) { return e; }
let before = crate::routing::pour_state(&json!({}));
let all = zones(&before);
let (mut lines, mut rules, mut touched) = (Vec::new(), Vec::new(), Vec::new());
for (i, t) in want.iter().enumerate() {
let names = targets(t, &all);
if names.is_empty() { return json!({"success": false, "errorCode": "no_such_pour", "index": i, "error": format!("no pour matches {t}"), "pours": all.iter().map(|z| json!({"name": z["name"], "net": z["net"], "layer": z["layer"]})).collect::<Vec<_>>()}); }
for n in names {
let (ops, clearance) = match ops_for(&n, &t["set"]) { Ok(x) => x, Err(e) => return json!({"success": false, "errorCode": "bad_args", "index": i, "error": e, "mutated": false}) };
lines.extend(ops);
if let Some(c) = clearance { rules.push((n.clone(), c)); }
if !touched.contains(&n) { touched.push(n); }
}
}
let mut results = Value::Null;
if !lines.is_empty() {
let r = crate::agent::call("edit_pour", &[], Some(&lines.join("\n")), Duration::from_secs(180));
let d = r.get("data").cloned().unwrap_or(Value::Null);
if d["ok"] != json!(true) { return json!({"success": false, "errorCode": "edit_failed", "error": d.get("error").cloned().unwrap_or(json!("the pours were not edited")), "reply": r}); }
results = d["results"].clone();
}
// clearance is a rule in Altium: one per pour, scoped to the polygon itself
let mut written = Vec::new();
for (n, gap) in &rules {
let r = crate::verbs::dispatch("add_rule", &json!({"kind": "clearance", "name": format!("Pour {n}"), "scope1": format!("IsNamedPolygon('{n}')"), "scope2": "All", "gap": gap}), &[]);
written.push(json!({"pour": n, "rule": format!("Adom Pour {n}"), "kind": "clearance", "gapMm": gap, "ok": r.get("success").and_then(|b| b.as_bool()) == Some(true), "error": r.get("error")}));
}
let after = if args.get("repour").and_then(|v| v.as_bool()) != Some(false) { crate::routing::repour(&json!({})); crate::routing::pour_state(&json!({})) } else { crate::routing::pour_state(&json!({})) };
let pick = |ps: &Value| -> Vec<Value> { zones(ps).into_iter().filter(|z| z["name"].as_str().map(|n| touched.iter().any(|t| t == n)).unwrap_or(false))
.map(|z| json!({"name": z["name"], "net": z["net"], "layer": z["layer"], "pourIndex": z["pourIndex"], "filled": z["filled"], "filledMm2": z["filledMm2"], "hatchedPieces": z["hatchedPieces"], "islands": z["islands"]})).collect() };
let failed: Vec<&Value> = results.as_array().map(|a| a.iter().filter(|x| x.as_str().map(|s| s.starts_with("err")).unwrap_or(false)).collect()).unwrap_or_default();
json!({"success": failed.is_empty() && written.iter().all(|w| w["ok"] == json!(true)), "mutated": true, "edited": touched, "results": results, "rulesWritten": written,
"before": pick(&before), "after": pick(&after),
"_hint": "Each pour is changed in place and repoured (repour:false skips it). Clearance and thermals are Altium design rules, not the polygon's own: rulesWritten names the rules scoped to each polygon (connect writes its AdomPC rule). The board is left unsaved: altium_save keeps it."})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_pours_changes_as_agent_lines() {
let (ops, clr) = ops_for("GND top", &json!({"net": "GND", "hatch": "45", "removeIslands": true, "pourIndex": 2, "clearanceMm": 0.3,
"connect": "relief", "reliefWidthMm": 0.254, "reliefEntries": 2})).unwrap();
assert_eq!(clr, Some(0.3));
assert!(ops.contains(&"GND top|net|GND".to_string()));
assert!(ops.contains(&"GND top|hatch|45".to_string()));
assert!(ops.contains(&"GND top|islands|1".to_string()));
assert!(ops.contains(&"GND top|index|2".to_string()));
assert!(ops.iter().any(|o| o.starts_with("GND top|connect|R,100000,100000,2")), "{ops:?}");
assert!(ops_for("X", &json!({"hatch": "zigzag"})).is_err());
assert!(ops_for("X", &json!({"reliefGapMm": 0.2})).is_err(), "relief settings go with connect");
assert!(ops_for("X", &json!({"colour": "red"})).is_err());
}
#[test]
fn targets_by_name_or_net_and_layer() {
let z = |n: &str, net: &str, l: i64| json!({"id": n, "name": n, "net": net, "layerId": l});
let zones = vec![z("A", "GND", 1), z("B", "GND", 32), z("C", "3V3", 1)];
assert_eq!(targets(&json!({"name": "B"}), &zones), ["B"]);
assert_eq!(targets(&json!({"id": "C"}), &zones), ["C"]);
assert_eq!(targets(&json!({"net": "GND"}), &zones), ["A", "B"]);
assert_eq!(targets(&json!({"net": "GND", "layer": "B.Cu"}), &zones), ["B"]);
assert!(targets(&json!({"name": "Z"}), &zones).is_empty());
}
}