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.
← Commit history
0.2.113: altium_layer_map (organisation layers, template footprints), typed layers kept when placing and copying, every agent iterator reads all layers (#41)
18 files changed
+1539−469
CHANGELOG.md+10README.md+5−4bridge-rs/src/footprint.rs+9−3bridge-rs/src/layermap.rs+272bridge-rs/src/layermap_verb.rs+246bridge-rs/src/library.rs+30−13bridge-rs/src/main.rs+3−1bridge-rs/src/support.rs+22−1bridge-rs/src/verbs.rs+13−6dev-skills/altium-bridge-test/run_verb_tests.py+3docs/discovery-triggers-all.json+256−252package.json+2−2page.json+3−3scripts/release.py+4skills/altium-libraries/SKILL.md+31−6src/BRIDGE_VERSION+1−1src/agent/AdomAgent.pas.tmpl+626−176src/bridge.json+3−1CHANGELOG.md+10@@ -1,5 +1,15 @@ # Changelog +## 0.2.113++- **New verb `altium_layer_map`: your organisation's layers for the footprints the bridge makes** (#41). Map Adom's kinds of graphic (`overlay`, `fab`, `courtyard`, `body3d`, `comment`, `balls`, `centroid`, `designator`) to an Altium layer by type (`AssemblyTop`, `CourtyardTop`, `3DBodyTop`, ...), by name or by number. Set it per call (`layerMap`), for a library folder (`adom-layer-map.json` beside the library: the organisation's default) or as your own default; the call wins, then the folder, then yours. With nothing set, footprints come out exactly as before.+- `altium_build_footprint`, `altium_footprint_from_land_pattern`, `altium_import_part` (and so the wiki import) and `altium_add_body` use it, and each reply reports the layer every kind went on and where the setting came from (`layerMap`). A layer type the library lacks is made as a top/bottom pair, the only way Altium lets a script type a layer.+- **Template footprints.** `altium_layer_map {action:'from_template'}` reads a template footprint, proposes the map from the typed layers it uses and saves it with the template. Each new footprint then starts with the template's `.Designator` and centroid marker; the template's example pad, outline, courtyard and dimensions stay behind. A `.Designator` centred on the origin is given a centred text frame, so the real designator stays centred whatever its length. `find_template` reads Altium's Template Files preference and the cached Workspace copies.+- **Placing and copying keeps typed-layer graphics.** Placing a part (`altium_build_board`, `altium_place_parts`, `altium_test_board`, `altium_swap_footprint`, `altium_place_on_pcb`) or copying a footprint between libraries (`altium_xcopy_footprint`) dropped every graphic on a typed layer. Each now lands on the destination's layer of the same type, made with the source's numbers and names when missing, so a part flipped to the bottom moves to Bottom Assembly, Bottom Courtyard and so on.+- Every iterator in the agent now reads all layers. Altium's `AllLayers` set leaves out mechanical layers above 16, so other verbs missed objects there too (a 3D body on a Top 3D Body layer, for one). The release lint refuses it from now on, and also refuses a routine used above its declaration and a reserved word as a name: both halt Altium's script engine.+- A verb that opens a document first now says why it could not (`errorCode: file_not_found` and the path), where `error` was empty.+- Tested on Altium Designer Develop: a footprint built with no map (Mechanical 13 and 15 as before); the reporter's template proposing and saving the map; a footprint built with it (Top Assembly, Top Courtyard, Top Component Center, Top Designator and Top 3D Body made as pairs, the designator centred on the origin); placing it on a board (the same types made on the board), flipping it (Bottom layers), and copying it to another library; precedence between the call, the folder and the user's default. The verb battery passed on Develop (281 of 283; `altium_export_3d` found no Parasolid exporter on Develop's menu, with unchanged code). The typed-layer calls were checked on Altium Designer 26.11.1 too.+ ## 0.2.112 - **Footprint reads see the typed component layers of Altium Designer 24+** (#41). Top Assembly, Top Courtyard, Top Component Outline, Top Component Center, Top Designator, Top 3D Body and their bottom pairs are mechanical layers above Mechanical 16, and the reads asked Altium only for the first 16: a footprint drawn on them read as a pad and a silkscreen dot. `altium_read_footprint` and `altium_footprint_primitives` now read every layer.
README.md+5−4@@ -15,7 +15,7 @@ normal session. Ask in plain words and it: - makes the outputs: Gerbers, NC drill, pick and place, BOMs grouped by MPN (JLCPCB, Mouser, DigiKey files), schematic PDF and STEP, checking that the outline and every copper layer reached the Gerbers -282 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+283 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free desktop app, through Adom Bridge. You bring your own AI subscription and your own Altium licence. ::youtube{id="dFecpcIzdSE" title="An AI designs a 12 V to 5 V buck converter in Altium Designer"}@@ -29,7 +29,7 @@ and the verb prefix `altium_`. ## What it can do -Tested on Altium Designer 26.11.1 and Altium Designer Develop. 282 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 283 verbs; each row names the ones behind it (prefix `altium_`). | Area | What the AI can do | Verbs |@@ -70,7 +70,7 @@ This bridge is the reference for the [EDA Bridge Standard](https://wiki.adom.inc Altium Designer is the user's own **host app**. The bridge finds an installed Altium (`%ProgramFiles%\Altium\AD*\X2.EXE`, Designer or Develop), starts it in the background, runs a small-**DelphiScript agent** inside it, and gives the AI 282 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 283 `altium_*` verbs. - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -170,7 +170,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`. <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 282 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 283 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -339,6 +339,7 @@ All 282 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_remove_pours`: Delete polygon pours by net (and layer), or all of them, and the pour keepouts (cutouts) apply_pours made. - `altium_repour`: Repour every polygon on the board (Altium's Repour All) and answer the copper after. - `altium_gloss`: Gloss the routing of the nets you name with Altium's own Gloss (Route > Gloss Selected): shorter routes with fewer corners, within the board's rules.+- `altium_layer_map`: Choose which Altium layer each kind of footprint graphic goes on (silkscreen, fab/assembly, courtyard, 3D body, centroid, designator, ...) and the template footprint new footprints start from, per call, per library folder (your organisation's default) or as your own default. - `altium_routing_drc`: Design-rule violations on the current board (or filePath, opened first) WITH locations, plus the unrouted (ratsnest) count, as one clean/not-clean answer. - `altium_build_board`: Build a NEW board from a parts list and a netlist: outline (rounded corners allowed), every footprint from one PcbLib placed by its own origin, pad nets assigned, saved; then read back pin by pin. - `altium_set_outline`: Reshape the current board's outline (a rectangle with rounded corners, or a polygon).
bridge-rs/src/footprint.rs+9−3@@ -50,14 +50,20 @@ pub fn from_land_pattern(args: &Value) -> Value { let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); let path = dir.join(format!("{safe}.spec")); if let Err(e) = std::fs::write(&path, crate::agent::agent_text(&text)) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }- let mut r = crate::library::build_footprint(&json!({"libraryPath": lib, "spec": path.to_string_lossy(), "timeout": 240}));+ // the call's layer map and template ride along (#41); the library's and the user's are read by build_footprint+ let mut fa = json!({"libraryPath": lib, "spec": path.to_string_lossy(), "timeout": 240});+ for k in ["layerMap", "template"] { if let Some(v) = args.get(k) { fa[k] = v.clone(); } }+ let mut r = crate::library::build_footprint(&fa); // a 3D body when the height is known: an extruded box the size of the body let body = args.get("body").cloned().unwrap_or(json!({})); if r.get("success").and_then(|b| b.as_bool()) != Some(false) { if let (Some(w), Some(l), Some(h)) = (num(&body, "w"), num(&body, "l"), num(&body, "height")) { let mil = |mm: f64| (mm / 0.0254).round() as i64;- let b = crate::library::add_body(&json!({"libraryPath": lib, "footprintName": name, "bwMil": mil(w), "bhMil": mil(l), "hMil": mil(h), "soMil": mil(num(&body, "standoff").unwrap_or(0.0))}));- r["body3d"] = json!({"success": b.get("success"), "error": b.get("error")});+ let mut ba = json!({"libraryPath": lib, "footprintName": name, "bwMil": mil(w), "bhMil": mil(l), "hMil": mil(h), "soMil": mil(num(&body, "standoff").unwrap_or(0.0))});+ // the call's layer map reaches the body too (body3d, #41)+ if let Some(v) = args.get("layerMap") { ba["layerMap"] = v.clone(); }+ let b = crate::library::add_body(&ba);+ r["body3d"] = json!({"success": b.get("success"), "error": b.get("error"), "layer": b.pointer("/layerMap/keys/body3d/layer")}); } r["_hint"] = json!("Built in the PcbLib (unsaved): check shot.image, then altium_save {filePath: libraryPath}. Link it to a symbol with altium_set_models."); }
bridge-rs/src/layermap.rsadded+272@@ -0,0 +1,272 @@+//! The footprint layer map (#41): which Altium layer each kind of footprint graphic goes on, so footprints the bridge+//! makes land on an organisation's own layers. Keys are Adom's logical layers; a value names an Altium layer by type+//! (a typed component layer of AD 24+, "CourtyardTop"), by name ("Top Courtyard", "Mechanical 15") or by number.+//!+//! Precedence, per key: the call's `layerMap`, then `adom-layer-map.json` beside the library (the organisation's+//! default), then the user's default, then the bridge's built-in layers (unchanged since before the map). Pure: the+//! files are read in layermap_verb.+use serde_json::{json, Map, Value};++/// The logical layers, with what the bridge draws on each and its built-in Altium layer.+pub const KEYS: &[(&str, &str, &str)] = &[+ ("overlay", "silkscreen (KiCad F.SilkS)", "Top Overlay"),+ ("fab", "fabrication / assembly outline (KiCad F.Fab)", "Mechanical 13"),+ ("courtyard", "courtyard (KiCad F.CrtYd)", "Mechanical 15"),+ ("body3d", "3D body (altium_add_body)", "Mechanical 1"),+ ("comment", "comments (KiCad Cmts.User)", "Mechanical 1"),+ ("balls", "BGA solder balls (KiCad User.9)", "Mechanical 9"),+ ("centroid", "the centre marker a template carries", "the template's own layer"),+ ("designator", "the .Designator string a template carries", "the template's own layer"),+ ("outline", "component outline (nothing the bridge draws yet)", "-"),+ ("dimensions", "dimensions (nothing the bridge draws yet)", "-"),+];++/// Keys the bridge draws on today. The rest are accepted, so one map serves a whole organisation, and reported unused.+pub const DRAWN: &[&str] = &["overlay", "fab", "courtyard", "body3d", "comment", "balls", "centroid", "designator"];++/// A typed component layer's kind number by its type name (as Altium's layer type, "CourtyardTop"; spaces, dots and+/// case ignored, so "Top Courtyard" is not a type but "courtyard top" is).+pub fn kind_of(name: &str) -> Option<i64> {+ let n: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();+ (1..=30).find(|k| crate::fplayers::kind_name(*k).map(|t| t.to_ascii_lowercase()) == Some(n.clone()))+}++/// The top/bottom pair a kind belongs to: (pair kind, top kind, bottom kind), as Altium sets them (AD 26.11, read+/// 2026-11-30). Only a pair can be given a type from a script.+pub fn pair_of(kind: i64) -> Option<(i64, i64, i64)> {+ Some(match kind {+ 1 | 2 => (1, 1, 2), 5 | 6 => (2, 5, 6), 7 | 8 => (3, 7, 8), 9 | 10 => (4, 9, 10), 11 | 12 => (5, 11, 12),+ 13 | 14 => (6, 13, 14), 16 | 17 => (7, 16, 17), 19 | 20 => (8, 19, 20), 21 | 22 => (9, 21, 22),+ 23 | 24 => (10, 23, 24), 26 | 27 => (11, 26, 27),+ _ => return None,+ })+}++/// A mechanical layer's id: Mechanical 1-16 keep their old ids, the rest are 67108864 + n.+pub fn is_mech(id: i64) -> bool { (57..=72).contains(&id) || (67_108_865..=67_109_888).contains(&id) }++/// Standard layer names the bridge knows by id (non-mechanical).+fn named_id(name: &str) -> Option<i64> {+ Some(match name.trim().to_ascii_lowercase().as_str() {+ "top overlay" | "f.silks" | "f.silkscreen" => 33, "bottom overlay" | "b.silks" | "b.silkscreen" => 34,+ "top paste" | "f.paste" => 35, "bottom paste" | "b.paste" => 36, "top solder" | "f.mask" => 37, "bottom solder" | "b.mask" => 38,+ "top layer" | "f.cu" => 1, "bottom layer" | "b.cu" => 32, "keep-out layer" => 56, "multi-layer" => 74,+ _ => return None,+ })+}++/// One value as the agent's code: `k<kind>` a typed layer (made if the library has none), `m<n>` Mechanical n,+/// `i<id>` an Altium layer id, `n<name>` a mechanical layer by its name. Err names what was wrong.+pub fn encode(v: &Value) -> Result<String, String> {+ if let Some(i) = v.as_i64() {+ return if i > 0 { Ok(format!("i{i}")) } else { Err(format!("{i} is not a layer id")) };+ }+ if let Some(o) = v.as_object() {+ if let Some(k) = o.get("kind").and_then(|x| x.as_str()) { return encode(&json!(k)).and_then(|c| if c.starts_with('k') { Ok(c) } else { Err(format!("{k} is not a layer type")) }); }+ if let Some(n) = o.get("mechanical").and_then(|x| x.as_i64()) { return if (1..=1024).contains(&n) { Ok(format!("m{n}")) } else { Err(format!("Mechanical {n} is out of 1..1024")) }; }+ if let Some(n) = o.get("name").and_then(|x| x.as_str()) { return Ok(format!("n{}", n.trim())); }+ if let Some(i) = o.get("id").and_then(|x| x.as_i64()) { return encode(&json!(i)); }+ return Err("an object value takes kind, name, mechanical or id".into());+ }+ let Some(s) = v.as_str().map(str::trim).filter(|s| !s.is_empty()) else { return Err("a layer is a type, a name or a number".into()) };+ if s.contains(';') || s.contains('>') || s.contains('|') { return Err(format!("{s}: a layer name cannot hold ; > or |")); }+ if let Some(k) = kind_of(s) { return Ok(format!("k{k}")); }+ if let Some(i) = named_id(s) { return Ok(format!("i{i}")); }+ let low = s.to_ascii_lowercase();+ if let Some(rest) = low.strip_prefix("mechanical") {+ if let Ok(n) = rest.trim().parse::<i64>() {+ return if (1..=1024).contains(&n) { Ok(format!("m{n}")) } else { Err(format!("Mechanical {n} is out of 1..1024")) };+ }+ }+ Ok(format!("n{s}"))+}++/// Where an entry came from.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Source { Call, Library, User }++impl Source {+ pub fn word(self) -> &'static str { match self { Source::Call => "call", Source::Library => "library", Source::User => "user" } }+}++/// The map in effect: each key's given value, its agent code and its source; the template; and what was refused.+#[derive(Clone, Debug, Default)]+pub struct Effective {+ pub entries: Vec<(String, Value, String, Source)>,+ pub template: Option<(String, String, Source)>,+ pub errors: Vec<String>,+}++/// A map document as stored or passed: `{layerMap: {key: value}, template: {libraryPath, footprint}}`, or the bare+/// `{key: value}` map.+fn split(doc: &Value) -> (Map<String, Value>, Option<(String, String)>) {+ let map = doc.get("layerMap").and_then(|m| m.as_object()).cloned()+ .unwrap_or_else(|| doc.as_object().cloned().unwrap_or_default().into_iter().filter(|(k, _)| KEYS.iter().any(|(n, _, _)| n == k)).collect());+ let t = doc.get("template").and_then(|t| Some((t.get("libraryPath")?.as_str()?.to_string(), t.get("footprint")?.as_str()?.to_string())));+ (map, t)+}++/// Merges the call's, the library's and the user's maps, key by key, the call first.+pub fn merge(call: Option<&Value>, library: Option<&Value>, user: Option<&Value>) -> Effective {+ let mut e = Effective::default();+ for (doc, src) in [(call, Source::Call), (library, Source::Library), (user, Source::User)] {+ let Some(doc) = doc else { continue };+ let (map, t) = split(doc);+ for (k, v) in map {+ if !KEYS.iter().any(|(n, _, _)| *n == k) { e.errors.push(format!("{k} ({}): not a layer key; the keys are {}", src.word(), KEYS.iter().map(|k| k.0).collect::<Vec<_>>().join(", "))); continue; }+ if e.entries.iter().any(|x| x.0 == k) { continue; }+ match encode(&v) {+ Ok(c) => e.entries.push((k, v, c, src)),+ Err(m) => e.errors.push(format!("{k} ({}): {m}", src.word())),+ }+ }+ if e.template.is_none() { if let Some((l, f)) = t { e.template = Some((l, f, src)); } }+ }+ e+}++/// The agent's `lmap` parameter: `;key>code;key>code;`, only the keys that were set (an unset key keeps the+/// built-in layer, and its naming, exactly as before).+pub fn agent_param(e: &Effective) -> String {+ if e.entries.is_empty() { return String::new(); }+ format!(";{};", e.entries.iter().map(|(k, _, c, _)| format!("{k}>{c}")).collect::<Vec<_>>().join(";"))+}++/// The map a reply reports: for every key, the layer asked for (or the built-in one) and where it came from, merged+/// with what the agent resolved (`[[key, id, name, kind]]`).+pub fn report(e: &Effective, resolved: &Value) -> Value {+ let mut out = Map::new();+ for (k, _, builtin) in KEYS {+ let entry = e.entries.iter().find(|x| x.0 == *k);+ let mut v = match entry {+ Some((_, given, _, src)) => json!({"asked": given, "source": src.word()}),+ None => json!({"asked": builtin, "source": "built-in"}),+ };+ if let Some(r) = resolved.as_array().and_then(|a| a.iter().find(|r| r[0] == *k)) {+ v["layer"] = r[1].clone();+ v["layerId"] = r[2].clone();+ if let Some(kn) = r[3].as_i64().and_then(crate::fplayers::kind_name) { v["kind"] = json!(kn); }+ }+ if !DRAWN.contains(k) { v["used"] = json!(false); }+ out.insert(k.to_string(), v);+ }+ let mut r = json!({"keys": out});+ if let Some((l, f, s)) = &e.template { r["template"] = json!({"libraryPath": l, "footprint": f, "source": s.word()}); }+ if !e.errors.is_empty() { r["refused"] = json!(e.errors); }+ r+}++/// The map a template footprint suggests, from its layers as altium_read_footprint gives them (`layerDetails`):+/// each typed layer it uses becomes the key of that kind, by type, so the map works in any library. Silkscreen stays+/// on Top Overlay.+pub fn propose(details: &[Value]) -> (Map<String, Value>, Vec<String>) {+ let by_kind = [("AssemblyTop", "fab"), ("CourtyardTop", "courtyard"), ("ComponentOutlineTop", "outline"), ("ComponentCenterTop", "centroid"),+ ("DesignatorTop", "designator"), ("DimensionsTop", "dimensions"), ("3DBodyTop", "body3d")];+ let mut map = Map::new();+ let mut notes = Vec::new();+ for (kind, key) in by_kind {+ if details.iter().any(|d| d["kind"] == kind) { map.insert(key.into(), json!(kind)); }+ }+ if details.iter().any(|d| d["id"] == 33) { map.insert("overlay".into(), json!("Top Overlay")); }+ for d in details {+ if d.get("kind").is_none() && d["id"].as_i64().is_some_and(|i| is_mech(i)) {+ notes.push(format!("{} has no layer type: map a key to it by name if the template means it", d["altiumName"].as_str().unwrap_or("?")));+ }+ }+ if !map.contains_key("body3d") { notes.push("the template has no 3D body layer in use: body3d keeps Mechanical 1 unless you set it".into()); }+ (map, notes)+}++/// The entries of Altium's Template Files preference (`PCBLIB=dxp://...ItemGUID=...;...`): (document kind, value,+/// the item GUID when it names a Workspace item).+pub fn template_entries(pref: &str) -> Vec<(String, String, Option<String>)> {+ pref.split(['\n', '\r', '|']).flat_map(|chunk| chunk.split(';').map(str::to_string).collect::<Vec<_>>()).filter_map(|e| {+ let e = e.trim();+ let (k, v) = e.split_once('=')?;+ if k.trim().is_empty() || v.trim().is_empty() { return None; }+ let guid = v.split(['?', '&']).find_map(|p| p.strip_prefix("ItemGUID=").map(str::to_string));+ Some((k.trim().to_string(), v.trim().to_string(), guid))+ }).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn values_name_a_layer_by_type_name_or_number() {+ assert_eq!(encode(&json!("CourtyardTop")).unwrap(), "k11");+ assert_eq!(encode(&json!("courtyard top")).unwrap(), "k11");+ assert_eq!(encode(&json!("3DBodyTop")).unwrap(), "k26");+ assert_eq!(encode(&json!("Top Courtyard")).unwrap(), "nTop Courtyard", "a layer's name, not its type");+ assert_eq!(encode(&json!("Mechanical 15")).unwrap(), "m15");+ assert_eq!(encode(&json!("Mechanical13")).unwrap(), "m13");+ assert_eq!(encode(&json!("Top Overlay")).unwrap(), "i33");+ assert_eq!(encode(&json!(69)).unwrap(), "i69");+ assert_eq!(encode(&json!({"kind": "AssemblyTop"})).unwrap(), "k1");+ assert_eq!(encode(&json!({"mechanical": 57})).unwrap(), "m57");+ assert!(encode(&json!({"kind": "Top Assembly"})).is_err(), "kind must be a type");+ assert!(encode(&json!("Mechanical 2000")).is_err());+ assert!(encode(&json!("a;b")).is_err());+ }++ #[test]+ fn the_call_wins_then_the_library_then_the_user() {+ let e = merge(Some(&json!({"courtyard": "CourtyardTop"})), Some(&json!({"layerMap": {"courtyard": "Mechanical 15", "fab": "AssemblyTop"},+ "template": {"libraryPath": "C:/org/Templates.PcbLib", "footprint": "Default Footprint"}})), Some(&json!({"fab": "Mechanical 13", "body3d": "3DBodyTop"})));+ let get = |k: &str| e.entries.iter().find(|x| x.0 == k).map(|x| (x.2.clone(), x.3));+ assert_eq!(get("courtyard"), Some(("k11".into(), Source::Call)));+ assert_eq!(get("fab"), Some(("k1".into(), Source::Library)));+ assert_eq!(get("body3d"), Some(("k26".into(), Source::User)));+ assert_eq!(e.template.as_ref().map(|t| t.2), Some(Source::Library));+ assert_eq!(agent_param(&e), ";courtyard>k11;fab>k1;body3d>k26;");+ }++ #[test]+ fn no_map_sends_nothing_so_footprints_stay_as_they_were() {+ let e = merge(None, None, None);+ assert_eq!(agent_param(&e), "");+ let r = report(&e, &json!([]));+ assert_eq!(r["keys"]["fab"]["asked"], "Mechanical 13");+ assert_eq!(r["keys"]["fab"]["source"], "built-in");+ assert_eq!(r["keys"]["outline"]["used"], false);+ }++ #[test]+ fn unknown_keys_and_bad_values_are_refused_by_name() {+ let e = merge(Some(&json!({"layerMap": {"silk": "Top Overlay", "fab": "Mechanical 9999"}})), None, None);+ assert!(e.entries.is_empty());+ assert_eq!(e.errors.len(), 2);+ assert!(e.errors.iter().any(|m| m.contains("silk")) && e.errors.iter().any(|m| m.contains("9999")), "{:?}", e.errors);+ }++ #[test]+ fn a_template_proposes_its_typed_layers_by_type() {+ let d = vec![json!({"id": 33, "name": "F.SilkS"}), json!({"id": 67108917, "kind": "AssemblyTop", "altiumName": "Top Assembly"}),+ json!({"id": 67108925, "kind": "CourtyardTop"}), json!({"id": 67108921, "kind": "ComponentCenterTop"}),+ json!({"id": 67108927, "kind": "DesignatorTop"}), json!({"id": 69, "altiumName": "Mechanical 13"})];+ let (m, notes) = propose(&d);+ assert_eq!(m["fab"], "AssemblyTop");+ assert_eq!(m["courtyard"], "CourtyardTop");+ assert_eq!(m["centroid"], "ComponentCenterTop");+ assert_eq!(m["designator"], "DesignatorTop");+ assert_eq!(m["overlay"], "Top Overlay");+ assert!(notes.iter().any(|n| n.contains("Mechanical 13")));+ }++ #[test]+ fn pairs_follow_altiums_kinds() {+ assert_eq!(pair_of(11), Some((5, 11, 12)));+ assert_eq!(pair_of(27), Some((11, 26, 27)));+ assert_eq!(pair_of(15), None, "an unpaired kind cannot be made from a script");+ }++ #[test]+ fn the_template_preference_gives_each_kind_and_item() {+ let p = "PCBLIB=dxp://VaultExplorer:Navigate_URL?ItemGUID=ABC-123&RevisionMode=Last&FileExt=PcbLib;SCHLIB=C:\\t\\a.SchLib";+ let e = template_entries(p);+ assert_eq!(e[0].0, "PCBLIB");+ assert_eq!(e[0].2.as_deref(), Some("ABC-123"));+ assert_eq!(e[1].2, None);+ }+}
bridge-rs/src/layermap_verb.rsadded+246@@ -0,0 +1,246 @@+//! altium_layer_map and the layer map's files (#41). The organisation's default is `adom-layer-map.json` beside its+//! library; the user's default is `layer-map.json` in the bridge's own folder. The footprint verbs call `agent_params`+//! for the map in effect and `report` to say in their reply which layer each kind of graphic went on.+use crate::layermap::{self, Effective};+use crate::support::s;+use serde_json::{json, Value};+use std::path::{Path, PathBuf};++const LIBRARY_FILE: &str = "adom-layer-map.json";++fn user_file() -> PathBuf { crate::agent::cache_dir().join("layer-map.json") }++fn library_file(lib: &str) -> Option<PathBuf> {+ let p = Path::new(lib);+ let dir = if p.is_dir() { p } else { p.parent()? };+ Some(dir.join(LIBRARY_FILE))+}++fn read_json(p: &Path) -> Option<Value> { serde_json::from_str(&std::fs::read_to_string(p).ok()?).ok() }++/// A template's library path as written, made absolute against the folder of the file that named it.+fn absolute(t: &str, base: Option<&Path>) -> String {+ let p = Path::new(t);+ if p.is_absolute() || t.contains(':') { return t.to_string(); }+ base.and_then(|b| b.parent()).map(|d| d.join(p).to_string_lossy().to_string()).unwrap_or_else(|| t.to_string())+}++fn with_template_abs(doc: Option<Value>, file: &Path) -> Option<Value> {+ let mut d = doc?;+ if let Some(l) = d.pointer("/template/libraryPath").and_then(|v| v.as_str()).map(|v| absolute(v, Some(file))) {+ d["template"]["libraryPath"] = json!(l);+ }+ Some(d)+}++/// The call's own map: `layerMap` and `template` ({libraryPath, footprint}) from the verb's arguments.+fn call_doc(args: &Value) -> Option<Value> {+ let m = args.get("layerMap").filter(|v| v.is_object());+ let t = args.get("template").filter(|v| v.is_object());+ if m.is_none() && t.is_none() { return None; }+ let mut d = json!({});+ if let Some(m) = m { d["layerMap"] = m.clone(); }+ if let Some(t) = t { d["template"] = t.clone(); }+ Some(d)+}++/// The map in effect for a footprint in `lib`.+pub fn effective(args: &Value, lib: Option<&str>) -> Effective {+ let lf = lib.and_then(library_file);+ let library = lf.as_ref().and_then(|f| with_template_abs(read_json(f), f));+ let uf = user_file();+ let user = with_template_abs(read_json(&uf), &uf);+ layermap::merge(call_doc(args).as_ref(), library.as_ref(), user.as_ref())+}++/// The agent parameters for the map in effect (empty when no map is set: footprints come out as before), and the map.+pub fn agent_params(args: &Value, lib: Option<&str>) -> (Vec<(&'static str, String)>, Effective) {+ let e = effective(args, lib);+ let mut p = Vec::new();+ let lm = layermap::agent_param(&e);+ if !lm.is_empty() { p.push(("lmap", lm)); }+ if let Some((l, f, _)) = &e.template { p.push(("tplLib", l.replace('/', "\\"))); p.push(("tplFp", f.clone())); }+ (p, e)+}++/// Adds `layerMap` to a footprint verb's reply: the map, with the layers the agent used (`layersUsed`) and what a+/// template copy did.+pub fn report(r: &mut Value, e: &Effective) {+ let d = r.get("data").cloned().unwrap_or_else(|| r.clone());+ let mut m = layermap::report(e, &d["layersUsed"]);+ if let Some(t) = d.get("template").filter(|t| t["library"].as_str().is_some_and(|l| !l.is_empty())) { m["templateCopy"] = t.clone(); }+ r["layerMap"] = m;+}++fn write(p: &Path, doc: &Value) -> Result<(), String> {+ if let Some(d) = p.parent() { std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; }+ std::fs::write(p, serde_json::to_string_pretty(doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", p.display()))+}++fn scope_file(args: &Value) -> Result<PathBuf, Value> {+ match s(args, "scope").as_deref() {+ Some("user") => Ok(user_file()),+ Some("library") => s(args, "libraryPath").and_then(|l| library_file(&l)).ok_or_else(|| json!({"success": false, "errorCode": "bad_args", "error": "scope library needs libraryPath (the library, or its folder)"})),+ _ => Err(json!({"success": false, "errorCode": "bad_args", "error": "scope is user (your default) or library (adom-layer-map.json beside libraryPath: everyone using that folder)"})),+ }+}++fn get(args: &Value) -> Value {+ let lib = s(args, "libraryPath");+ let e = effective(args, lib.as_deref());+ let lf = lib.as_deref().and_then(library_file);+ let mut r = json!({"success": true, "files": {"user": {"path": user_file(), "exists": user_file().is_file()}}});+ if let Some(f) = lf { r["files"]["library"] = json!({"path": f, "exists": f.is_file()}); }+ let m = layermap::report(&e, &json!([]));+ r["layerMap"] = m;+ r["_hint"] = json!("Each key shows the layer asked for and where it comes from: the call, the library's adom-layer-map.json, your default, or the built-in layer. A typed layer (CourtyardTop) the library lacks is made, as a top/bottom pair, the first time a footprint uses it.");+ r+}++fn set(args: &Value) -> Value {+ let file = match scope_file(args) { Ok(f) => f, Err(e) => return e };+ let incoming = call_doc(args).unwrap_or(json!({}));+ let check = layermap::merge(Some(&incoming), None, None);+ if !check.errors.is_empty() { return json!({"success": false, "errorCode": "bad_layer_map", "error": "nothing was written", "refused": check.errors}); }+ if incoming.get("layerMap").is_none() && incoming.get("template").is_none() {+ return json!({"success": false, "errorCode": "bad_args", "error": "set takes layerMap ({key: layer}) and/or template ({libraryPath, footprint})"});+ }+ let replace = args.get("replace").and_then(|b| b.as_bool()) == Some(true);+ let mut doc = if replace { json!({}) } else { read_json(&file).unwrap_or(json!({})) };+ if let Some(m) = incoming["layerMap"].as_object() {+ let cur = doc["layerMap"].as_object().cloned().unwrap_or_default();+ let mut merged = cur;+ for (k, v) in m { if v.is_null() { merged.remove(k); } else { merged.insert(k.clone(), v.clone()); } }+ doc["layerMap"] = json!(merged);+ }+ if let Some(t) = incoming.get("template") { doc["template"] = t.clone(); }+ doc["note"] = json!("Read by altium-bridge for every footprint it builds in this scope (altium_layer_map). Keys: overlay, fab, courtyard, body3d, comment, balls, centroid, designator, outline, dimensions.");+ if let Err(e) = write(&file, &doc) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }+ let mut r = get(args);+ r["written"] = json!(file);+ r["_hint"] = json!("Written. Footprints built from now on use it; ones already built keep their layers. altium_layer_map {action:'get'} shows the map in effect.");+ r+}++fn clear(args: &Value) -> Value {+ let file = match scope_file(args) { Ok(f) => f, Err(e) => return e };+ if !file.is_file() { return json!({"success": true, "cleared": false, "path": file, "_hint": "There was no map in this scope."}); }+ let keys: Vec<String> = args.get("keys").and_then(|k| k.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();+ if keys.is_empty() {+ if let Err(e) = std::fs::remove_file(&file) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+ return json!({"success": true, "cleared": true, "path": file, "_hint": "The map in this scope is gone; the next scope down (or the built-in layers) applies."});+ }+ let mut doc = read_json(&file).unwrap_or(json!({}));+ for k in &keys {+ if k == "template" { if let Some(o) = doc.as_object_mut() { o.remove("template"); } }+ else if let Some(m) = doc["layerMap"].as_object_mut() { m.remove(k); }+ }+ if let Err(e) = write(&file, &doc) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }+ json!({"success": true, "cleared": keys, "path": file})+}++fn from_template(args: &Value) -> Value {+ let (Some(lib), Some(fp)) = (s(args, "libraryPath"), s(args, "footprint")) else {+ return json!({"success": false, "errorCode": "bad_args", "error": "libraryPath and footprint (the template footprint) are required"});+ };+ let read = crate::project::read_footprint(&json!({"libraryPath": lib, "name": fp}));+ if read["success"] != true { return read; }+ let details = read["layerDetails"].as_array().cloned().unwrap_or_default();+ let (map, notes) = layermap::propose(&details);+ let proposal = json!({"layerMap": map, "template": {"libraryPath": lib, "footprint": fp}});+ let keep: Vec<Value> = read["texts"].as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["text"].as_str().is_some_and(|x| x.starts_with('.'))).collect();+ let mut r = json!({"success": true, "proposal": proposal, "notes": notes, "templateLayers": details,+ "templateCopy": {"keeps": {"specialStrings": keep, "centroidLayer": map.get("centroid")}, "leavesOut": "pads, the example outline, courtyard, assembly and silkscreen graphics, dimensions, and texts that are not special strings"}});+ if let Some(scope) = s(args, "save") {+ let mut a = proposal.clone();+ a["scope"] = json!(scope);+ a["libraryPath"] = json!(s(args, "saveTo").unwrap_or(lib.clone()));+ let w = set(&a);+ if w["success"] != true { return w; }+ r["written"] = w["written"].clone();+ }+ r["_hint"] = json!(if r.get("written").is_some() { "Saved: footprints built in that scope now use these layers and start from the template." }+ else { "A proposal only: altium_layer_map {action:'set', scope:'library'|'user', layerMap, template} keeps it (or call again with save)." });+ r+}++/// PcbLib files under a folder, a few levels deep.+fn pcblibs(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {+ if depth == 0 || out.len() > 200 { return; }+ let Ok(rd) = std::fs::read_dir(dir) else { return };+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() { pcblibs(&p, depth - 1, out); }+ else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| x.eq_ignore_ascii_case("pcblib")) { out.push(p); }+ }+}++fn find_template(args: &Value) -> Value {+ let mut pa = json!({"under": "WorkspaceManager"});+ if let Some(ed) = s(args, "edition") { pa["edition"] = json!(ed); }+ let prefs = crate::prefs::preferences(&pa);+ let cur = prefs["current"].as_object().cloned().unwrap_or_default();+ let pick = |suffix: &str| cur.iter().find(|(k, _)| k.ends_with(suffix)).and_then(|(_, v)| v.as_str()).unwrap_or("").to_string();+ let files = pick("Template Files");+ let local = pick("Template Path");+ let entries = layermap::template_entries(&files);+ let pcb: Vec<&(String, String, Option<String>)> = entries.iter().filter(|e| e.0.to_ascii_uppercase().ends_with("PCBLIB")).collect();+ let mut found = Vec::new();+ let pd = std::env::var("ProgramData").unwrap_or_else(|_| "C:\\ProgramData".into());+ if let Ok(rd) = std::fs::read_dir(Path::new(&pd).join("Altium")) {+ for e in rd.flatten() { pcblibs(&e.path().join("VaultsFileCache"), 6, &mut found); }+ }+ let mut local_libs = Vec::new();+ if !local.is_empty() { pcblibs(Path::new(&local), 3, &mut local_libs); }+ let guids: Vec<String> = pcb.iter().filter_map(|e| e.2.clone()).map(|g| g.to_ascii_lowercase().trim_matches(['{', '}']).to_string()).collect();+ let cached: Vec<Value> = found.iter().map(|p| {+ let ps = p.to_string_lossy().to_string();+ let matches = guids.iter().any(|g| ps.to_ascii_lowercase().contains(g.as_str()));+ let modified = std::fs::metadata(p).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs());+ json!({"path": ps, "matchesPreference": matches, "modifiedUnix": modified})+ }).collect();+ let best: Vec<&Value> = cached.iter().filter(|c| c["matchesPreference"] == true).collect();+ let mut r = json!({"success": prefs["success"] == true, "edition": prefs["edition"], "templateFiles": files,+ "entries": entries.iter().map(|e| json!({"kind": e.0, "value": e.1, "itemGuid": e.2})).collect::<Vec<_>>(),+ "cachedLibraries": cached, "localTemplatePath": local, "localLibraries": local_libs});+ if best.len() == 1 { r["template"] = json!({"libraryPath": best[0]["path"]}); }+ r["_hint"] = json!(if pcb.is_empty() {+ "Altium's Template Files names no PCB library template here: give the template yourself (altium_layer_map {action:'from_template', libraryPath, footprint})."+ } else if best.len() == 1 {+ "The cached copy of your PCB library template is template.libraryPath: altium_list_library lists its footprints, then altium_layer_map {action:'from_template', libraryPath, footprint, save:'library'}."+ } else {+ "Your Template Files names a PCB library template, but its cached copy was not told apart from the others (cachedLibraries): open it in Altium once so it is cached, or pick the right path, then altium_layer_map {action:'from_template'}."+ });+ r+}++pub fn layer_map(args: &Value) -> Value {+ match s(args, "action").as_deref().unwrap_or("get") {+ "get" => get(args),+ "set" => set(args),+ "clear" => clear(args),+ "from_template" => from_template(args),+ "find_template" => find_template(args),+ a => json!({"success": false, "errorCode": "bad_args", "error": format!("unknown action {a}: get, set, clear, from_template or find_template")}),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_relative_template_is_read_beside_the_file_that_names_it() {+ assert_eq!(absolute("C:/org/T.PcbLib", Some(Path::new("D:/lib/adom-layer-map.json"))), "C:/org/T.PcbLib");+ let a = absolute("Templates/T.PcbLib", Some(Path::new("/lib/adom-layer-map.json")));+ assert!(a.ends_with("Templates/T.PcbLib") && a.starts_with("/lib"), "{a}");+ }++ #[test]+ fn the_call_map_comes_from_layer_map_and_template() {+ assert!(call_doc(&json!({"libraryPath": "x"})).is_none());+ let d = call_doc(&json!({"layerMap": {"fab": "AssemblyTop"}, "template": {"libraryPath": "T.PcbLib", "footprint": "F"}})).unwrap();+ assert_eq!(d["layerMap"]["fab"], "AssemblyTop");+ assert_eq!(d["template"]["footprint"], "F");+ }+}
bridge-rs/src/library.rs+30−13@@ -122,9 +122,18 @@ pub fn build_footprint(args: &Value) -> Value { if s(args, "libraryPath").unwrap_or_default().is_empty() || s(args, "spec").unwrap_or_default().is_empty() { return json!({"success": false, "error": "libraryPath (.PcbLib) and spec (Windows path to a kicad2altium spec) are required"}); }- with_shot(agent::call("build_footprint",- &[("libraryPath", s_or(args, "libraryPath", "")), ("spec", agent::agent_readable(&s_or(args, "spec", "")))],- None, timeout_of(args, 240)))+ // the layer map in effect (#41): the call's, the library folder's, the user's; none sends nothing+ let lib = s_or(args, "libraryPath", "");+ let (lm, eff) = crate::layermap_verb::agent_params(args, Some(&lib));+ if !eff.errors.is_empty() && args.get("layerMap").is_some() {+ return json!({"success": false, "errorCode": "bad_layer_map", "error": "the layerMap was refused: nothing was built", "refused": eff.errors,+ "_hint": "altium_layer_map {action:'get'} shows the keys and the layer forms it takes."});+ }+ let mut params = vec![("libraryPath", lib.clone()), ("spec", agent::agent_readable(&s_or(args, "spec", "")))];+ params.extend(lm);+ let mut r = with_shot(agent::call("build_footprint", ¶ms, None, timeout_of(args, 240)));+ crate::layermap_verb::report(&mut r, &eff);+ r } pub fn build_symbol_modes(args: &Value) -> Value {@@ -182,12 +191,14 @@ pub fn add_body(args: &Value) -> Value { "_hint": "step:'C:/…/part.step' for a real model, else bwMil/bhMil/hMil/soMil for an extruded box"}), }; let keep = keep_existing(args);- let mut r = lib_call(args, "add_body",- vec![("name", s_or(args, "footprintName", "")), ("step", s_or(args, "step", "")),+ let (lm, eff) = crate::layermap_verb::agent_params(args, Some(&lib));+ let mut params = vec![("name", s_or(args, "footprintName", "")), ("step", s_or(args, "step", "")), ("bw_mil", s_or(args, "bwMil", "100")), ("bh_mil", s_or(args, "bhMil", "100")), ("h_mil", s_or(args, "hMil", "40")), ("so_mil", s_or(args, "soMil", "0")),- ("keep", if keep { "1".into() } else { "0".into() })],- Some(&lib), 90);+ ("keep", if keep { "1".into() } else { "0".into() })];+ params.extend(lm.into_iter().filter(|(k, _)| *k == "lmap"));+ let mut r = lib_call(args, "add_body", params, Some(&lib), 90);+ crate::layermap_verb::report(&mut r, &eff); if r.get("success").and_then(|b| b.as_bool()) == Some(true) { let d = r.get("data").cloned().unwrap_or(json!({})); r["replacedBodies"] = d.get("replacedBodies").cloned().unwrap_or(Value::Null);@@ -727,6 +738,7 @@ pub fn import_part(args: &Value) -> Value { } let mut steps: Vec<Value> = Vec::new(); let mut fp_name: Option<String> = None;+ let mut layer_report: Option<Value> = None; let pcb_lib = s(args, "pcbLib").unwrap_or_default(); let sch_lib = s(args, "schLib").unwrap_or_default(); // Given nothing to import, this used to run zero steps and answer success:true (found by the@@ -739,7 +751,12 @@ pub fn import_part(args: &Value) -> Value { "_hint": "See the altium-part-import skill for the spec format; altium_create_footprint / altium_create_symbol build a single item."}); } if let Some(spec) = s(args, "footprintSpec").filter(|v| !v.is_empty()) {- let r = agent::call("build_footprint", &[("libraryPath", pcb_lib.clone()), ("spec", agent::agent_readable(&spec))], None, Duration::from_secs(240));+ let (lm, eff) = crate::layermap_verb::agent_params(args, Some(&pcb_lib));+ let mut params = vec![("libraryPath", pcb_lib.clone()), ("spec", agent::agent_readable(&spec))];+ params.extend(lm);+ let mut r = agent::call("build_footprint", ¶ms, None, Duration::from_secs(240));+ crate::layermap_verb::report(&mut r, &eff);+ layer_report = r.get("layerMap").cloned(); if r.get("success").and_then(|b| b.as_bool()) != Some(true) { let mut out = r; out["success"] = json!(false);@@ -752,11 +769,11 @@ pub fn import_part(args: &Value) -> Value { if let (Some(step), Some(fp)) = (s(args, "step").filter(|v| !v.is_empty()), fp_name.clone()) { // keep=0: a part imported again REPLACES its 3D body (it used to stack a second one on the // footprint: AMPLH5030S, 2026-10-16), the way build_symbol_modes replaces its symbol.- let r = agent::call("add_body",- &[("libraryPath", pcb_lib.clone()), ("name", fp.clone()), ("step", step),+ let mut params = vec![("libraryPath", pcb_lib.clone()), ("name", fp.clone()), ("step", step), ("bw_mil", "100".into()), ("bh_mil", "100".into()), ("h_mil", "40".into()), ("so_mil", "0".into()),- ("keep", "0".into())],- None, Duration::from_secs(180));+ ("keep", "0".into())];+ params.extend(crate::layermap_verb::agent_params(args, Some(&pcb_lib)).0.into_iter().filter(|(k, _)| *k == "lmap"));+ let r = agent::call("add_body", ¶ms, None, Duration::from_secs(180)); let d = r.get("data").cloned().unwrap_or(json!({})); steps.push(json!({"add_body": r.get("success").and_then(|b| b.as_bool()).unwrap_or(false), "replacedBodies": d.get("replacedBodies"), "bodiesNow": d.get("bodiesNow"),@@ -807,7 +824,7 @@ pub fn import_part(args: &Value) -> Value { let _ = crate::surfaces::save(&json!({"filePath": lib})); } }- json!({"success": true, "symbol": sym_name, "footprint": fp_name, "steps": steps,+ json!({"success": true, "symbol": sym_name, "footprint": fp_name, "steps": steps, "layerMap": layer_report, "_hint": "One-call part import (Barrett's import_part on the resident lane). Importing a part again REPLACES its symbol and its footprint's 3D body (steps[].replacedBodies says how many old bodies went; bodiesNow should be 1). Verify with altium_read_symbol + altium_pcb_report; placed parts pick the change up with PCB:UpdateFootprints."}) }
bridge-rs/src/main.rs+3−1@@ -10,6 +10,8 @@ mod installs; mod keepouts; mod gloss; mod fplayers;+mod layermap;+mod layermap_verb; mod autoclass; mod board; mod bodies;@@ -85,7 +87,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.112";+pub const BRIDGE_VERSION: &str = "0.2.113"; fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> { let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/support.rs+22−1@@ -223,13 +223,34 @@ pub fn open_verdict(path: &str, mut r: Value, file_exists: bool, workspace_unava /// as-is, None when it opened. pub fn must_open(path: &str, timeout_s: u64) -> Option<Value> { let r = agent_open(path, timeout_s);- if r.get("success").and_then(|b| b.as_bool()) == Some(true) { None } else { Some(r) }+ if r.get("success").and_then(|b| b.as_bool()) == Some(true) { None } else { Some(lift_open_error(r)) }+}++/// A failed open says why at the top: the agent's reason ("file not found: ...") sat only in data.error, under an+/// empty error (found on read_footprint, 2026-11-30).+fn lift_open_error(mut r: Value) -> Value {+ if r.get("error").and_then(|e| e.as_str()).unwrap_or("").is_empty() {+ if let Some(e) = r.pointer("/data/error").and_then(|e| e.as_str()).filter(|e| !e.is_empty()).map(str::to_string) {+ if e.starts_with("file not found") && r.get("errorCode").map(|c| c.is_null()).unwrap_or(true) { r["errorCode"] = json!("file_not_found"); }+ r["error"] = json!(e);+ }+ }+ r } #[cfg(test)] mod tests { use super::*; + #[test]+ fn a_failed_open_says_why_at_the_top() {+ let r = lift_open_error(json!({"success": false, "error": "", "data": {"ok": false, "error": "file not found: C:\\x\\a.PcbLib"}}));+ assert_eq!(r["error"], json!("file not found: C:\\x\\a.PcbLib"));+ assert_eq!(r["errorCode"], json!("file_not_found"));+ let kept = lift_open_error(json!({"success": false, "error": "timed out", "errorCode": "timed_out", "data": {"error": "x"}}));+ assert_eq!(kept["error"], json!("timed out"));+ }+ #[test] fn a_document_that_did_not_open_is_a_failure() { let ok = |shown: bool| json!({"success": true, "data": {"ok": true, "shown": shown}});
bridge-rs/src/verbs.rs+13−6@@ -22,7 +22,7 @@ pub const KNOWN: &[&str] = &[ "list_nets", "net_connections", "layers", "copper_layers", "read_rules", "set_layer_visibility", "footprint_primitives", "schematic_data", "layer_stack", "net_classes", "diff_pairs", "board_outline", "set_track_width", "find_space", "selection", "check_orientation", "replicate_layout", "outjob_info", "find_symbol", "part_parameters", // the live-board lane AI Flow drives- "sch_no_connect", "sch_label", "sch_wire", "edit_tracks", "select_items", "preferences", "extensions", "cancel_run", "physical_properties", "model_check", "place_parts", "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "simulate", "export_spice", "update_footprints_from_library", "lint_library", "export_pos", "verb_times", "prewarm", "render_board", "log_tail", "sch_batch", "import_step", "edit_pours", "export_3d", "tool_update", "import_design", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "gloss", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",+ "sch_no_connect", "sch_label", "sch_wire", "edit_tracks", "select_items", "preferences", "extensions", "cancel_run", "physical_properties", "model_check", "place_parts", "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "simulate", "export_spice", "update_footprints_from_library", "lint_library", "export_pos", "verb_times", "prewarm", "render_board", "log_tail", "sch_batch", "import_step", "edit_pours", "export_3d", "tool_update", "import_design", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "gloss", "layer_map", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen", // surfaces "show_project", "show_schematic", "show_2d_board", "show_3d_board", "show_library", "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo",@@ -113,8 +113,8 @@ fn describe() -> Value { json!({"findings": "[{check, severity, message, ...}]", "counts": "{}", "skipped": "{}", "notImplemented": "{}"}), 120, "PARTIAL results by design: skipped says which checks had no data; a clean result means the checks that RAN found nothing.", &["read_board", "cross_check"], &["Altium holds ONE current document - the review activates board and sheet in turn."], json!({"includeSchematic": true})),- verb_doc("import_part", "One call imports a whole part: footprint spec + STEP + symbol modes + models + params + save.", json!({"schLib": "path", "pcbLib": "path", "footprintSpec": "path", "symbolSpec": "path", "step": "path", "params": "{}", "comment": "string", "description": "string"}),- json!({"symbol": "string", "footprint": "string", "steps": "[] - the add_body step carries replacedBodies, bodiesNow, sameNameFootprints"}), 300,+ verb_doc("import_part", "One call imports a whole part: footprint spec + STEP + symbol modes + models + params + save.", json!({"schLib": "path", "pcbLib": "path", "footprintSpec": "path", "symbolSpec": "path", "step": "path", "params": "{}", "comment": "string", "description": "string", "layerMap": "{key: layer} optional (#41): footprint and 3D body layers; else adom-layer-map.json beside pcbLib, else your default (altium_layer_map)", "template": "{libraryPath, footprint} optional: the footprint new ones start from"}),+ json!({"symbol": "string", "footprint": "string", "steps": "[] - the add_body step carries replacedBodies, bodiesNow, sameNameFootprints", "layerMap": "the footprint's layer map: each key's layer and where the setting came from"}), 300, "Check the step counts: models:0 fails the call - a symbol with no footprint model places with nothing attached. Importing again REPLACES the symbol and the footprint's 3D body (add_body step: bodiesNow 1); boards that place the part need PCB:UpdateFootprints.", &["read_symbol", "show_symbol"], &["add_models APPENDS on every call (not idempotent) - repair is remove_symbol + re-import.", "The add_body step's sameNameFootprints > 1 means the library holds stale footprints of that name: the body went to the FIRST only.", "The first part into a NEW library can silently skip models+params if the bridge restarted mid-flight - verify with read_symbol."], json!({})), verb_doc("test_board", "Place one footprint, or a ';' list, from the open PcbLib on ONE board: a NEW board (wMm x hMm outline) when pcbPath is new or omitted, APPENDED to the existing board when pcbPath already exists (issue 11).",@@ -589,6 +589,12 @@ fn describe() -> Value { json!({"glossed": "bool", "tracksSelected": "int", "nets": "[{net, lengthMm:[before, after], segments:[..], corners:[..]}] the nets that changed, most shortened first", "totalLengthMm": "[before, after] of the glossed nets", "protected": "{lengthRuled:[net], differentialPairs:[net], lockedTracks, lockedOn:[net]}", "offAngle": "{net: tracks} Gloss leaves alone: not at a multiple of 45 degrees", "drc": "{before, after, new:[violation], cleared, clean}", "unconnected": "[before, after]", "repoured": "bool|null", "glossEffort": "Altium's Gloss and Retrace effort preference", "saved": "false", "undo": "how to go back"}), 900, "Gloss works on tracks at multiples of 45 degrees (altium_plan_route's routes are); other tracks are left as they are and listed in offAngle. Locked tracks are left alone too. A net tuned for length with no rule behind it cannot be told from the board, so all:true can straighten it: exclude it or lock its tracks. Gloss cannot be undone from a script: the board is left unsaved, and reopening it without saving goes back.", &["plan_route", "route_net", "routing_state", "repour", "routing_drc", "save"], &["Needs a board with routed tracks.", "Takes a few seconds per thousand tracks, plus a repour and two batch DRCs.", "The board is left unsaved."], json!({"nets": ["N1", "GND"]})),+ verb_doc("layer_map", "Choose which Altium layer each kind of footprint graphic goes on (silkscreen, fab/assembly, courtyard, 3D body, centroid, designator, ...) and the template footprint new footprints start from, per call, per library folder (your organisation's default) or as your own default. Reads a template footprint and proposes the map from the typed layers it uses (Top Assembly, Top Courtyard, ...), and finds the PCB library template in Altium's Template Files setting.",+ json!({"action": "get (default) | set | clear | from_template | find_template", "libraryPath": "the library (or its folder): get shows the map in effect there; set/clear scope:'library' write adom-layer-map.json beside it; from_template reads the template from it", "scope": "user | library (set, clear)", "layerMap": "{key: layer} (set, and the footprint verbs per call). Keys: overlay, fab, courtyard, body3d, comment, balls, centroid, designator, outline, dimensions. A layer is a type (CourtyardTop, AssemblyTop, 3DBodyTop, ...), a name (Top Courtyard, Mechanical 15) or an id; null removes a key", "template": "{libraryPath, footprint}: the footprint new footprints start from (set, and per call)", "replace": "bool (set): replace the scope's map instead of merging into it", "keys": "[key] (clear): only these keys ('template' for the template); all when omitted", "footprint": "the template footprint (from_template)", "save": "user | library (from_template): keep the proposal in that scope", "edition": "Altium Designer | Altium Designer Develop (find_template)"}),+ json!({"layerMap": "{keys: {key: {asked, source: call|library|user|built-in, layer?, layerId?, kind?, used?}}, template?, refused?}", "files": "{user, library}: {path, exists} (get)", "written": "path (set)", "proposal": "{layerMap, template} (from_template)", "templateCopy": "what a footprint keeps from the template (from_template)", "entries": "[{kind, value, itemGuid}] Altium's Template Files (find_template)", "cachedLibraries": "[{path, matchesPreference}] (find_template)", "template": "{libraryPath} when one cached copy matches (find_template)"}), 120,+ "Precedence per key: the call's layerMap, then adom-layer-map.json beside the library, then your default, then the bridge's built-in layers (unchanged when nothing is set). A typed layer the library or board lacks is made as a top/bottom pair the first time it is used. The footprint verbs (build_footprint, footprint_from_land_pattern, import_part, add_body) take layerMap and template per call and report the map they used.",+ &["read_footprint", "build_footprint", "import_part", "add_body", "list_library"], &["A layer type can be made only as a pair (Top and Bottom Courtyard): Altium's single-layer kinds (Board, Dimensions, V Cut, ...) are reached by name.", "outline and dimensions are accepted and reported but nothing the bridge draws goes there yet.", "From a template a footprint keeps its special strings (.Designator) and its Component Center graphics; the example pad, outline, courtyard, assembly drawing and dimensions stay behind."],+ json!({"action": "from_template", "libraryPath": "C:/org/Templates.PcbLib", "footprint": "Default Footprint", "save": "library"})), verb_doc("repour", "Repour every polygon on the board (Altium's Repour All) and answer the copper after. Runs outside the script engine so scoped rules apply.", json!({"inScript": "bool (default false) - repour from inside the agent instead (scoped rules then match nothing)"}), json!({"zones": "[...]", "filledAreaByLayerMm2": "{...}", "unfilled": "[...]", "run": "{helperExited, seconds, agentStart}"}), 600, "Run after moving parts or copper that pours flow around. Altium evaluates rule queries through its scripting system, so a repour from inside the resident agent ignores every scoped rule (a pour's own connect style, net-class clearances); this verb stops the agent, repours, and starts it again (a few seconds). apply_pours does the same on its own when it wrote connect rules.",@@ -1384,7 +1390,7 @@ fn describe() -> Value { &["A fresh library carries the stray Component_1: altium_cleanup_libs.", "Pin offsets are mils along the chosen side; check shot.image for overlapping pins."], json!({"name": "CH340G", "libraryPath": "C:/lib/Test.SchLib", "pins": "1,GND,left,100;2,TXD,left,200;16,VCC,right,100"})), verb_doc("footprint_from_land_pattern", "Build a complete footprint from the land pattern a datasheet prints: pads numbered the standard way (chip, dual SOIC/TSSOP/DFN, SOT, quad QFP/QFN, BGA), an exposed pad, the courtyard, silkscreen kept clear of the copper with a pin-1 dot, a fab outline with a pin-1 chamfer, and an extruded 3D body when the height is given.",- json!({"libraryPath": ".PcbLib (required unless dryRun; created if missing)", "name": "footprint name (required)", "family": "chip | dual | sot | quad | bga",+ json!({"libraryPath": ".PcbLib (required unless dryRun; created if missing)", "name": "footprint name (required)", "layerMap": "{key: layer} optional (#41): which Altium layer each kind of graphic goes on, e.g. {fab: AssemblyTop, courtyard: CourtyardTop}; beats the library folder's adom-layer-map.json and your default (altium_layer_map)", "template": "{libraryPath, footprint} optional: the footprint new ones start from (its .Designator and centroid marker)", "family": "chip | dual | sot | quad | bga", "pins": "dual/quad total", "leftPins": "sot", "rightPins": "sot", "pinsPerSideX": "quad, top/bottom", "pinsPerSideY": "quad, left/right", "pitch": "mm", "span": "mm, pad centre to pad centre across the rows (quad: left-right)", "spanY": "quad, top-bottom (default span)", "padLength": "mm, along the lead (across the row)", "padWidth": "mm, along the row", "ballPad": "bga pad diameter mm", "rows": "bga", "cols": "bga", "missing": "bga ['B2', ...]",@@ -1396,7 +1402,7 @@ fn describe() -> Value { &["The numbers are the datasheet's RECOMMENDED LAND PATTERN, not the package outline: pad size and the pad-centre span.", "Pin 1 is top-left (Y up), counter-clockwise, the IPC convention."], json!({"libraryPath": "C:\\\\lib\\\\Parts.PcbLib", "name": "SOIC-8_3.9x4.9mm_P1.27mm", "family": "dual", "pins": 8, "pitch": 1.27, "span": 5.4, "padLength": 1.55, "padWidth": 0.6, "body": {"w": 3.9, "l": 4.9, "height": 1.75}})), verb_doc("build_footprint", "Build a complete footprint (pads, silkscreen, courtyard, arcs) in a PcbLib from a kicad2altium spec file on this machine, and return a proof frame.",- json!({"libraryPath": "path to a .PcbLib (required; created if missing)", "spec": "Windows path to the spec (tools/kicad2altium.py output; mm, Y up) (required)", "timeout": "seconds, default 240"}),+ json!({"libraryPath": "path to a .PcbLib (required; created if missing)", "spec": "Windows path to the spec (tools/kicad2altium.py output; mm, Y up) (required)", "timeout": "seconds, default 240", "layerMap": "{key: layer} optional (#41): which Altium layer each kind of graphic goes on, e.g. {fab: AssemblyTop, courtyard: CourtyardTop}; beats the library folder's adom-layer-map.json and your default (altium_layer_map)", "template": "{libraryPath, footprint} optional: the footprint new ones start from (its .Designator and centroid marker)"}), json!({"data": "{footprint, description, library, libraryState, pads, throughHolePads, drawingPrimitives}", "shot": "{image: base64 png, width, height}", "windowEtiquette": "background"}), 240, "Stage the spec with ab's send_files first. Then altium_add_body {step}, altium_plate_vias for thermal vias, altium_save. altium_import_part does all of it in one call.", &["import_part", "add_body", "plate_vias", "show_footprint"],@@ -1410,7 +1416,7 @@ fn describe() -> Value { &["libref comes from the spec's META line.", "Compare data.displayModeCount with data.modes before trusting the alternates.", "Library is left UNSAVED."], json!({"libraryPath": "C:/lib/Adom_ToF.SchLib", "spec": "C:/lib/specs/VL53L5CX.sym.txt"})), verb_doc("add_body", "Put a 3D body on a footprint of a PcbLib: a STEP model, or an extruded box when no step is given. It REPLACES the footprint's existing 3D bodies (a re-import never stacks a second model) unless keepExisting:true. The bridge then re-aligns bodies onto the pads (normalize_bodies) and returns a frame.",- json!({"libraryPath": "path to a .PcbLib (required)", "footprintName": "string - required when the library holds more than one footprint", "step": "Windows path to a .step - optional", "bwMil": "int, default 100 - box width", "bhMil": "int, default 100 - box depth", "hMil": "int, default 40 - box height", "soMil": "int, default 0 - standoff", "keepExisting": "bool, default false - ADD next to the existing bodies instead of replacing them (a deliberate second body)", "timeout": "seconds, default 90"}),+ json!({"libraryPath": "path to a .PcbLib (required)", "layerMap": "{body3d: layer} optional (#41): the 3D body's layer, e.g. 3DBodyTop; else the library's or your map, else Mechanical 1", "footprintName": "string - required when the library holds more than one footprint", "step": "Windows path to a .step - optional", "bwMil": "int, default 100 - box width", "bhMil": "int, default 100 - box depth", "hMil": "int, default 40 - box height", "soMil": "int, default 0 - standoff", "keepExisting": "bool, default false - ADD next to the existing bodies instead of replacing them (a deliberate second body)", "timeout": "seconds, default 90"}), json!({"data": "{footprint, body, replacedBodies, keptExisting, bodiesBefore, sameNameFootprints, bodiesNow, bodiesOnCanvas}", "replacedBodies": "int - old bodies removed before the add", "normalized": "string - the shifts applied", "shot": "{image: base64 png, width, height}", "_hint": "string - what was replaced, and a WARNING when bodies are still stacked"}), 90, "altium_save {filePath: libraryPath}, then altium_show_3d_chip to look at it; boards that already place the part need PCB:UpdateFootprints. Never engrave the MPN into the STEP.", &["normalize_bodies", "show_3d_chip", "pcb_report", "import_part", "footprint_primitives"],@@ -2163,6 +2169,7 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "remove_pours" => { if let Some(g) = need_licensed() { return g; } crate::routing::remove_pours(args) } "repour" => { if let Some(g) = need_licensed() { return g; } crate::routing::repour(args) } "gloss" => crate::gloss::gloss(args),+ "layer_map" => crate::layermap_verb::layer_map(args), "routing_drc" => { if let Some(g) = need_licensed() { return g; } crate::routing::routing_drc(args) } "build_board" => { if let Some(g) = need_licensed() { return g; } crate::routing::build_board(args) } "set_outline" => { if let Some(g) = need_licensed() { return g; } crate::routing::set_outline(args) }
dev-skills/altium-bridge-test/run_verb_tests.py+3@@ -471,6 +471,9 @@ def matrix(w): M["project_info"] = dict(phase=3.5, **ok(project=LP), check=lambda d: d.get("name") == "lane" and len(d.get("files") or []) >= 3) M["cross_probe"] = dict(phase=3.5, **ok(filePath=LB, ref="U1"), check=lambda d: len(d.get("matches") or []) == 1) M["read_footprint"] = dict(phase=3.5, **ok(libraryPath=PL, name="TST_SOIC8"), check=lambda d: len(d.get("pads") or []) == 8)+ # 0.2.113: the layer map (#41). A read: the battery's library has no map file, so every key is built-in+ M["layer_map"] = dict(phase=3.5, **ok(action="get", libraryPath=PL),+ check=lambda d: (d.get("layerMap") or {}).get("keys", {}).get("fab", {}).get("source") in ("built-in", "user", "library")) M["project_create"] = dict(phase=3.5, timeout=320, **ok(parentDir=D, name="NewProj", layers=4), check=lambda d: len(d.get("files") or []) == 3) M["project_rename"] = dict(phase=3.5, **ok(project=D + "/NewProj/NewProj.PrjPcb", newName="NewProj2", dryRun=True), check=lambda d: len(d.get("renamed") or []) == 3) M["project_snapshot"] = dict(phase=3.5, **ok(project=LP, label="battery", pdfs=False), check=lambda d: len(d.get("files") or []) >= 3)
docs/discovery-triggers-all.json+256−252@@ -1,253 +1,257 @@ {- "note": "Every search phrase this page carried before the wiki limited a page to 50 discovery triggers (2026-11-25). package.json carries the 50 kept.",- "triggers": [- "open my design in altium",- "show me the board in altium",- "open altium",- "launch altium designer",- "altium schematic",- "altium pcb",- "show the pcb in 3d in altium",- "altium 3d board",- "run drc in altium",- "altium design rule check",- "compile my altium project",- "altium erc",- "generate gerbers from altium",- "altium gerber",- "altium outjob",- "run the output job",- "altium bom",- "export bom from altium",- "altium pick and place",- "altium odb++",- "open an altium library",- "altium symbol",- "altium footprint",- "altium schlib",- "altium pcblib",- "run a delphiscript in altium",- "altium script",- "altium eval",- "altium process launcher",- "control altium designer",- "drive altium",- "automate altium",- "altium bridge",- "altium demo",- "altium screenshot",- "what is open in altium",- "altium dialog",- "altium not responding",- "add a part to my altium library",- "import a component into altium",- "altium part with lcsc number",- "altium part with mouser number",- "add a resistor to altium",- "import kicad symbol into altium",- "kicad to altium",- "convert kicad library to altium",- "altium intlib import",- "ai for altium",- "altium ai",- "ai altium designer",- "let an ai run altium",- "chatgpt altium",- "claude altium",- "altium copilot",- "altium mcp",- "ai pcb design in altium",- "altium update pcb",- "annotate my altium schematic",- "altium stack-up",- "altium net class",- "altium diff pair",- "altium mounting holes",- "altium fiducials",- "altium stitching vias",- "altium 365 workspace part",- "altium jlcpcb bom",- "altium step export",- "altium multi-part symbol",- "altium no erc",- "altium hierarchical schematic",- "altium sheet symbol",- "altium sheet entry",- "add a sheet in altium",- "altium netlist",- "check my altium netlist",- "altium port",- "make an altium footprint from a datasheet",- "altium footprint from land pattern",- "altium qfn footprint",- "altium soic footprint",- "altium bga footprint",- "altium footprint wizard",- "altium ipc footprint",- "altium silkscreen over pads",- "altium silkscreen preparation",- "clip silkscreen altium",- "altium silk to solder mask",- "altium net length",- "altium length matching",- "altium matched length rule",- "altium differential pair rule",- "altium teardrops",- "altium room",- "altium component class",- "altium via style rule",- "altium skew",- "altium odb++ export",- "altium ipc-2581 export",- "export odb++ from altium",- "altium assembly drawing pdf",- "altium fabrication drawing",- "altium keepout",- "altium polygon connect style rule",- "altium impedance calculator",- "altium controlled impedance trace width",- "altium 90 ohm usb differential pair width",- "altium trace current capacity",- "will this trace carry 3a altium",- "altium panelize",- "altium panel array step and repeat",- "altium fab capability check",- "read altium schdoc without altium",- "altium v-score panel",- "altium v-cut panel jlcpcb",- "altium mouse bites panel",- "panelize for jlcpcb",- "altium component height check enclosure",- "altium 3d clearance check",- "altium copper balance",- "altium return path check",- "signal crossing a split plane altium",- "jlcpcb design rule check altium",- "check my altium board against jlcpcb capabilities",- "jlcpcb assembly check",- "is my board ready for jlcpcb assembly",- "altium place reference designators",- "designators overlapping pads altium",- "altium via fence",- "via stitching along rf trace",- "altium jlcpcb order files",- "export altium board for jlcpcb order",- "altium gerber zip for jlcpcb",- "fix return path gap altium",- "altium schematic review",- "check altium schematic before update pcb",- "altium footprint pin mismatch",- "altium differential pair routing",- "route usb pair in altium",- "altium length matching serpentine",- "altium thermal vias exposed pad",- "altium placement check",- "altium board report pdf",- "altium net classes automatically",- "altium jlcpcb design rules",- "flip a part to the bottom side in altium",- "move a component to the other side of the altium board",- "altium 3d body sizes of every part",- "wire these pins together in altium",- "add a bus in an altium schematic",- "altium schematic junction dots and labels",- "trace a net on an altium schematic sheet",- "create a new schematic sheet in altium",- "altium sheet hierarchy page numbers",- "render an altium schematic to an image",- "update altium symbols from library",- "remove a part from the altium board",- "align parts in altium",- "change altium board layer count to 4",- "copy routing to another channel in altium",- "altium part clearance check",- "export ipc-2581 from altium",- "check my altium board against pcbway limits",- "which altium documents are open",- "close all altium documents without losing changes",- "altium project summary",- "create a new altium project",- "rename an altium project",- "snapshot my altium project",- "cross probe altium schematic to pcb",- "read an altium footprint's pads",- "export one part from an altium library",- "make a demo project for an altium part",- "render altium board in 3d to an image",- "render altium copper layer to png",- "show altium symbol and footprint images",- "export ipc-356 netlist from altium",- "export gencad from altium",- "export altium board layers to dxf",- "altium board outline dxf for enclosure",- "import svg logo onto altium pcb",- "add a logo to altium silkscreen",- "edit an altium footprint's pads",- "renumber pads in an altium footprint",- "generate a 3d step body for a soic",- "make a 3d model from package dimensions",- "route a net between two pads in altium",- "find a path for a trace in altium",- "plan a route in altium",- "route one net in altium",- "place decoupling caps in altium",- "fan out a bga in altium",- "escape routing for a qfn in altium",- "estimate pcb cost from altium",- "how much will this altium board cost",- "simulate this circuit in altium",- "run an ac analysis in altium",- "transient simulation in altium",- "spice netlist from altium",- "altium mixed signal simulation",- "update footprints from library in altium",- "bring altium footprints up to date with the library",- "replace placed footprints with the library version",- "lint my altium library",- "check an altium library before i ship it",- "does every symbol pin have a pad altium",- "export pick and place from altium",- "altium cpl file for jlcpcb",- "altium centroid file",- "how long do altium verbs take",- "prewarm the altium bridge",- "render my altium board",- "apply several schematic edits at once in altium",- "undo a batch of altium schematic changes",- "altium messages panel warnings",- "what did altium complain about",- "check my altium schematic for dangling wires",- "altium schematic label not on a wire",- "overlapping symbols altium schematic",- "export my altium board as parasolid",- "altium vrml export",- "edit a polygon pour in altium",- "place an enclosure step with my altium board",- "does the board fit the enclosure altium",- "which altium version is installed",- "import an eagle design into altium",- "eagle to altium",- "import eagle board into altium",- "check for altium updates",- "is there a newer altium version",- "turn off altium update check",- "place a no connect flag in altium",- "no erc marker altium",- "add a net label on a wire in altium",- "draw a wire in altium schematic",- "place footprints on an altium board",- "change a track width in altium",- "check 3d models on an altium board",- "list altium extensions",- "read altium preferences",- "change an altium setting",- "select parts in altium",- "cancel a running altium job",- "release my altium licence seat",- "gloss the routing in altium",- "tidy up traces in altium",- "altium gloss selected",- "shorten routes in altium",- "clean up routing in altium"- ]-}+ "note": "Every search phrase this page carried before the wiki limited a page to 50 discovery triggers (2026-11-25). package.json carries the 50 kept.",+ "triggers": [+ "open my design in altium",+ "show me the board in altium",+ "open altium",+ "launch altium designer",+ "altium schematic",+ "altium pcb",+ "show the pcb in 3d in altium",+ "altium 3d board",+ "run drc in altium",+ "altium design rule check",+ "compile my altium project",+ "altium erc",+ "generate gerbers from altium",+ "altium gerber",+ "altium outjob",+ "run the output job",+ "altium bom",+ "export bom from altium",+ "altium pick and place",+ "altium odb++",+ "open an altium library",+ "altium symbol",+ "altium footprint",+ "altium schlib",+ "altium pcblib",+ "run a delphiscript in altium",+ "altium script",+ "altium eval",+ "altium process launcher",+ "control altium designer",+ "drive altium",+ "automate altium",+ "altium bridge",+ "altium demo",+ "altium screenshot",+ "what is open in altium",+ "altium dialog",+ "altium not responding",+ "add a part to my altium library",+ "import a component into altium",+ "altium part with lcsc number",+ "altium part with mouser number",+ "add a resistor to altium",+ "import kicad symbol into altium",+ "kicad to altium",+ "convert kicad library to altium",+ "altium intlib import",+ "ai for altium",+ "altium ai",+ "ai altium designer",+ "let an ai run altium",+ "chatgpt altium",+ "claude altium",+ "altium copilot",+ "altium mcp",+ "ai pcb design in altium",+ "altium update pcb",+ "annotate my altium schematic",+ "altium stack-up",+ "altium net class",+ "altium diff pair",+ "altium mounting holes",+ "altium fiducials",+ "altium stitching vias",+ "altium 365 workspace part",+ "altium jlcpcb bom",+ "altium step export",+ "altium multi-part symbol",+ "altium no erc",+ "altium hierarchical schematic",+ "altium sheet symbol",+ "altium sheet entry",+ "add a sheet in altium",+ "altium netlist",+ "check my altium netlist",+ "altium port",+ "make an altium footprint from a datasheet",+ "altium footprint from land pattern",+ "altium qfn footprint",+ "altium soic footprint",+ "altium bga footprint",+ "altium footprint wizard",+ "altium ipc footprint",+ "altium silkscreen over pads",+ "altium silkscreen preparation",+ "clip silkscreen altium",+ "altium silk to solder mask",+ "altium net length",+ "altium length matching",+ "altium matched length rule",+ "altium differential pair rule",+ "altium teardrops",+ "altium room",+ "altium component class",+ "altium via style rule",+ "altium skew",+ "altium odb++ export",+ "altium ipc-2581 export",+ "export odb++ from altium",+ "altium assembly drawing pdf",+ "altium fabrication drawing",+ "altium keepout",+ "altium polygon connect style rule",+ "altium impedance calculator",+ "altium controlled impedance trace width",+ "altium 90 ohm usb differential pair width",+ "altium trace current capacity",+ "will this trace carry 3a altium",+ "altium panelize",+ "altium panel array step and repeat",+ "altium fab capability check",+ "read altium schdoc without altium",+ "altium v-score panel",+ "altium v-cut panel jlcpcb",+ "altium mouse bites panel",+ "panelize for jlcpcb",+ "altium component height check enclosure",+ "altium 3d clearance check",+ "altium copper balance",+ "altium return path check",+ "signal crossing a split plane altium",+ "jlcpcb design rule check altium",+ "check my altium board against jlcpcb capabilities",+ "jlcpcb assembly check",+ "is my board ready for jlcpcb assembly",+ "altium place reference designators",+ "designators overlapping pads altium",+ "altium via fence",+ "via stitching along rf trace",+ "altium jlcpcb order files",+ "export altium board for jlcpcb order",+ "altium gerber zip for jlcpcb",+ "fix return path gap altium",+ "altium schematic review",+ "check altium schematic before update pcb",+ "altium footprint pin mismatch",+ "altium differential pair routing",+ "route usb pair in altium",+ "altium length matching serpentine",+ "altium thermal vias exposed pad",+ "altium placement check",+ "altium board report pdf",+ "altium net classes automatically",+ "altium jlcpcb design rules",+ "flip a part to the bottom side in altium",+ "move a component to the other side of the altium board",+ "altium 3d body sizes of every part",+ "wire these pins together in altium",+ "add a bus in an altium schematic",+ "altium schematic junction dots and labels",+ "trace a net on an altium schematic sheet",+ "create a new schematic sheet in altium",+ "altium sheet hierarchy page numbers",+ "render an altium schematic to an image",+ "update altium symbols from library",+ "remove a part from the altium board",+ "align parts in altium",+ "change altium board layer count to 4",+ "copy routing to another channel in altium",+ "altium part clearance check",+ "export ipc-2581 from altium",+ "check my altium board against pcbway limits",+ "which altium documents are open",+ "close all altium documents without losing changes",+ "altium project summary",+ "create a new altium project",+ "rename an altium project",+ "snapshot my altium project",+ "cross probe altium schematic to pcb",+ "read an altium footprint's pads",+ "export one part from an altium library",+ "make a demo project for an altium part",+ "render altium board in 3d to an image",+ "render altium copper layer to png",+ "show altium symbol and footprint images",+ "export ipc-356 netlist from altium",+ "export gencad from altium",+ "export altium board layers to dxf",+ "altium board outline dxf for enclosure",+ "import svg logo onto altium pcb",+ "add a logo to altium silkscreen",+ "edit an altium footprint's pads",+ "renumber pads in an altium footprint",+ "generate a 3d step body for a soic",+ "make a 3d model from package dimensions",+ "route a net between two pads in altium",+ "find a path for a trace in altium",+ "plan a route in altium",+ "route one net in altium",+ "place decoupling caps in altium",+ "fan out a bga in altium",+ "escape routing for a qfn in altium",+ "estimate pcb cost from altium",+ "how much will this altium board cost",+ "simulate this circuit in altium",+ "run an ac analysis in altium",+ "transient simulation in altium",+ "spice netlist from altium",+ "altium mixed signal simulation",+ "update footprints from library in altium",+ "bring altium footprints up to date with the library",+ "replace placed footprints with the library version",+ "lint my altium library",+ "check an altium library before i ship it",+ "does every symbol pin have a pad altium",+ "export pick and place from altium",+ "altium cpl file for jlcpcb",+ "altium centroid file",+ "how long do altium verbs take",+ "prewarm the altium bridge",+ "render my altium board",+ "apply several schematic edits at once in altium",+ "undo a batch of altium schematic changes",+ "altium messages panel warnings",+ "what did altium complain about",+ "check my altium schematic for dangling wires",+ "altium schematic label not on a wire",+ "overlapping symbols altium schematic",+ "export my altium board as parasolid",+ "altium vrml export",+ "edit a polygon pour in altium",+ "place an enclosure step with my altium board",+ "does the board fit the enclosure altium",+ "which altium version is installed",+ "import an eagle design into altium",+ "eagle to altium",+ "import eagle board into altium",+ "check for altium updates",+ "is there a newer altium version",+ "turn off altium update check",+ "place a no connect flag in altium",+ "no erc marker altium",+ "add a net label on a wire in altium",+ "draw a wire in altium schematic",+ "place footprints on an altium board",+ "change a track width in altium",+ "check 3d models on an altium board",+ "list altium extensions",+ "read altium preferences",+ "change an altium setting",+ "select parts in altium",+ "cancel a running altium job",+ "release my altium licence seat",+ "gloss the routing in altium",+ "tidy up traces in altium",+ "altium gloss selected",+ "shorten routes in altium",+ "clean up routing in altium",+ "use my company footprint layers in altium",+ "altium template footprint",+ "altium typed component layers",+ "put footprints on top courtyard and top assembly in altium"+ ]+}
package.json+2−2@@ -1,6 +1,6 @@ { "slug": "altium-bridge",- "version": "0.2.112",+ "version": "0.2.113", "type": "app", "description": "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.", "tags": [@@ -100,7 +100,7 @@ "altium panelize", "is my board ready for jlcpcb assembly", "altium jlcpcb order files",- "jlcpcb design rule check altium",+ "use my company footprint layers in altium", "altium mounting holes", "altium stitching vias", "altium teardrops",
page.json+3−3@@ -4,7 +4,7 @@ "type": "app", "title": "Altium Bridge: AI for Altium Designer", "brief": "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.",- "version": "0.2.112",+ "version": "0.2.113", "hero": { "type": "image", "path": "screenshots/hero.png"@@ -88,7 +88,7 @@ "altium panelize", "is my board ready for jlcpcb assembly", "altium jlcpcb order files",- "jlcpcb design rule check altium",+ "use my company footprint layers in altium", "altium mounting holes", "altium stitching vias", "altium teardrops",@@ -159,4 +159,4 @@ "tools/symbol_modes.py", "uninstall.sh" ]-}+}
scripts/release.py+4@@ -222,6 +222,10 @@ def lint_agent_script(): u = re.search(r"(?<![A-Za-z0-9_.])" + re.escape(low) + r"(?![A-Za-z0-9_])", decl_code[:pos], flags=re.I) if u: hits.append(f"{name} is used at line {decl_code[:u.start()].count(chr(10)) + 1} before its declaration at line {decl_code[:pos].count(chr(10)) + 1}")+ # AllLayers leaves out mechanical layers above 16, where AD 24+ keeps its typed component layers: an iterator+ # with it read a footprint on them as empty and dropped them when placing it (#41). LayerSetUtils.AllLayers.+ for m in re.finditer(r"AddFilter_LayerSet\(\s*AllLayers\s*\)", code):+ hits.append(f"AddFilter_LayerSet(AllLayers) skips typed layers: use AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers) (line {code[:m.start()].count(chr(10)) + 1})") # A reserved word as a parameter or variable name halts the engine at compile: a parameter named Out did # (2026-11-30, #41). Out is a parameter modifier in DelphiScript. for m in re.finditer(r"(?:\(|;)\s*(?:Var\s+|Const\s+)?(Out|Type|Label)\s*:\s*[A-Za-z]", code, flags=re.I):
skills/altium-libraries/SKILL.md+31−6@@ -3,8 +3,8 @@ name: altium-libraries description: >- Author native Altium libraries through altium-bridge: symbols with display modes, footprints and variants, persistent 3D bodies, Mouser + DigiKey + LCSC parameters, the pin-1 check. Use when- creating or editing .SchLib/.PcbLib content, binding 3D bodies, footprint variants, or verifying- pin-1.+ creating or editing .SchLib/.PcbLib content, binding 3D bodies, footprint variants, verifying+ pin-1, or putting footprints on your organisation's layers (layer map, template footprint, typed layers). --- Parent skill: **altium-bridge**@@ -66,12 +66,38 @@ included. Save afterwards. - **Via pads**: through-hole pads sharing a designator (16 × "49") all map to that pin — the heatsink-via convention; real copper + drill, carried to the board and the drill file. - **Rounded-rect pads**: `eRoundedRectangular` + `SetState_StackCRPctOnLayer` (KiCad ratio ×100).-- **Layer map**: F.SilkS→Top Overlay, F.Fab→Mechanical 13 "Fab", F.CrtYd→Mechanical 15- "Courtyard", User.9→Mechanical 9 renamed **"Adom.SolderBalls"** (hidden by default).+- **Layers (built-in)**: F.SilkS→Top Overlay, F.Fab→Mechanical 13 "Fab", F.CrtYd→Mechanical 15+ "Courtyard", User.9→Mechanical 9 renamed **"Adom.SolderBalls"** (hidden by default). An organisation's own+ layers come from the layer map, below. - KiCad Y-down is flipped; filled discs are full arcs at r/2 with stroke r. - Pads must carry a Layer or they are SILENTLY DROPPED (measured); `Bottom*/Mid*` pad size properties do not exist in this engine (halt). +## Your organisation's layers and template footprint: `altium_layer_map` (0.2.113, #41)++Footprints the bridge makes (`build_footprint`, `footprint_from_land_pattern`, `import_part`, the wiki import,+`add_body`) can land on an organisation's own layers and start from its template footprint.++- **The map**: keys `overlay`, `fab`, `courtyard`, `body3d`, `comment`, `balls`, `centroid`, `designator` (and+ `outline`, `dimensions`, accepted but nothing is drawn there yet). A value is a layer type of AD 24++ (`AssemblyTop`, `CourtyardTop`, `3DBodyTop`, `ComponentCenterTop`, `DesignatorTop`, ...), a layer name+ (`Top Courtyard`, `Mechanical 15`) or an id. A type the library lacks is made as a top/bottom pair (Altium types+ only pairs; one pair of each kind per library or board).+- **Where it lives**, per key, first wins: the call's `layerMap`, then `adom-layer-map.json` beside the library (the+ organisation's default: commit it with the library), then your default, then the built-in layers above. With+ nothing set, footprints come out exactly as before. Every footprint verb's reply has `layerMap`: each key's layer+ and where the setting came from.+- **From a template**: `altium_layer_map {action:'from_template', libraryPath, footprint, save:'library'}` reads the+ template footprint and proposes the map by the types it uses, and saves it with the template. Each new footprint+ then starts with the template's `.Designator` (kept centred on the origin with a centred text frame) and its+ Component Center graphics; the template's example pad, outline, courtyard, assembly drawing and dimensions stay+ behind (`templateCopy` counts both).+- `find_template` reads Altium's Template Files preference and the cached Workspace copies. `get` shows the map in+ effect for a library; `set` / `clear` change one scope.+- **Placing and copying** (`build_board`, `place_parts`, `swap_footprint`, `xcopy_footprint`, ...) put each typed+ layer's graphics on the board's (or library's) layer of the same type, made with the source's numbers and names+ when missing, so a part flipped to the bottom moves to Bottom Assembly, Bottom Courtyard and so on.+ ## Heatsink vias from an imported library: `altium_plate_vias` (from 0.2.20) adom-lbr writes heatsink vias as pads with a hole inside the thermal pad. Altium loaded those@@ -196,8 +222,7 @@ altium_footprint_from_land_pattern '{"libraryPath":"C:\\lib\\Parts.PcbLib","name the courtyard, in mm from the footprint's origin (not the library's sheet). The courtyard is the extent of a Top Courtyard layer's graphics, else Mechanical 15's, else of everything but the pads. From 0.2.112 it reads the typed component layers of AD 24+ (Top Assembly, Top Courtyard, Top Designator, Top 3D Body, ...): `layerDetails` gives each- layer's Altium name and kind, `texts` the `.Designator` string and other texts. Placing or copying a footprint still- drops graphics on those layers (#41).+ layer's Altium name and kind, `texts` the `.Designator` string and other texts. - `altium_library_views {libraryPath, parts, views?}`: images of the symbol, the footprint and its 3D body (`device` is KiCad's; Altium answers it as not in Altium); a view the part lacks is listed with why. - `altium_export_library_part {part, libraryPath, outputDir?, what?}`: `<part>.SchLib` and `<part>.PcbLib` holding only
src/BRIDGE_VERSION+1−1@@ -1 +1 @@-0.2.112+0.2.113
src/agent/AdomAgent.pas.tmpl+626−176@@ -893,7 +893,7 @@ Begin N := 0; Iter := Board.BoardIterator_Create; Iter.AddFilter_ObjectSet(MkSet(eViolationObject));- Iter.AddFilter_LayerSet(AllLayers);+ Iter.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Iter.AddFilter_Method(eProcessAll); V := Iter.FirstPCBObject; While V <> Nil Do@@ -1522,7 +1522,7 @@ Begin S := ''; GIt := Grp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -1544,7 +1544,7 @@ Begin N := 0; S := ''; GIt := Grp.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -1566,7 +1566,7 @@ Begin N := 0; GIt := Grp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(Kind));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -1587,7 +1587,7 @@ Begin N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -1599,6 +1599,347 @@ Begin Result := N; End; +{ A footprint in a library by name (case ignored), Nil when it has none. }+Function FindFp(PLib : IPCB_Library; Name : String) : IPCB_LibComponent;+Var+ I : Integer;+ F : IPCB_LibComponent;+Begin+ Result := Nil;+ For I := 0 To PLib.ComponentCount - 1 Do+ Begin+ F := PLib.GetComponent(I);+ If UpperCase(F.Name) = UpperCase(Name) Then Begin Result := F; Break; End;+ End;+End;++{ ---- Footprint layers and the layer map (#41) ----+ Since AD 24 a footprint can be drawn on typed component layers (Top Assembly, Top Courtyard, Top Designator, Top 3D+ Body, ...): mechanical layers, usually above Mechanical 16, with a kind. A kind is given to a top/bottom PAIR, never+ to one layer from a script (ML.Kind := K did not hold; LayerPairKind did, AD 26.11 and Develop, 2026-11-30), and a+ board holds one pair of each kind. }++{ The mechanical layer number of a layer id, 0 for any other layer: Mechanical 1-16 keep their old ids (57-72), the+ rest (AD 19+, up to 1024) are 67108864 + N. }+Function MechLayerNo(L : Integer) : Integer;+Begin+ Result := 0;+ If (L >= 57) And (L <= 72) Then Result := L - 56+ Else If (L > 67108864) And (L <= 67109888) Then Result := L - 67108864;+End;++{ A mechanical layer's kind (0 none), -1 for a layer that is not mechanical. }+Function LayerKindOf(Board : IPCB_Board; L : Integer) : Integer;+Var+ N : Integer;+Begin+ Result := -1; N := MechLayerNo(L);+ If N = 0 Then Exit;+ Result := 0;+ Try Result := Board.MasterLayerStack.GetMechanicalLayer(N).Kind; Except Result := 0; End;+End;++{ The name the user sees in Altium: a mechanical layer's own name ("Top Courtyard"), else Altium's layer name.+ LayerStack.LayerObject reads only the low byte of the id (67108921 came back as Mechanical 1), so a mechanical layer+ is looked up by its number. }+Function LayerNameOf(Board : IPCB_Board; L : Integer) : String;+Var+ ML : IPCB_MechanicalLayer;+ N : Integer;+Begin+ Result := Layer2String(L); N := MechLayerNo(L);+ If N = 0 Then Exit;+ Try+ ML := Board.MasterLayerStack.GetMechanicalLayer(N);+ If (ML <> Nil) And (ML.Name <> '') Then Result := ML.Name;+ Except End;+End;++{ One layer as [id, "name", kind] (kind -1 for a layer that is not mechanical). }+Function LayerInfoJson(Board : IPCB_Board; L : Integer) : String;+Begin+ Result := '[' + IntToStr(L) + ',"' + JsonEsc(LayerNameOf(Board, L)) + '",' + IntToStr(LayerKindOf(Board, L)) + ']';+End;++{ Adds L to the comma-wrapped list Seen (',1,33,') and its [id, name, kind] to Acc when it is new. (Out is a reserved+ word in DelphiScript: a parameter named Out halts the engine on compile.) }+Procedure NoteLayer(Board : IPCB_Board; L : Integer; Var Seen : String; Var Acc : String);+Begin+ If Pos(',' + IntToStr(L) + ',', Seen) > 0 Then Exit;+ Seen := Seen + IntToStr(L) + ',';+ If Acc <> '' Then Acc := Acc + ',';+ Acc := Acc + LayerInfoJson(Board, L);+End;++{ The value stored for Key in a ',key=value,' cache, '' when absent. }+Function CacheGet(Cache : String; Key : String) : String;+Var+ P, Q : Integer;+ Rest : String;+Begin+ Result := '';+ P := Pos(',' + Key + '=', Cache);+ If P = 0 Then Exit;+ Rest := Copy(Cache, P + Length(Key) + 2, Length(Cache));+ Q := Pos(',', Rest);+ If Q > 0 Then Result := Copy(Rest, 1, Q - 1) Else Result := Rest;+End;++{ The code a layer map gives Tag in LMap (';fab>k1;courtyard>k11;'): k<kind>, m<n>, i<id> or n<name>; '' unset. }+Function LMapCode(LMap : String; Tag : String) : String;+Var+ P, Q : Integer;+ Rest : String;+Begin+ Result := '';+ P := Pos(';' + Tag + '>', LMap);+ If P = 0 Then Exit;+ Rest := Copy(LMap, P + Length(Tag) + 2, Length(LMap));+ Q := Pos(';', Rest);+ If Q > 0 Then Result := Copy(Rest, 1, Q - 1) Else Result := Rest;+End;++{ The mechanical layer number holding kind K on Board, 0 when there is none. }+Function MechNoOfKind(Board : IPCB_Board; K : Integer) : Integer;+Var+ N : Integer;+ ML : IPCB_MechanicalLayer;+Begin+ Result := 0;+ If K <= 0 Then Exit;+ For N := 1 To 1024 Do+ Begin+ Try+ ML := Board.MasterLayerStack.GetMechanicalLayer(N);+ If ML <> Nil Then If ML.Kind = K Then Begin Result := N; Exit; End;+ Except End;+ End;+End;++{ The enabled mechanical layer named Nm (case ignored), 0 when there is none. }+Function MechNoNamed(Board : IPCB_Board; Nm : String) : Integer;+Var+ N : Integer;+ ML : IPCB_MechanicalLayer;+Begin+ Result := 0;+ For N := 1 To 1024 Do+ Begin+ Try+ ML := Board.MasterLayerStack.GetMechanicalLayer(N);+ If ML <> Nil Then If ML.MechanicalLayerEnabled And (UpperCase(ML.Name) = UpperCase(Nm)) Then Begin Result := N; Exit; End;+ Except End;+ End;+End;++{ A mechanical layer free to become a typed layer: off and with no kind. Prefer when it is free, else the first free one+ above 16 (the old 16 are left to the user's own uses); never Avoid. 0 when none is free. }+Function FreeMechNo(Board : IPCB_Board; Prefer, Avoid : Integer) : Integer;+Var+ N : Integer;+ ML : IPCB_MechanicalLayer;+Begin+ Result := 0;+ If (Prefer > 0) And (Prefer <= 1024) And (Prefer <> Avoid) Then+ Begin+ ML := Board.MasterLayerStack.GetMechanicalLayer(Prefer);+ If ML <> Nil Then If (Not ML.MechanicalLayerEnabled) And (ML.Kind = 0) Then Begin Result := Prefer; Exit; End;+ End;+ For N := 17 To 1024 Do+ Begin+ If N <> Avoid Then+ Begin+ ML := Board.MasterLayerStack.GetMechanicalLayer(N);+ If ML <> Nil Then If (Not ML.MechanicalLayerEnabled) And (ML.Kind = 0) Then Begin Result := N; Exit; End;+ End;+ End;+End;++{ The pair kind a layer kind belongs to (0: not a paired kind, which a script cannot make). }+Function PairKindOf(K : Integer) : Integer;+Begin+ Result := 0;+ If (K = 1) Or (K = 2) Then Result := 1+ Else If (K = 5) Or (K = 6) Then Result := 2+ Else If (K = 7) Or (K = 8) Then Result := 3+ Else If (K = 9) Or (K = 10) Then Result := 4+ Else If (K = 11) Or (K = 12) Then Result := 5+ Else If (K = 13) Or (K = 14) Then Result := 6+ Else If (K = 16) Or (K = 17) Then Result := 7+ Else If (K = 19) Or (K = 20) Then Result := 8+ Else If (K = 21) Or (K = 22) Then Result := 9+ Else If (K = 23) Or (K = 24) Then Result := 10+ Else If (K = 26) Or (K = 27) Then Result := 11;+End;++{ The top layer kind of a pair kind (the bottom one is the next number). }+Function PairTopKind(PK : Integer) : Integer;+Begin+ Result := 0;+ If PK = 1 Then Result := 1 Else If PK = 2 Then Result := 5 Else If PK = 3 Then Result := 7 Else If PK = 4 Then Result := 9+ Else If PK = 5 Then Result := 11 Else If PK = 6 Then Result := 13 Else If PK = 7 Then Result := 16 Else If PK = 8 Then Result := 19+ Else If PK = 9 Then Result := 21 Else If PK = 10 Then Result := 23 Else If PK = 11 Then Result := 26;+End;++{ The name Altium gives a typed layer. }+Function KindLayerName(K : Integer) : String;+Var+ Side, Base : String;+ PK : Integer;+Begin+ PK := PairKindOf(K);+ If K = PairTopKind(PK) Then Side := 'Top ' Else Side := 'Bottom ';+ Base := 'Mechanical';+ If PK = 1 Then Base := 'Assembly' Else If PK = 2 Then Base := 'Coating' Else If PK = 3 Then Base := 'Component Center'+ Else If PK = 4 Then Base := 'Component Outline' Else If PK = 5 Then Base := 'Courtyard' Else If PK = 6 Then Base := 'Designator'+ Else If PK = 7 Then Base := 'Dimensions' Else If PK = 8 Then Base := 'Glue Points' Else If PK = 9 Then Base := 'Gold Plating'+ Else If PK = 10 Then Base := 'Value' Else If PK = 11 Then Base := '3D Body';+ Result := Side + Base;+End;++{ The layer of kind K on Board, made when it has none: a top/bottom pair on free mechanical layers (PreferTop and+ PreferBot first: the source's own numbers keep a library and its boards alike), named TopName/BotName (Altium's+ names when blank), with the pair kind that types both. 0 when K is not a paired kind or no layer is free. }+Function EnsureKindLayer(Board : IPCB_Board; K, PreferTop, PreferBot : Integer; TopName, BotName : String) : Integer;+Var+ N, N1, N2, PK, TK : Integer;+ ML : IPCB_MechanicalLayer;+Begin+ Result := 0;+ N := MechNoOfKind(Board, K);+ If N > 0 Then Begin Result := LayerUtils.MechanicalLayer(N); Exit; End;+ PK := PairKindOf(K);+ If PK = 0 Then Exit;+ TK := PairTopKind(PK);+ { one pair of each kind: a board with the other side of this kind has its pair already }+ If (MechNoOfKind(Board, TK) > 0) Or (MechNoOfKind(Board, TK + 1) > 0) Then Exit;+ N1 := FreeMechNo(Board, PreferTop, 0);+ If N1 = 0 Then Exit;+ N2 := FreeMechNo(Board, PreferBot, N1);+ If N2 = 0 Then Exit;+ If TopName = '' Then TopName := KindLayerName(TK);+ If BotName = '' Then BotName := KindLayerName(TK + 1);+ ML := Board.MasterLayerStack.GetMechanicalLayer(N1); ML.MechanicalLayerEnabled := True; ML.Name := TopName;+ ML := Board.MasterLayerStack.GetMechanicalLayer(N2); ML.MechanicalLayerEnabled := True; ML.Name := BotName;+ Board.MechanicalPairs.AddPair(LayerUtils.MechanicalLayer(N1), LayerUtils.MechanicalLayer(N2));+ Board.MechanicalPairs.LayerPairKind(Board.MechanicalPairs.Count - 1) := PK;+ N := MechNoOfKind(Board, K);+ If N > 0 Then Result := LayerUtils.MechanicalLayer(N);+End;++{ The layer a layer-map code names on Board (0 when it names none): k<kind> made if missing, m<n> turned on,+ i<id> as it is, n<name> an enabled mechanical layer of that name. }+Function ResolveLayerCode(Board : IPCB_Board; Code : String) : Integer;+Var+ C, V : String;+ N : Integer;+Begin+ Result := 0;+ C := Copy(Code, 1, 1); V := Copy(Code, 2, Length(Code));+ If C = 'i' Then Result := StrToIntDef(V, 0)+ Else If C = 'k' Then Result := EnsureKindLayer(Board, StrToIntDef(V, 0), 0, 0, '', '')+ Else If C = 'm' Then+ Begin+ N := StrToIntDef(V, 0);+ If (N >= 1) And (N <= 1024) Then+ Begin+ Board.MasterLayerStack.GetMechanicalLayer(N).MechanicalLayerEnabled := True;+ Result := LayerUtils.MechanicalLayer(N);+ End;+ End+ Else If C = 'n' Then+ Begin+ N := MechNoNamed(Board, V);+ If N > 0 Then Result := LayerUtils.MechanicalLayer(N);+ End;+End;++{ The layer Tag resolves to through the map, cached in Cache (',tag=id,'); -1 when the map leaves Tag unset (the+ built-in layer applies), 0 when it names a layer that cannot be found or made. }+Function MappedTagLayer(Board : IPCB_Board; LMap, Tag : String; Var Cache : String) : Integer;+Var+ Code, Hit : String;+Begin+ Result := -1;+ Code := LMapCode(LMap, Tag);+ If Code = '' Then Exit;+ Hit := CacheGet(Cache, Tag);+ If Hit <> '' Then Begin Result := StrToIntDef(Hit, 0); Exit; End;+ Result := ResolveLayerCode(Board, Code);+ Cache := Cache + Tag + '=' + IntToStr(Result) + ',';+End;++{ Where a primitive on Src's layer L goes on Dst: a typed layer to Dst's layer of the same kind (made, with the+ source's numbers and names, when Dst has none); any other mechanical layer to the same number, turned on; anything+ else as it is. Cached in Cache (',L=id,'). Call it before PreProcess for each layer, then read the cache. }+Function MapLayerTo(Src, Dst : IPCB_Board; L : Integer; Var Cache : String) : Integer;+Var+ Hit, TopNm, BotNm : String;+ K, N, PK, NT, NB : Integer;+Begin+ Result := L;+ N := MechLayerNo(L);+ If N = 0 Then Exit;+ Hit := CacheGet(Cache, IntToStr(L));+ If Hit <> '' Then Begin Result := StrToIntDef(Hit, L); Exit; End;+ K := LayerKindOf(Src, L);+ If K > 0 Then+ Begin+ PK := PairKindOf(K);+ NT := MechNoOfKind(Src, PairTopKind(PK)); NB := MechNoOfKind(Src, PairTopKind(PK) + 1);+ TopNm := ''; BotNm := '';+ If NT > 0 Then TopNm := Src.MasterLayerStack.GetMechanicalLayer(NT).Name;+ If NB > 0 Then BotNm := Src.MasterLayerStack.GetMechanicalLayer(NB).Name;+ Result := EnsureKindLayer(Dst, K, NT, NB, TopNm, BotNm);+ If Result = 0 Then Result := L;+ End+ Else If Src.I_ObjectAddress <> Dst.I_ObjectAddress Then+ Try Dst.MasterLayerStack.GetMechanicalLayer(N).MechanicalLayerEnabled := True; Except End;+ Cache := Cache + IntToStr(L) + '=' + IntToStr(Result) + ',';+End;++{ The cached destination of L (MapLayerTo filled it), else L. }+Function MappedLayer(Cache : String; L : Integer) : Integer;+Var+ Hit : String;+Begin+ Result := L;+ Hit := CacheGet(Cache, IntToStr(L));+ If Hit <> '' Then Result := StrToIntDef(Hit, L);+End;++{ Maps every layer a library footprint uses onto Dst ahead of a copy, and answers the cache: typed layers land on+ Dst's layers of the same kind (#41). Src is the footprint's library board, passed in: LibFp.Board answered another+ board with no layer kinds when build_board placed a part (2026-11-30). }+Function PrepareFpLayers(Src : IPCB_Board; LibFp : IPCB_LibComponent; Dst : IPCB_Board) : String;+Var+ GIt : IPCB_GroupIterator;+ Prim : IPCB_Primitive;+ Cache : String;+Begin+ Cache := ',';+ If (Src = Nil) Or (Dst = Nil) Then Begin Result := Cache; Exit; End;+ GIt := LibFp.GroupIterator_Create;+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+ Prim := GIt.FirstPCBObject;+ While Prim <> Nil Do+ Begin+ MapLayerTo(Src, Dst, Prim.Layer, Cache);+ Prim := GIt.NextPCBObject;+ End;+ LibFp.GroupIterator_Destroy(GIt);+ Result := Cache;+End;++{ Puts a copied primitive on the layer the cache maps its source layer to (typed layers by kind, #41). }+Procedure MapCopyLayer(Cpy : IPCB_Primitive; L : Integer; Cache : String);+Var+ NL : Integer;+Begin+ NL := MappedLayer(Cache, L);+ If NL <> L Then Cpy.Layer := NL;+End;+ Function CmdAddBody(Lines : TStringList) : String; Var PLib : IPCB_Library;@@ -1611,9 +1952,11 @@ Var Old : IPCB_Primitive; Name, StepPath, Note, KeepS : String; I, BW, BH, HG, SO : Integer;- NRep, NBefore, NSame : Integer;+ NRep, NBefore, NSame, BodyL : Integer; Found, Keep : Boolean;+ LCache : String; Begin+ LCache := ','; Name := Param(Lines, 'name'); StepPath := Param(Lines, 'step'); { keep=1 is the deliberate-second-body opt-out; anything else REPLACES the footprint's bodies }@@ -1660,11 +2003,14 @@ Begin { A primitive without a layer is silently dropped on AddPCBObject (measured 2026-08-30: add returned ok, census showed 16 pads and 0 bodies). Component bodies live on a mechanical layer. }- Body.Layer := eMechanical1;+ { the layer map's body3d (#41), else Mechanical 1 as always }+ BodyL := MappedTagLayer(PLib.Board, Param(Lines, 'lmap'), 'body3d', LCache);+ If BodyL <= 0 Then BodyL := eMechanical1;+ Body.Layer := BodyL; { An invisible body is indistinguishable from a missing one: opacity defaults to 0 in this engine. Make sure the mech layer is enabled and the body opaque. }- PLib.Board.LayerStack.LayerObject[eMechanical1].MechanicalLayerEnabled := True;- PLib.Board.LayerIsDisplayed[eMechanical1] := True;+ If BodyL = eMechanical1 Then PLib.Board.LayerStack.LayerObject[eMechanical1].MechanicalLayerEnabled := True;+ PLib.Board.LayerIsDisplayed[BodyL] := True; Body.BodyOpacity3D := 1.0; If StepPath <> '' Then Begin@@ -1717,7 +2063,7 @@ Begin (PCB:Clear) on the selection, then start a new command for the add. Nothing else may be selected: Clear deletes the whole selection. } BIt := PLib.Board.BoardIterator_Create;- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Old := BIt.FirstPCBObject; While Old <> Nil Do@@ -1728,7 +2074,7 @@ Begin PLib.Board.BoardIterator_Destroy(BIt); BIt := PLib.Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Old := BIt.FirstPCBObject; While Old <> Nil Do@@ -1756,7 +2102,8 @@ Begin JRaw('replacedBodies', IntToStr(NRep)) + ',' + JRaw('keptExisting', KeepS) + ',' + JRaw('bodiesBefore', IntToStr(NBefore)) + ',' + JRaw('sameNameFootprints', IntToStr(NSame)) + ',' + JRaw('bodiesNow', IntToStr(GroupCount(Fp, eComponentBodyObject))) + ',' +- JRaw('bodiesOnCanvas', IntToStr(BoardBodyCount(PLib.Board))) + '}';+ JRaw('bodiesOnCanvas', IntToStr(BoardBodyCount(PLib.Board))) + ',' ++ JRaw('layersUsed', '[["body3d","' + JsonEsc(LayerNameOf(PLib.Board, BodyL)) + '",' + IntToStr(BodyL) + ',' + IntToStr(LayerKindOf(PLib.Board, BodyL)) + ']]') + '}'; End; { --------------------------------------------------- demo: place on sch + pcb --- }@@ -2566,6 +2913,7 @@ Var R : TCoordRect; DX, DY, CL, CB, CR, CT : Integer; AnyP : Boolean;+ LCache : String; Begin PcbPath := Param(Lines, 'pcb'); FpName := Param(Lines, 'footprint');@@ -2609,6 +2957,8 @@ Begin 16 free pads, no eComponentObject, no body - measured 2026-08-30. Build a fresh board component and copy each child primitive, the same cure the schematic placement needed. }+ { typed layers land on the board's layers of the same kind (#41) }+ LCache := PrepareFpLayers(PLib.Board, LibFp, Board); PCBServer.PreProcess; Inst := PCBServer.PCBObjectFactory(eComponentObject, eNoDimension, eCreate_Default); Inst.Layer := eTopLayer;@@ -2622,11 +2972,12 @@ Begin create_footprint, where pads go in before RegisterComponent. } NCopied := 0; GIt := LibFp.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin Cpy := Prim.Replicate;+ MapCopyLayer(Cpy, Prim.Layer, LCache); Inst.AddPCBObject(Cpy); NCopied := NCopied + 1; Prim := GIt.NextPCBObject;@@ -2652,7 +3003,7 @@ Begin CL := 0; CB := 0; CR := 0; CT := 0; GIt := Inst.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -2678,7 +3029,7 @@ Begin DY := MilsToCoord(3000) - ((CB + CT) Div 2); End; GIt := Inst.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -2726,7 +3077,7 @@ Begin S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(AllObjects);- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While (Prim <> Nil) And (N < 200) Do@@ -2753,7 +3104,7 @@ Begin L := 0; B := 0; Rt := 0; T := 0; GIt := Grp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -2793,7 +3144,7 @@ Begin S := ''; PadIt := Comp.GroupIterator_Create; PadIt.AddFilter_ObjectSet(MkSet(ePadObject));- PadIt.AddFilter_LayerSet(AllLayers);+ PadIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := PadIt.FirstPCBObject; While Pad <> Nil Do Begin@@ -2819,7 +3170,7 @@ Begin S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); T := BIt.FirstPCBObject; While T <> Nil Do@@ -2902,7 +3253,7 @@ Begin S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -2973,6 +3324,50 @@ Begin Else Result := eTopLayer; End; +{ A spec tag's layer through the layer map (#41): the mapped layer, else the built-in one. }+Function SpecLayerMapped(Board : IPCB_Board; LMap, Tag : String; Var Cache : String) : Integer;+Begin+ Result := MappedTagLayer(Board, LMap, Tag, Cache);+ If Result <= 0 Then Result := SpecLayer(Tag);+End;++{ A template primitive the new footprint starts with: a special string (.Designator, .Comment) or a graphic on a+ Component Center layer (the centroid marker). The example pad, outline, courtyard, assembly drawing, silkscreen and+ dimensions are the template's own and stay behind. }+Function TemplateKeeps(TplBoard : IPCB_Board; Prim : IPCB_Primitive) : Boolean;+Var+ K : Integer;+Begin+ Result := False;+ If Prim.ObjectId = eTextObject Then+ Begin+ If Copy(Prim.Text, 1, 1) = '.' Then Result := True;+ Exit;+ End;+ If Prim.ObjectId = ePadObject Then Exit;+ K := LayerKindOf(TplBoard, Prim.Layer);+ If (K = 7) Or (K = 8) Then Result := True;+End;++{ Where a kept template primitive goes in the new footprint's library: .Designator to the map's designator layer, a+ centroid graphic to its centroid layer, else the library's layer of the same kind (made if missing). }+Function TemplateLayer(TplBoard, Board : IPCB_Board; Prim : IPCB_Primitive; LMap : String; Var TCache : String; Var MCache : String) : Integer;+Var+ K : Integer;+Begin+ Result := -1;+ If Prim.ObjectId = eTextObject Then+ Begin+ If UpperCase(Prim.Text) = '.DESIGNATOR' Then Result := MappedTagLayer(Board, LMap, 'designator', TCache);+ End+ Else+ Begin+ K := LayerKindOf(TplBoard, Prim.Layer);+ If K = 7 Then Result := MappedTagLayer(Board, LMap, 'centroid', TCache);+ End;+ If Result <= 0 Then Result := MapLayerTo(TplBoard, Board, Prim.Layer, MCache);+End;+ { Build a footprint from a spec file (tools/kicad2altium.py output): META|name|desc PAD|des|x|y|w|h|shape|hole|layer|crpct LINE|layer|x1|y1|x2|y2|w ARC|layer|cx|cy|r|w|a0|a1 DISC|layer|cx|cy|r. Units mm, Y up. Args:@@ -2988,7 +3383,15 @@ Var Spec : TStringList; I, NPads, NTh, NPrims : Integer; L, Kind, Name, Desc, LibState, LibPath, SpecPath, Shape : String;- R : Integer;+ LMap, TCache, MCache, Used, UsedJ, Tag, TplPath, TplNote : String;+ R, NTpl, NTplSkip, TL : Integer;+ TplLib : IPCB_Library;+ TplFp : IPCB_LibComponent;+ TIt : IPCB_GroupIterator;+ TPrim, TCpy : IPCB_Primitive;+ TR : TCoordRect;+ TW, TH : Integer;+ Centred : Boolean; Begin LibPath := Param(Lines, 'libraryPath'); SpecPath := Param(Lines, 'spec');@@ -3008,17 +3411,70 @@ Begin Spec.LoadFromFile(SpecPath); Name := ''; Desc := ''; NPads := 0; NTh := 0; NPrims := 0;- { mech layers this spec may use: enable + name them once per library }- PLib.Board.LayerStack.LayerObject[eMechanical1].MechanicalLayerEnabled := True;- PLib.Board.LayerStack.LayerObject[eMechanical9].MechanicalLayerEnabled := True;- PLib.Board.LayerStack.LayerObject[eMechanical9].Name := 'Adom.SolderBalls';- PLib.Board.LayerStack.LayerObject[eMechanical13].MechanicalLayerEnabled := True;- PLib.Board.LayerStack.LayerObject[eMechanical13].Name := 'Fab';- PLib.Board.LayerStack.LayerObject[eMechanical15].MechanicalLayerEnabled := True;- PLib.Board.LayerStack.LayerObject[eMechanical15].Name := 'Courtyard';- PLib.Board.LayerIsDisplayed[eMechanical9] := False;- PLib.Board.LayerIsDisplayed[eMechanical13] := True;- PLib.Board.LayerIsDisplayed[eMechanical15] := True;+ { mech layers this spec may use: enable + name them once per library. A layer the map (#41) moves elsewhere is+ not touched: Mechanical 13 may be the organisation's own. }+ LMap := Param(Lines, 'lmap'); TCache := ','; MCache := ','; Used := ','; UsedJ := '';+ If LMapCode(LMap, 'comment') = '' Then PLib.Board.LayerStack.LayerObject[eMechanical1].MechanicalLayerEnabled := True;+ If LMapCode(LMap, 'balls') = '' Then+ Begin+ PLib.Board.LayerStack.LayerObject[eMechanical9].MechanicalLayerEnabled := True;+ PLib.Board.LayerStack.LayerObject[eMechanical9].Name := 'Adom.SolderBalls';+ PLib.Board.LayerIsDisplayed[eMechanical9] := False;+ End;+ If LMapCode(LMap, 'fab') = '' Then+ Begin+ PLib.Board.LayerStack.LayerObject[eMechanical13].MechanicalLayerEnabled := True;+ PLib.Board.LayerStack.LayerObject[eMechanical13].Name := 'Fab';+ PLib.Board.LayerIsDisplayed[eMechanical13] := True;+ End;+ If LMapCode(LMap, 'courtyard') = '' Then+ Begin+ PLib.Board.LayerStack.LayerObject[eMechanical15].MechanicalLayerEnabled := True;+ PLib.Board.LayerStack.LayerObject[eMechanical15].Name := 'Courtyard';+ PLib.Board.LayerIsDisplayed[eMechanical15] := True;+ End;+ { every layer the spec draws on, found (and a typed one made) before the edit begins }+ For I := 0 To Spec.Count - 1 Do+ Begin+ Kind := FieldP(Spec[I], 1);+ If (Kind = 'LINE') Or (Kind = 'ARC') Or (Kind = 'DISC') Then+ Begin+ Tag := FieldP(Spec[I], 2);+ If Pos(',' + Tag + ',', Used) = 0 Then+ Begin+ Used := Used + Tag + ',';+ TL := SpecLayerMapped(PLib.Board, LMap, Tag, TCache);+ If UsedJ <> '' Then UsedJ := UsedJ + ',';+ UsedJ := UsedJ + '["' + JsonEsc(Tag) + '","' + JsonEsc(LayerNameOf(PLib.Board, TL)) + '",' + IntToStr(TL) + ',' + IntToStr(LayerKindOf(PLib.Board, TL)) + ']';+ End;+ End;+ End;+ { the template footprint (#41): its special strings and centroid marker start the new footprint }+ TplPath := Param(Lines, 'tplLib'); TplNote := ''; TplFp := Nil; TplLib := Nil; NTpl := 0; NTplSkip := 0; Centred := False;+ If TplPath <> '' Then+ Begin+ TplLib := PCBServer.LoadPCBLibraryByPath(TplPath);+ If TplLib = Nil Then TplNote := 'the template library could not be loaded: ' + TplPath+ Else+ Begin+ TplFp := FindFp(TplLib, Param(Lines, 'tplFp'));+ If TplFp = Nil Then TplNote := 'the template library has no footprint ' + Param(Lines, 'tplFp')+ Else+ Begin+ { its primitives sit on the library's origin only while it is the footprint on display }+ If TplLib.CurrentComponent <> TplFp Then Begin TplLib.CurrentComponent := TplFp; TplLib.Board.ViewManager_FullUpdate; End;+ TIt := TplFp.GroupIterator_Create;+ TIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+ TPrim := TIt.FirstPCBObject;+ While TPrim <> Nil Do+ Begin+ If TemplateKeeps(TplLib.Board, TPrim) Then TemplateLayer(TplLib.Board, PLib.Board, TPrim, LMap, TCache, MCache);+ TPrim := TIt.NextPCBObject;+ End;+ TplFp.GroupIterator_Destroy(TIt);+ End;+ End;+ End; PCBServer.PreProcess; Comp := PCBServer.CreatePCBLibComp; For I := 0 To Spec.Count - 1 Do@@ -3058,7 +3514,7 @@ Begin Else If Kind = 'LINE' Then Begin Trk := PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default);- Trk.Layer := SpecLayer(FieldP(L, 2));+ Trk.Layer := SpecLayerMapped(PLib.Board, LMap, FieldP(L, 2), TCache); Trk.X1 := MmC(FieldP(L, 3)); Trk.Y1 := MmC(FieldP(L, 4)); Trk.X2 := MmC(FieldP(L, 5)); Trk.Y2 := MmC(FieldP(L, 6)); Trk.Width := MmC(FieldP(L, 7));@@ -3068,7 +3524,7 @@ Begin Else If Kind = 'ARC' Then Begin Arc := PCBServer.PCBObjectFactory(eArcObject, eNoDimension, eCreate_Default);- Arc.Layer := SpecLayer(FieldP(L, 2));+ Arc.Layer := SpecLayerMapped(PLib.Board, LMap, FieldP(L, 2), TCache); Arc.XCenter := MmC(FieldP(L, 3)); Arc.YCenter := MmC(FieldP(L, 4)); Arc.Radius := MmC(FieldP(L, 5)); Arc.LineWidth := MmC(FieldP(L, 6));@@ -3080,7 +3536,7 @@ Begin Begin { a filled disc of radius r = a full arc at r/2 with stroke r } Arc := PCBServer.PCBObjectFactory(eArcObject, eNoDimension, eCreate_Default);- Arc.Layer := SpecLayer(FieldP(L, 2));+ Arc.Layer := SpecLayerMapped(PLib.Board, LMap, FieldP(L, 2), TCache); Arc.XCenter := MmC(FieldP(L, 3)); Arc.YCenter := MmC(FieldP(L, 4)); Arc.Radius := MmC(FieldP(L, 5)) Div 2; Arc.LineWidth := MmC(FieldP(L, 5));@@ -3090,6 +3546,45 @@ Begin End; End; Spec.Free;+ If TplFp <> Nil Then+ Begin+ TIt := TplFp.GroupIterator_Create;+ TIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+ TPrim := TIt.FirstPCBObject;+ While TPrim <> Nil Do+ Begin+ If TemplateKeeps(TplLib.Board, TPrim) Then+ Begin+ TL := TemplateLayer(TplLib.Board, PLib.Board, TPrim, LMap, TCache, MCache);+ TCpy := TPrim.Replicate;+ TCpy.MoveByXY(-TplLib.Board.XOrigin, -TplLib.Board.YOrigin);+ TCpy.Layer := TL;+ { a designator centred on the origin stays centred whatever its length: a centred frame does it, where+ Center-Center justification of one line did not (measured by the reporter on AD 26.10, #41) }+ If TCpy.ObjectId = eTextObject Then+ If (UpperCase(TCpy.Text) = '.DESIGNATOR') And (Not TCpy.Multiline) Then+ Begin+ TR := TCpy.BoundingRectangle;+ If (Abs((TR.Left + TR.Right) Div 2) < MilsToCoord(4)) And (Abs((TR.Bottom + TR.Top) Div 2) < MilsToCoord(4)) Then+ Begin+ TW := TR.Right - TR.Left; TH := TR.Top - TR.Bottom;+ TCpy.Multiline := True;+ TCpy.MultilineTextWidth := TW;+ TCpy.MultilineTextHeight := TH;+ TCpy.MultilineTextAutoPosition := eAutoPos_CenterCenter;+ TCpy.XLocation := -(TW Div 2);+ TCpy.YLocation := -(TH Div 2);+ Centred := True;+ End;+ End;+ Comp.AddPCBObject(TCpy);+ NTpl := NTpl + 1;+ End+ Else NTplSkip := NTplSkip + 1;+ TPrim := TIt.NextPCBObject;+ End;+ TplFp.GroupIterator_Destroy(TIt);+ End; PLib.RegisterComponent(Comp); PLib.CurrentComponent := Comp; PCBServer.PostProcess;@@ -3100,7 +3595,9 @@ Begin Result := '{' + JRaw('ok', 'true') + ',' + JStr('footprint', Name) + ',' + JStr('description', Desc) + ',' + JStr('library', LibPath) + ',' + JStr('libraryState', LibState) + ',' + JRaw('pads', IntToStr(NPads)) + ',' + JRaw('throughHolePads', IntToStr(NTh)) + ',' +- JRaw('drawingPrimitives', IntToStr(NPrims)) + '}';+ JRaw('drawingPrimitives', IntToStr(NPrims)) + ',' + JRaw('layersUsed', '[' + UsedJ + ']') + ',' ++ JRaw('template', '{' + JStr('library', TplPath) + ',' + JStr('footprint', Param(Lines, 'tplFp')) + ',' + JRaw('copied', IntToStr(NTpl)) + ',' ++ JRaw('leftOut', IntToStr(NTplSkip)) + ',' + JRaw('designatorCentred', JBool(Centred)) + ',' + JStr('error', TplNote) + '}') + '}'; End; @@ -3406,7 +3903,7 @@ Begin If (Name <> '') And (UpperCase(Fp.Name) <> UpperCase(Name)) Then Continue; GIt := Fp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; While Pad <> Nil Do Begin@@ -3470,7 +3967,7 @@ Begin AnyP := False; PL := 0; PB := 0; PR := 0; PT := 0; GIt := Fp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -3489,7 +3986,7 @@ Begin If Not AnyP Then Continue; GIt := Fp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -3519,7 +4016,7 @@ End; { Copy a library footprint onto Board as a fresh component centred at (CX,CY) coords, per-primitive (group Replicate dissolves), children BEFORE the board add, pad cluster and bodies normalised to the target independently. }-Function PlaceCopy(Board : IPCB_Board; LibFp : IPCB_LibComponent; CX, CY : Integer) : IPCB_Component;+Function PlaceCopy(Board, SrcBoard : IPCB_Board; LibFp : IPCB_LibComponent; CX, CY : Integer) : IPCB_Component; Var Inst : IPCB_Component; GIt : IPCB_GroupIterator;@@ -3527,17 +4024,20 @@ Var R : TCoordRect; DX, DY, CL, CB, CR, CT : Integer; AnyP : Boolean;+ LCache : String; Begin+ LCache := PrepareFpLayers(SrcBoard, LibFp, Board); Inst := PCBServer.PCBObjectFactory(eComponentObject, eNoDimension, eCreate_Default); Inst.Layer := eTopLayer; Inst.NameOn := False; Inst.CommentOn := False; GIt := LibFp.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin Cpy := Prim.Replicate;+ MapCopyLayer(Cpy, Prim.Layer, LCache); Inst.AddPCBObject(Cpy); Prim := GIt.NextPCBObject; End;@@ -3548,7 +4048,7 @@ Begin AnyP := False; CL := 0; CB := 0; CR := 0; CT := 0; GIt := Inst.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -3567,7 +4067,7 @@ Begin DX := 0; DY := 0; If AnyP Then Begin DX := CX - ((CL + CR) Div 2); DY := CY - ((CB + CT) Div 2); End; GIt := Inst.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -3594,7 +4094,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eNetObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); N := BIt.FirstPCBObject; While N <> Nil Do@@ -3634,7 +4134,7 @@ Begin End; GIt := Inst.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; While Pad <> Nil Do Begin@@ -3760,7 +4260,7 @@ Begin Begin BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); ECmp := BIt.FirstPCBObject; While ECmp <> Nil Do@@ -3814,7 +4314,7 @@ Begin AnyF := 0; FL := 0; FR := 0; GIt2 := LibFp.GroupIterator_Create; GIt2.AddFilter_ObjectSet(MkSet(ePadObject));- GIt2.AddFilter_LayerSet(AllLayers);+ GIt2.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); MPrim := GIt2.FirstPCBObject; While MPrim <> Nil Do Begin@@ -3832,7 +4332,7 @@ Begin End Else CX := (WC * (K + 1)) Div (FpList.Count + 1);- Inst := PlaceCopy(Board, LibFp, CX, CY);+ Inst := PlaceCopy(Board, PLib.Board, LibFp, CX, CY); { U1..Un so the read verbs (component_pins, footprint_primitives) can address each part; the factory left every part named Designator1 (measured 2026-09-20). Name stays hidden. } Inst.Name.Text := 'U' + IntToStr(NExist + K + 1);@@ -3863,7 +4363,7 @@ Begin PY := CY + MMsToCoord(AdomFloat(Field(Copy(Item, Pos('=', Item) + 1, Length(Item)), 2))); GIt := Inst.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; Found := 0; While (Pad <> Nil) And (Found = 0) Do@@ -3939,7 +4439,7 @@ Begin End; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Old := BIt.FirstPCBObject; Board.BoardIterator_Destroy(BIt);@@ -3951,7 +4451,7 @@ Begin CX := Old.x; CY := Old.y; PCBServer.PreProcess; Board.RemovePCBObject(Old);- Inst := PlaceCopy(Board, LibFp, CX, CY);+ Inst := PlaceCopy(Board, PLib.Board, LibFp, CX, CY); AssignPadNets(Board, Inst, Param(Lines, 'assigns')); PCBServer.PostProcess; Board.ViewManager_FullUpdate;@@ -4094,18 +4594,6 @@ Begin SLib.SchIterator_Destroy(Iter); End; -Function FindFp(PLib : IPCB_Library; Name : String) : IPCB_LibComponent;-Var- I : Integer;- F : IPCB_LibComponent;-Begin- Result := Nil;- For I := 0 To PLib.ComponentCount - 1 Do- Begin- F := PLib.GetComponent(I);- If UpperCase(F.Name) = UpperCase(Name) Then Begin Result := F; Break; End;- End;-End; { Clone a symbol inside the current SchLib under a new LibReference, all display modes included (per-primitive copy - group Replicate drops children). }@@ -4298,7 +4786,7 @@ Begin Dst.Description := Src.Description; NCopied := 0; GIt := Src.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -4487,7 +4975,7 @@ Begin Result := Nil; GIt := Fp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); P := GIt.FirstPCBObject; While P <> Nil Do Begin@@ -4506,7 +4994,7 @@ Begin Result := ''; GIt := Fp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); P := GIt.FirstPCBObject; If P <> Nil Then Result := P.Name; Fp.GroupIterator_Destroy(GIt);@@ -4518,7 +5006,7 @@ Var GIt : IPCB_GroupIterator; Begin GIt := Fp.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Result := GIt.FirstPCBObject; Fp.GroupIterator_Destroy(GIt); End;@@ -4532,7 +5020,7 @@ Var SP, DP : IPCB_Pad; NCopied, SX, SY : Integer; Dflt : IPCB_LibComponent;- Dropped, PN : String;+ Dropped, PN, LCache : String; Begin DstLib := PCBServer.GetCurrentPCBLibrary; If DstLib = Nil Then@@ -4564,13 +5052,15 @@ Begin PN := FirstPadName(Src); SP := FpPad(Src, PN); If SP <> Nil Then Begin SX := SP.X - SrcLib.Board.XOrigin; SY := SP.Y - SrcLib.Board.YOrigin; End;+ { typed layers land on the destination library's layers of the same kind (#41) }+ LCache := PrepareFpLayers(SrcLib.Board, Src, DstLib.Board); PCBServer.PreProcess; Dst := PCBServer.CreatePCBLibComp; Dst.Name := Param(Lines, 'to'); Dst.Description := Src.Description; NCopied := 0; GIt := Src.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -4578,6 +5068,7 @@ Begin { the source is on display, so its primitives sit on the library's origin; a footprint not on display keeps them from the origin itself, and Altium puts it back on the origin when it is shown } Cpy.MoveByXY(-SrcLib.Board.XOrigin, -SrcLib.Board.YOrigin);+ MapCopyLayer(Cpy, Prim.Layer, LCache); Dst.AddPCBObject(Cpy); NCopied := NCopied + 1; Prim := GIt.NextPCBObject;@@ -4623,7 +5114,7 @@ Begin S := ''; K := 0; GIt := Comp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; While (Pad <> Nil) And (K < 400) Do Begin@@ -4646,7 +5137,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While (Comp <> Nil) And (Result = Nil) Do@@ -4741,7 +5232,7 @@ Begin S := ''; N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -4785,7 +5276,7 @@ Begin S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -4842,7 +5333,7 @@ Begin S := ''; N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -4879,7 +5370,7 @@ Begin S := ''; N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While (Comp <> Nil) And (N < Limit) Do@@ -4912,7 +5403,7 @@ Begin S := ''; K := 0; GIt := Comp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; While (Pad <> Nil) And (K < 1000) Do Begin@@ -4948,7 +5439,7 @@ Begin SL := TStringList.Create; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePadObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Pad := BIt.FirstPCBObject; While Pad <> Nil Do@@ -5122,7 +5613,7 @@ Begin S := ''; K := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePadObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Pad := BIt.FirstPCBObject; While (Pad <> Nil) And (K < Limit) Do@@ -5447,7 +5938,7 @@ Begin S := ''; N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eRuleObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Rule := BIt.FirstPCBObject; While Rule <> Nil Do@@ -5614,7 +6105,7 @@ Begin mid-iteration crashed Altium (2026-10-22) } BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -5666,7 +6157,7 @@ Begin Begin BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -5735,7 +6226,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eNetObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); N := BIt.FirstPCBObject; While N <> Nil Do@@ -5763,7 +6254,7 @@ Begin Old := Nil; S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eClassObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Cls := BIt.FirstPCBObject; While Cls <> Nil Do@@ -5778,7 +6269,7 @@ Begin Begin NIt := Board.BoardIterator_Create; NIt.AddFilter_ObjectSet(MkSet(eNetObject));- NIt.AddFilter_LayerSet(AllLayers);+ NIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); NIt.AddFilter_Method(eProcessAll); Net := NIt.FirstPCBObject; While Net <> Nil Do@@ -5841,7 +6332,7 @@ Begin Old := Nil; S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eDifferentialPairObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); DP := BIt.FirstPCBObject; While DP <> Nil Do@@ -5881,52 +6372,6 @@ Begin Result := '{' + JRaw('ok','true') + ',' + JStr('pair', Name) + ',' + JStr('pos', PN.Name) + ',' + JStr('neg', NN.Name) + ',' + JRaw('replaced', JBool(Old <> Nil)) + '}'; End; -{ The mechanical layer number of a layer id, 0 for any other layer: Mechanical 1-16 keep their old ids (57-72), the- rest (AD 19+, up to 1024) are 67108864 + N. The typed component layers of AD 24+ (Top Assembly, Top Courtyard,- Top 3D Body, ...) are mechanical layers with a kind, usually above 16 (#41). }-Function MechLayerNo(L : Integer) : Integer;-Begin- Result := 0;- If (L >= 57) And (L <= 72) Then Result := L - 56- Else If (L > 67108864) And (L <= 67109888) Then Result := L - 67108864;-End;--{ One layer as [id, "name", kind]: the name the user sees in Altium (a mechanical layer's own name, as "Top Courtyard")- and a mechanical layer's kind (0 none, 11 Courtyard Top, ...; -1 for a layer that is not mechanical).- LayerStack.LayerObject reads only the low byte of the id (67108921 came back as Mechanical 1, 2026-11-30), so a- mechanical layer is looked up by its number. }-Function LayerInfoJson(Board : IPCB_Board; L : Integer) : String;-Var- ML : IPCB_MechanicalLayer;- N, K : Integer;- Nm : String;-Begin- Nm := Layer2String(L); K := -1; N := MechLayerNo(L);- If N > 0 Then- Begin- K := 0;- Try- ML := Board.MasterLayerStack.GetMechanicalLayer(N);- If ML <> Nil Then- Begin- If ML.Name <> '' Then Nm := ML.Name;- Try K := ML.Kind; Except K := 0; End;- End;- Except End;- End;- Result := '[' + IntToStr(L) + ',"' + JsonEsc(Nm) + '",' + IntToStr(K) + ']';-End;--{ Adds L to the comma-wrapped list Seen (',1,33,') and its [id, name, kind] to Acc when it is new. (Out is a reserved- word in DelphiScript: a parameter named Out halts the engine on compile.) }-Procedure NoteLayer(Board : IPCB_Board; L : Integer; Var Seen : String; Var Acc : String);-Begin- If Pos(',' + IntToStr(L) + ',', Seen) > 0 Then Exit;- Seen := Seen + IntToStr(L) + ',';- If Acc <> '' Then Acc := Acc + ',';- Acc := Acc + LayerInfoJson(Board, L);-End;- { footprint_primitives: designator=<board component> -> geometry dump (tracks, arcs, pads, texts, others counted) } Function CmdFootprintPrimitives(Lines : TStringList) : String; Var@@ -6085,7 +6530,7 @@ Begin N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePadObject, eTrackObject, eArcObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -6289,7 +6734,7 @@ Begin Unrouted := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eViaObject, ePadObject, eComponentObject, ePolyObject, eConnectionObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -6365,7 +6810,7 @@ Begin { keepout fills and regions: few on any board, so their own walk } BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eFillObject, eRegionObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -6432,7 +6877,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Trk := BIt.FirstPCBObject; While Trk <> Nil Do@@ -6458,7 +6903,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eViaObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Via := BIt.FirstPCBObject; While Via <> Nil Do@@ -6479,7 +6924,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eViaObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -6548,7 +6993,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eTextObject, eFillObject, eRegionObject, eDimensionObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -6573,7 +7018,7 @@ Begin S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eTextObject, eFillObject, eRegionObject, eDimensionObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -6844,7 +7289,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eRuleObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Rule := BIt.FirstPCBObject; While Rule <> Nil Do@@ -6863,7 +7308,7 @@ Begin Result := False; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePolyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Poly := BIt.FirstPCBObject; While Poly <> Nil Do@@ -6970,7 +7415,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePolyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Poly := BIt.FirstPCBObject; While (Poly <> Nil) And (Result = Nil) Do@@ -7199,7 +7644,7 @@ Begin N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePolyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Poly := BIt.FirstPCBObject; While Poly <> Nil Do@@ -7234,7 +7679,7 @@ Begin LG := TStringList.Create; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePolyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Poly := BIt.FirstPCBObject; While Poly <> Nil Do@@ -7243,7 +7688,7 @@ Begin Fills := ''; GIt := Poly.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(eRegionObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -7263,7 +7708,7 @@ Begin Pieces := 0; GIt := Poly.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin Pieces := Pieces + 1; Prim := GIt.NextPCBObject; End; Poly.GroupIterator_Destroy(GIt);@@ -7285,7 +7730,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(ePolyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Poly := BIt.FirstPCBObject; While Poly <> Nil Do@@ -7307,7 +7752,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eRegionObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Reg := BIt.FirstPCBObject; While Reg <> Nil Do@@ -7328,7 +7773,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eRuleObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Rule := BIt.FirstPCBObject; While Rule <> Nil Do@@ -7417,7 +7862,7 @@ Begin Unrouted := 0; N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eViolationObject, eConnectionObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -7506,7 +7951,7 @@ Begin OX := 0; OY := 0; AnyP := False; CL := 0; CB := 0; CR := 0; CT := 0; GIt := LibFp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -7538,19 +7983,22 @@ Var GIt : IPCB_GroupIterator; Prim, Cpy : IPCB_Primitive; OX, OY : Integer;+ LCache : String; Begin FpOffset(PLib, LibFp, OX, OY);+ LCache := PrepareFpLayers(PLib.Board, LibFp, Board); Inst := PCBServer.PCBObjectFactory(eComponentObject, eNoDimension, eCreate_Default); Inst.Layer := eTopLayer; Inst.NameOn := False; Inst.CommentOn := False; GIt := LibFp.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin Cpy := Prim.Replicate; If (OX <> 0) Or (OY <> 0) Then Cpy.MoveByXY(-OX, -OY);+ MapCopyLayer(Cpy, Prim.Layer, LCache); Inst.AddPCBObject(Cpy); Prim := GIt.NextPCBObject; End;@@ -7741,7 +8189,7 @@ Begin PCBServer.PreProcess; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eRuleObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Rule := BIt.FirstPCBObject; While Rule <> Nil Do@@ -8189,7 +8637,7 @@ Begin Old := Nil; OldRoom := Nil; S := ''; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eClassObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Cls := BIt.FirstPCBObject; While Cls <> Nil Do@@ -8202,7 +8650,7 @@ Begin M := ''; CIt := Board.BoardIterator_Create; CIt.AddFilter_ObjectSet(MkSet(eComponentObject));- CIt.AddFilter_LayerSet(AllLayers);+ CIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); CIt.AddFilter_Method(eProcessAll); Comp := CIt.FirstPCBObject; While Comp <> Nil Do@@ -8322,7 +8770,7 @@ Var I, CX, CY, OX, OY, DX, DY, NX, NY, CmX, CmY, Nets : Integer; Rot : Double; Bottom, Locked, NOn, COn, Found : Boolean;- Des, Cmt, SrcU, SrcD, SrcL, SrcC, SrcF, SrcH : String;+ Des, Cmt, SrcU, SrcD, SrcL, SrcC, SrcF, SrcH, LCache : String; Begin Board := PCBServer.GetCurrentPCBBoard; If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_board') + ',' + JStr('error','no current PCB board') + '}'; Exit; End;@@ -8349,7 +8797,7 @@ Begin SrcF := Copy(SrcF, I + 1, Length(SrcF)); NetMap := TStringList.Create; GIt := Old.GroupIterator_Create;- GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; While Pad <> Nil Do Begin@@ -8357,13 +8805,15 @@ Begin Pad := GIt.NextPCBObject; End; Old.GroupIterator_Destroy(GIt);+ { typed layers land on the board's layers of the same kind (#41) }+ LCache := PrepareFpLayers(PLib.Board, LibFp, Board); PCBServer.PreProcess; Inst := PCBServer.PCBObjectFactory(eComponentObject, eNoDimension, eCreate_Default); Inst.Layer := eTopLayer; GIt := LibFp.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject;- While Prim <> Nil Do Begin Cpy := Prim.Replicate; Inst.AddPCBObject(Cpy); Prim := GIt.NextPCBObject; End;+ While Prim <> Nil Do Begin Cpy := Prim.Replicate; MapCopyLayer(Cpy, Prim.Layer, LCache); Inst.AddPCBObject(Cpy); Prim := GIt.NextPCBObject; End; LibFp.GroupIterator_Destroy(GIt); Board.AddPCBObject(Inst); PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Inst.I_ObjectAddress);@@ -8371,13 +8821,13 @@ Begin { put the library's origin on the part's: a pad of the copy goes where its library pad sits from the origin } Found := False; DX := 0; DY := 0; GIt := LibFp.GroupIterator_Create;- GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); LP := GIt.FirstPCBObject; LibFp.GroupIterator_Destroy(GIt); If LP <> Nil Then Begin GIt := Inst.GroupIterator_Create;- GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; While (Pad <> Nil) And (Not Found) Do Begin@@ -8389,7 +8839,7 @@ Begin If (DX <> 0) Or (DY <> 0) Then Begin GIt := Inst.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin If Prim.ObjectId <> eTextObject Then Prim.MoveByXY(DX, DY); Prim := GIt.NextPCBObject; End; Inst.GroupIterator_Destroy(GIt);@@ -8406,7 +8856,7 @@ Begin { the nets, pad by pad name } Nets := 0; GIt := Inst.GroupIterator_Create;- GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_ObjectSet(MkSet(ePadObject)); GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Pad := GIt.FirstPCBObject; While Pad <> Nil Do Begin@@ -8445,7 +8895,7 @@ Begin S := ''; N := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Body := BIt.FirstPCBObject; While (Body <> Nil) And (N < 20000) Do@@ -8481,7 +8931,7 @@ Begin If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End; N := 0; It := Board.BoardIterator_Create;- It.AddFilter_ObjectSet(AllObjects); It.AddFilter_LayerSet(AllLayers); It.AddFilter_Method(eProcessAll);+ It.AddFilter_ObjectSet(AllObjects); It.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); It.AddFilter_Method(eProcessAll); P := It.FirstPCBObject; While P <> Nil Do Begin If P.TearDrop Then N := N + 1; P := It.NextPCBObject; End; Board.BoardIterator_Destroy(It);@@ -9419,7 +9869,7 @@ Begin LibFp := PLib.GetComponent(I); If UpperCase(LibFp.Name) = UpperCase(FieldP(Op, 2)) Then Break; End;- Inst := PlaceCopy(Board, LibFp, Board.XOrigin + AdomInt(FieldP(Op, 3)), Board.YOrigin + AdomInt(FieldP(Op, 4)));+ Inst := PlaceCopy(Board, PLib.Board, LibFp, Board.XOrigin + AdomInt(FieldP(Op, 3)), Board.YOrigin + AdomInt(FieldP(Op, 4))); Inst.Name.Text := FieldP(Op, 1); Inst.Pattern := LibFp.Name; Inst.NameOn := True;@@ -9455,7 +9905,7 @@ Begin S := ''; GIt := Grp.GroupIterator_Create; GIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin@@ -9495,7 +9945,7 @@ Begin If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current board or footprint library') + '}'; Exit; End; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -9522,7 +9972,7 @@ Begin NT := 0; NA := 0; NV := 0; NP := 0; NPoly := 0; NO := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eViaObject, ePadObject, eFillObject, eRegionObject, ePolyObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -9601,7 +10051,7 @@ Begin Begin BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eDifferentialPairObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); DP := BIt.FirstPCBObject; While DP <> Nil Do@@ -9618,7 +10068,7 @@ Begin Begin BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -9638,7 +10088,7 @@ Begin N := 0; NL := 0; NP := 0; NK := 0; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Prim := BIt.FirstPCBObject; While Prim <> Nil Do@@ -9703,7 +10153,7 @@ Begin LC := TStringList.Create; LT := TStringList.Create; LL := TStringList.Create; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -9753,7 +10203,7 @@ Begin Result := Nil; BIt := Board.BoardIterator_Create; BIt.AddFilter_ObjectSet(MkSet(eComponentObject));- BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); BIt.AddFilter_Method(eProcessAll); Comp := BIt.FirstPCBObject; While Comp <> Nil Do@@ -10532,7 +10982,7 @@ Begin GIt := Fp.GroupIterator_Create; If Lay = 0 Then GIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject)) Else GIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eFillObject, eRegionObject));- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); P := GIt.FirstPCBObject; While P <> Nil Do Begin@@ -10595,7 +11045,7 @@ Begin Fp.Description := Old.Description; Fp.Height := Old.Height; GIt := Old.GroupIterator_Create;- GIt.AddFilter_LayerSet(AllLayers);+ GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers); Prim := GIt.FirstPCBObject; While Prim <> Nil Do Begin
src/bridge.json+3−1@@ -2,7 +2,7 @@ "manifest_version": 1, "name": "altium", "displayName": "Altium Designer",- "version": "0.2.112",+ "version": "0.2.113", "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.", "homepage": "https://wiki.adom.inc/adom/altium-bridge", "docs": "https://wiki.adom.inc/adom/altium-bridge",@@ -186,6 +186,7 @@ "altium_render_schematic", "altium_replicate_layout", "altium_gloss",+ "altium_layer_map", "altium_repour", "altium_return_path", "altium_review_board",@@ -386,6 +387,7 @@ "remove_pours": 300, "repour": 600, "gloss": 900,+ "layer_map": 120, "routing_drc": 300, "build_board": 900, "set_outline": 120,