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.78 source: export_ipc356, export_dxf, export_gencad, import_svg, edit_footprint, generate_body (251 verbs); footprints read and copied on their origin; Altium's crash box reaped
22 files changed
+2063−29
CHANGELOG.md+46README.md+10−4SKILL.md+3bridge-rs/Cargo.lock+65bridge-rs/Cargo.toml+3bridge-rs/src/boardfiles.rs+490bridge-rs/src/body3d.rs+383bridge-rs/src/dialogs.rs+10−1bridge-rs/src/main.rs+4−1bridge-rs/src/manufacturing.rs+33−5bridge-rs/src/project.rs+177−2bridge-rs/src/svgart.rs+353bridge-rs/src/verbs.rs+31−1dev-skills/altium-bridge-test/run_verb_tests.py+15−1package.json+25−2page.json+26−3skills/altium-boards/SKILL.md+10skills/altium-libraries/SKILL.md+12skills/altium-outputs/SKILL.md+10src/BRIDGE_VERSION+1−1src/agent/AdomAgent.pas.tmpl+343−7src/bridge.json+13−1CHANGELOG.md+46@@ -1,5 +1,51 @@ # Changelog +## 0.2.78 (2026-10-28)++Six more of the EDA Bridge Standard's verbs (251 in all), all tried live on Altium Develop:++- `export_ipc356`: the board's IPC-D-356A netlist for bare-board electrical test, through Altium's own Test Point+ Report (IPC format alone, both sides, metric). On the lane board it wrote 27 SMD and 8 through-hole/via records.+- `export_dxf`: chosen layers to DXF, one file per layer (Edge.Cuts, copper, silkscreen, mask, paste, mechanical or+ Altium's L<id>). Altium's DXF export only runs through a dialog, so the bridge writes it from the board model:+ outline as lines and arcs, or one closed polyline with `contours`; tracks and arcs with their width; pads, vias and+ pours. Read back with ezdxf (no errors) and drawn: the lane board's outline, holes, pads and both sides' copper.+- `export_gencad`: GenCAD 1.4. Altium has no GenCAD exporter, so the bridge writes it from the board model: outline,+ pads and padstacks, a shape per footprint with pins in its own frame, components (bottom parts MIRRORX FLIP),+ devices, signals and routes with vias, in inches. The syntax was checked against a file KiCad 10 wrote+ (thanks, kicad-lane). `uniquePins` renames duplicate pad numbers.+- `import_svg`: SVG artwork as filled regions on any layer, at a position and width, one undo step. Paths (arcs and+ curves flattened to `toleranceMm`), rects (rounded too), circles, ellipses, polygons, transforms; text, images and+ stroke-only shapes are listed in `skipped` with why. A shape inside another is its hole. Altium printed a region's+ hole contour filled, so each shape is one contour that reaches its holes through zero-width slits, which prints+ open. Bottom layers are mirrored by default. `dryRun` answers the plan.+- `edit_footprint`: edit a library footprint in place. Pads are changed, deleted, added or renumbered (a swap goes+ through temporary names); graphics are appended to, replaced on or deleted from a layer (line, arc, rect, circle,+ poly); the description is set; 3D models are replaced, appended or deleted. Positions are mm from the footprint's+ origin. Altium did not take pads or lines added to, or removed from, a registered footprint (only changes to+ existing pads), so the edit is made on a copy that takes the footprint's place. Tags and BOM attributes (which+ Altium keeps on the placed part) and a model's offset/scale/rotate are reported under notApplied. `dryRun`+ answers the operations.+- `generate_body`: a part's 3D body as a STEP file from its package family and datasheet dimensions (chip, SOIC,+ SOT-23, QFP, QFN, DFN, BGA, MELF, electrolytic can, crystal, pin header), to IPC-7351 proportions, seated on z = 0+ with pin 1 top-left. Written by the bridge as an AP214 boundary representation (a dark body, bright leads), so no+ CAD tool is needed. Every family was read back by OCCT (step2glb) with the expected box and drawn, and a SOIC-8+ body attached in Altium sits on its pads. A marking is not made yet (notApplied).+- `edit_board` gained a region operation (Y), which import_svg uses.+- **Fixes:**+ - `read_footprint` read a footprint that was not the one on display in raw coordinates near 0, so a library with+ several footprints answered positions 1270 mm off (a library's origin is at 50000 mil). It now shows the+ footprint first, in the library it names.+ - A footprint copied into a new library (export_library_part) landed 1270 mm off its origin when the source library+ was not on display: the copy is now lined up on a pad.+ - A new PcbLib made for one footprint no longer keeps Altium's empty PCBComponent_1.+ - Altium's crash-report box (an access violation in ADVPCB.DLL that hits the first DRC of a newly built board about+ one battery in three, on both builds) is now seen and closed without sending a report. Its window class was not+ scanned, so `run_drc` waited out its timeout and every verb after it answered `altium_modal_orphan`. Altium+ carries on after the box; the DRC report still appears.+- The deploy script stops a stale bridge process itself (`bridge_kill` missed one that ab's auto-update had+ started). Never `process_kill` it: that is `taskkill /T`, and an Altium the bridge launched is its child.+ ## 0.2.77 (2026-10-27) The EDA Bridge Standard's project, library-part and render verbs (13 new, 245 in all), all tried live on Altium Develop.
README.md+10−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 -245 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+251 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. 245 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 251 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 245 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 251 `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 245 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 251 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -260,6 +260,12 @@ All 245 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_read_footprint`: Every detail of one library footprint: pads (number, type, shape, position, size, drill, layers), the layers it uses, its courtyard box, graphics per layer, attributes, properties and 3D models. - `altium_export_odb`: Export the board as ODB++ (copper, drill, stack-up, netlist and parts in one archive) through the tool's own exporter. - `altium_export_ipc2581`: Export the board as IPC-2581: one XML file with copper, drill, stack-up, netlist and BOM, through the tool's own exporter.+- `altium_export_ipc356`: Export the IPC-D-356 netlist of the board, for bare-board electrical test (flying probe or bed of nails).+- `altium_export_dxf`: Export chosen board layers to DXF, one file per layer (the outline, panel drawings, stencils, enclosure work).+- `altium_export_gencad`: Export the board as GenCAD 1.4, the input of test-fixture tools and some assembly houses' CAM.+- `altium_import_svg`: Import SVG artwork (a logo, a label) as filled polygons on a silkscreen, copper, mask or user layer, at a position and size; curves flattened, holes kept.+- `altium_edit_footprint`: Edit a library footprint in place: change, delete, add or renumber pads; add, replace or delete graphics on a layer; set its description; replace, add or delete 3D models.+- `altium_generate_body`: Make a part's 3D body from its package family and its datasheet dimensions (chip, SOIC, QFN, QFP, BGA, SOT-23, DFN, MELF, electrolytic can, crystal, pin header), to IPC-7351 proportions, and write it as a STEP file. - `altium_remove_parts`: Remove placed parts from the board by designator, as one undo step. - `altium_edit_parts`: Edit placed parts: value, designator, any field (add, change, remove), do-not-populate, exclusion from the BOM or position files, mounting type and the lock. - `altium_align_parts`: Line parts up on a common left, right, top, bottom or centre line, or space them evenly, by courtyard box or by anchor point.
SKILL.md+3@@ -47,6 +47,9 @@ Say **altium** to reach this bridge. Every verb returns `success`, a stable `err | A new project, rename one, a dated copy | `altium_project_create {parentDir, name, layers?}`, `altium_project_rename` (refused while open), `altium_project_snapshot {project, label?}` | | A sheet symbol to its board part and back | `altium_cross_probe {ref}` (both positions; Altium's unique id, not the designator, links them) | | A part as its own library, or as a one-part demo project | `altium_export_library_part {part, libraryPath}`, `altium_create_part_project {part, libraryPath}` (**altium-libraries**) |+| Fixture and CAM files: IPC-D-356, GenCAD, DXF per layer | `altium_export_ipc356`, `altium_export_gencad`, `altium_export_dxf {layers}` (**altium-outputs**) |+| A logo or label from an SVG on the board | `altium_import_svg {svgPath, at, widthMm, layer}` (**altium-boards**) |+| Change a library footprint, or make a 3D body from package dimensions | `altium_edit_footprint`, `altium_generate_body {family, dimensionsMm, outputPath}` (**altium-libraries**) | | A picture of the board without a window | `altium_render_board_layers {preset \| layers, mirror?}`, `altium_render_board_3d {side}`, `altium_render_schematic` (**altium-outputs**) | | A project's parameters | `altium_part_parameters {projectPath, name?}` | | Manufacturing files, STEP, PDF | `altium_export_manufacturing` (checks the outline and copper layers in its Gerbers: `fabChecks`), `altium_board_outline`, `altium_export_step`, `altium_export_pdf`, `altium_run_outjob`, `altium_outjob_info` (read an OutJob's containers without running it) (**altium-outputs**) |
bridge-rs/Cargo.lock+65@@ -21,19 +21,33 @@ version = "0.2.39" dependencies = [ "adom-eda-checks", "getrandom",+ "roxmltree", "serde", "serde_json",+ "svgtypes", "tiny_http", "ureq", "zip", ] +[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"+ [[package]] name = "ascii" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" +[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"+ [[package]] name = "base64" version = "0.22.1"@@ -94,6 +108,15 @@ dependencies = [ "syn 3.0.4", ] +[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]+ [[package]] name = "find-msvc-tools" version = "0.1.11"@@ -246,6 +269,17 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]]+name = "kurbo"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62"+dependencies = [+ "arrayvec",+ "euclid",+ "smallvec",+]+ [[package]] name = "libc" version = "0.2.189"@@ -280,6 +314,15 @@ dependencies = [ "simd-adler32", ] +[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]+ [[package]] name = "once_cell" version = "1.21.4"@@ -333,6 +376,12 @@ dependencies = [ "windows-sys", ] +[[package]]+name = "roxmltree"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"+ [[package]] name = "rustls" version = "0.23.43"@@ -423,6 +472,12 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"+ [[package]] name = "smallvec" version = "1.15.2"@@ -441,6 +496,16 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]]+name = "svgtypes"+version = "0.15.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc"+dependencies = [+ "kurbo",+ "siphasher",+]+ [[package]] name = "syn" version = "2.0.119"
bridge-rs/Cargo.toml+3@@ -17,6 +17,9 @@ ureq = { version = "2", default-features = false, features = ["json", "tls"] } getrandom = "0.2" # install_library_bundle unpacks staged zips; deflate only (pure Rust), no bzip2 C dependency zip = { version = "0.6", default-features = false, features = ["deflate"] }+# import_svg: the SVG document and its path data, transforms and arcs (pure Rust, no system libraries)+roxmltree = "0.20"+svgtypes = "0.15" [profile.release] opt-level = "z"
bridge-rs/src/boardfiles.rsadded+490@@ -0,0 +1,490 @@+//! Board files written from the board model (routing_state, mm, y up) where Altium has no exporter that runs without+//! a dialog: DXF per layer (altium_export_dxf). Pure functions over the board model, so another bridge could use them.++use serde_json::{json, Value};++/// Altium layer ids for the standard's non-copper layer names (the copper ones come through the stack).+fn named_layer(name: &str) -> Option<i64> {+ Some(match name {+ "F.SilkS" | "F.Silkscreen" => 33,+ "B.SilkS" | "B.Silkscreen" => 34,+ "F.Paste" => 35,+ "B.Paste" => 36,+ "F.Mask" => 37,+ "B.Mask" => 38,+ _ => {+ // Mechanical<n> / M<n> / Altium's own L<id>+ if let Some(n) = name.strip_prefix("Mechanical").or_else(|| name.strip_prefix('M')).and_then(|n| n.parse::<i64>().ok()) {+ return (1..=32).contains(&n).then_some(56 + n);+ }+ return name.strip_prefix('L').and_then(|n| n.parse().ok());+ }+ })+}++fn is_copper(name: &str) -> bool {+ name == "F.Cu" || name == "B.Cu" || (name.starts_with("In") && name.ends_with(".Cu"))+}++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }++/// DXF R12 text, one entity list. `scale` converts mm to the file's unit.+struct Dxf { body: String, n: usize, scale: f64 }++impl Dxf {+ fn new(scale: f64) -> Self { Dxf { body: String::new(), n: 0, scale } }+ fn num(&self, v: f64) -> String { format!("{:.6}", v * self.scale) }+ fn line(&mut self, layer: &str, a: (f64, f64), b: (f64, f64)) {+ self.body += &format!("0\nLINE\n8\n{layer}\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", self.num(a.0), self.num(a.1), self.num(b.0), self.num(b.1));+ self.n += 1;+ }+ fn circle(&mut self, layer: &str, c: (f64, f64), r: f64) {+ self.body += &format!("0\nCIRCLE\n8\n{layer}\n10\n{}\n20\n{}\n40\n{}\n", self.num(c.0), self.num(c.1), self.num(r));+ self.n += 1;+ }+ /// counter-clockwise from a1 to a2, degrees+ fn arc(&mut self, layer: &str, c: (f64, f64), r: f64, a1: f64, a2: f64) {+ self.body += &format!("0\nARC\n8\n{layer}\n10\n{}\n20\n{}\n40\n{}\n50\n{a1:.6}\n51\n{a2:.6}\n", self.num(c.0), self.num(c.1), self.num(r));+ self.n += 1;+ }+ /// A polyline of (x, y, bulge) vertices; width for a track's copper.+ fn polyline(&mut self, layer: &str, pts: &[(f64, f64, f64)], closed: bool, width: f64) {+ self.body += &format!("0\nPOLYLINE\n8\n{layer}\n66\n1\n70\n{}\n40\n{}\n41\n{}\n", if closed { 1 } else { 0 }, self.num(width), self.num(width));+ for (x, y, b) in pts {+ self.body += &format!("0\nVERTEX\n8\n{layer}\n10\n{}\n20\n{}\n", self.num(*x), self.num(*y));+ if *b != 0.0 { self.body += &format!("42\n{b:.6}\n"); }+ }+ self.body += "0\nSEQEND\n";+ self.n += 1;+ }+ fn text(&self, insunits: i64) -> String {+ format!("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1009\n9\n$INSUNITS\n70\n{insunits}\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{}0\nENDSEC\n0\nEOF\n", self.body)+ }+}++/// The bulge of an arc drawn from `start` (counter-clockwise from a1 to a2 when start is at a1, else clockwise).+fn bulge(e: &Value) -> f64 {+ let (a1, a2) = (f(&e["angle1"]), f(&e["angle2"]));+ let mut sweep = (a2 - a1).rem_euclid(360.0);+ if sweep == 0.0 { sweep = 360.0; }+ let c = (f(&e["center"][0]), f(&e["center"][1]));+ let s = (f(&e["start"][0]), f(&e["start"][1]));+ let at_a1 = ((s.1 - c.1).atan2(s.0 - c.0).to_degrees() - a1).rem_euclid(360.0);+ let ccw = at_a1 < 1.0 || at_a1 > 359.0;+ let b = (sweep.to_radians() / 4.0).tan();+ if ccw { b } else { -b }+}++/// A pad's outline on its layer: round as a circle (or an obround), everything else as its rotated rectangle.+fn pad(d: &mut Dxf, layer: &str, p: &Value) {+ let (x, y, w, h) = (f(&p["x"]), f(&p["y"]), f(&p["sizeX"]), f(&p["sizeY"]));+ let rot = f(&p["rotation"]).to_radians();+ let shape = p["shape"].as_str().unwrap_or("rect");+ if shape == "round" && (w - h).abs() < 1e-6 {+ d.circle(layer, (x, y), w / 2.0);+ return;+ }+ let r = |dx: f64, dy: f64| (x + dx * rot.cos() - dy * rot.sin(), y + dx * rot.sin() + dy * rot.cos());+ if shape == "round" {+ // an obround: two straight sides and two half circles+ let (l, rad) = if w > h { ((w - h) / 2.0, h / 2.0) } else { ((h - w) / 2.0, w / 2.0) };+ let pts: Vec<(f64, f64, f64)> = if w > h {+ vec![(-l, -rad, 0.0), (l, -rad, 1.0), (l, rad, 0.0), (-l, rad, 1.0)]+ } else {+ vec![(rad, -l, 0.0), (rad, l, 1.0), (-rad, l, 0.0), (-rad, -l, 1.0)]+ }.into_iter().map(|(a, b, bu)| { let (px, py) = r(a, b); (px, py, bu) }).collect();+ d.polyline(layer, &pts, true, 0.0);+ return;+ }+ let pts: Vec<(f64, f64, f64)> = [(-w / 2.0, -h / 2.0), (w / 2.0, -h / 2.0), (w / 2.0, h / 2.0), (-w / 2.0, h / 2.0)]+ .iter().map(|(a, b)| { let (px, py) = r(*a, *b); (px, py, 0.0) }).collect();+ d.polyline(layer, &pts, true, 0.0);+}++/// One layer of the board as DXF text, with how many entities it holds. `layer` is a standard name (Edge.Cuts, F.Cu,+/// In1.Cu, B.Cu, F.SilkS, F.Mask, Mechanical1 ...) or Altium's own L<id>. None: a name this writer does not know.+pub fn layer_dxf(state: &Value, layer: &str, contours: bool, inches: bool) -> Option<(String, usize)> {+ let mut d = Dxf::new(if inches { 1.0 / 25.4 } else { 1.0 });+ let name = layer.replace('.', "_");+ let arr = |k: &str| state[k].as_array().cloned().unwrap_or_default();+ if layer == "Edge.Cuts" {+ let edges = arr("outlineEdges");+ if contours && !edges.is_empty() {+ let pts: Vec<(f64, f64, f64)> = edges.iter().map(|e| (f(&e["start"][0]), f(&e["start"][1]), if e["kind"] == "arc" { bulge(e) } else { 0.0 })).collect();+ d.polyline(&name, &pts, true, 0.0);+ } else {+ for e in &edges {+ if e["kind"] == "arc" {+ d.arc(&name, (f(&e["center"][0]), f(&e["center"][1])), f(&e["radius"]), f(&e["angle1"]), f(&e["angle2"]));+ } else {+ d.line(&name, (f(&e["start"][0]), f(&e["start"][1])), (f(&e["end"][0]), f(&e["end"][1])));+ }+ }+ }+ return Some((d.text(if inches { 1 } else { 4 }), d.n));+ }+ let copper = is_copper(layer);+ let id = if copper { None } else { Some(named_layer(layer)?) };+ let on = |v: &Value| if copper { v["layer"].as_str() == Some(layer) } else { v["layerId"].as_i64() == id };+ for t in arr("tracks").iter().filter(|t| on(t)) {+ let w = f(&t["width"]);+ d.polyline(&name, &[(f(&t["start"]["x"]), f(&t["start"]["y"]), 0.0), (f(&t["end"]["x"]), f(&t["end"]["y"]), 0.0)], false, w);+ }+ for a in arr("arcs").iter().filter(|a| on(a)) {+ let (c, r) = ((f(&a["center"]["x"]), f(&a["center"]["y"])), f(&a["radius"]));+ let (a1, a2) = (f(&a["startAngle"]), f(&a["endAngle"]));+ let mut sweep = (a2 - a1).rem_euclid(360.0);+ if sweep == 0.0 { sweep = 360.0; }+ let p = |deg: f64| (c.0 + r * deg.to_radians().cos(), c.1 + r * deg.to_radians().sin());+ let (s, e) = (p(a1), p(a1 + sweep));+ d.polyline(&name, &[(s.0, s.1, (sweep.to_radians() / 4.0).tan()), (e.0, e.1, 0.0)], false, f(&a["width"]));+ }+ if copper {+ for p in arr("pads").iter().filter(|p| p["layer"].as_str() == Some(layer) || p["layer"].as_str() == Some("*.Cu")) {+ pad(&mut d, &name, p);+ }+ for v in arr("vias") {+ let ls: Vec<&str> = v["layers"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).collect()).unwrap_or_default();+ // a through via is on every copper layer; a blind or buried one on its ends (the model names only those)+ let through = ls.first() == Some(&"F.Cu") && ls.last() == Some(&"B.Cu");+ if through || ls.contains(&layer) {+ d.circle(&name, (f(&v["position"]["x"]), f(&v["position"]["y"])), f(&v["size"]) / 2.0);+ }+ }+ for g in arr("polygons").iter().filter(|g| g["layer"].as_str() == Some(layer)) {+ let pts: Vec<(f64, f64, f64)> = g["points"].as_array().map(|ps| ps.iter().map(|p| (f(&p[0]), f(&p[1]), 0.0)).collect()).unwrap_or_default();+ if pts.len() > 2 { d.polyline(&name, &pts, true, 0.0); }+ }+ }+ Some((d.text(if inches { 1 } else { 4 }), d.n))+}++/// altium_export_dxf {filePath?, layers, outputDir?, units?, contours?, titleBlock?, excludeDesignators?, excludeValues?, useDrillOrigin?}+pub fn export_dxf(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ let layers: Vec<String> = args.get("layers").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();+ if layers.is_empty() {+ return json!({"success": false, "errorCode": "bad_args", "error": "layers is required: [\"Edge.Cuts\", \"F.Cu\", ...]", "_hint": "Edge.Cuts with contours:true is the enclosure drawing."});+ }+ if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }+ let st = crate::routing::routing_state(&json!({}));+ let Some(board) = st["file"].as_str().filter(|f| !f.is_empty()).map(str::to_string) else { return st };+ let inches = args.get("units").and_then(|v| v.as_str()) == Some("in");+ let contours = args.get("contours").and_then(|v| v.as_bool()) == Some(true);+ let dir = crate::support::s(args, "outputDir").map(std::path::PathBuf::from)+ .unwrap_or_else(|| std::path::Path::new(&board).parent().unwrap_or(std::path::Path::new(".")).join("DXF"));+ if let Err(e) = std::fs::create_dir_all(&dir) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+ let stem = std::path::Path::new(&board).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("board".into());+ let (mut files, mut unknown) = (Vec::new(), Vec::new());+ for l in &layers {+ match layer_dxf(&st, l, contours, inches) {+ Some((text, n)) => {+ let path = dir.join(format!("{stem}-{}.dxf", l.replace('.', "_")));+ if let Err(e) = std::fs::write(&path, text) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }+ files.push(json!({"layer": l, "path": path.to_string_lossy(), "entities": n}));+ }+ None => unknown.push(l.clone()),+ }+ }+ // text is not drawn, so designators and values are left out whatever the flags say+ let not_applied: Vec<&str> = ["titleBlock", "useDrillOrigin"].into_iter().filter(|k| args.get(*k).and_then(|v| v.as_bool()) == Some(true)).collect();+ json!({"success": unknown.is_empty() && !files.is_empty(), "files": files, "unknownLayers": unknown, "outputDir": dir.to_string_lossy(), "units": if inches { "in" } else { "mm" },+ "optionsNotApplied": not_applied, "windowEtiquette": "background",+ "_hint": "Written from the board model: the outline, tracks, arcs, pads, vias and pours on each layer (texts are not drawn). Edge.Cuts with contours:true is one closed polyline, what CAM and laser tools want. Layers: Edge.Cuts, F.Cu, In<n>.Cu, B.Cu, F.SilkS, B.SilkS, F.Mask, B.Mask, F.Paste, B.Paste, Mechanical<n>, or Altium's L<id>."})+}++/// GenCAD's name for a copper layer of the board model.+fn gencad_layer(l: &str) -> String {+ match l {+ "F.Cu" => "TOP".into(),+ "B.Cu" => "BOTTOM".into(),+ _ => l.strip_prefix("In").and_then(|n| n.strip_suffix(".Cu")).map(|n| format!("INNER{n}")).unwrap_or_else(|| "TOP".into()),+ }+}++fn q(s: &str) -> String { format!("\"{}\"", s.replace('"', "'")) }++/// The board as GenCAD 1.4 text, in inches as fixture and assembly tools expect: outline, pads and padstacks, one+/// shape per footprint (pins in the footprint's own frame), components, devices, signals, and the routes with their+/// vias. Returns the text and counts.+pub fn gencad(state: &Value, title: &str, unique_pins: bool) -> (String, Value) {+ let inch = |mm: f64| format!("{:.6}", mm / 25.4);+ let arr = |k: &str| state[k].as_array().cloned().unwrap_or_default();+ let mut o = String::new();+ o += &format!("$HEADER\nGENCAD 1.4\nUSER {}\nDRAWING {}\nREVISION {}\nUNITS INCH\nORIGIN 0 0\nINTERTRACK 0\n$ENDHEADER\n",+ q(&format!("Adom altium-bridge {}", crate::BRIDGE_VERSION)), q(title), q("1"));+ // the outline+ o += "$BOARD\n";+ for e in arr("outlineEdges") {+ let (s, t) = ((f(&e["start"][0]), f(&e["start"][1])), (f(&e["end"][0]), f(&e["end"][1])));+ if e["kind"] == "arc" {+ // GenCAD arcs run counter-clockwise from the first point to the second+ let (a, b) = if bulge(&e) >= 0.0 { (s, t) } else { (t, s) };+ o += &format!("ARC {} {} {} {} {} {}\n", inch(a.0), inch(a.1), inch(b.0), inch(b.1), inch(f(&e["center"][0])), inch(f(&e["center"][1])));+ } else {+ o += &format!("LINE {} {} {} {}\n", inch(s.0), inch(s.1), inch(t.0), inch(t.1));+ }+ }+ o += "$ENDBOARD\n";+ // pads: one per shape, size and drill, in the footprint's frame+ let comps = arr("components");+ let pads = arr("pads");+ let mut pad_defs: Vec<(String, f64, f64, f64)> = Vec::new(); // (shape, w, h, drill)+ let mut pad_name = |shape: &str, w: f64, h: f64, drill: f64| -> usize {+ let k = (shape.to_string(), (w * 1000.0).round() / 1000.0, (h * 1000.0).round() / 1000.0, (drill * 1000.0).round() / 1000.0);+ match pad_defs.iter().position(|p| *p == k) { Some(i) => i, None => { pad_defs.push(k); pad_defs.len() - 1 } }+ };+ // shapes: each footprint pattern once, from its first part+ struct Pin { name: String, pad: usize, x: f64, y: f64, rot: f64, through: bool }+ let mut shapes: Vec<(String, Vec<Pin>, bool)> = Vec::new();+ let mut shape_of: Vec<(String, String)> = Vec::new(); // ref -> shape name+ for c in &comps {+ let rf = c["ref"].as_str().unwrap_or("").to_string();+ let pattern = c["pattern"].as_str().unwrap_or("").to_string();+ let name = if pattern.is_empty() { format!("SHAPE_{rf}") } else { pattern.clone() };+ shape_of.push((rf.clone(), name.clone()));+ if shapes.iter().any(|s| s.0 == name) { continue; }+ let (cx, cy, th) = (f(&c["x"]), f(&c["y"]), f(&c["rotation"]).to_radians());+ let bottom = c["side"] == "bottom";+ let mut pins = Vec::new();+ let mut seen: Vec<String> = Vec::new();+ for p in pads.iter().filter(|p| p["ref"].as_str() == Some(&rf)) {+ let (dx, dy) = (f(&p["x"]) - cx, f(&p["y"]) - cy);+ let (mut lx, ly) = (dx * th.cos() + dy * th.sin(), -dx * th.sin() + dy * th.cos());+ if bottom { lx = -lx; }+ let mut rot = (f(&p["rotation"]) - f(&c["rotation"])).rem_euclid(360.0);+ if bottom { rot = (360.0 - rot).rem_euclid(360.0); }+ let (mut w, mut h) = (f(&p["sizeX"]), f(&p["sizeY"]));+ // the pad's own size along the footprint's axes+ if (rot - 90.0).abs() < 0.5 || (rot - 270.0).abs() < 0.5 { std::mem::swap(&mut w, &mut h); rot = 0.0; }+ if rot.abs() < 0.5 || (rot - 180.0).abs() < 0.5 { rot = 0.0; }+ let through = f(&p["drill"]) > 0.0;+ let mut nm = p["name"].as_str().unwrap_or("").to_string();+ if unique_pins && seen.contains(&nm) {+ let mut k = 2;+ while seen.contains(&format!("{nm}_{k}")) { k += 1; }+ nm = format!("{nm}_{k}");+ }+ seen.push(nm.clone());+ let id = pad_name(p["shape"].as_str().unwrap_or("rect"), w, h, f(&p["drill"]));+ pins.push(Pin { name: nm, pad: id, x: lx, y: ly, rot, through });+ }+ let th_part = pins.iter().any(|p| p.through);+ shapes.push((name, pins, th_part));+ }+ // vias: one pad per size and drill+ let vias = arr("vias");+ let via_pad: Vec<usize> = vias.iter().map(|v| pad_name("round", f(&v["size"]), f(&v["size"]), f(&v["drill"]))).collect();+ o += "$PADS\n";+ for (i, (shape, w, h, drill)) in pad_defs.iter().enumerate() {+ let d = if *drill > 0.0 { inch(*drill) } else { "0".into() };+ if shape == "round" && (w - h).abs() < 1e-6 {+ o += &format!("PAD P{i} ROUND {d}\nCIRCLE 0 0 {}\n", inch(w / 2.0));+ } else if shape == "round" {+ o += &format!("PAD P{i} FINGER {d}\nRECTANGLE {} {} {} {}\n", inch(-w / 2.0), inch(-h / 2.0), inch(*w), inch(*h));+ } else {+ o += &format!("PAD P{i} RECTANGULAR {d}\nRECTANGLE {} {} {} {}\n", inch(-w / 2.0), inch(-h / 2.0), inch(*w), inch(*h));+ }+ }+ o += "$ENDPADS\n$PADSTACKS\n";+ let coppers: Vec<String> = {+ let mut ls: Vec<String> = arr("tracks").iter().chain(pads.iter()).filter_map(|x| x["layer"].as_str()).filter(|l| is_copper(l)).map(str::to_string).collect();+ ls.push("F.Cu".into()); ls.push("B.Cu".into());+ ls.sort_by_key(|l| match l.as_str() { "F.Cu" => 0, "B.Cu" => 999, x => x.trim_start_matches("In").trim_end_matches(".Cu").parse::<i32>().unwrap_or(500) });+ ls.dedup();+ ls+ };+ for (i, (_, _, _, drill)) in pad_defs.iter().enumerate() {+ let d = if *drill > 0.0 { inch(*drill) } else { "0".into() };+ o += &format!("PADSTACK PS{i} {d}\n");+ if *drill > 0.0 {+ for l in &coppers { o += &format!("PAD P{i} {} 0 0\n", gencad_layer(l)); }+ } else {+ o += &format!("PAD P{i} TOP 0 0\n");+ }+ }+ o += "$ENDPADSTACKS\n$SHAPES\n";+ for (name, pins, th) in &shapes {+ o += &format!("SHAPE {}\nINSERT {}\n", q(name), if *th { "TH" } else { "SMD" });+ for p in pins {+ o += &format!("PIN {} PS{} {} {} TOP {} 0\n", q(&p.name), p.pad, inch(p.x), inch(p.y), p.rot);+ }+ }+ o += "$ENDSHAPES\n$COMPONENTS\n";+ let mut devices: Vec<String> = Vec::new();+ for c in &comps {+ let rf = c["ref"].as_str().unwrap_or("");+ let shape = shape_of.iter().find(|s| s.0 == rf).map(|s| s.1.clone()).unwrap_or_default();+ let bottom = c["side"] == "bottom";+ let dev = format!("DEV_{shape}");+ if !devices.contains(&dev) { devices.push(dev.clone()); }+ o += &format!("COMPONENT {}\nDEVICE {}\nPLACE {} {}\nLAYER {}\nROTATION {}\nSHAPE {} {} {}\n",+ q(rf), q(&dev), inch(f(&c["x"])), inch(f(&c["y"])), if bottom { "BOTTOM" } else { "TOP" }, f(&c["rotation"]), q(&shape),+ if bottom { "MIRRORX" } else { "0" }, if bottom { "FLIP" } else { "0" });+ }+ o += "$ENDCOMPONENTS\n$DEVICES\n";+ for d in &devices { o += &format!("DEVICE {}\nPACKAGE {}\n", q(d), q(d.trim_start_matches("DEV_"))); }+ o += "$ENDDEVICES\n$SIGNALS\n";+ let mut nets: Vec<String> = pads.iter().filter_map(|p| p["net"].as_str()).filter(|n| !n.is_empty()).map(str::to_string).collect();+ nets.sort(); nets.dedup();+ for n in &nets {+ o += &format!("SIGNAL {}\n", q(n));+ for p in pads.iter().filter(|p| p["net"].as_str() == Some(n) && !p["ref"].as_str().unwrap_or("").is_empty()) {+ o += &format!("NODE {} {}\n", q(p["ref"].as_str().unwrap_or("")), q(p["name"].as_str().unwrap_or("")));+ }+ }+ o += "$ENDSIGNALS\n";+ // tracks by width, then each net's copper+ let tracks: Vec<Value> = arr("tracks").into_iter().filter(|t| t["layer"].as_str().map(is_copper).unwrap_or(false)).collect();+ let arcs: Vec<Value> = arr("arcs").into_iter().filter(|t| t["layer"].as_str().map(is_copper).unwrap_or(false)).collect();+ let mut widths: Vec<f64> = tracks.iter().chain(arcs.iter()).map(|t| (f(&t["width"]) * 1000.0).round() / 1000.0).collect();+ widths.sort_by(|a, b| a.partial_cmp(b).unwrap()); widths.dedup();+ o += "$TRACKS\n";+ for (i, w) in widths.iter().enumerate() { o += &format!("TRACK T{i} {}\n", inch(*w)); }+ o += "$ENDTRACKS\n$ROUTES\n";+ let code = |w: f64| widths.iter().position(|x| (*x - (w * 1000.0).round() / 1000.0).abs() < 1e-9).unwrap_or(0);+ let mut route_nets: Vec<String> = tracks.iter().chain(arcs.iter()).filter_map(|t| t["net"].as_str()).chain(vias.iter().filter_map(|v| v["net"].as_str())).filter(|n| !n.is_empty()).map(str::to_string).collect();+ route_nets.sort(); route_nets.dedup();+ let mut unrouted_copper = 0;+ for t in tracks.iter().chain(arcs.iter()) { if t["net"].as_str().unwrap_or("").is_empty() { unrouted_copper += 1; } }+ for n in &route_nets {+ o += &format!("ROUTE {}\n", q(n));+ for t in tracks.iter().filter(|t| t["net"].as_str() == Some(n)) {+ o += &format!("TRACK T{}\nLAYER {}\nLINE {} {} {} {}\n", code(f(&t["width"])), gencad_layer(t["layer"].as_str().unwrap_or("F.Cu")),+ inch(f(&t["start"]["x"])), inch(f(&t["start"]["y"])), inch(f(&t["end"]["x"])), inch(f(&t["end"]["y"])));+ }+ for a in arcs.iter().filter(|a| a["net"].as_str() == Some(n)) {+ let (c, r) = ((f(&a["center"]["x"]), f(&a["center"]["y"])), f(&a["radius"]));+ let p = |deg: f64| (c.0 + r * deg.to_radians().cos(), c.1 + r * deg.to_radians().sin());+ let (s, e) = (p(f(&a["startAngle"])), p(f(&a["endAngle"])));+ o += &format!("TRACK T{}\nLAYER {}\nARC {} {} {} {} {} {}\n", code(f(&a["width"])), gencad_layer(a["layer"].as_str().unwrap_or("F.Cu")),+ inch(s.0), inch(s.1), inch(e.0), inch(e.1), inch(c.0), inch(c.1));+ }+ for (i, v) in vias.iter().enumerate().filter(|(_, v)| v["net"].as_str() == Some(n)) {+ // as KiCad writes it: the padstack, the position, the layers and the drill+ o += &format!("VIA PS{} {} {} ALL {} VIA{i}\n", via_pad[i], inch(f(&v["position"]["x"])), inch(f(&v["position"]["y"])), inch(f(&v["drill"])));+ }+ }+ o += "$ENDROUTES\n";+ let counts = json!({"components": comps.len(), "shapes": shapes.len(), "pads": pad_defs.len(), "signals": nets.len(), "routes": route_nets.len(),+ "vias": vias.len(), "copperWithoutNet": unrouted_copper});+ (o, counts)+}++/// altium_export_gencad {filePath?, outputDir?, uniquePins?, flipBottomPads?, useDrillOrigin?}+pub fn export_gencad(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }+ let st = crate::routing::routing_state(&json!({}));+ let Some(board) = st["file"].as_str().filter(|f| !f.is_empty()).map(str::to_string) else { return st };+ let b = |k: &str| args.get(k).and_then(|v| v.as_bool()) == Some(true);+ let stem = std::path::Path::new(&board).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("board".into());+ let dir = crate::support::s(args, "outputDir").map(std::path::PathBuf::from)+ .unwrap_or_else(|| std::path::Path::new(&board).parent().unwrap_or(std::path::Path::new(".")).to_path_buf());+ if let Err(e) = std::fs::create_dir_all(&dir) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+ let (text, counts) = gencad(&st, &stem, b("uniquePins"));+ let path = dir.join(format!("{stem}.cad"));+ if let Err(e) = std::fs::write(&path, text) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }+ // a bottom part is written MIRRORX FLIP as KiCad writes it; separate flipped padstacks are not made+ let not_applied: Vec<&str> = ["useDrillOrigin", "flipBottomPads"].into_iter().filter(|k| b(k)).collect();+ json!({"success": true, "file": path.to_string_lossy(), "counts": counts, "units": "in", "optionsNotApplied": not_applied, "windowEtiquette": "background",+ "_hint": "GenCAD 1.4 written from the board model (Altium has no GenCAD exporter): outline, pads, padstacks, a shape per footprint, components, signals and routes, in inches. Ask the fixture or assembly house which options it needs; uniquePins is the common one. copperWithoutNet counts tracks on no net, which no route can carry."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn lane() -> Value {+ let t = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../fixtures/altium/lane.routing_state.json")).unwrap();+ let v: Value = serde_json::from_str(&t).unwrap();+ v.get("reply").cloned().unwrap_or(v)+ }++ #[test]+ fn the_outline_is_eight_edges_or_one_closed_polyline() {+ let (t, n) = layer_dxf(&lane(), "Edge.Cuts", false, false).unwrap();+ assert_eq!(n, 8);+ assert_eq!(t.matches("\nARC\n").count(), 4);+ let (t, n) = layer_dxf(&lane(), "Edge.Cuts", true, false).unwrap();+ assert_eq!(n, 1);+ assert_eq!(t.matches("\nVERTEX\n").count(), 8);+ // a corner arc turns a quarter: bulge tan(90/4)+ assert!(t.contains("42\n0.414214\n"), "{t}");+ assert!(t.ends_with("0\nEOF\n"));+ }++ #[test]+ fn copper_holds_its_tracks_pads_and_through_vias() {+ let st = lane();+ let (_, top) = layer_dxf(&st, "F.Cu", false, false).unwrap();+ let tracks = st["tracks"].as_array().unwrap().iter().filter(|t| t["layer"] == "F.Cu").count();+ let pads = st["pads"].as_array().unwrap().iter().filter(|p| p["layer"] == "F.Cu" || p["layer"] == "*.Cu").count();+ let vias = st["vias"].as_array().unwrap().len();+ let arcs = st["arcs"].as_array().unwrap().iter().filter(|a| a["layer"] == "F.Cu").count();+ assert_eq!(top, tracks + arcs + pads + vias);+ assert!(layer_dxf(&st, "Mechanical1", false, false).unwrap().1 > 0, "the L57 lines");+ assert!(layer_dxf(&st, "Dwgs.User", false, false).is_none());+ }++ /// DXF_DUMP=<dir>: write the lane's layers there, for a DXF reader to check+ #[test]+ fn dump_for_a_reader() {+ let Ok(dir) = std::env::var("DXF_DUMP") else { return };+ for (l, c) in [("Edge.Cuts", true), ("Edge.Cuts", false), ("F.Cu", false), ("B.Cu", false), ("Mechanical1", false)] {+ let (t, _) = layer_dxf(&lane(), l, c, false).unwrap();+ std::fs::write(format!("{dir}/{}{}.dxf", l.replace('.', "_"), if c { "-contours" } else { "" }), t).unwrap();+ }+ }++ #[test]+ fn inches_scale_every_coordinate() {+ let (t, _) = layer_dxf(&lane(), "Edge.Cuts", false, true).unwrap();+ assert!(t.contains("$INSUNITS\n70\n1\n"));+ assert!(t.contains(&format!("{:.6}", 40.0 / 25.4)));+ }++ #[test]+ fn gencad_has_every_section_and_the_lane_parts() {+ let st = lane();+ let (t, c) = gencad(&st, "lane", false);+ for s in ["HEADER", "BOARD", "PADS", "PADSTACKS", "SHAPES", "COMPONENTS", "DEVICES", "SIGNALS", "TRACKS", "ROUTES"] {+ assert_eq!(t.matches(&format!("${s}\n")).count(), 1, "{s}");+ assert_eq!(t.matches(&format!("$END{s}\n")).count(), 1, "{s}");+ }+ assert_eq!(c["components"], json!(st["components"].as_array().unwrap().len()));+ assert_eq!(t.matches("\nCOMPONENT ").count(), st["components"].as_array().unwrap().len());+ // the outline: four lines and four corner arcs, a 40 x 20 mm board in inches+ assert_eq!(t.split("$ENDBOARD").next().unwrap().matches("\nARC ").count(), 4);+ assert!(t.contains(&format!("{:.6}", 40.0 / 25.4)));+ // every pin of a SOIC-8 sits in its own frame: x is +-2.7 mm whatever the part's rotation+ let shape = t.split("SHAPE \"TST_SOIC8\"\n").nth(1).unwrap().split("SHAPE ").next().unwrap();+ assert_eq!(shape.matches("PIN ").count(), 8);+ for l in shape.lines().filter(|l| l.starts_with("PIN ")) {+ let x: f64 = l.split_whitespace().nth(3).unwrap().parse().unwrap();+ assert!((x.abs() * 25.4 - 2.7).abs() < 0.01, "{l}");+ }+ }++ #[test]+ fn duplicate_pin_names_are_made_unique_on_request() {+ let st = json!({"components": [{"ref": "J1", "pattern": "TAB", "x": 0.0, "y": 0.0, "rotation": 0.0, "side": "top"}],+ "pads": [{"ref": "J1", "name": "1", "x": 0.0, "y": 0.0, "sizeX": 1.0, "sizeY": 1.0, "shape": "rect", "drill": 0.0, "rotation": 0.0, "layer": "F.Cu", "net": ""},+ {"ref": "J1", "name": "1", "x": 2.0, "y": 0.0, "sizeX": 1.0, "sizeY": 1.0, "shape": "rect", "drill": 0.0, "rotation": 0.0, "layer": "F.Cu", "net": ""}]});+ assert_eq!(gencad(&st, "x", false).0.matches("PIN \"1\" ").count(), 2);+ let (t, _) = gencad(&st, "x", true);+ assert!(t.contains("PIN \"1\" ") && t.contains("PIN \"1_2\" "));+ }++ #[test]+ fn bottom_parts_and_vias_read_as_kicad_writes_them() {+ let st = json!({"components": [{"ref": "R1", "pattern": "R0603", "x": 10.0, "y": 5.0, "rotation": 180.0, "side": "bottom"}],+ "pads": [{"ref": "R1", "name": "1", "x": 10.825, "y": 5.0, "sizeX": 0.8, "sizeY": 0.95, "shape": "rect", "drill": 0.0, "rotation": 180.0, "layer": "B.Cu", "net": "A"}],+ "vias": [{"net": "A", "drill": 0.3, "size": 0.6, "layers": ["F.Cu", "B.Cu"], "position": {"x": 10.0, "y": 7.0}}]});+ let (t, _) = gencad(&st, "x", false);+ assert!(t.contains("LAYER BOTTOM\nROTATION 180\nSHAPE \"R0603\" MIRRORX FLIP\n"), "{t}");+ // pad 1 is 0.825 mm left of the part's centre in its own frame (rotated 180, then mirrored back to the top view)+ assert!(t.contains(&format!("PIN \"1\" PS0 {:.6} 0.000000 TOP", 0.825 / 25.4)) || t.contains(&format!("PIN \"1\" PS0 {:.6} -0.000000 TOP", 0.825 / 25.4)), "{t}");+ assert!(t.contains(&format!("ALL {:.6} VIA0", 0.3 / 25.4)), "{t}");+ }+}
bridge-rs/src/body3d.rsadded+383@@ -0,0 +1,383 @@+//! generate_body: a part's 3D body from its package family and datasheet dimensions, to IPC-7351 proportions, written+//! as a STEP file (AP214 boundary representation, mm, coloured body and leads). Pure Rust: no CAD tool is needed.+//! Bodies are made of prisms (a planar outline swept along an axis), which is all these packages need; a round can or+//! ball is a many-sided prism. The package sits in its own frame: IPC-7351 zero orientation, seated on z = 0.++use serde_json::{json, Map, Value};++type P3 = [f64; 3];++/// A solid as its faces, each a planar polygon listed counter-clockwise seen from outside.+#[derive(Clone)]+pub struct Solid { pub faces: Vec<Vec<P3>>, pub lead: bool }++/// A prism: `outline` (counter-clockwise in its own u,v plane) swept from w0 to w1, placed by `map(u, v, w)`.+fn prism(outline: &[(f64, f64)], w0: f64, w1: f64, lead: bool, map: impl Fn(f64, f64, f64) -> P3) -> Solid {+ let n = outline.len();+ let bot: Vec<P3> = outline.iter().rev().map(|&(u, v)| map(u, v, w0)).collect();+ let top: Vec<P3> = outline.iter().map(|&(u, v)| map(u, v, w1)).collect();+ let mut faces = vec![bot, top];+ for i in 0..n {+ let (a, b) = (outline[i], outline[(i + 1) % n]);+ faces.push(vec![map(a.0, a.1, w0), map(b.0, b.1, w0), map(b.0, b.1, w1), map(a.0, a.1, w1)]);+ }+ let mut s = Solid { faces, lead };+ // a map that mirrors (an odd number of axis flips) turns every face inside out: put them right+ if signed_volume(&s) < 0.0 { for f in &mut s.faces { f.reverse(); } }+ s+}++fn signed_volume(s: &Solid) -> f64 {+ s.faces.iter().map(|f| (1..f.len() - 1).map(|i| { let (a, b, c) = (f[0], f[i], f[i + 1]); a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]) }).sum::<f64>()).sum::<f64>() / 6.0+}++fn rect(w: f64, h: f64) -> Vec<(f64, f64)> { vec![(-w / 2.0, -h / 2.0), (w / 2.0, -h / 2.0), (w / 2.0, h / 2.0), (-w / 2.0, h / 2.0)] }+fn ngon(r: f64, n: usize) -> Vec<(f64, f64)> { (0..n).map(|i| { let a = 2.0 * std::f64::consts::PI * (i as f64 + 0.5) / n as f64; (r * a.cos(), r * a.sin()) }).collect() }++/// A box from (x0, y0, z0) to (x1, y1, z1).+fn bx(x0: f64, y0: f64, z0: f64, x1: f64, y1: f64, z1: f64, lead: bool) -> Solid {+ let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);+ prism(&rect((x1 - x0).abs(), (y1 - y0).abs()), z0, z1, lead, |u, v, w| [cx + u, cy + v, w])+}++/// A gull-wing lead running outward along +x from the body edge at x = x0 to the tip at x = x1, centred on y, width b,+/// thickness t, shoulder at height zs, foot of length l on the seating plane.+fn gull(x0: f64, x1: f64, y: f64, b: f64, t: f64, zs: f64, l: f64, sign: f64) -> Solid {+ let knee = (x1 - l).max(x0 + t * 1.5);+ let mid = x0 + (knee - x0) * 0.5;+ // the profile in (x, z), counter-clockwise: under the shoulder, down the leg, along the foot, and back over+ let prof = vec![(x0, zs), (mid, zs), (knee, 0.0), (x1, 0.0), (x1, t), (knee + t * 0.4, t), (mid + t * 0.4, zs + t), (x0, zs + t)];+ prism(&prof, y - b / 2.0, y + b / 2.0, true, |u, v, w| [sign * u, w, v])+}++fn d(dims: &Map<String, Value>, k: &str, def: f64) -> f64 { dims.get(k).and_then(|v| v.as_f64()).unwrap_or(def) }++/// The families and their default dimensions (JEDEC letters, mm), from common parts: an 0603 chip, a SOIC-8,+/// a QFN-16 4x4, a TQFP-32 7x7, a SOT-23, a DFN-8 3x3, a BGA-16 0.8 mm, a MiniMELF, a 6.3 mm can, a 3.2x2.5 crystal,+/// a 1x4 2.54 mm header.+pub fn families() -> Vec<(&'static str, Value)> {+ vec![+ ("chip", json!({"D": 1.6, "E": 0.8, "A": 0.45, "L": 0.3})),+ ("soic", json!({"pins": 8, "D": 4.9, "E": 6.0, "E1": 3.9, "A": 1.75, "A1": 0.15, "b": 0.42, "e": 1.27, "L": 0.6, "c": 0.2})),+ ("qfn", json!({"pins": 16, "D": 4.0, "E": 4.0, "A": 0.9, "b": 0.3, "e": 0.65, "L": 0.4, "D2": 2.1, "E2": 2.1})),+ ("qfp", json!({"pins": 32, "D": 9.0, "E": 9.0, "D1": 7.0, "E1": 7.0, "A": 1.2, "A1": 0.1, "b": 0.37, "e": 0.8, "L": 0.6, "c": 0.15})),+ ("sot23", json!({"pins": 3, "D": 2.9, "E": 2.4, "E1": 1.3, "A": 1.0, "A1": 0.05, "b": 0.4, "e": 0.95, "L": 0.4, "c": 0.12})),+ ("dfn", json!({"pins": 8, "D": 3.0, "E": 3.0, "A": 0.85, "b": 0.3, "e": 0.65, "L": 0.4, "D2": 2.4, "E2": 1.6})),+ ("bga", json!({"rows": 4, "cols": 4, "D": 4.0, "E": 4.0, "A": 1.2, "A1": 0.25, "b": 0.4, "e": 0.8})),+ ("melf", json!({"D": 3.5, "E": 1.4, "L": 0.45})),+ ("ecap", json!({"D": 6.3, "A": 5.4, "E": 6.6})),+ ("crystal", json!({"D": 3.2, "E": 2.5, "A": 0.8, "b": 1.2, "L": 1.0})),+ ("header", json!({"pins": 4, "rows": 1, "e": 2.54, "A": 2.5, "L": 3.0, "L1": 6.0, "b": 0.64})),+ ]+}++/// The solids of a package: its body (and leads) in the IPC-7351 zero orientation, pin 1 top-left.+pub fn package(family: &str, dims: &Map<String, Value>) -> Option<Vec<Solid>> {+ let mut s = Vec::new();+ let pins = |def: f64| d(dims, "pins", def).round().max(1.0) as usize;+ match family {+ "chip" => {+ let (len, w, h, l) = (d(dims, "D", 1.6), d(dims, "E", 0.8), d(dims, "A", 0.45), d(dims, "L", 0.3));+ s.push(bx(-len / 2.0 + l, -w / 2.0, 0.0, len / 2.0 - l, w / 2.0, h, false));+ s.push(bx(-len / 2.0, -w / 2.0, 0.0, -len / 2.0 + l, w / 2.0, h, true));+ s.push(bx(len / 2.0 - l, -w / 2.0, 0.0, len / 2.0, w / 2.0, h, true));+ }+ "soic" | "sot23" | "qfp" => {+ let n = pins(if family == "sot23" { 3.0 } else { 8.0 });+ let (a, a1, b, e, l, c) = (d(dims, "A", 1.75), d(dims, "A1", 0.1), d(dims, "b", 0.42), d(dims, "e", 1.27), d(dims, "L", 0.6), d(dims, "c", 0.2));+ let zs = a1 + (a - a1) * 0.4;+ if family == "qfp" {+ let (dd, ee, d1, e1) = (d(dims, "D", 9.0), d(dims, "E", 9.0), d(dims, "D1", 7.0), d(dims, "E1", 7.0));+ s.push(bx(-e1 / 2.0, -d1 / 2.0, a1, e1 / 2.0, d1 / 2.0, a, false));+ let per = (n / 4).max(1);+ let span = (per - 1) as f64 * e;+ for i in 0..per {+ let off = span / 2.0 - i as f64 * e;+ // left (pins 1..), bottom, right, top: counter-clockwise from pin 1 top-left+ s.push(gull(e1 / 2.0, ee / 2.0, off, b, c, zs, l, -1.0));+ let mut bt = gull(d1 / 2.0, dd / 2.0, -off, b, c, zs, l, 1.0);+ for f in &mut bt.faces { for p in f.iter_mut() { *p = [-p[1], -p[0], p[2]]; } f.reverse(); }+ s.push(bt);+ s.push(gull(e1 / 2.0, ee / 2.0, -off, b, c, zs, l, 1.0));+ let mut tp = gull(d1 / 2.0, dd / 2.0, off, b, c, zs, l, 1.0);+ for f in &mut tp.faces { for p in f.iter_mut() { *p = [p[1], p[0], p[2]]; } f.reverse(); }+ s.push(tp);+ }+ } else {+ let (dd, ee, e1) = (d(dims, "D", 4.9), d(dims, "E", 6.0), d(dims, "E1", 3.9));+ s.push(bx(-e1 / 2.0, -dd / 2.0, a1, e1 / 2.0, dd / 2.0, a, false));+ if family == "sot23" && n == 3 {+ s.push(gull(e1 / 2.0, ee / 2.0, e, b, c, zs, l, -1.0));+ s.push(gull(e1 / 2.0, ee / 2.0, -e, b, c, zs, l, -1.0));+ s.push(gull(e1 / 2.0, ee / 2.0, 0.0, b, c, zs, l, 1.0));+ } else {+ let per = n.div_ceil(2);+ let span = (per - 1) as f64 * e;+ for i in 0..per { s.push(gull(e1 / 2.0, ee / 2.0, span / 2.0 - i as f64 * e, b, c, zs, l, -1.0)); }+ for i in 0..(n - per) { s.push(gull(e1 / 2.0, ee / 2.0, -span / 2.0 + i as f64 * e, b, c, zs, l, 1.0)); }+ }+ }+ }+ "qfn" | "dfn" => {+ let n = pins(if family == "dfn" { 8.0 } else { 16.0 });+ let (dd, ee, a, b, e, l) = (d(dims, "D", 4.0), d(dims, "E", 4.0), d(dims, "A", 0.9), d(dims, "b", 0.3), d(dims, "e", 0.65), d(dims, "L", 0.4));+ let t = 0.02;+ s.push(bx(-ee / 2.0, -dd / 2.0, t, ee / 2.0, dd / 2.0, a, false));+ let sides = if family == "dfn" { 2 } else { 4 };+ let per = (n / sides).max(1);+ let span = (per - 1) as f64 * e;+ for i in 0..per {+ let off = span / 2.0 - i as f64 * e;+ s.push(bx(-ee / 2.0, off - b / 2.0, 0.0, -ee / 2.0 + l, off + b / 2.0, t, true));+ s.push(bx(ee / 2.0 - l, -off - b / 2.0, 0.0, ee / 2.0, -off + b / 2.0, t, true));+ if sides == 4 {+ s.push(bx(-off - b / 2.0, -dd / 2.0, 0.0, -off + b / 2.0, -dd / 2.0 + l, t, true));+ s.push(bx(off - b / 2.0, dd / 2.0 - l, 0.0, off + b / 2.0, dd / 2.0, t, true));+ }+ }+ let (d2, e2) = (d(dims, "D2", 0.0), d(dims, "E2", 0.0));+ if d2 > 0.0 && e2 > 0.0 { s.push(bx(-e2 / 2.0, -d2 / 2.0, 0.0, e2 / 2.0, d2 / 2.0, t, true)); }+ }+ "bga" => {+ let (rows, cols) = (d(dims, "rows", 4.0).round().max(1.0) as usize, d(dims, "cols", 4.0).round().max(1.0) as usize);+ let (dd, ee, a, a1, b, e) = (d(dims, "D", 4.0), d(dims, "E", 4.0), d(dims, "A", 1.2), d(dims, "A1", 0.25), d(dims, "b", 0.4), d(dims, "e", 0.8));+ s.push(bx(-ee / 2.0, -dd / 2.0, a1, ee / 2.0, dd / 2.0, a, false));+ for r in 0..rows {+ for c in 0..cols {+ let (x, y) = ((c as f64 - (cols - 1) as f64 / 2.0) * e, ((rows - 1) as f64 / 2.0 - r as f64) * e);+ s.push(prism(&ngon(b / 2.0, 12), 0.0, a1, true, |u, v, w| [x + u, y + v, w]));+ }+ }+ }+ "melf" => {+ let (len, dia, l) = (d(dims, "D", 3.5), d(dims, "E", 1.4), d(dims, "L", 0.45));+ let r = dia / 2.0;+ // a cylinder lying along x, resting on z = 0+ s.push(prism(&ngon(r * 0.97, 24), -len / 2.0 + l, len / 2.0 - l, false, |u, v, w| [w, u, r + v]));+ s.push(prism(&ngon(r, 24), -len / 2.0, -len / 2.0 + l, true, |u, v, w| [w, u, r + v]));+ s.push(prism(&ngon(r, 24), len / 2.0 - l, len / 2.0, true, |u, v, w| [w, u, r + v]));+ }+ "ecap" => {+ let (dia, h, base) = (d(dims, "D", 6.3), d(dims, "A", 5.4), d(dims, "E", 6.6));+ s.push(bx(-base / 2.0, -base / 2.0, 0.0, base / 2.0, base / 2.0, 0.6, false));+ s.push(prism(&ngon(dia / 2.0, 32), 0.6, h, true, |u, v, w| [u, v, w]));+ }+ "crystal" => {+ let (dd, ee, a, b, l) = (d(dims, "D", 3.2), d(dims, "E", 2.5), d(dims, "A", 0.8), d(dims, "b", 1.2), d(dims, "L", 1.0));+ s.push(bx(-dd / 2.0, -ee / 2.0, 0.05, dd / 2.0, ee / 2.0, a, false));+ for (sx, sy) in [(-1.0, 1.0), (1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)] {+ let (x, y) = (sx * (dd / 2.0 - l / 2.0), sy * (ee / 2.0 - b / 2.0));+ s.push(bx(x - l / 2.0, y - b / 2.0, 0.0, x + l / 2.0, y + b / 2.0, 0.05, true));+ }+ }+ "header" => {+ let (n, rows, e, a, l, l1, b) = (pins(4.0), d(dims, "rows", 1.0).round().max(1.0) as usize, d(dims, "e", 2.54), d(dims, "A", 2.5), d(dims, "L", 3.0), d(dims, "L1", 6.0), d(dims, "b", 0.64));+ let per = n.div_ceil(rows);+ let (w, h) = (rows as f64 * e, per as f64 * e);+ // pin 1 at the origin, the rest down the column (and across the rows)+ s.push(bx(-e / 2.0, -h + e / 2.0, 0.0, w - e / 2.0, e / 2.0, a, false));+ for i in 0..n {+ let (x, y) = ((i / per) as f64 * e, -((i % per) as f64) * e);+ s.push(bx(x - b / 2.0, y - b / 2.0, -l, x + b / 2.0, y + b / 2.0, a + l1, true));+ }+ }+ _ => return None,+ }+ Some(s)+}++/// STEP AP214 text of the solids: one product, every solid a MANIFOLD_SOLID_BREP of planar faces, coloured.+pub fn step(solids: &[Solid], name: &str) -> String {+ let mut out = Vec::<String>::new();+ let mut id = 0usize;+ let mut add = |out: &mut Vec<String>, s: String| -> usize { id += 1; out.push(format!("#{id}={s};")); id };+ let r = |v: f64| { let s = format!("{:.6}", if v.abs() < 5e-7 { 0.0 } else { v }); s };+ let app = add(&mut out, "APPLICATION_CONTEXT('core data for automotive mechanical design processes')".into());+ add(&mut out, format!("APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#{app})"));+ let pc = add(&mut out, format!("PRODUCT_CONTEXT('',#{app},'mechanical')"));+ let prod = add(&mut out, format!("PRODUCT('{name}','{name}','',(#{pc}))"));+ let pdf = add(&mut out, format!("PRODUCT_DEFINITION_FORMATION('','',#{prod})"));+ let pdc = add(&mut out, format!("PRODUCT_DEFINITION_CONTEXT('part definition',#{app},'design')"));+ let pd = add(&mut out, format!("PRODUCT_DEFINITION('design','',#{pdf},#{pdc})"));+ let pds = add(&mut out, format!("PRODUCT_DEFINITION_SHAPE('','',#{pd})"));+ add(&mut out, format!("PRODUCT_RELATED_PRODUCT_CATEGORY('part',$,(#{prod}))"));+ let lu = add(&mut out, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))".into());+ let au = add(&mut out, "(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))".into());+ let su = add(&mut out, "(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())".into());+ let unc = add(&mut out, format!("UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-06),#{lu},'distance_accuracy_value','confusion accuracy')"));+ let ctx = add(&mut out, format!("(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{unc}))GLOBAL_UNIT_ASSIGNED_CONTEXT((#{lu},#{au},#{su}))REPRESENTATION_CONTEXT('Context #1','3D Context with UNIT and UNCERTAINTY'))"));+ let o = add(&mut out, "CARTESIAN_POINT('',(0.,0.,0.))".into());+ let z = add(&mut out, "DIRECTION('',(0.,0.,1.))".into());+ let x = add(&mut out, "DIRECTION('',(1.,0.,0.))".into());+ let ax = add(&mut out, format!("AXIS2_PLACEMENT_3D('',#{o},#{z},#{x})"));+ let mut breps = Vec::new();+ let mut styled = Vec::new();+ // colours: a dark moulded body, bright leads+ let mut style = |out: &mut Vec<String>, rgb: (f64, f64, f64)| -> usize {+ let c = add(out, format!("COLOUR_RGB('',{},{},{})", r(rgb.0), r(rgb.1), r(rgb.2)));+ let fc = add(out, format!("FILL_AREA_STYLE_COLOUR('',#{c})"));+ let fa = add(out, format!("FILL_AREA_STYLE('',(#{fc}))"));+ let sf = add(out, format!("SURFACE_STYLE_FILL_AREA(#{fa})"));+ let ss = add(out, format!("SURFACE_SIDE_STYLE('',(#{sf}))"));+ let su = add(out, format!("SURFACE_STYLE_USAGE(.BOTH.,#{ss})"));+ add(out, format!("PRESENTATION_STYLE_ASSIGNMENT((#{su}))"))+ };+ let body_style = style(&mut out, (0.15, 0.15, 0.16));+ let lead_style = style(&mut out, (0.80, 0.80, 0.82));+ for sol in solids {+ // shared vertices and edges, so the shell is closed+ let mut verts: Vec<(P3, usize)> = Vec::new();+ let mut edges: Vec<((usize, usize), usize)> = Vec::new();+ let key = |p: &P3| [(p[0] * 1e5).round() as i64, (p[1] * 1e5).round() as i64, (p[2] * 1e5).round() as i64];+ let mut faces = Vec::new();+ for f in &sol.faces {+ let mut vids = Vec::new();+ for p in f {+ let k = key(p);+ let vid = match verts.iter().find(|(q, _)| key(q) == k) {+ Some((_, v)) => *v,+ None => {+ let cp = add(&mut out, format!("CARTESIAN_POINT('',({},{},{}))", r(p[0]), r(p[1]), r(p[2])));+ let v = add(&mut out, format!("VERTEX_POINT('',#{cp})"));+ verts.push((*p, v));+ v+ }+ };+ vids.push((vid, *p));+ }+ let mut oes = Vec::new();+ for i in 0..vids.len() {+ let (a, b) = (vids[i], vids[(i + 1) % vids.len()]);+ let (lo, hi) = if a.0 < b.0 { (a.0, b.0) } else { (b.0, a.0) };+ let eid = match edges.iter().find(|(k, _)| *k == (lo, hi)) {+ Some((_, e)) => *e,+ None => {+ // the edge runs from the lower vertex id to the higher+ let (pa, pb) = if a.0 == lo { (a.1, b.1) } else { (b.1, a.1) };+ let len = ((pb[0] - pa[0]).powi(2) + (pb[1] - pa[1]).powi(2) + (pb[2] - pa[2]).powi(2)).sqrt().max(1e-12);+ let cp = add(&mut out, format!("CARTESIAN_POINT('',({},{},{}))", r(pa[0]), r(pa[1]), r(pa[2])));+ let dir = add(&mut out, format!("DIRECTION('',({},{},{}))", r((pb[0] - pa[0]) / len), r((pb[1] - pa[1]) / len), r((pb[2] - pa[2]) / len)));+ let vec = add(&mut out, format!("VECTOR('',#{dir},{})", r(len)));+ let ln = add(&mut out, format!("LINE('',#{cp},#{vec})"));+ let e = add(&mut out, format!("EDGE_CURVE('',#{lo},#{hi},#{ln},.T.)"));+ edges.push(((lo, hi), e));+ e+ }+ };+ oes.push(add(&mut out, format!("ORIENTED_EDGE('',*,*,#{eid},{})", if a.0 == lo { ".T." } else { ".F." })));+ }+ let loop_ = add(&mut out, format!("EDGE_LOOP('',({}))", oes.iter().map(|e| format!("#{e}")).collect::<Vec<_>>().join(",")));+ let bound = add(&mut out, format!("FACE_OUTER_BOUND('',#{loop_},.T.)"));+ // the face's plane: Newell's normal, a reference direction along its first edge+ let mut nrm = [0.0f64; 3];+ for i in 0..f.len() { let (a, b) = (f[i], f[(i + 1) % f.len()]); nrm[0] += (a[1] - b[1]) * (a[2] + b[2]); nrm[1] += (a[2] - b[2]) * (a[0] + b[0]); nrm[2] += (a[0] - b[0]) * (a[1] + b[1]); }+ let nl = (nrm[0] * nrm[0] + nrm[1] * nrm[1] + nrm[2] * nrm[2]).sqrt().max(1e-12);+ let nn = [nrm[0] / nl, nrm[1] / nl, nrm[2] / nl];+ let e0 = [f[1][0] - f[0][0], f[1][1] - f[0][1], f[1][2] - f[0][2]];+ let el = (e0[0] * e0[0] + e0[1] * e0[1] + e0[2] * e0[2]).sqrt().max(1e-12);+ let cp = add(&mut out, format!("CARTESIAN_POINT('',({},{},{}))", r(f[0][0]), r(f[0][1]), r(f[0][2])));+ let dn = add(&mut out, format!("DIRECTION('',({},{},{}))", r(nn[0]), r(nn[1]), r(nn[2])));+ let dr = add(&mut out, format!("DIRECTION('',({},{},{}))", r(e0[0] / el), r(e0[1] / el), r(e0[2] / el)));+ let pl_ax = add(&mut out, format!("AXIS2_PLACEMENT_3D('',#{cp},#{dn},#{dr})"));+ let plane = add(&mut out, format!("PLANE('',#{pl_ax})"));+ faces.push(add(&mut out, format!("ADVANCED_FACE('',(#{bound}),#{plane},.T.)")));+ }+ let shell = add(&mut out, format!("CLOSED_SHELL('',({}))", faces.iter().map(|f| format!("#{f}")).collect::<Vec<_>>().join(",")));+ let brep = add(&mut out, format!("MANIFOLD_SOLID_BREP('{}',#{shell})", if sol.lead { "lead" } else { "body" }));+ breps.push(brep);+ styled.push(add(&mut out, format!("STYLED_ITEM('color',(#{}),#{brep})", if sol.lead { lead_style } else { body_style })));+ }+ let rep = add(&mut out, format!("ADVANCED_BREP_SHAPE_REPRESENTATION('{name}',(#{ax},{}),#{ctx})", breps.iter().map(|b| format!("#{b}")).collect::<Vec<_>>().join(",")));+ add(&mut out, format!("SHAPE_DEFINITION_REPRESENTATION(#{pds},#{rep})"));+ add(&mut out, format!("MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',({}),#{ctx})", styled.iter().map(|s| format!("#{s}")).collect::<Vec<_>>().join(",")));+ format!("ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION(('altium-bridge generate_body'),'2;1');\nFILE_NAME('{name}.step','2026-01-01T00:00:00',(''),(''),'altium-bridge','altium-bridge','');\nFILE_SCHEMA(('AUTOMOTIVE_DESIGN {{ 1 0 10303 214 1 1 1 1 }}'));\nENDSEC;\nDATA;\n{}\nENDSEC;\nEND-ISO-10303-21;\n", out.join("\n"))+}++fn bbox(solids: &[Solid]) -> [f64; 6] {+ solids.iter().flat_map(|s| s.faces.iter().flatten()).fold([f64::MAX, f64::MAX, f64::MAX, f64::MIN, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].min(p[2]), b[3].max(p[0]), b[4].max(p[1]), b[5].max(p[2])])+}++/// altium_generate_body {family, dimensionsMm?, marking?, markingStyle?, outputPath}+pub fn generate_body(args: &Value) -> Value {+ let fams = families();+ let family = args.get("family").and_then(|v| v.as_str()).unwrap_or("").to_lowercase().replace(['-', '_', ' '], "");+ let family = match family.as_str() { "sot23" | "sot233" => "sot23".to_string(), "tqfp" | "lqfp" => "qfp".into(), "son" | "wson" => "dfn".into(), "minimelf" => "melf".into(), "electrolytic" | "can" => "ecap".into(), f => f.to_string() };+ let Some((name, defaults)) = fams.iter().find(|(n, _)| *n == family) else {+ return json!({"success": false, "errorCode": "unknown_family", "error": format!("family {:?} is not one this bridge makes", args.get("family")),+ "families": fams.iter().map(|(n, _)| *n).collect::<Vec<_>>()});+ };+ let Some(path) = crate::support::s(args, "outputPath") else { return json!({"success": false, "errorCode": "bad_args", "error": "outputPath (.step) is required"}) };+ let mut dims = defaults.as_object().cloned().unwrap_or_default();+ if let Some(given) = args.get("dimensionsMm").and_then(|v| v.as_object()) {+ for (k, v) in given { if v.is_number() { dims.insert(k.clone(), v.clone()); } }+ }+ let Some(solids) = package(name, &dims) else { return json!({"success": false, "errorCode": "unknown_family"}) };+ let stem = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("body".into()).replace('\'', "");+ if let Some(p) = std::path::Path::new(&path).parent() { let _ = std::fs::create_dir_all(p); }+ if let Err(e) = std::fs::write(&path, step(&solids, &stem)) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{path}: {e}")}); }+ let b = bbox(&solids);+ let r3 = |v: f64| (v * 1000.0).round() / 1000.0;+ let marking = args.get("marking").and_then(|v| v.as_str());+ json!({"success": true, "stepPath": path, "family": name, "dimensionsMm": dims, "solids": solids.len(),+ "bboxMm": {"x": r3(b[3] - b[0]), "y": r3(b[4] - b[1]), "z": r3(b[5] - b[2])}, "marking": Value::Null,+ "notApplied": if marking.is_some() { json!(["marking: text geometry is not made yet; the body is plain"]) } else { json!([]) },+ "_hint": "The body is in the package's own frame (IPC-7351 zero orientation, pin 1 top-left, seated on z = 0), ready for altium_add_body {libraryPath, footprintName, step}. Compare bboxMm with the datasheet's body size before attaching it."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn closed(s: &Solid) -> bool {+ // every edge is used once each way: a closed, consistently oriented shell+ let key = |p: &P3| [(p[0] * 1e5).round() as i64, (p[1] * 1e5).round() as i64, (p[2] * 1e5).round() as i64];+ let mut e: Vec<([i64; 3], [i64; 3])> = Vec::new();+ for f in &s.faces { for i in 0..f.len() { e.push((key(&f[i]), key(&f[(i + 1) % f.len()]))); } }+ e.iter().all(|(a, b)| e.iter().filter(|x| x == &&(*b, *a)).count() == 1)+ }++ #[test]+ fn every_family_is_closed_solids_with_outward_faces() {+ for (name, def) in families() {+ let solids = package(name, def.as_object().unwrap()).unwrap();+ for s in &solids {+ assert!(closed(s), "{name}: a shell is open");+ assert!(signed_volume(s) > 0.0, "{name}: a solid is inside out");+ }+ }+ }++ #[test]+ fn a_soic8_has_its_lead_span_and_height() {+ let dims = families().into_iter().find(|f| f.0 == "soic").unwrap().1;+ let s = package("soic", dims.as_object().unwrap()).unwrap();+ assert_eq!(s.len(), 9);+ let b = bbox(&s);+ assert!((b[3] - b[0] - 6.0).abs() < 1e-9 && (b[5] - 1.75).abs() < 1e-9 && b[2].abs() < 1e-9, "{b:?}");+ // pin 1 is the top-left lead+ let lead1 = bbox(&s[1..2]);+ assert!(lead1[0] < 0.0 && lead1[4] > 1.9, "{lead1:?}");+ }++ /// STEP_DUMP=<dir>: write every family's default body there, for a STEP reader to check+ #[test]+ fn dump_for_a_reader() {+ let Ok(dir) = std::env::var("STEP_DUMP") else { return };+ for (name, def) in families() {+ std::fs::write(format!("{dir}/{name}.step"), step(&package(name, def.as_object().unwrap()).unwrap(), name)).unwrap();+ }+ }++ #[test]+ fn the_step_text_is_well_formed() {+ let s = package("chip", families()[0].1.as_object().unwrap()).unwrap();+ let t = step(&s, "R0603");+ assert!(t.starts_with("ISO-10303-21;") && t.trim_end().ends_with("END-ISO-10303-21;"));+ assert_eq!(t.matches("MANIFOLD_SOLID_BREP").count(), 3);+ assert_eq!(t.matches("ADVANCED_FACE").count(), 18);+ // every referenced entity exists+ let ids: Vec<usize> = t.lines().filter_map(|l| l.strip_prefix('#').and_then(|r| r.split('=').next()).and_then(|n| n.parse().ok())).collect();+ let max = *ids.iter().max().unwrap();+ for cap in t.split('#').skip(1) { let n: String = cap.chars().take_while(|c| c.is_ascii_digit()).collect(); if let Ok(n) = n.parse::<usize>() { assert!(n <= max); } }+ }+}
bridge-rs/src/dialogs.rs+10−1@@ -19,7 +19,10 @@ use std::time::Duration; // TFailedToRenewWarningForm: "License Renewal Failed" (the stranded-seat re-firer). UIA enumerates // NO buttons on it, yet its OK is clickable by name — so it is admitted by class and cleared by // the title rule, never by button count.-const DIALOG_CLASSES: [&str; 7] = ["TMessageForm", "#32770", "TForm", "TMessageDialog", "TForm_RunScriptParameters", "TThemedConfirmDialog", "TFailedToRenewWarningForm"];+// TShowException: Altium's crash-report box. It was not admitted, so an access violation in ADVPCB.DLL during+// run_drc left the agent blocked behind a box the reaper never saw (run_drc timed out, every verb after it answered+// altium_modal_orphan: two batteries on 2026-10-27 and 2026-10-28).+const DIALOG_CLASSES: [&str; 8] = ["TMessageForm", "#32770", "TForm", "TMessageDialog", "TForm_RunScriptParameters", "TThemedConfirmDialog", "TFailedToRenewWarningForm", "TShowException"]; /// title/body substring -> (category, safe default action or "" = none, meaning). /// A safeAction of "" means the reaper must NEVER touch it (save prompts carry decisions).@@ -199,6 +202,12 @@ fn scan_impl(main_pid_only: bool, sel_pid: Option<u64>) -> Vec<Value> { safe_action = Some("Choose a license".into()); meaning = "Altium's 'You are not currently using an Altium Designer license' prompt (Choose a license | Continue). Choose a license opens the License Management page; the reaper then presses Use License via UIA. 'Continue' would leave Altium in Viewer mode, where scripting is refused — never the right answer for a bridge user.".into(); }+ if category == "unknown" && class.eq_ignore_ascii_case("TShowException") {+ // the crash box by its class, whether or not its text could be read: closed without a report+ category = "altium_internal".into();+ safe_action = Some("Send and Close".into());+ meaning = "Altium's crash-report box after an internal fault (an access violation in ADVPCB.DLL during DRC, 2026-10-28). The bridge closes it WITHOUT sending a report; Altium carries on (the DRC report still appeared). Read back what the interrupted command was doing before trusting it.".into();+ } if category == "unknown" && title.trim() == "X2" && btns.len() == 2 && btns.iter().any(|b| b.eq_ignore_ascii_case("ok")) && btns.iter().any(|b| b.eq_ignore_ascii_case("cancel")) { // the script debugger's "<error> at Line:N ... Continue execution?" box: its text is
bridge-rs/src/main.rs+4−1@@ -18,6 +18,9 @@ mod boardedit; mod checks; mod project; mod render;+mod boardfiles;+mod svgart;+mod body3d; mod design; mod dialogs; mod health;@@ -64,7 +67,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.77";+pub const BRIDGE_VERSION: &str = "0.2.78"; 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/manufacturing.rs+33−5@@ -109,8 +109,11 @@ pub fn write_outjob_layers(prj: &str, pcb: &str, bom_columns: Option<&Vec<Value> "ipc2581" | "ipc-2581" => (Ok(fab.clone()), "IPC2581"), "odb" | "odb++" => (crate::support::altium_public_file(r"Examples\Bluetooth Sentinel\Fabrication.OutJob") .and_then(|p| std::fs::read_to_string(&p).map_err(|e| format!("{p}: {e}"))).map(|t| parse_ini(&t)), "ODB"),+ // IPC-D-356A comes from Altium's Test Point Report; only the SpiritLevel example's OutJob carries one+ "ipc356" | "ipc-356" | "ipc-d-356" => (crate::support::altium_public_file(r"Examples\SpiritLevel-SL1\3D Prints.OutJob")+ .and_then(|p| std::fs::read_to_string(&p).map_err(|e| format!("{p}: {e}"))).map(|t| parse_ini(&t)), "Test Points"), "gerber" => continue,- other => return Err(json!({"success": false, "errorCode": "bad_format", "error": format!("format '{other}' is not one of gerber, odb, ipc2581")})),+ other => return Err(json!({"success": false, "errorCode": "bad_format", "error": format!("format '{other}' is not one of gerber, odb, ipc2581, ipc356")})), }; let src = match src { Ok(s) => s, Err(e) => return Err(json!({"success": false, "errorCode": "no_templates", "error": format!("no OutJob carries {kind} on this install: {e}")})) }; match take_output(&src, kind, outputs.len() + 1) {@@ -132,6 +135,12 @@ pub fn write_outjob_layers(prj: &str, pcb: &str, bom_columns: Option<&Vec<Value> e.1 = plot_with(&e.1, inner); } }+ if kind == "Test Points" {+ // the example sets nothing: ask for the IPC-D-356A netlist alone, every test point on both sides+ o.retain(|(k, _)| !k.starts_with(&format!("Configuration{n}_")));+ o.push((format!("Configuration{n}_Name1"), "OutputConfigurationParameter1".into()));+ o.push((format!("Configuration{n}_Item1"), "GenerateCSVFormat=False|GenerateIPCFormat=True|GenerateSpreadSheetFormat=False|GenerateTextFormat=False|Record=TestPointView|ReportBottomLayerTestpoints=True|ReportTopLayerTestpoints=True|Units=Metric".into()));+ } if kind == "Pick Place" { // a CSV in millimetres, what an assembly house loads if let Some(e) = o.iter_mut().find(|(k, v)| k.starts_with(&format!("Configuration{n}_Item")) && v.contains("Record=PickPlaceView")) {@@ -239,7 +248,7 @@ pub fn export_manufacturing(args: &Value) -> Value { let key = f.to_lowercase(); let hit: Vec<String> = walk_names(std::path::Path::new(&dir)).into_iter().filter(|n| { let l = n.to_lowercase();- (key.starts_with("odb") && (l.contains("odb") || l.ends_with(".tgz"))) || (key.starts_with("ipc") && (l.ends_with(".xml") || l.ends_with(".cvg") || l.contains("2581")))+ format_file(&key, &l) }).take(20).collect(); found.insert(f.clone(), json!({"files": hit, "ok": !hit.is_empty()})); }@@ -277,6 +286,14 @@ fn outline_check(r: &Value) -> Value { mod tests { use super::*; + #[test]+ fn each_format_knows_its_files() {+ assert!(format_file("odb", "odb\\lane\\matrix\\matrix") && format_file("odb", "lane.tgz"));+ assert!(format_file("ipc2581", "ipc-2581\\lane.cvg") && !format_file("ipc2581", "lane.ipc"));+ assert!(format_file("ipc356", "test points\\lane.ipc") && !format_file("ipc356", "lane.cvg"));+ assert!(!format_file("ipc356", "gerber\\lane.gtl"));+ }+ #[test] fn renumbers_one_output() { let ini = parse_ini("[OutputGroup1]\nOutputType1=Gerber\nOutputName1=Gerber\nOutputEnabled1=1\nOutputEnabled1_OutputMedium3=1\nConfiguration1_Item1=a=b\nOutputType2=NC Drill\nOutputName2=NC\nConfiguration2_Item1=Record=DrillView\n");@@ -315,7 +332,19 @@ fn project_of(pcb: &str) -> Option<String> { .map(|p| p.to_string_lossy().to_string()) } -/// altium_export_odb / altium_export_ipc2581 {filePath?, outputDir?}: one fab format through Altium's own output+/// Is this file (lower-case path under the output folder) one the format wrote? ODB++ writes a tree in a folder named for+/// it plus archives, IPC-2581 a .cvg (or .xml), the test point report's IPC-D-356A an .ipc.+fn format_file(format: &str, l: &str) -> bool {+ let top = l.split(['\\', '/']).next().unwrap_or("");+ match format {+ f if f.starts_with("odb") => top.contains("odb") || l.ends_with(".tgz"),+ "ipc356" | "ipc-356" | "ipc-d-356" => l.ends_with(".ipc"),+ f if f.starts_with("ipc") => top.contains("2581") || l.ends_with(".cvg") || l.ends_with(".xml"),+ _ => false,+ }+}++/// altium_export_odb / altium_export_ipc2581 / altium_export_ipc356 {filePath?, outputDir?}: one fab format through Altium's own output /// (the project's manufacturing OutJob with that format), its files copied to outputDir when one is given. pub fn export_format(args: &Value, format: &str) -> Value { if let Some(g) = crate::support::need_licensed() { return g; }@@ -335,9 +364,8 @@ pub fn export_format(args: &Value, format: &str) -> Value { let r = export_manufacturing(&json!({"projectPath": prj, "pcbPath": pcb, "formats": [format], "silkPrep": false, "addOutline": false, "timeout": args.get("timeout").cloned().unwrap_or(json!(600))})); let out_dir = r["outputDir"].as_str().unwrap_or("").to_string(); // every file of the format's own folder (ODB++ writes a tree), archives first- let key = if format == "odb" { "odb" } else { "2581" }; let mut names: Vec<String> = walk_names(std::path::Path::new(&out_dir)).into_iter()- .filter(|n| n.split(['\\', '/']).next().map(|top| top.to_lowercase().contains(key)).unwrap_or(false) || (key == "2581" && n.to_lowercase().ends_with(".cvg"))).collect();+ .filter(|n| format_file(format, &n.to_lowercase())).collect(); names.sort_by_key(|n| { let l = n.to_lowercase(); (!(l.ends_with(".tgz") || l.ends_with(".zip") || l.ends_with(".cvg") || l.ends_with(".xml")), n.matches(['\\', '/']).count(), l) }); if names.is_empty() { return json!({"success": false, "errorCode": "not_written", "error": format!("Altium's {format} output wrote no file"), "outjob": r.get("outjob"), "outputDir": out_dir, "reply": r.get("error")});
bridge-rs/src/project.rs+177−2@@ -352,7 +352,7 @@ pub fn read_footprint(args: &Value) -> Value { if let Some(g) = support::need_licensed() { return g; } let (Some(lib), Some(name)) = (support::s(args, "libraryPath"), support::s(args, "name")) else { return bad("libraryPath (.PcbLib) and name are required (Altium has no library table: libId is not used)") }; if let Some(e) = support::must_open(&lib, 60) { return e; }- let d = match agent_data(&agent::call("lib_fp", &[("name", name.clone())], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };+ let d = match agent_data(&agent::call("lib_fp", &[("name", name.clone()), ("path", lib.replace('/', "\\"))], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e }; let k = d["k"].as_f64().filter(|k| *k > 0.0).unwrap_or(10_000_000.0); let mm = |v: &Value| r3(v.as_f64().unwrap_or(0.0) * 25.4 / k); // Altium's pad shapes (TShape): 9 is the rounded rectangle of newer libraries@@ -378,7 +378,7 @@ pub fn read_footprint(args: &Value) -> Value { let court = ext(others.iter().filter(|o| o[1].as_i64() == Some(71)).collect()).or_else(|| ext(others.iter().collect())); let b = court.map(|c| json!(c)).unwrap_or(d["box"].clone()); let models: Vec<Value> = d["bodies"].as_array().cloned().unwrap_or_default().iter().map(|x| json!({"path": x["model"], "heightMm": mm(&x["overallHeight"]), "standoffMm": mm(&x["standoff"])})).collect();- json!({"success": true, "name": d["name"], "library": lib, "pads": pads, "layers": layers, "courtyardMm": if court.is_some() { b.clone() } else { json!([mm(&b[0]), mm(&b[1]), mm(&b[2]), mm(&b[3])]) },+ json!({"success": true, "name": d["name"], "library": lib, "description": d["description"], "pads": pads, "layers": layers, "courtyardMm": if court.is_some() { b.clone() } else { json!([mm(&b[0]), mm(&b[1]), mm(&b[2]), mm(&b[3])]) }, "graphics": graphics, "attributes": {"mount": if pads.iter().any(|p| p["type"] == "pth") { "through_hole" } else { "smd" }}, "properties": {"description": d["description"], "heightMm": mm(&d["height"])}, "models": models, "_hint": "Positions from the footprint's origin, mm. courtyardMm is the footprint's bounding box (Altium courtyards are a mechanical layer's graphics). altium_footprint_primitives reads a placed part."})@@ -388,6 +388,31 @@ pub fn read_footprint(args: &Value) -> Value { mod tests { use super::*; + #[test]+ fn footprint_edits_become_agent_operations_in_order() {+ let args = json!({"pads": [{"number": "1", "set": {"sizeMm": [1.0, 0.6], "at": [-2.7, 1.905]}}, {"number": "8", "delete": true}],+ "addPads": [{"number": "9", "at": [0, 0], "sizeMm": [2, 2], "shape": "rect"}, {"number": "MH", "at": [3, 3], "sizeMm": [1, 1], "drillMm": 1.0, "type": "npth"}],+ "renumber": {"map": {"1": "2", "2": "1"}},+ "graphics": [{"layer": "F.SilkS", "mode": "replace", "widthMm": 0.15, "shapes": [{"type": "rect", "start": [-1, -1], "end": [1, 1]}]}],+ "metadata": {"description": "edited", "tags": "x"}, "models": {"mode": "delete"}});+ let (ops, na) = fp_ops(&args, &[]).unwrap();+ assert_eq!(ops[0], "PS|1|size|1|0.6");+ assert_eq!(ops[1], "PS|1|at|-2.7|1.905");+ assert_eq!(ops[2], "PD|8");+ assert_eq!(ops[3], "PA|9|0|0|2|2|rect|0|top|0|");+ assert_eq!(ops[4], "PA|MH|3|3|1|1|rect|1|multi|0|npth");+ // 1 and 2 swap through temporary names+ assert_eq!(&ops[5..9], &["PS|1|number|__adom0", "PS|2|number|__adom1", "PS|__adom0|number|2", "PS|__adom1|number|1"]);+ assert_eq!(ops[9], "GD|33");+ assert_eq!(ops.iter().filter(|o| o.starts_with("GL|33|")).count(), 4);+ assert!(ops.contains(&"MD|edited".to_string()) && ops.last() == Some(&"BD".to_string()));+ assert_eq!(na, vec!["metadata.tags".to_string()]);+ let (seq, _) = fp_ops(&json!({"renumber": {"sequential": true, "start": 1}}), &["A".into(), "B".into()]).unwrap();+ assert_eq!(seq, ["PS|A|number|__adom0", "PS|B|number|__adom1", "PS|__adom0|number|1", "PS|__adom1|number|2"]);+ assert!(fp_ops(&json!({"graphics": [{"layer": "Dwgs.User"}]}), &[]).is_err());+ }++ #[test] fn kinds_by_extension() { assert_eq!(kind_of("a.PrjPcb"), "project");@@ -432,6 +457,156 @@ fn part_pieces(args: &Value) -> Result<(String, String, Option<String>, Option<S Ok((part, lib, fp, fp_lib)) } +/// A footprint graphics layer by the standard's name: silkscreen, fab, courtyard, mask, paste, Mechanical<n> or L<id>.+fn fp_graphics_layer(l: &str) -> Option<i64> {+ Some(match l {+ "F.SilkS" | "F.Silkscreen" => 33, "B.SilkS" | "B.Silkscreen" => 34, "F.Paste" => 35, "B.Paste" => 36, "F.Mask" => 37, "B.Mask" => 38,+ // as this bridge builds footprints: Fab on Mechanical 13, Courtyard on Mechanical 15+ "F.Fab" | "B.Fab" => 69, "F.CrtYd" | "B.CrtYd" | "F.Courtyard" | "B.Courtyard" => 71,+ "F.Cu" => 1, "B.Cu" => 32,+ _ => return l.strip_prefix("Mechanical").and_then(|n| n.parse::<i64>().ok()).filter(|n| (1..=32).contains(n)).map(|n| 56 + n)+ .or_else(|| l.strip_prefix('L').and_then(|n| n.parse().ok())),+ })+}++fn xy(v: &Value) -> Option<(f64, f64)> { Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)) }++/// A pad's layer word for the agent: a hole or a pth/npth type is multi-layer.+fn pad_layer_word(p: &Value) -> &'static str {+ let ty = p.get("type").and_then(|v| v.as_str()).unwrap_or("");+ let drill = p.get("drillMm").and_then(|v| v.as_f64()).unwrap_or(0.0);+ let layers: Vec<&str> = p.get("layers").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).collect()).unwrap_or_default();+ if ty == "pth" || ty == "npth" || drill > 0.0 || layers.iter().any(|l| l.starts_with('*')) || (layers.contains(&"F.Cu") && layers.contains(&"B.Cu")) { "multi" }+ else if layers.contains(&"B.Cu") { "bottom" } else { "top" }+}++/// The agent's edit_fp operations for an edit_footprint request, and what was not applied. `pads_now` is the+/// footprint's pad numbers in order (for sequential renumbering).+pub(crate) fn fp_ops(args: &Value, pads_now: &[String]) -> Result<(Vec<String>, Vec<String>), Value> {+ let bad = |m: String| json!({"success": false, "errorCode": "bad_args", "error": m});+ let mut ops = Vec::new();+ let mut not_applied = Vec::new();+ let f = |v: &Value| v.as_f64().unwrap_or(0.0);+ for p in args.get("pads").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let n = p.get("number").map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).ok_or_else(|| bad("pads[].number is required".into()))?;+ if p.get("delete").and_then(|v| v.as_bool()) == Some(true) { ops.push(format!("PD|{n}")); continue; }+ let set = p.get("set").cloned().unwrap_or(json!({}));+ if let Some((w, h)) = set.get("sizeMm").and_then(xy) { ops.push(format!("PS|{n}|size|{w}|{h}")); }+ if let Some((x, y)) = set.get("at").and_then(xy) { ops.push(format!("PS|{n}|at|{x}|{y}")); }+ if let Some(sh) = set.get("shape").and_then(|v| v.as_str()) { ops.push(format!("PS|{n}|shape|{}", if sh == "circle" || sh == "oval" { "round" } else { sh })); }+ if let Some(d) = set.get("drillMm").and_then(|v| v.as_f64()) { ops.push(format!("PS|{n}|drill|{d}")); }+ if let Some(r) = set.get("rotation").and_then(|v| v.as_f64()) { ops.push(format!("PS|{n}|rotation|{r}")); }+ if let Some(t) = set.get("type").and_then(|v| v.as_str()) { ops.push(format!("PS|{n}|type|{t}")); }+ else if set.get("layers").is_some() { ops.push(format!("PS|{n}|layer|{}", pad_layer_word(&set))); }+ if let Some(nn) = set.get("newNumber").and_then(|v| v.as_str()) { ops.push(format!("PS|{n}|number|{nn}")); }+ }+ for p in args.get("addPads").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let n = p.get("number").map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())).ok_or_else(|| bad("addPads[].number is required".into()))?;+ let (x, y) = p.get("at").and_then(xy).ok_or_else(|| bad(format!("addPads {n}: at [x, y] is required")))?;+ let (w, h) = p.get("sizeMm").and_then(xy).ok_or_else(|| bad(format!("addPads {n}: sizeMm [w, h] is required")))?;+ let sh = p.get("shape").and_then(|v| v.as_str()).unwrap_or("rect");+ ops.push(format!("PA|{n}|{x}|{y}|{w}|{h}|{}|{}|{}|{}|{}", if sh == "circle" || sh == "oval" { "round" } else { sh },+ p.get("drillMm").and_then(|v| v.as_f64()).unwrap_or(0.0), pad_layer_word(&p), p.get("rotation").and_then(|v| v.as_f64()).unwrap_or(0.0),+ p.get("type").and_then(|v| v.as_str()).unwrap_or("")));+ }+ if let Some(r) = args.get("renumber") {+ // two steps through temporary names, so 1->2 and 2->1 never meet+ let map: Vec<(String, String)> = if r.get("sequential").and_then(|v| v.as_bool()) == Some(true) {+ let start = r.get("start").and_then(|v| v.as_i64()).unwrap_or(1);+ pads_now.iter().enumerate().map(|(i, p)| (p.clone(), (start + i as i64).to_string())).collect()+ } else {+ r.get("map").and_then(|v| v.as_object()).map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string()))).collect()).unwrap_or_default()+ };+ for (i, (a, _)) in map.iter().enumerate() { ops.push(format!("PS|{a}|number|__adom{i}")); }+ for (i, (_, b)) in map.iter().enumerate() { ops.push(format!("PS|__adom{i}|number|{b}")); }+ }+ for g in args.get("graphics").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let ln = g.get("layer").and_then(|v| v.as_str()).unwrap_or("");+ let lid = fp_graphics_layer(ln).ok_or_else(|| bad(format!("graphics layer {ln}: F.SilkS, F.Fab, F.CrtYd, F.Mask, F.Paste (or B.), Mechanical<n>, L<id>")))?;+ let mode = g.get("mode").and_then(|v| v.as_str()).unwrap_or("append");+ if mode == "replace" || mode == "delete" { ops.push(format!("GD|{lid}")); }+ if mode == "delete" { continue; }+ let w = g.get("widthMm").and_then(|v| v.as_f64()).unwrap_or(0.12);+ for sh in g.get("shapes").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+ let line = |a: (f64, f64), b: (f64, f64)| format!("GL|{lid}|{}|{}|{}|{}|{w}", a.0, a.1, b.0, b.1);+ match sh.get("type").and_then(|v| v.as_str()).unwrap_or("") {+ "line" => ops.push(line(sh.get("start").and_then(xy).ok_or_else(|| bad("a line needs start".into()))?, sh.get("end").and_then(xy).ok_or_else(|| bad("a line needs end".into()))?)),+ "rect" => {+ let (a, b) = (sh.get("start").and_then(xy).ok_or_else(|| bad("a rect needs start".into()))?, sh.get("end").and_then(xy).ok_or_else(|| bad("a rect needs end".into()))?);+ for (p, q) in [(a, (b.0, a.1)), ((b.0, a.1), b), (b, (a.0, b.1)), ((a.0, b.1), a)] { ops.push(line(p, q)); }+ }+ "poly" => {+ let pts: Vec<(f64, f64)> = sh.get("points").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(xy).collect()).unwrap_or_default();+ for i in 0..pts.len() { if pts.len() > 1 { ops.push(line(pts[i], pts[(i + 1) % pts.len()])); } }+ }+ "circle" => {+ let c = sh.get("center").and_then(xy).ok_or_else(|| bad("a circle needs center".into()))?;+ ops.push(format!("GA|{lid}|{}|{}|{}|{w}|0|360", c.0, c.1, f(sh.get("radius").unwrap_or(&json!(0)))));+ }+ "arc" => {+ let c = sh.get("center").and_then(xy).ok_or_else(|| bad("an arc needs center, radius, startAngle, endAngle (degrees, counter-clockwise)".into()))?;+ ops.push(format!("GA|{lid}|{}|{}|{}|{w}|{}|{}", c.0, c.1, f(sh.get("radius").unwrap_or(&json!(0))), f(sh.get("startAngle").unwrap_or(&json!(0))), f(sh.get("endAngle").unwrap_or(&json!(360)))));+ }+ other => return Err(bad(format!("graphics shape type {other}: line, arc, rect, circle or poly"))),+ }+ }+ }+ if let Some(m) = args.get("metadata") {+ if let Some(d) = m.get("description").and_then(|v| v.as_str()) { ops.push(format!("MD|{}", d.replace(['|', '\n'], " "))); }+ // an Altium footprint carries no tags or BOM flags: those live on the component (its kind) and the symbol+ if m.get("tags").is_some() { not_applied.push("metadata.tags".to_string()); }+ if m.get("attributes").is_some() { not_applied.push("metadata.attributes (set them on the placed part: edit_parts)".to_string()); }+ }+ if args.pointer("/models/mode").and_then(|v| v.as_str()) == Some("delete") { ops.push("BD".into()); }+ Ok((ops, not_applied))+}++/// altium_edit_footprint {libraryPath, name, pads?, addPads?, renumber?, graphics?, metadata?, models?, dryRun?}+pub fn edit_footprint(args: &Value) -> Value {+ let (Some(lib), Some(name)) = (support::s(args, "libraryPath"), support::s(args, "name")) else { return bad("libraryPath (.PcbLib) and name are required") };+ let dry = args.get("dryRun").and_then(|v| v.as_bool()) == Some(true);+ if let Some(g) = support::need_licensed() { return g; }+ if let Some(e) = support::must_open(&lib, 60) { return e; }+ // the pads as they are, for sequential renumbering and to refuse an unknown footprint before any change+ let now = read_footprint(&json!({"libraryPath": lib, "name": name}));+ if now.get("success").and_then(|v| v.as_bool()) != Some(true) { return now; }+ let pads_now: Vec<String> = now["pads"].as_array().cloned().unwrap_or_default().iter().filter_map(|p| p["number"].as_str().map(str::to_string)).collect();+ let (ops, mut not_applied) = match fp_ops(args, &pads_now) { Ok(x) => x, Err(e) => return e };+ let models = args.get("models").cloned().unwrap_or(Value::Null);+ let model_list: Vec<Value> = models.get("list").and_then(|v| v.as_array()).cloned().unwrap_or_default();+ let model_mode = models.get("mode").and_then(|v| v.as_str()).unwrap_or("");+ for m in &model_list {+ for k in ["offset", "scale", "rotate"] { if m.get(k).is_some() { not_applied.push(format!("models.{k} (the body is aligned onto the pads)")); } }+ }+ not_applied.dedup();+ if ops.is_empty() && model_list.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no edits in the request"}); }+ if dry {+ return json!({"success": true, "dryRun": true, "operations": ops, "models": model_list, "notApplied": not_applied,+ "_hint": "Nothing changed. The operations run in this order: pads, addPads, renumber, graphics, metadata, models."});+ }+ let mut changes: Vec<Value> = Vec::new();+ let mut failed = 0;+ if !ops.is_empty() {+ let d = match agent_data(&agent::call("edit_fp", &[("name", name.clone()), ("path", lib.replace('/', "\\"))], Some(&ops.join("\n")), Duration::from_secs(120))) { Ok(d) => d, Err(e) => return e };+ failed += d["failed"].as_i64().unwrap_or(0);+ changes.extend(d["results"].as_array().cloned().unwrap_or_default());+ }+ for (i, m) in model_list.iter().enumerate() {+ let Some(step) = m.get("path").and_then(|v| v.as_str()) else { continue };+ let keep = model_mode == "append" || i > 0;+ let r = crate::library::add_body(&json!({"libraryPath": lib, "footprintName": name, "step": step, "keepExisting": keep}));+ let ok = r.get("success").and_then(|v| v.as_bool()) != Some(false);+ if !ok { failed += 1; }+ changes.push(json!(if ok { format!("ok:model {step}") } else { format!("err:model {step}: {}", r.get("error").and_then(|v| v.as_str()).unwrap_or("not added")) }));+ }+ let _ = support::must_open(&lib, 60);+ let saved = crate::surfaces::save(&json!({"filePath": lib}));+ let after = read_footprint(&json!({"libraryPath": lib, "name": name}));+ json!({"success": failed == 0, "changes": changes, "failed": failed, "notApplied": not_applied, "saved": saved.get("success"),+ "footprint": {"pads": after["pads"].as_array().map(|a| a.len()), "graphics": after["graphics"], "courtyardMm": after["courtyardMm"]},+ "_hint": "changes[] answers each operation in order (err: ones did not land). Boards that already use the footprint keep their own copy: update them with altium_swap_footprint."})+}+ /// altium_export_library_part {part, libraryPath, footprint?, footprintLibrary?, what?, outputDir?} pub fn export_library_part(args: &Value) -> Value { if let Some(g) = support::need_licensed() { return g; }
bridge-rs/src/svgart.rsadded+353@@ -0,0 +1,353 @@+//! import_svg: SVG artwork (a logo, a label) as filled regions on a board layer. The SVG's filled shapes are+//! flattened to polygons, a shape inside another becomes its hole, and each shape with its holes is one contour that+//! reaches every hole through a zero-width slit (Altium printed a region's hole contour filled; the slit form prints+//! open, measured on Develop 2026-10-28).++use serde_json::{json, Value};+use std::str::FromStr;++type Pt = (f64, f64);++#[derive(Clone, Copy)]+struct Tf { a: f64, b: f64, c: f64, d: f64, e: f64, f: f64 }++impl Tf {+ fn id() -> Self { Tf { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 } }+ /// self, then t applied inside it (SVG nesting: the parent's transform is outermost)+ fn then(&self, t: &Tf) -> Tf {+ Tf { a: self.a * t.a + self.c * t.b, b: self.b * t.a + self.d * t.b, c: self.a * t.c + self.c * t.d, d: self.b * t.c + self.d * t.d,+ e: self.a * t.e + self.c * t.f + self.e, f: self.b * t.e + self.d * t.f + self.f }+ }+ fn ap(&self, p: Pt) -> Pt { (self.a * p.0 + self.c * p.1 + self.e, self.b * p.0 + self.d * p.1 + self.f) }+ fn scale(&self) -> f64 { (self.a * self.d - self.b * self.c).abs().sqrt().max(1e-12) }+}++/// One element's style value, from its attribute or its style="" (the style wins).+fn style<'a>(n: &roxmltree::Node<'a, 'a>, key: &str) -> Option<String> {+ if let Some(s) = n.attribute("style") {+ for decl in s.split(';') {+ if let Some((k, v)) = decl.split_once(':') { if k.trim() == key { return Some(v.trim().to_string()); } }+ }+ }+ n.attribute(key).map(|v| v.trim().to_string())+}++/// The inherited value of a style property (fill, display, visibility...).+fn inherited(n: &roxmltree::Node, key: &str) -> Option<String> {+ let mut cur = Some(*n);+ while let Some(x) = cur {+ if x.is_element() { if let Some(v) = style(&x, key) { if v != "inherit" { return Some(v); } } }+ cur = x.parent();+ }+ None+}++fn num(n: &roxmltree::Node, k: &str) -> f64 {+ n.attribute(k).and_then(|v| svgtypes::Length::from_str(v).ok()).map(|l| l.number).unwrap_or(0.0)+}++/// Points along a cubic or quadratic curve, flattened to `tol` in the SVG's own units.+fn flatten_cubic(out: &mut Vec<Pt>, p0: Pt, p1: Pt, p2: Pt, p3: Pt, tol: f64) {+ let d = ((p1.0 - p0.0).hypot(p1.1 - p0.1) + (p2.0 - p1.0).hypot(p2.1 - p1.1) + (p3.0 - p2.0).hypot(p3.1 - p2.1)).max(1e-9);+ let n = ((d / tol).sqrt().ceil() as usize).clamp(2, 200);+ for i in 1..=n {+ let t = i as f64 / n as f64;+ let u = 1.0 - t;+ out.push((u * u * u * p0.0 + 3.0 * u * u * t * p1.0 + 3.0 * u * t * t * p2.0 + t * t * t * p3.0,+ u * u * u * p0.1 + 3.0 * u * u * t * p1.1 + 3.0 * u * t * t * p2.1 + t * t * t * p3.1));+ }+}++/// A path's closed subpaths, flattened. An open subpath is closed (SVG fills it as if it were).+fn path_rings(d: &str, tol: f64) -> Result<Vec<Vec<Pt>>, String> {+ let mut rings = Vec::new();+ let mut cur: Vec<Pt> = Vec::new();+ let mut last = (0.0, 0.0);+ for seg in svgtypes::SimplifyingPathParser::from(d) {+ match seg.map_err(|e| e.to_string())? {+ svgtypes::SimplePathSegment::MoveTo { x, y } => {+ if cur.len() > 2 { rings.push(std::mem::take(&mut cur)); } else { cur.clear(); }+ cur.push((x, y)); last = (x, y);+ }+ svgtypes::SimplePathSegment::LineTo { x, y } => { cur.push((x, y)); last = (x, y); }+ svgtypes::SimplePathSegment::CurveTo { x1, y1, x2, y2, x, y } => { flatten_cubic(&mut cur, last, (x1, y1), (x2, y2), (x, y), tol); last = (x, y); }+ svgtypes::SimplePathSegment::Quadratic { x1, y1, x, y } => {+ let c1 = (last.0 + 2.0 / 3.0 * (x1 - last.0), last.1 + 2.0 / 3.0 * (y1 - last.1));+ let c2 = (x + 2.0 / 3.0 * (x1 - x), y + 2.0 / 3.0 * (y1 - y));+ flatten_cubic(&mut cur, last, c1, c2, (x, y), tol); last = (x, y);+ }+ svgtypes::SimplePathSegment::ClosePath => {+ if cur.len() > 2 { last = cur[0]; rings.push(std::mem::take(&mut cur)); }+ }+ }+ }+ if cur.len() > 2 { rings.push(cur); }+ Ok(rings)+}++fn ellipse_ring(cx: f64, cy: f64, rx: f64, ry: f64, tol: f64) -> Vec<Pt> {+ let n = ((std::f64::consts::PI * (rx + ry) / (8.0 * tol).sqrt().max(1e-6)).ceil() as usize).clamp(16, 360);+ (0..n).map(|i| { let a = 2.0 * std::f64::consts::PI * i as f64 / n as f64; (cx + rx * a.cos(), cy + ry * a.sin()) }).collect()+}++fn rect_ring(x: f64, y: f64, w: f64, h: f64, rx: f64, ry: f64, tol: f64) -> Vec<Pt> {+ if rx <= 0.0 && ry <= 0.0 { return vec![(x, y), (x + w, y), (x + w, y + h), (x, y + h)]; }+ let (rx, ry) = (if rx > 0.0 { rx } else { ry }.min(w / 2.0), if ry > 0.0 { ry } else { rx }.min(h / 2.0));+ let mut out = Vec::new();+ let corners = [((x + w - rx, y + ry), -90.0), ((x + w - rx, y + h - ry), 0.0), ((x + rx, y + h - ry), 90.0), ((x + rx, y + ry), 180.0)];+ let n = ((rx.max(ry) / tol).sqrt().ceil() as usize).clamp(3, 24);+ for (c, a0) in corners {+ for i in 0..=n {+ let a = (a0 + 90.0 * i as f64 / n as f64).to_radians();+ out.push((c.0 + rx * a.cos(), c.1 + ry * a.sin()));+ }+ }+ out+}++fn point_list(s: &str) -> Vec<Pt> {+ let v: Vec<f64> = svgtypes::NumberListParser::from(s).filter_map(|n| n.ok()).collect();+ v.chunks(2).filter(|c| c.len() == 2).map(|c| (c[0], c[1])).collect()+}++pub struct Art { pub rings: Vec<Vec<Pt>>, pub skipped: Vec<Value>, pub mm_per_unit: Option<f64> }++/// Every filled shape of the SVG as rings in the root's user units (y down), transforms applied.+pub fn parse(text: &str, tol_units: f64) -> Result<Art, String> {+ let doc = roxmltree::Document::parse_with_options(text, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }).map_err(|e| format!("not an SVG: {e}"))?;+ let root = doc.root_element();+ if root.tag_name().name() != "svg" { return Err("the document's root is not <svg>".into()); }+ // the size of one user unit in mm, when the SVG says it (width="40mm" viewBox="0 0 400 200")+ let mm_per_unit = root.attribute("width").and_then(|w| svgtypes::Length::from_str(w).ok()).and_then(|l| {+ let mm = match l.unit {+ svgtypes::LengthUnit::Mm => l.number, svgtypes::LengthUnit::Cm => l.number * 10.0, svgtypes::LengthUnit::In => l.number * 25.4,+ svgtypes::LengthUnit::Pt => l.number * 25.4 / 72.0, svgtypes::LengthUnit::Pc => l.number * 25.4 / 6.0,+ svgtypes::LengthUnit::Px | svgtypes::LengthUnit::None => l.number * 25.4 / 96.0,+ _ => return None,+ };+ let vbw = root.attribute("viewBox").map(|v| point_list(v)).filter(|v| v.len() == 2).map(|v| v[1].0).unwrap_or(l.number);+ (vbw > 0.0).then_some(mm / vbw)+ });+ let mut art = Art { rings: Vec::new(), skipped: Vec::new(), mm_per_unit };+ let mut stack: Vec<(roxmltree::Node, Tf)> = vec![(root, Tf::id())];+ while let Some((n, tf)) = stack.pop() {+ for c in n.children().filter(|c| c.is_element()) {+ let name = c.tag_name().name();+ let mut t = tf;+ if let Some(s) = c.attribute("transform") {+ match svgtypes::Transform::from_str(s) {+ Ok(x) => t = tf.then(&Tf { a: x.a, b: x.b, c: x.c, d: x.d, e: x.e, f: x.f }),+ Err(e) => { art.skipped.push(json!({"element": name, "why": format!("transform not read: {e}")})); continue; }+ }+ }+ if style(&c, "display").as_deref() == Some("none") { continue; }+ match name {+ "g" | "a" | "switch" => { stack.push((c, t)); continue; }+ "defs" | "clipPath" | "mask" | "pattern" | "symbol" | "marker" | "title" | "desc" | "metadata" | "style" | "linearGradient" | "radialGradient" | "filter" => continue,+ "text" | "image" | "use" | "foreignObject" => { art.skipped.push(json!({"element": name, "why": match name { "text" => "text: convert it to paths first", "image" => "a bitmap image", _ => "not imported" }})); continue; }+ "line" => { art.skipped.push(json!({"element": name, "why": "a line has no area"})); continue; }+ _ => {}+ }+ if inherited(&c, "visibility").as_deref() == Some("hidden") { continue; }+ if inherited(&c, "fill").as_deref() == Some("none") {+ art.skipped.push(json!({"element": name, "id": c.attribute("id"), "why": "no fill (stroke only): give the SVG filled shapes"}));+ continue;+ }+ // flatten in the element's own units, to the tolerance asked in the root's units+ let tol = (tol_units / t.scale()).max(1e-6);+ let local: Vec<Vec<Pt>> = match name {+ "path" => match path_rings(c.attribute("d").unwrap_or(""), tol) { Ok(r) => r, Err(e) => { art.skipped.push(json!({"element": name, "why": format!("path data not read: {e}")})); continue; } },+ "rect" => vec![rect_ring(num(&c, "x"), num(&c, "y"), num(&c, "width"), num(&c, "height"), num(&c, "rx"), num(&c, "ry"), tol)],+ "circle" => vec![ellipse_ring(num(&c, "cx"), num(&c, "cy"), num(&c, "r"), num(&c, "r"), tol)],+ "ellipse" => vec![ellipse_ring(num(&c, "cx"), num(&c, "cy"), num(&c, "rx"), num(&c, "ry"), tol)],+ "polygon" | "polyline" => vec![point_list(c.attribute("points").unwrap_or(""))],+ other => { art.skipped.push(json!({"element": other, "why": "not a shape this import reads"})); continue; }+ };+ for r in local.into_iter().filter(|r| r.len() > 2) {+ art.rings.push(r.into_iter().map(|p| t.ap(p)).collect());+ }+ }+ }+ Ok(art)+}++fn area(r: &[Pt]) -> f64 {+ let n = r.len();+ (0..n).map(|i| { let (a, b) = (r[i], r[(i + 1) % n]); a.0 * b.1 - b.0 * a.1 }).sum::<f64>() / 2.0+}++fn inside(p: Pt, r: &[Pt]) -> bool {+ let mut c = false;+ let n = r.len();+ let mut j = n - 1;+ for i in 0..n {+ let (a, b) = (r[i], r[j]);+ if (a.1 > p.1) != (b.1 > p.1) && p.0 < (b.0 - a.0) * (p.1 - a.1) / (b.1 - a.1) + a.0 { c = !c; }+ j = i;+ }+ c+}++fn cross(o: Pt, a: Pt, b: Pt) -> f64 { (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0) }++/// Do segments ab and cd cross (touching at an end does not count)?+fn crosses(a: Pt, b: Pt, c: Pt, d: Pt) -> bool {+ let (d1, d2, d3, d4) = (cross(c, d, a), cross(c, d, b), cross(a, b, c), cross(a, b, d));+ ((d1 > 1e-12 && d2 < -1e-12) || (d1 < -1e-12 && d2 > 1e-12)) && ((d3 > 1e-12 && d4 < -1e-12) || (d3 < -1e-12 && d4 > 1e-12))+}++/// Group rings into shapes with holes by nesting (a ring inside an odd number of others is a hole of its tightest+/// container), then make each shape one contour that reaches its holes through zero-width slits.+pub fn contours(rings: &[Vec<Pt>]) -> Vec<Vec<Pt>> {+ let n = rings.len();+ let depth: Vec<usize> = (0..n).map(|i| (0..n).filter(|&j| j != i && inside(rings[i][0], &rings[j])).count()).collect();+ let mut out = Vec::new();+ for o in (0..n).filter(|&i| depth[i] % 2 == 0) {+ // counter-clockwise outside, clockwise holes+ let mut c = rings[o].clone();+ if area(&c) < 0.0 { c.reverse(); }+ let mut holes: Vec<Vec<Pt>> = (0..n).filter(|&h| depth[h] == depth[o] + 1 && inside(rings[h][0], &rings[o])+ && (0..n).all(|k| k == o || k == h || depth[k] != depth[o] + 1 || !inside(rings[h][0], &rings[k]) || depth[k] != depth[h]))+ .map(|h| { let mut r = rings[h].clone(); if area(&r) > 0.0 { r.reverse(); } r }).collect();+ // the leftmost holes first, each joined to the nearest point of the contour so far that it can see+ holes.sort_by(|a, b| a.iter().map(|p| p.0).fold(f64::MAX, f64::min).partial_cmp(&b.iter().map(|p| p.0).fold(f64::MAX, f64::min)).unwrap());+ for (hi, h) in holes.iter().enumerate() {+ let (hv, _) = h.iter().enumerate().min_by(|a, b| a.1 .0.partial_cmp(&b.1 .0).unwrap()).unwrap();+ let hp = h[hv];+ let others: Vec<&Vec<Pt>> = holes.iter().enumerate().filter(|(k, _)| *k > hi).map(|(_, r)| r).collect();+ let visible = |q: Pt| {+ let segs = |r: &[Pt]| (0..r.len()).any(|i| crosses(hp, q, r[i], r[(i + 1) % r.len()]));+ !segs(&c) && !segs(h) && !others.iter().any(|r| segs(r))+ };+ let mut best: Option<(usize, f64)> = None;+ for (i, q) in c.iter().enumerate() {+ let d = (q.0 - hp.0).hypot(q.1 - hp.1);+ if best.map(|b| d < b.1).unwrap_or(true) && visible(*q) { best = Some((i, d)); }+ }+ let Some((ci, _)) = best else { continue };+ let mut merged: Vec<Pt> = c[..=ci].to_vec();+ merged.extend(h[hv..].iter().chain(h[..=hv].iter()).copied());+ merged.push(c[ci]);+ merged.extend_from_slice(&c[ci + 1..]);+ c = merged;+ }+ out.push(c);+ }+ out+}++/// altium_import_svg {filePath?, expectedRevision?, svgPath | svg, at, widthMm?, scale?, anchor?, layer?, mirror?, net?, toleranceMm?, dryRun?}+pub fn import_svg(args: &Value) -> Value {+ let bad = |m: &str| json!({"success": false, "errorCode": "bad_args", "error": m});+ let text = match (crate::support::s(args, "svg"), crate::support::s(args, "svgPath")) {+ (Some(t), _) => t,+ (None, Some(p)) => match std::fs::read_to_string(&p) { Ok(t) => t, Err(e) => return json!({"success": false, "errorCode": "file_not_found", "error": format!("{p}: {e}")}) },+ _ => return bad("svgPath or svg is required"),+ };+ let Some(at) = args.get("at").and_then(|v| v.as_array()).filter(|a| a.len() == 2).and_then(|a| Some((a[0].as_f64()?, a[1].as_f64()?))) else { return bad("at [x, y] in mm is required") };+ let layer = crate::support::s(args, "layer").unwrap_or_else(|| "F.SilkS".into());+ let tol_mm = args.get("toleranceMm").and_then(|v| v.as_f64()).unwrap_or(0.02).max(0.001);+ // first pass in user units to learn the size, then flatten again to the tolerance in mm+ let probe = match parse(&text, 0.5) { Ok(a) => a, Err(e) => return json!({"success": false, "errorCode": "bad_svg", "error": e}) };+ let pts: Vec<Pt> = probe.rings.iter().flatten().copied().collect();+ if pts.is_empty() {+ return json!({"success": false, "errorCode": "nothing_to_import", "error": "the SVG has no filled shape", "skipped": probe.skipped,+ "_hint": "Filled shapes import; stroke-only artwork and text do not (convert text and strokes to filled paths first)."});+ }+ let (x0, y0, x1, y1) = pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));+ let (w, h) = ((x1 - x0).max(1e-9), (y1 - y0).max(1e-9));+ let scale = args.get("scale").and_then(|v| v.as_f64()).unwrap_or(1.0);+ let k = match args.get("widthMm").and_then(|v| v.as_f64()) {+ Some(wm) if wm > 0.0 => wm / w,+ _ => probe.mm_per_unit.unwrap_or(25.4 / 96.0) * scale,+ };+ let art = match parse(&text, tol_mm / k) { Ok(a) => a, Err(e) => return json!({"success": false, "errorCode": "bad_svg", "error": e}) };+ let bottom = layer.starts_with("B.");+ let mirror = args.get("mirror").and_then(|v| v.as_bool()).unwrap_or(bottom);+ let center = args.get("anchor").and_then(|v| v.as_str()) == Some("center");+ let (wm, hm) = (w * k, h * k);+ // SVG y runs down, the board's up; the artwork's top-left (or centre) lands on at+ let to_board = |p: Pt| -> Pt {+ let u = if mirror { x1 - p.0 } else { p.0 - x0 } * k;+ let v = (p.1 - y0) * k;+ if center { (at.0 - wm / 2.0 + u, at.1 + hm / 2.0 - v) } else { (at.0 + u, at.1 - v) }+ };+ let rings: Vec<Vec<Pt>> = art.rings.iter().map(|r| r.iter().map(|p| to_board(*p)).collect()).collect();+ let shapes = contours(&rings);+ let holes = rings.len() - shapes.len();+ let plan = json!({"polygons": shapes.len(), "holes": holes, "points": shapes.iter().map(|s| s.len()).sum::<usize>(), "sizeMm": [(wm * 1000.0).round() / 1000.0, (hm * 1000.0).round() / 1000.0],+ "layer": layer, "mirror": mirror, "skipped": art.skipped});+ if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {+ let mut p = plan; p["success"] = json!(true); p["dryRun"] = json!(true);+ p["_hint"] = json!("Nothing changed. Call again without dryRun to place it.");+ return p;+ }+ if let Some(g) = crate::support::need_licensed() { return g; }+ if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }+ let before = match crate::routing::guarded(args) { Ok(s) => s, Err(e) => return e };+ let lid = match layer.as_str() {+ "F.SilkS" => Some(33), "B.SilkS" => Some(34), "F.Paste" => Some(35), "B.Paste" => Some(36), "F.Mask" => Some(37), "B.Mask" => Some(38),+ l => l.strip_prefix('L').and_then(|n| n.parse::<i64>().ok()).or_else(|| crate::routing::layer_id(&json!(l))),+ };+ let Some(lid) = lid else {+ return bad(&format!("layer {layer}: F.SilkS, B.SilkS, F.Mask, B.Mask, a copper layer (F.Cu, In1.Cu, B.Cu) or Altium's L<id>"));+ };+ let net = crate::support::s(args, "net").unwrap_or_default();+ let per = crate::routing::PER_MM;+ let ops: Vec<String> = shapes.iter().map(|s| format!("Y|{lid}|{net}|{}", s.iter().map(|p| format!("{},{}", (p.0 * per).round() as i64, (p.1 * per).round() as i64)).collect::<Vec<_>>().join(";"))).collect();+ let mut r = crate::routing::apply(&ops, &before, "import_svg");+ let ids: Vec<Value> = r["results"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).filter_map(|x| x.strip_prefix("ok:")).map(|k| json!(k)).collect()).unwrap_or_default();+ for (k, v) in plan.as_object().unwrap() { r[k] = v.clone(); }+ r["ids"] = json!(ids);+ if !net.is_empty() || lid <= 32 { r["_hint"] = json!("On copper the artwork is graphics on the net given: run altium_run_drc."); }+ r+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_square_with_a_square_hole_is_one_contour_with_a_slit() {+ let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40mm" height="40mm" viewBox="0 0 40 40">+ <path d="M0 0 H40 V40 H0 Z M10 10 V30 H30 V10 Z"/></svg>"#;+ let art = parse(svg, 0.01).unwrap();+ assert_eq!(art.rings.len(), 2);+ assert_eq!(art.mm_per_unit, Some(1.0));+ let c = contours(&art.rings);+ assert_eq!(c.len(), 1);+ // 4 outside, 4 + 1 around the hole, back to the outside: 10 points; the area is 40^2 - 20^2+ assert_eq!(c[0].len(), 10);+ assert!((area(&c[0]).abs() - 1200.0).abs() < 1e-6, "{}", area(&c[0]));+ }++ #[test]+ fn stroke_only_and_text_are_skipped_with_a_reason() {+ let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><g fill="none" stroke="black"><path d="M0 0 L10 10"/></g>+ <text>Hi</text><circle cx="5" cy="5" r="2"/></svg>"#;+ let art = parse(svg, 0.01).unwrap();+ assert_eq!(art.rings.len(), 1);+ assert_eq!(art.skipped.len(), 2);+ }++ #[test]+ fn transforms_and_arcs_are_applied() {+ let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><g transform="translate(100 0) scale(2)">+ <path d="M0 0 A5 5 0 0 1 10 0 Z"/></g></svg>"#;+ let art = parse(svg, 0.001).unwrap();+ let xs: Vec<f64> = art.rings[0].iter().map(|p| p.0).collect();+ assert!(xs.iter().cloned().fold(f64::MAX, f64::min) >= 99.999 && xs.iter().cloned().fold(f64::MIN, f64::max) <= 120.001);+ // a half circle of radius 10 after the scale+ assert!((area(&art.rings[0]).abs() - std::f64::consts::PI * 50.0).abs() < 0.5, "{}", area(&art.rings[0]));+ }++ #[test]+ fn letter_o_holes_go_to_their_own_letter() {+ // two rings each with a hole: two contours, each reaching only its own hole+ let svg = r#"<svg xmlns="http://www.w3.org/2000/svg">+ <path d="M0 0 H10 V10 H0 Z M3 3 V7 H7 V3 Z"/><path d="M20 0 H30 V10 H20 Z M23 3 V7 H27 V3 Z"/></svg>"#;+ let c = contours(&parse(svg, 0.01).unwrap().rings);+ assert_eq!(c.len(), 2);+ for s in &c { assert!((area(s).abs() - 84.0).abs() < 1e-6); }+ }+}
bridge-rs/src/verbs.rs+31−1@@ -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- "routing_state", "route_net", "move_parts", "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", "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", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",+ "routing_state", "route_net", "move_parts", "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", "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",@@ -764,6 +764,30 @@ fn describe() -> Value { json!({"filePath": "path to the board file (default: the board open in the tool)", "outputDir": "folder for the output (default beside the board)", "version": "B|C, default C", "units": "mm|in, default mm", "compress": "bool, default false: zip the XML", "bomFields": "{mpn, manufacturer, distributorPn, distributor}: the part field names that carry these, so the embedded BOM is useful to the fab"}), json!({"file": "path"}), 600, "Name the part fields with bomFields, or the BOM inside the file carries no part numbers.", &["export_manufacturing", "run_drc"], &["Run run_drc first: the file carries the board's errors with it.", "Altium writes it with its manufacturing template's settings: units, compression and version options are reported under optionsNotApplied.", "The board must be a document of a .PrjPcb in its folder."], json!({"filePath": "C:/proj/Board.PcbDoc", "bomFields": {"mpn": "MPN"}})),+ verb_doc("generate_body", "Make a part's 3D body from its package family and its datasheet dimensions (chip, SOIC, QFN, QFP, BGA, SOT-23, DFN, MELF, electrolytic can, crystal, pin header), to IPC-7351 proportions, and write it as a STEP file.",+ json!({"family": "chip | soic | qfn | qfp | bga | sot23 | dfn | melf | ecap | crystal | header (required; an unknown one is answered with the families the bridge supports)", "dimensionsMm": "{letter: mm}: the package drawing's JEDEC letters (A height, A1 standoff, D body length, E lead span, E1 body width, D1 body length of a QFP, b lead width, e pitch, L lead length, c lead thickness, D2/E2 exposed pad) plus pins (rows, cols for a BGA); a missing one takes the family's default", "marking": "text on the top face (not made yet: reported under notApplied)", "markingStyle": "raised | engraved (default raised)", "outputPath": "the .step file to write (required)"}),+ json!({"stepPath": "path", "family": "string", "dimensionsMm": "{letter: mm}: every dimension used, defaults included", "bboxMm": "{x, y, z}", "solids": "int", "marking": "string | null", "families": "[string] (when family is unknown)"}), 60,+ "The body is in the package's own frame (IPC-7351 zero orientation, pin 1 top-left, seated on z = 0), ready for add_body. Compare bboxMm with the datasheet's body size before attaching it.", &["add_body", "bodies", "export_step"], &["A wrong dimension gives a plausible but wrong body: nothing checks it against a datasheet.", "Written by the bridge, no CAD tool needed: plain prisms (round cans and balls are many-sided), a dark body and bright leads.", "A marking is not made yet: the body is plain and notApplied says so."], json!({"family": "soic", "dimensionsMm": {"pins": 8, "D": 4.9, "E1": 3.9, "E": 6.0, "A": 1.75, "e": 1.27}, "outputPath": "C:/lib/SOIC8.step"})),+ verb_doc("edit_footprint", "Edit a library footprint in place: change, delete, add or renumber pads; add, replace or delete graphics on a layer; set its description; replace, add or delete 3D models. Everything not edited stays as it was.",+ json!({"libraryPath": "path to the footprint library (required)", "name": "the footprint's name (required)", "pads": "[{number, set?: {sizeMm, at, shape, drillMm, layers, rotation, type, newNumber}, delete?: true}]", "addPads": "[pad]: {number, at, sizeMm, shape, drillMm, layers, rotation, type}", "renumber": "{map: {\"1\": \"A1\"}} | {sequential: true, start?: 1}", "graphics": "[{layer, mode: append|replace|delete, widthMm?, shapes: [{type: line {start, end} | arc {center, radius, startAngle, endAngle} | rect {start, end} | circle {center, radius} | poly {points}}]}]", "metadata": "{description?, tags?, attributes?}", "models": "{mode: replace|append|delete, list: [{path, offset, scale, rotate}]}", "dryRun": "bool, default false: answer the plan and change nothing"}),+ json!({"changes": "[string]: what was done, in order (ok:... or err:...)", "notApplied": "[string]", "footprint": "{pads, graphics, courtyardMm} read back"}), 300,+ "Operations run in the order pads, addPads, renumber, graphics, metadata, models. An edited pad keeps its id. Positions are mm from the footprint's origin, as read_footprint gives them.", &["read_footprint", "swap_footprint", "add_body"], &["Boards that already use the footprint keep their own copy: update them with swap_footprint.", "Graphics replace and delete touch shapes only, never text on that layer.", "An Altium footprint has no tags or BOM attributes (they belong to the placed part): those are reported under notApplied.", "Models are aligned onto the pads by add_body: offset, scale and rotate are reported under notApplied."], json!({"libraryPath": "C:/lib/Parts.PcbLib", "name": "SOIC8", "pads": [{"number": "1", "set": {"sizeMm": [1.6, 0.6]}}], "metadata": {"description": "SOIC-8, wider pads"}})),+ verb_doc("import_svg", "Import SVG artwork (a logo, a label) as filled polygons on a silkscreen, copper, mask or user layer, at a position and size; curves flattened, holes kept. One undo step.",+ json!({"filePath": "path to the board file (default: the board open in the tool)", "expectedRevision": "string: the revision you last read (routing_state); refused with stale_board if the board changed", "svgPath": "path to the .svg", "svg": "the SVG text (instead of svgPath)", "at": "[x, y] mm (required)", "widthMm": "number: the artwork's width (or scale)", "scale": "number, default 1", "anchor": "topleft|center, default topleft: which point of the artwork at names", "layer": "default F.SilkS", "mirror": "bool, default true on bottom layers", "net": "a net for artwork on copper", "toleranceMm": "number, default 0.02: curve flattening", "dryRun": "bool, default false: answer the plan and change nothing"}),+ json!({"polygons": "int", "holes": "int", "sizeMm": "[w, h]", "ids": "[id]", "skipped": "[{element, why}]", "revision": "string: the board's new revision"}), 300,+ "Filled shapes import; text and images are listed in skipped (convert text to paths first). A shape inside another becomes a hole.", &["routing_state", "remove_graphics", "render_board_layers"], &["Stroke-only artwork imports nothing: give the SVG filled shapes.", "On copper the shapes are graphics: give net to tie them to a net, and run run_drc.", "On a bottom layer the artwork is mirrored so it reads correctly from the back; mirror:false keeps it as drawn.", "Without widthMm the size comes from the SVG's width in mm or in, else 96 px to the inch."], json!({"svgPath": "C:/art/logo.svg", "at": [5, 15], "widthMm": 12, "layer": "F.SilkS"})),+ verb_doc("export_gencad", "Export the board as GenCAD 1.4, the input of test-fixture tools and some assembly houses' CAM.",+ json!({"filePath": "path to the board file (default: the board open in the tool)", "outputDir": "folder for the output (default beside the board)", "uniquePins": "bool, default false: rename duplicate pad numbers (several fixture tools need it)", "flipBottomPads": "bool, default false", "useDrillOrigin": "bool, default false: coordinates from the drill origin instead of the board's origin"}),+ json!({"file": "path", "counts": "{components, shapes, pads, signals, routes, vias, copperWithoutNet}", "optionsNotApplied": "[option]"}), 300,+ "Ask the fixture or assembly house which options it needs; uniquePins is the common one.", &["export_manufacturing", "export_ipc356"], &["Run run_drc first: the file carries the board's errors with it.", "Altium has no GenCAD exporter: the bridge writes it from the board model, in inches. useDrillOrigin is reported under optionsNotApplied."], json!({"filePath": "C:/proj/Board.PcbDoc", "uniquePins": true})),+ verb_doc("export_dxf", "Export chosen board layers to DXF, one file per layer (the outline, panel drawings, stencils, enclosure work).",+ json!({"filePath": "path to the board file (default: the board open in the tool)", "layers": "[\"Edge.Cuts\", \"F.Cu\"]: layer names (required; there is no sensible default)", "outputDir": "folder for the output (default a DXF folder beside the board)", "units": "mm|in, default mm", "contours": "bool, default false: join outline segments into polylines (most CAM and laser tools want it)", "titleBlock": "bool, default false", "excludeDesignators": "bool, default false", "excludeValues": "bool, default false", "useDrillOrigin": "bool, default false"}),+ json!({"files": "[{layer, path, entities}]", "unknownLayers": "[name]", "optionsNotApplied": "[option]"}), 300,+ "One file per layer, named after the board and the layer. For an enclosure drawing export Edge.Cuts with contours:true.", &["render_board_layers", "export_step"], &["The board's DXF only: a mechanical DXF of a 3D design is a different job and not this verb.", "Written from the board model, not Altium's exporter: texts are not drawn, and titleBlock and useDrillOrigin are reported under optionsNotApplied."], json!({"filePath": "C:/proj/Board.PcbDoc", "layers": ["Edge.Cuts"], "contours": true})),+ verb_doc("export_ipc356", "Export the IPC-D-356 netlist of the board, for bare-board electrical test (flying probe or bed of nails).",+ json!({"filePath": "path to the board file (default: the board open in the tool)", "outputDir": "folder for the output (default beside the board)"}),+ json!({"file": "path", "files": "[path]"}), 600,+ "Send it with the Gerbers when the fab tests boards against the netlist. Altium writes it as its Test Point Report in IPC-D-356A, every pad and via on both sides.", &["export_manufacturing", "netlist", "run_drc"], &["Run run_drc first: the file carries the board's errors with it.", "The board must be a document of a .PrjPcb in its folder."], json!({"filePath": "C:/proj/Board.PcbDoc"})), verb_doc("document_info", "The active document: its name, what kind it is, whether it has unsaved changes, where it is saved and which version it is. Read only; opens nothing.", json!({}), json!({"name": "string", "kind": "project | schematic | board | library | model | other", "saved": "bool: it exists as a file or a cloud item", "modified": "bool: it has unsaved changes", "path": "file path or cloud location | null", "version": "int | null: the saved version, where the tool keeps versions", "project": "string | null"}), 300,@@ -1988,6 +2012,12 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "read_footprint" => crate::project::read_footprint(args), "export_odb" => crate::manufacturing::export_format(args, "odb"), "export_ipc2581" => crate::manufacturing::export_format(args, "ipc2581"),+ "export_ipc356" => crate::manufacturing::export_format(args, "ipc356"),+ "export_dxf" => crate::boardfiles::export_dxf(args),+ "export_gencad" => crate::boardfiles::export_gencad(args),+ "import_svg" => crate::svgart::import_svg(args),+ "edit_footprint" => crate::project::edit_footprint(args),+ "generate_body" => crate::body3d::generate_body(args), "remove_parts" => crate::boardedit::remove_parts(args), "edit_parts" => crate::boardedit::edit_parts(args), "align_parts" => crate::boardedit::align_parts(args),
dev-skills/altium-bridge-test/run_verb_tests.py+15−1@@ -161,6 +161,9 @@ def matrix(w): M["remove_footprint"] = dict(phase=2, **ok(libraryPath=PL, footprintName="BAT_FP_RENAMED")) M["xcopy_footprint"] = dict(phase=2, **anyo("cross-library copy onto itself: ok or named refusal", fromLib=PL, toLib=PL, **{"from": "BAT_FP", "to": "BAT_FP_X"})) M["add_body"] = dict(phase=2, **anyo("extruded body on the scratch footprint", libraryPath=PL, footprintName="BAT_FP", hMil=40))+ M["edit_footprint"] = dict(phase=2.5, **ok(libraryPath=PL, name="BAT_FP", addPads=[{"number": "99", "at": [5, 5], "sizeMm": [0.5, 0.5]}],+ metadata={"description": "edited by the battery"}),+ check=lambda d: d.get("failed") == 0 and len(d.get("changes") or []) == 2) M["build_footprint"] = dict(phase=2, **ref("no spec given: must refuse by name", libraryPath=PL)) M["cleanup_libs"] = dict(phase=2, **anyo("library housekeeping", libraryPath=SL)) M["save"] = dict(phase=2, **ok(filePath=SL))@@ -399,6 +402,9 @@ def matrix(w): M["copy_routing"] = dict(phase=3.5, **anyo("planned, or nothing in the box", filePath=LB, box=[0, 0, 40, 20], offset=[0, 30], keepUnmappedNets=True, dryRun=True)) M["check_clearance"] = dict(phase=3.5, **ok(filePath=LB, thresholdMm=20), check=lambda d: isinstance(d.get("pairs"), list)) M["remove_graphics"] = dict(phase=3.5, **ok(filePath=LB), check=lambda d: (d.get("count") or 0) > 0)+ M["import_svg"] = dict(phase=3.5, **ok(filePath=LB, at=[2, 18], widthMm=4, layer="F.SilkS",+ svg='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 20"><path d="M0 0 H20 V20 H0 Z M5 5 V15 H15 V5 Z"/><circle cx="32" cy="10" r="8"/></svg>'),+ check=lambda d: d.get("polygons") == 2 and d.get("holes") == 1) # 0.2.77: documents, projects, renders and library parts (reads, a new scratch project, dry runs) M["document_info"] = dict(phase=3.5, **ok(), check=lambda d: d.get("kind") in ("board", "schematic", "library", "project", "other") and isinstance(d.get("openDocuments"), list)) M["project_info"] = dict(phase=3.5, **ok(project=LP), check=lambda d: d.get("name") == "lane" and len(d.get("files") or []) >= 3)@@ -417,6 +423,14 @@ def matrix(w): # ---- phase 4: outputs -------------------------------------------------------------------- M["export_odb"] = dict(phase=4, timeout=700, **anyo("ODB++ of the lane board, or no project / OutJob named", filePath=LB)) M["export_ipc2581"] = dict(phase=4, timeout=700, **anyo("IPC-2581 of the lane board, or no project / OutJob named", filePath=LB))+ # 0.2.78: the standard's last fab exports, SVG artwork, footprint edits and generated bodies+ M["export_ipc356"] = dict(phase=4, timeout=700, **anyo("IPC-D-356A of the lane board, or no project / OutJob named", filePath=LB))+ M["export_dxf"] = dict(phase=4, timeout=300, **ok(filePath=LB, layers=["Edge.Cuts", "F.Cu"], contours=True, outputDir=D + "/dxf"),+ check=lambda d: len(d.get("files") or []) == 2 and not d.get("unknownLayers"))+ M["export_gencad"] = dict(phase=4, timeout=300, **ok(filePath=LB, outputDir=D + "/gencad", uniquePins=True),+ check=lambda d: str(d.get("file", "")).endswith(".cad") and (d.get("counts") or {}).get("components", 0) > 0)+ M["generate_body"] = dict(phase=4, **ok(family="qfn", outputPath=D + "/bodies/QFN16.step"),+ check=lambda d: abs(((d.get("bboxMm") or {}).get("x") or 0) - 4.0) < 0.01) M["export_step"] = dict(phase=4, timeout=300, **anyo("STEP of the battery board", filePath=PD, output=D + "/battery.step")) M["export_bom"] = dict(phase=4, **anyo("missing OutJob: named refusal (the demo OutJob opens its .xlsx on screen)", outjobPath=D + "/missing.OutJob")) M["export_gerber"] = dict(phase=4, **anyo("missing OutJob: named refusal", outjobPath=D + "/missing.OutJob"))@@ -437,7 +451,7 @@ def matrix(w): # only seen when the wait expires (18 s to over 60 s on one machine). Keep this ABOVE the verb's # own declared budget (180 s), or the battery blames the bridge for its own cut-off. M["selftest_script_error"] = dict(phase=5, timeout=220, **ok(), check=lambda d: d.get("netWorks") is True)- M["agent_recover"] = dict(phase=5, **ok())+ M["agent_recover"] = dict(phase=5, timeout=120, **ok()) # 40-50 s on AD 26: 60 s was a coin toss M["agent_stop"] = dict(phase=6, **ok()) M["close"] = dict(phase=6, timeout=300, **ok(discardChanges=True, waitSec=90), note="releases the licence seat; every modified document is the battery's own scratch")
package.json+25−2@@ -1,6 +1,6 @@ { "slug": "altium-bridge",- "version": "0.2.77",+ "version": "0.2.78", "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": [@@ -222,7 +222,30 @@ "copy routing to another channel in altium", "altium part clearance check", "export ipc-2581 from altium",- "check my altium board against pcbway limits"+ "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" ], "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.", "sample_prompts": [
page.json+26−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.77",+ "version": "0.2.78", "hero": { "type": "image", "path": "screenshots/hero.png"@@ -214,7 +214,30 @@ "copy routing to another channel in altium", "altium part clearance check", "export ipc-2581 from altium",- "check my altium board against pcbway limits"+ "check my altium board against pcbway limits",+ "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",+ "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" ], "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.", "metadata": {},@@ -269,4 +292,4 @@ "tools/symbol_modes.py", "uninstall.sh" ]-}+}
skills/altium-boards/SKILL.md+10@@ -447,3 +447,13 @@ altium_board_features '{"keepouts":[{"rect":[20,2,26,8]},{"rect":[20,12,26,18]," - `teardrops` runs Altium's Tools > Teardrops with its dialog answered in the background (vias, SMD pads, tracks, T-junctions; all or selected) and counts teardrops before and after. Measured: 0 to 12 on the battery board, and `remove:true` back to 0. Repour and DRC afterwards.++## Artwork from an SVG (0.2.78)++`altium_import_svg {svgPath | svg, at, widthMm?, layer?, net?, mirror?, dryRun?}` puts filled SVG shapes on a layer+(F.SilkS by default) as regions, at `at` (the artwork's top-left, or its centre with `anchor:"center"`), one undo step.+A shape inside another becomes its hole; curves are flattened to `toleranceMm` (0.02). Text, images and stroke-only+shapes are listed in `skipped`: convert text and strokes to filled paths first. On a bottom layer the artwork is+mirrored so it reads from the back. `dryRun:true` answers the size and polygon count first. The reply's `ids` remove+a shape again with altium_remove_graphics.+
skills/altium-libraries/SKILL.md+12@@ -206,3 +206,15 @@ altium_footprint_from_land_pattern '{"libraryPath":"C:\\lib\\Parts.PcbLib","name at the origin. The source libraries join the project and are not rewritten. `overwrite:true` closes only that folder's documents before replacing it. +## Edit a footprint in place, and make a 3D body (0.2.78)++- `altium_edit_footprint {libraryPath, name, pads?, addPads?, renumber?, graphics?, metadata?, models?, dryRun?}`:+ change, delete, add or renumber pads (`renumber: {map: {"1": "A1"}}` or `{sequential: true}`), append to, replace+ or delete a layer's graphics, set the description, and replace, append or delete 3D models, in that order. Positions+ are mm from the footprint's origin, as altium_read_footprint gives them; read it back to check. Boards that already+ use the footprint keep their copy (altium_swap_footprint).+- `altium_generate_body {family, dimensionsMm?, outputPath}`: a STEP body from the package family (chip, soic,+ sot23, qfp, qfn, dfn, bga, melf, ecap, crystal, header) and the datasheet's JEDEC letters; missing letters take+ the family's defaults, and `dimensionsMm` in the reply lists every one used. Compare `bboxMm` with the datasheet,+ then attach it with altium_add_body (or `edit_footprint {models: {mode: "replace", list: [{path}]}}`).+
skills/altium-outputs/SKILL.md+10@@ -123,6 +123,16 @@ bottom, parts with their designators) and its PCB Print fabrication drawing to t Assembly and Fabrication OutJob templates the install ships. Measured on the battery project: 6 pages (2 sheets, the composite, the drawings) in 26 s. `board: true` alone adds just the composite print. +## Fixture, test and CAM files (0.2.78)++- `altium_export_ipc356 {filePath?, outputDir?}`: the IPC-D-356A netlist for bare-board electrical test (Altium's Test+ Point Report, IPC format, both sides). The board must be in a .PrjPcb beside it.+- `altium_export_gencad {filePath?, outputDir?, uniquePins?}`: GenCAD 1.4 for fixture tools and assembly CAM. Altium+ has no GenCAD exporter, so the bridge writes it from the board model, in inches; its syntax follows KiCad's.+- `altium_export_dxf {filePath?, layers, contours?, units?, outputDir?}`: one DXF per layer, written from the board+ model (Edge.Cuts, copper, silkscreen, mask, paste, Mechanical<n>). `contours:true` makes the outline one closed+ polyline, what CAM and laser tools want. Texts are not drawn.+ ## Board pictures without a window (0.2.77) - `altium_render_board_layers {filePath?, preset?, layers?, mirror?, dpi?, area?, outputPath?}`: Altium's composite
src/BRIDGE_VERSION+1−1@@ -1 +1 @@-0.2.77+0.2.78
src/agent/AdomAgent.pas.tmpl+343−7@@ -4381,13 +4381,61 @@ Begin End; { Copy a footprint ACROSS libraries: fromLib(path)+from -> the CURRENT PcbLib as to. }+{ a footprint's pad by its name, Nil when it has none }+Function FpPad(Fp : IPCB_LibComponent; Name : String) : IPCB_Pad;+Var+ GIt : IPCB_GroupIterator;+ P : IPCB_Pad;+Begin+ Result := Nil;+ GIt := Fp.GroupIterator_Create;+ GIt.AddFilter_ObjectSet(MkSet(ePadObject));+ GIt.AddFilter_LayerSet(AllLayers);+ P := GIt.FirstPCBObject;+ While P <> Nil Do+ Begin+ If P.Name = Name Then Begin Result := P; Break; End;+ P := GIt.NextPCBObject;+ End;+ Fp.GroupIterator_Destroy(GIt);+End;++{ the name of a footprint's first pad, '' when it has none }+Function FirstPadName(Fp : IPCB_LibComponent) : String;+Var+ GIt : IPCB_GroupIterator;+ P : IPCB_Pad;+Begin+ Result := '';+ GIt := Fp.GroupIterator_Create;+ GIt.AddFilter_ObjectSet(MkSet(ePadObject));+ GIt.AddFilter_LayerSet(AllLayers);+ P := GIt.FirstPCBObject;+ If P <> Nil Then Result := P.Name;+ Fp.GroupIterator_Destroy(GIt);+End;++{ any primitive of a footprint, Nil when it is empty }+Function FpFirstAny(Fp : IPCB_LibComponent) : IPCB_Primitive;+Var+ GIt : IPCB_GroupIterator;+Begin+ GIt := Fp.GroupIterator_Create;+ GIt.AddFilter_LayerSet(AllLayers);+ Result := GIt.FirstPCBObject;+ Fp.GroupIterator_Destroy(GIt);+End;+ Function CmdXCopyFootprint(Lines : TStringList) : String; Var SrcLib, DstLib : IPCB_Library; Src, Dst : IPCB_LibComponent; GIt : IPCB_GroupIterator; Prim, Cpy : IPCB_Primitive;- NCopied : Integer;+ SP, DP : IPCB_Pad;+ NCopied, DX, DY : Integer;+ Dflt : IPCB_LibComponent;+ Dropped : String; Begin DstLib := PCBServer.GetCurrentPCBLibrary; If DstLib = Nil Then@@ -4423,18 +4471,43 @@ Begin While Prim <> Nil Do Begin Cpy := Prim.Replicate;- { a footprint sits on its library's origin, and libraries differ (a new one is at 50000 mil, measured- 2026-10-27), so the copy moves by the difference }- Cpy.MoveByXY(DstLib.Board.XOrigin - SrcLib.Board.XOrigin, DstLib.Board.YOrigin - SrcLib.Board.YOrigin); Dst.AddPCBObject(Cpy); NCopied := NCopied + 1; Prim := GIt.NextPCBObject; End; Src.GroupIterator_Destroy(GIt); DstLib.RegisterComponent(Dst);+ { the copy sits where the source sat on ITS library's origin: a pad keeps its place from the origin. A library's+ origin read from a library not on display was stale (the copy landed 1270 mm off, 2026-10-28), so both+ footprints are shown first and the shift is measured on a pad. }+ SrcLib.CurrentComponent := Src;+ DstLib.CurrentComponent := Dst;+ SP := FpPad(Src, FirstPadName(Src));+ DP := FpPad(Dst, FirstPadName(Src));+ If (SP <> Nil) And (DP <> Nil) Then+ Begin+ DX := (SP.X - SrcLib.Board.XOrigin) - (DP.X - DstLib.Board.XOrigin);+ DY := (SP.Y - SrcLib.Board.YOrigin) - (DP.Y - DstLib.Board.YOrigin);+ If (DX <> 0) Or (DY <> 0) Then+ Begin+ GIt := Dst.GroupIterator_Create;+ GIt.AddFilter_LayerSet(AllLayers);+ Prim := GIt.FirstPCBObject;+ While Prim <> Nil Do Begin Prim.MoveByXY(DX, DY); Prim := GIt.NextPCBObject; End;+ Dst.GroupIterator_Destroy(GIt);+ End;+ End;+ { a PcbLib Altium has just made holds an empty PCBComponent_1: it goes once a real footprint is in }+ Dropped := '';+ Dflt := FindFp(DstLib, 'PCBComponent_1');+ If (Dflt <> Nil) And (UpperCase(Dst.Name) <> 'PCBCOMPONENT_1') And (FirstPadName(Dflt) = '') And (FpFirstAny(Dflt) = Nil) Then+ Begin+ DstLib.RemoveComponent(Dflt);+ Dropped := 'PCBComponent_1';+ End; PCBServer.PostProcess; DstLib.Board.ViewManager_FullUpdate;- Result := '{' + JRaw('ok','true') + ',' + JStr('to', Dst.Name) + ',' + JRaw('primitives', IntToStr(NCopied)) + '}';+ Result := '{' + JRaw('ok','true') + ',' + JStr('to', Dst.Name) + ',' + JRaw('primitives', IntToStr(NCopied)) + ',' + JStr('removedDefault', Dropped) + '}'; End; @@ -6257,6 +6330,9 @@ Var Comp : IPCB_Component; Prim : IPCB_Primitive; Net : IPCB_Net;+ Reg : IPCB_Region;+ Cont : IPCB_Contour;+ PtList, Pt : String; I, N, Okay, Failed : Integer; Begin Board := PCBServer.GetCurrentPCBBoard;@@ -6426,6 +6502,31 @@ Begin If Prim = Nil Then Res := 'err:not found: the graphic changed since it was read' Else Board.RemovePCBObject(Prim); End+ Else If Kind = 'Y' Then+ Begin+ { a filled region: Y|layer|net|x,y;x,y;... in internal units (import_svg). A hole is part of the one contour,+ reached by a zero-width slit: a hole contour (GeometricPolygon AddContourIsHole) printed filled on+ Develop, 2026-10-28, and the slit form printed with its hole open. }+ Net := FindNet(Board, FieldP(Op, 3));+ If (Net = Nil) And (FieldP(Op, 3) <> '') Then Res := 'err:no net ' + FieldP(Op, 3)+ Else+ Begin+ Cont := PCBServer.PCBContourFactory;+ PtList := FieldP(Op, 4) + ';';+ While Pos(';', PtList) > 0 Do+ Begin+ Pt := Copy(PtList, 1, Pos(';', PtList) - 1);+ PtList := Copy(PtList, Pos(';', PtList) + 1, Length(PtList));+ If Pos(',', Pt) > 0 Then Cont.AddPoint(AdomInt(Copy(Pt, 1, Pos(',', Pt) - 1)), AdomInt(Copy(Pt, Pos(',', Pt) + 1, Length(Pt))));+ End;+ Reg := PCBServer.PCBObjectFactory(eRegionObject, eNoDimension, eCreate_Default);+ Reg.Layer := AdomInt(FieldP(Op, 2));+ Reg.SetOutlineContour(Cont);+ If Net <> Nil Then Reg.Net := Net;+ If gInputError <> '' Then Res := 'err:bad number ' + gInputError+ Else Begin RegisterPrim(Board, Reg); Res := 'ok:' + GraphicKey(Reg); End;+ End;+ End Else If Kind = 'N' Then Begin N := 0;@@ -9380,10 +9481,238 @@ Begin Result := '{' + JRaw('ok','true') + ',' + JStr('current', Cur) + ',' + JRaw('documents', '[' + S + ']') + '}'; End; +{ Make the PcbLib at Path the current document (inside Altium), so GetCurrentPCBLibrary is that library. '' when it is,+ else why not. An empty Path leaves the current library as it is. }+Function CurrentLibAt(Path : String) : String;+Var+ SD : IServerDocument;+ PL : IPCB_Library;+Begin+ Result := '';+ If Path = '' Then Exit;+ SD := Nil;+ Try SD := Client.GetDocumentByPath(Path); Except SD := Nil; End;+ If SD = Nil Then Begin Result := Path + ' is not open in Altium'; Exit; End;+ PL := PCBServer.GetCurrentPCBLibrary;+ If (PL <> Nil) And (SamePathText(PL.Board.FileName) = SamePathText(Path)) Then Exit;+ Client.ShowDocument(SD);+ PL := PCBServer.GetCurrentPCBLibrary;+ If (PL = Nil) Or (SamePathText(PL.Board.FileName) <> SamePathText(Path)) Then Result := Path + ' did not become the current library';+End;++{ edit_fp: edit one footprint of the CURRENT PcbLib in place. name= the footprint; the payload is one operation a line,+ positions in mm from the footprint's origin (the library's, as lib_fp reads them):+ PS|pad|size|w|h PS|pad|at|x|y PS|pad|shape|rect|round|roundrect PS|pad|drill|d PS|pad|rotation|deg+ PS|pad|layer|top|bottom|multi PS|pad|type|smd|pth|npth PS|pad|number|new+ PD|pad PA|name|x|y|w|h|shape|drill|layer|rot|type GD|layerId GL|layerId|x1|y1|x2|y2|w GA|layerId|cx|cy|r|w|a1|a2+ MD|description BD (every 3D body)+ Each answers ok:<what> or err:<why>, in order; one undo step. }++{ the first drawing primitive (not a pad, a text or a body) on a layer of the footprint; layer 0 = the first 3D body }+Function FpFirstOn(Fp : IPCB_LibComponent; Lay : Integer) : IPCB_Primitive;+Var+ GIt : IPCB_GroupIterator;+ P : IPCB_Primitive;+Begin+ Result := Nil;+ 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);+ P := GIt.FirstPCBObject;+ While P <> Nil Do+ Begin+ If (Lay = 0) Or (P.Layer = Lay) Then Begin Result := P; Break; End;+ P := GIt.NextPCBObject;+ End;+ Fp.GroupIterator_Destroy(GIt);+End;++Function FpShape(S : String) : Integer;+Begin+ If S = 'rect' Then Result := eRectangular+ Else If S = 'roundrect' Then Result := eRoundedRectangular+ Else Result := eRounded;+End;++Function FpLayer(S : String) : Integer;+Begin+ If S = 'multi' Then Result := eMultiLayer+ Else If S = 'bottom' Then Result := eBottomLayer+ Else Result := eTopLayer;+End;++Function CmdEditFp(Lines : TStringList; Payload : String) : String;+Var+ LibErr : String;+ PLib : IPCB_Library;+ Fp : IPCB_LibComponent;+ Ops : TStringList;+ Op, Kind, Key, Res, Results : String;+ Pad : IPCB_Pad;+ Trk : IPCB_Track;+ Arc : IPCB_Arc;+ Prim, Cpy : IPCB_Primitive;+ Old : IPCB_LibComponent;+ GIt : IPCB_GroupIterator;+ I, K, OX, OY, Lay, Okay, Failed : Integer;+Begin+ { the library the bridge names, as the open document: a library loaded by path is a separate copy (pads added or+ deleted on it never reached the document, 2026-10-28), and open shows a document without making it current }+ LibErr := CurrentLibAt(Param(Lines, 'path'));+ If LibErr <> '' Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','library_not_current') + ',' + JStr('error', LibErr) + '}'; Exit; End;+ PLib := PCBServer.GetCurrentPCBLibrary;+ If PLib = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','not_a_pcblib') + ',' + JStr('error','the current document is not a PCB library') + '}'; Exit; End;+ Fp := FindFp(PLib, Param(Lines, 'name'));+ If Fp = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','footprint_not_found') + ',' + JStr('error','no footprint ' + Param(Lines, 'name') + ' in this library') + '}'; Exit; End;+ { the footprint on display sits on the library's origin (see lib_fp): show it before editing }+ If PLib.CurrentComponent <> Fp Then Begin PLib.CurrentComponent := Fp; PLib.Board.ViewManager_FullUpdate; End;+ OX := PLib.Board.XOrigin; OY := PLib.Board.YOrigin;+ Ops := TStringList.Create;+ Ops.Text := Payload;+ Results := ''; Okay := 0; Failed := 0;+ PCBServer.PreProcess;+ { the edit is made on a copy that is then registered in the footprint's place: on a registered footprint, pads+ and lines added or removed did not reach it (only changes to existing pads did, Develop 2026-10-28), while a+ footprint built before it is registered takes them all (build_footprint, xcopy) }+ Old := Fp;+ Fp := PCBServer.CreatePCBLibComp;+ Fp.Name := Old.Name;+ Fp.Description := Old.Description;+ Fp.Height := Old.Height;+ GIt := Old.GroupIterator_Create;+ GIt.AddFilter_LayerSet(AllLayers);+ Prim := GIt.FirstPCBObject;+ While Prim <> Nil Do+ Begin+ { the footprint on display reads from the library's origin; one not yet registered keeps its own frame,+ which Altium puts on the origin when it shows it (the copy came out 1270 mm off without this) }+ Cpy := Prim.Replicate;+ Cpy.MoveByXY(-OX, -OY);+ Fp.AddPCBObject(Cpy);+ Prim := GIt.NextPCBObject;+ End;+ Old.GroupIterator_Destroy(GIt);+ OX := 0; OY := 0;+ For I := 0 To Ops.Count - 1 Do+ Begin+ Op := Trim(Ops[I]);+ If Op = '' Then Continue;+ Kind := FieldP(Op, 1);+ Res := 'ok';+ gInputError := '';+ If (Kind = 'PS') Or (Kind = 'PD') Then+ Begin+ Pad := FpPad(Fp, FieldP(Op, 2));+ If Pad = Nil Then Res := 'err:no pad ' + FieldP(Op, 2)+ Else If Kind = 'PD' Then+ Begin+ Fp.RemovePCBObject(Pad);+ Res := 'ok:deleted pad ' + FieldP(Op, 2);+ End+ Else+ Begin+ Key := FieldP(Op, 3);+ Pad.BeginModify;+ If Key = 'size' Then Begin Pad.TopXSize := MmC(FieldP(Op, 4)); Pad.TopYSize := MmC(FieldP(Op, 5)); End+ Else If Key = 'at' Then Begin Pad.X := OX + MmC(FieldP(Op, 4)); Pad.Y := OY + MmC(FieldP(Op, 5)); End+ Else If Key = 'shape' Then Pad.TopShape := FpShape(FieldP(Op, 4))+ Else If Key = 'drill' Then Pad.HoleSize := MmC(FieldP(Op, 4))+ Else If Key = 'rotation' Then Pad.Rotation := AdomFloat(FieldP(Op, 4))+ Else If Key = 'layer' Then Pad.Layer := FpLayer(FieldP(Op, 4))+ Else If Key = 'type' Then+ Begin+ If FieldP(Op, 4) = 'smd' Then Begin Pad.Layer := eTopLayer; Pad.HoleSize := 0; End+ Else Begin Pad.Layer := eMultiLayer; Pad.Plated := FieldP(Op, 4) = 'pth'; End;+ End+ Else If Key = 'number' Then Pad.Name := FieldP(Op, 4)+ Else Res := 'err:unknown pad field ' + Key;+ Pad.EndModify;+ If Res = 'ok' Then Res := 'ok:pad ' + FieldP(Op, 2) + ' ' + Key;+ End;+ End+ Else If Kind = 'PA' Then+ Begin+ If FpPad(Fp, FieldP(Op, 2)) <> Nil Then Res := 'err:pad ' + FieldP(Op, 2) + ' exists'+ Else+ Begin+ Pad := PCBServer.PCBObjectFactory(ePadObject, eNoDimension, eCreate_Default);+ Pad.Name := FieldP(Op, 2);+ Pad.X := OX + MmC(FieldP(Op, 3)); Pad.Y := OY + MmC(FieldP(Op, 4));+ Pad.TopXSize := MmC(FieldP(Op, 5)); Pad.TopYSize := MmC(FieldP(Op, 6));+ Pad.TopShape := FpShape(FieldP(Op, 7));+ Pad.HoleSize := MmC(FieldP(Op, 8));+ Pad.Layer := FpLayer(FieldP(Op, 9));+ Pad.Rotation := AdomFloat(FieldP(Op, 10));+ If FieldP(Op, 11) = 'npth' Then Pad.Plated := False;+ Fp.AddPCBObject(Pad);+ Res := 'ok:added pad ' + FieldP(Op, 2);+ End;+ End+ Else If (Kind = 'GD') Or (Kind = 'BD') Then+ Begin+ If Kind = 'BD' Then Lay := 0 Else Lay := AdomInt(FieldP(Op, 2));+ K := 0;+ Prim := FpFirstOn(Fp, Lay);+ While (Prim <> Nil) And (K < 5000) Do+ Begin+ Fp.RemovePCBObject(Prim);+ K := K + 1;+ Prim := FpFirstOn(Fp, Lay);+ End;+ If Kind = 'BD' Then Res := 'ok:deleted ' + IntToStr(K) + ' 3D bodies'+ Else Res := 'ok:deleted ' + IntToStr(K) + ' shapes on layer ' + FieldP(Op, 2);+ End+ Else If Kind = 'GL' Then+ Begin+ Trk := PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default);+ Trk.Layer := AdomInt(FieldP(Op, 2));+ Trk.X1 := OX + MmC(FieldP(Op, 3)); Trk.Y1 := OY + MmC(FieldP(Op, 4));+ Trk.X2 := OX + MmC(FieldP(Op, 5)); Trk.Y2 := OY + MmC(FieldP(Op, 6));+ Trk.Width := MmC(FieldP(Op, 7));+ Fp.AddPCBObject(Trk);+ Res := 'ok:line on layer ' + FieldP(Op, 2);+ End+ Else If Kind = 'GA' Then+ Begin+ Arc := PCBServer.PCBObjectFactory(eArcObject, eNoDimension, eCreate_Default);+ Arc.Layer := AdomInt(FieldP(Op, 2));+ Arc.XCenter := OX + MmC(FieldP(Op, 3)); Arc.YCenter := OY + MmC(FieldP(Op, 4));+ Arc.Radius := MmC(FieldP(Op, 5));+ Arc.LineWidth := MmC(FieldP(Op, 6));+ Arc.StartAngle := AdomFloat(FieldP(Op, 7)); Arc.EndAngle := AdomFloat(FieldP(Op, 8));+ Fp.AddPCBObject(Arc);+ Res := 'ok:arc on layer ' + FieldP(Op, 2);+ End+ Else If Kind = 'MD' Then+ Begin+ Fp.Description := FieldP(Op, 2);+ Res := 'ok:description';+ End+ Else Res := 'err:unknown op ' + Kind;+ If (gInputError <> '') And (Copy(Res, 1, 3) <> 'err') Then Res := 'err:bad number ' + gInputError;+ If Copy(Res, 1, 3) = 'err' Then Failed := Failed + 1 Else Okay := Okay + 1;+ If Results <> '' Then Results := Results + ',';+ Results := Results + '"' + JsonEsc(Res) + '"';+ End;+ PLib.RemoveComponent(Old);+ PLib.RegisterComponent(Fp);+ PCBServer.PostProcess;+ gInputError := '';+ Ops.Free;+ PLib.CurrentComponent := Fp;+ PLib.Board.ViewManager_FullUpdate;+ PLib.RefreshView;+ Result := '{' + JRaw('ok','true') + ',' + JStr('footprint', Fp.Name) + ',' + JRaw('applied', IntToStr(Okay)) + ',' + JRaw('failed', IntToStr(Failed)) + ',' ++ JRaw('results', '[' + Results + ']') + '}';+End;++ { lib_fp: one footprint of the CURRENT PcbLib in full: name=<footprint>. Pads (mil, hole, layer, shape, rotation, plated), other primitives counted per layer, the bounding box, description, height and 3D bodies. } Function CmdLibFootprint(Lines : TStringList) : String; Var+ LibErr : String; PLib : IPCB_Library; Fp : IPCB_LibComponent; GIt : IPCB_GroupIterator;@@ -9393,6 +9722,10 @@ Var I, OX, OY : Integer; R : TCoordRect; Begin+ { the library the bridge names, as the open document: a library loaded by path is a separate copy (pads added or+ deleted on it never reached the document, 2026-10-28), and open shows a document without making it current }+ LibErr := CurrentLibAt(Param(Lines, 'path'));+ If LibErr <> '' Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','library_not_current') + ',' + JStr('error', LibErr) + '}'; Exit; End; PLib := PCBServer.GetCurrentPCBLibrary; If PLib = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','not_a_pcblib') + ',' + JStr('error','the current document is not a PCB library') + '}'; Exit; End; Nm := Param(Lines, 'name'); Fp := Nil;@@ -9400,7 +9733,9 @@ Begin If UpperCase(PLib.GetComponent(I).Name) = UpperCase(Nm) Then Begin Fp := PLib.GetComponent(I); Break; End; If Fp = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','footprint_not_found') + ',' + JStr('error','no footprint ' + Nm + ' in this library') + '}'; Exit; End; S := ''; B := ''; L := '';- { positions from the footprint's origin, which is its library's (not 0 on a library made by this Altium) }+ { positions from the footprint's origin. Only the footprint on display sits on the library's origin; another+ keeps raw coordinates near 0 (one library read +1270 mm, another -1272.7 mm, 2026-10-28), so it is shown first }+ If PLib.CurrentComponent <> Fp Then Begin PLib.CurrentComponent := Fp; PLib.Board.ViewManager_FullUpdate; End; OX := PLib.Board.XOrigin; OY := PLib.Board.YOrigin; GIt := Fp.GroupIterator_Create; GIt.AddFilter_LayerSet(AllLayers);@@ -9432,7 +9767,7 @@ Begin Fp.GroupIterator_Destroy(GIt); R := Fp.BoundingRectangle; Result := '{' + JRaw('ok','true') + ',' + JStr('name', Fp.Name) + ',' + JStr('description', Fp.Description) + ',' + JRaw('height', IntToStr(Fp.Height)) + ',' +- JRaw('k', IntToStr(MilsToCoord(1000))) + ',' + JRaw('box', '[' + IntToStr(R.Left - OX) + ',' + IntToStr(R.Bottom - OY) + ',' + IntToStr(R.Right - OX) + ',' + IntToStr(R.Top - OY) + ']') + ',' ++ JRaw('k', IntToStr(MilsToCoord(1000))) + ',' + JRaw('origin', '[' + IntToStr(OX) + ',' + IntToStr(OY) + ']') + ',' + JStr('libraryFile', PLib.Board.FileName) + ',' + JRaw('box', '[' + IntToStr(R.Left - OX) + ',' + IntToStr(R.Bottom - OY) + ',' + IntToStr(R.Right - OX) + ',' + IntToStr(R.Top - OY) + ']') + ',' + JRaw('pads', '[' + S + ']') + ',' + JRaw('bodies', '[' + B + ']') + ',' + JRaw('other', '[' + L + ']') + '}'; End; @@ -9570,6 +9905,7 @@ Begin Else If Cmd = 'run_process' Then Result := CmdRunProcess(Lines) Else If Cmd = 'open' Then Result := CmdOpen(Lines) Else If Cmd = 'save_doc' Then Result := CmdSaveDoc(Lines)+ Else If Cmd = 'edit_fp' Then Result := CmdEditFp(Lines, Payload) Else If Cmd = 'close_document' Then Result := CmdCloseDocument(Lines) Else If Cmd = 'eval' Then Result := CmdEval(Lines, Payload) Else If Cmd = 'io_bench' Then Result := CmdIoBench(Lines)
src/bridge.json+13−1@@ -2,7 +2,7 @@ "manifest_version": 1, "name": "altium", "displayName": "Altium Designer",- "version": "0.2.77",+ "version": "0.2.78", "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",@@ -98,6 +98,12 @@ "altium_export_bom", "altium_export_gerber", "altium_export_ipc2581",+ "altium_export_dxf",+ "altium_export_gencad",+ "altium_import_svg",+ "altium_edit_footprint",+ "altium_generate_body",+ "altium_export_ipc356", "altium_export_library_part", "altium_export_manufacturing", "altium_export_odb",@@ -451,6 +457,12 @@ "remove_graphics": 320, "export_odb": 660, "export_ipc2581": 660,+ "export_ipc356": 660,+ "export_dxf": 300,+ "export_gencad": 300,+ "import_svg": 300,+ "edit_footprint": 300,+ "generate_body": 60, "document_info": 320, "close_all_documents": 320, "project_info": 320,