← Commit history
Cargo.lock+351−1
@@ -10,12 +10,14 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-2dboard"-version = "0.4.1"+version = "0.5.0" dependencies = [  "anyhow",  "cfb",  "clap",+ "png",  "regex",+ "resvg",  "roxmltree",  "serde",  "serde_json",@@ -88,24 +90,60 @@ version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" +[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+ [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+ [[package]] name = "byteorder" version = "1.5.0"@@ -191,6 +229,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]]+name = "core_maths"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"+dependencies = [+ "libm",+]+ [[package]] name = "crc32fast" version = "1.5.0"@@ -200,6 +247,12 @@ dependencies = [  "cfg-if", ] +[[package]]+name = "data-url"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"+ [[package]] name = "displaydoc" version = "0.2.6"@@ -211,6 +264,24 @@ dependencies = [  "syn", ] +[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]+ [[package]] name = "find-msvc-tools" version = "0.1.9"@@ -227,12 +298,40 @@ dependencies = [  "miniz_oxide", ] +[[package]]+name = "float-cmp"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"+ [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]]+name = "fontconfig-parser"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"+dependencies = [+ "roxmltree",+]++[[package]]+name = "fontdb"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"+dependencies = [+ "fontconfig-parser",+ "log",+ "slotmap",+ "tinyvec",+ "ttf-parser",+]+ [[package]] name = "form_urlencoded" version = "1.2.2"@@ -392,6 +491,12 @@ dependencies = [  "icu_properties", ] +[[package]]+name = "imagesize"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285"+ [[package]] name = "is_terminal_polyfill" version = "1.70.2"@@ -415,12 +520,29 @@ dependencies = [  "wasm-bindgen", ] +[[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.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+ [[package]] name = "litemap" version = "0.8.2"@@ -449,6 +571,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"@@ -467,12 +598,31 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]]+name = "pico-args"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"+ [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]]+name = "png"+version = "0.17.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"+dependencies = [+ "bitflags 1.3.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]+ [[package]] name = "potential_utf" version = "0.1.5"@@ -529,6 +679,29 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]]+name = "resvg"+version = "0.45.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"+dependencies = [+ "log",+ "pico-args",+ "rgb",+ "svgtypes",+ "tiny-skia",+ "usvg",+]++[[package]]+name = "rgb"+version = "0.8.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"+dependencies = [+ "bytemuck",+]+ [[package]] name = "ring" version = "0.17.14"@@ -590,6 +763,24 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]]+name = "rustybuzz"+version = "0.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "core_maths",+ "log",+ "smallvec",+ "ttf-parser",+ "unicode-bidi-mirroring",+ "unicode-ccc",+ "unicode-properties",+ "unicode-script",+]+ [[package]] name = "serde" version = "1.0.228"@@ -645,12 +836,36 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]]+name = "simplecss"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"+dependencies = [+ "log",+]++[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"+ [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]+ [[package]] name = "smallvec" version = "1.15.2"@@ -663,6 +878,15 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"+dependencies = [+ "float-cmp",+]+ [[package]] name = "strsim" version = "0.11.1"@@ -675,6 +899,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"@@ -697,6 +931,32 @@ dependencies = [  "syn", ] +[[package]]+name = "tiny-skia"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "png",+ "tiny-skia-path",+]++[[package]]+name = "tiny-skia-path"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]+ [[package]] name = "tiny_http" version = "0.12.0"@@ -719,12 +979,63 @@ dependencies = [  "zerovec", ] +[[package]]+name = "tinyvec"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"++[[package]]+name = "ttf-parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+dependencies = [+ "core_maths",+]++[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"++[[package]]+name = "unicode-bidi-mirroring"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"++[[package]]+name = "unicode-ccc"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"+ [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]]+name = "unicode-properties"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"++[[package]]+name = "unicode-script"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"++[[package]]+name = "unicode-vo"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"+ [[package]] name = "untrusted" version = "0.9.0"@@ -759,6 +1070,33 @@ dependencies = [  "serde", ] +[[package]]+name = "usvg"+version = "0.45.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef"+dependencies = [+ "base64",+ "data-url",+ "flate2",+ "fontdb",+ "imagesize",+ "kurbo",+ "log",+ "pico-args",+ "roxmltree",+ "rustybuzz",+ "simplecss",+ "siphasher",+ "strict-num",+ "svgtypes",+ "tiny-skia-path",+ "unicode-bidi",+ "unicode-script",+ "unicode-vo",+ "xmlwriter",+]+ [[package]] name = "utf8_iter" version = "1.0.4"@@ -781,6 +1119,12 @@ dependencies = [  "wasm-bindgen", ] +[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+ [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1"@@ -944,6 +1288,12 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +[[package]]+name = "xmlwriter"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"+ [[package]] name = "yoke" version = "0.8.3"
Cargo.toml+3−1
@@ -1,6 +1,6 @@ [package] name = "adom-2dboard"-version = "0.4.1"+version = "0.5.0" edition = "2021" description = "Interactive PCB viewer (.kicad_pcb → themed, net-highlightable SVG) with component hover info — embeddable in any app" @@ -18,6 +18,8 @@ serde_json = "1" ureq = "2" roxmltree = "0.20" cfb = "0.10"+resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts"] }+png = "0.17"  [profile.release] opt-level = "z"
README.md+34
@@ -37,6 +37,40 @@ does both at once:   no external assets, so any app can drop it in an iframe as a live PCB view.   (adom-project-manager uses exactly this for its board pane.) +## Molecule plans and built boards++Before there is a `.kicad_pcb`, the same tool draws a molecule from its plan or its built tscircuit board, in one+look: dark green board, red contacts and orange corner pins labelled by net, power contacts ringed yellow, the+nominal board dotted inside its wings, each footprint's pads with pin numbers and a pin-1 dot, courtyards (overlaps+red, named exceptions amber), and a caption with the measured clearances.++```bash+# plan stage: the molecule plan (adom-tsci-molecule `bun scripts/plan.ts`) + footprints + placements; repeat+# --layout to compare variants side by side+adom-2dboard render --layout a-upright.json --layout b-turned.json --out compare.png++# built board: tscircuit circuit.json (+ the board's design.json: corner pin roles, power nets, courtyard+# exceptions); adds traces, vias, copper pours with their gap and edge pullback, and top silk+adom-2dboard render --circuit dist/lib/index/circuit.json --design design.json --out board.png++# the numbers behind the picture+adom-2dboard render --circuit dist/lib/index/circuit.json --out board.svg --json+```++![Two placements of the CD74HC4067 molecule, from plan files](screenshots/plan-cd74hc4067-ab.png)++![The built 74HC595 domino: bottom VCC / GND pours 0.30 mm apart, 0.40 mm from the edge](screenshots/built-74hc595bq-domino.png)++- `--out` decides the format: `.svg`, or `.png` at `--width` pixels (default 1000), a 256-colour PNG sized for chat+  (64 to 125 KB for a 10 mm molecule up to a 70 mm board).+- On a molecule (10 to 18 mm) at 1000 px, 0.4 mm silk reads at about 30 px. On a large board, raise `--width`.+- A layout file: `{ "title", "plan": "plan.json", "machinePinNets": {"MP1": "GND"}, "contactNets": {...},+  "powerNets": [...], "parts": [{ "ref", "footprint": "u1.kicad_mod", "x", "y", "rotation", "pins": {"1": "COM"},+  "label" }], "courtyardExceptions": [{ "refs": ["U1", "C1"], "reason" }] }`. Paths are relative to it.+  `examples/` holds three: the 74HC595 domino and the CD74HC4067 A / B.+- `--json` lists every machine pin, contact and pad position, clearances, crossings, free slots, courtyard+  overlaps, pours (gap, edge pullback) and silk text.+ ## Install  ```
SKILL.md+20−2
@@ -1,6 +1,6 @@ --- name: adom-2dboard-description: "Use when the user asks to view, open, preview, or inspect a PCB layout or .kicad_pcb board; to highlight a net or trace; to see which pads are on a net; to look up a part on the board (stock, price, MPN, wiki page); or to embed an interactive PCB view inside another app or web page. Also trigger for questions like 'show me the board', 'what net is this pad on', 'make the PCB preview clickable', or 'replace the board image with something interactive'."+description: "Use when the user asks to view, open, preview, or inspect a PCB layout or .kicad_pcb board; to mock up or compare a molecule layout (MP / MC / board size / chip placement) from a plan, or render a built tscircuit circuit.json to SVG or PNG; to highlight a net or trace; to see which pads are on a net; to look up a part on the board (stock, price, MPN, wiki page); or to embed an interactive PCB view inside another app or web page. Also trigger for questions like 'show me the board', 'what net is this pad on', 'make the PCB preview clickable', or 'replace the board image with something interactive'." ---  # adom-2dboard@@ -45,12 +45,30 @@ adom-2dboard render --file board.kicad_pcb --out board.svg --meta adom-2dboard serve --file board.kicad_pcb --port 8790 ``` +## Molecule plans (use this, not ad-hoc matplotlib)++For a molecule layout question ("mock up the layout", "where do the MPs and MCs go", "compare chip placements",+"show the board size"), write a layout file and render it; it replaces the scratch matplotlib mocks:++```bash+adom-2dboard render --layout a.json --layout b.json --out compare.png        # plans side by side+adom-2dboard render --circuit dist/lib/index/circuit.json --out board.png     # built board (design.json beside it is read)+```++A layout file holds the molecule plan (`bun scripts/plan.ts` in adom-tsci-molecule), `machinePinNets`, optional+`contactNets` / `powerNets`, and `parts` with a `.kicad_mod`, position, rotation and pad nets. Examples in+`examples/`. Machine pins carry power only, so their nets ring contacts yellow; overlapping courtyards are red,+named exceptions amber. Read the caption: it gives clearances, crossings, pour gap and edge pullback.+ ## Commands  | Command | Description | |---|---| | `embed --file F [--out O]` | One self-contained interactive HTML file (no external assets) |-| `render --file F --out O [--meta]` | Composed interactive SVG, optional `<out>.meta.json` |+| `render --file F --out O [--meta]` | Composed interactive SVG (or `.png`), optional `<out>.meta.json` |+| `render --layout L [--layout L2 ...] --out O` | Molecule plan(s) before routing, side by side: SVG or PNG |+| `render --circuit C [--design D] --out O` | A built tscircuit board: traces, vias, pours (gap, edge pullback), silk, courtyards |+| `render ... --json` | The measurements behind a plan / circuit render: positions, clearances, crossings, courtyard overlaps, pours, silk | | `serve [--file F] [--port P]` | Live app server (default :8790) |  ## Server routes (serve)
bin/adom-2dboard
⋯ 1 unchanged line ⋯
examples/74hc595bq-domino/0402b104j160ct.kicad_modadded+23
@@ -0,0 +1,23 @@+(footprint "0402B104J160CT"+  (version 20240108)+  (generator "adom-footprint")+  (layer "F.Cu")+  (descr "Walsin Technology Corporation · Multilayer Ceramic Capacitor (MLCC) · General Purpose")+  (attr smd)+  (fp_rect (start -0.95 -0.55) (end 0.95 0.55)+    (stroke (width 0.05) (type default)) (fill none) (layer "F.CrtYd"))+  (fp_rect (start -0.5 -0.25) (end 0.5 0.25)+    (stroke (width 0.1) (type default)) (fill none) (layer "F.Fab"))+  (fp_rect (start -0.62 -0.37) (end 0.62 0.37)+    (stroke (width 0.12) (type default)) (fill none) (layer "F.SilkS"))+  (fp_line (start -0.7 -0.5) (end -0.2 -0.5)+    (stroke (width 0.12) (type default)) (layer "F.SilkS"))+  (fp_text reference "REF**" (at 0 -2.8)+    (layer "F.SilkS") (effects (font (size 1 1) (thickness 0.15))))+  (fp_text value "0402B104J160CT" (at 0 2.8)+    (layer "F.Fab") (effects (font (size 1 1) (thickness 0.15))))+  (pad "1" smd roundrect (at -0.5 0) (size 0.6 0.5)+    (layers "F.Cu" "F.Paste" "F.Mask") (roundrect_rratio 0.25))+  (pad "2" smd roundrect (at 0.5 0) (size 0.6 0.5)+    (layers "F.Cu" "F.Paste" "F.Mask") (roundrect_rratio 0.25))+)
examples/74hc595bq-domino/74hc595bq.kicad_modadded+457
@@ -0,0 +1,457 @@+(footprint "DHVQFN-16-1EP_2.5x3.5mm_P0.5mm_EP1x2mm"+	(version 20260206)+	(generator "kicad-footprint-generator")+	(layer "F.Cu")+	(descr "DHVQFN, 16 Pin (JEDEC MO-241/VAB, https://assets.nexperia.com/documents/package-information/SOT763-1.pdf)")+	(tags "DHVQFN NoLead Nexperia_SOT763-1 Texas_BQB0016A")+	(property "Reference" "REF**"+		(at 0 -3.05 0)+		(layer "F.SilkS")+		(effects+			(font+				(size 1 1)+				(thickness 0.15)+			)+		)+	)+	(property "Value" "DHVQFN-16-1EP_2.5x3.5mm_P0.5mm_EP1x2mm"+		(at 0 3.05 0)+		(layer "F.Fab")+		(effects+			(font+				(size 1 1)+				(thickness 0.15)+			)+		)+	)+	(property "KiLib_Generator" "package/no_lead"+		(at 0 0 0)+		(layer "F.SilkS")+		(hide yes)+		(effects+			(font+				(size 1 1)+				(thickness 0.15)+			)+		)+	)+	(attr smd)+	(duplicate_pad_numbers_are_jumpers no)+	(fp_line+		(start -1.36 -1.86)+		(end -0.635 -1.86)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start -1.36 -1.635)+		(end -1.36 -1.86)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start -1.36 1.86)+		(end -1.36 1.635)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start -0.635 1.86)+		(end -1.36 1.86)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start 0.635 -1.86)+		(end 1.36 -1.86)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start 1.36 -1.86)+		(end 1.36 -1.635)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start 1.36 1.635)+		(end 1.36 1.86)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start 1.36 1.86)+		(end 0.635 1.86)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_poly+		(pts+			(xy -0.25 -2.37)+			(xy -0.49 -2.7)+			(xy -0.01 -2.7)+		)+		(stroke+			(width 0.12)+			(type solid)+		)+		(fill yes)+		(layer "F.SilkS")+	)+	(fp_line+		(start -1.85 -1.63)+		(end -1.5 -1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -1.85 1.63)+		(end -1.85 -1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -1.5 -2)+		(end -0.63 -2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -1.5 -1.63)+		(end -1.5 -2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -1.5 1.63)+		(end -1.85 1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -1.5 2)+		(end -1.5 1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -0.63 -2.35)+		(end 0.63 -2.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -0.63 -2)+		(end -0.63 -2.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -0.63 2)+		(end -1.5 2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -0.63 2.35)+		(end -0.63 2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 0.63 -2.35)+		(end 0.63 -2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 0.63 -2)+		(end 1.5 -2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 0.63 2)+		(end 0.63 2.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 0.63 2.35)+		(end -0.63 2.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 1.5 -2)+		(end 1.5 -1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 1.5 -1.63)+		(end 1.85 -1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 1.5 1.63)+		(end 1.5 2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 1.5 2)+		(end 0.63 2)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 1.85 -1.63)+		(end 1.85 1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 1.85 1.63)+		(end 1.5 1.63)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_poly+		(pts+			(xy -0.625 -1.75)+			(xy 1.25 -1.75)+			(xy 1.25 1.75)+			(xy -1.25 1.75)+			(xy -1.25 -1.125)+		)+		(stroke+			(width 0.1)+			(type solid)+		)+		(fill no)+		(layer "F.Fab")+	)+	(fp_text user "${REFERENCE}"+		(at 0 0 90)+		(layer "F.Fab")+		(effects+			(font+				(size 0.88 0.88)+				(thickness 0.13)+			)+		)+	)+	(pad "" smd roundrect+		(at 0 -0.5)+		(size 0.81 0.81)+		(layers "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "" smd roundrect+		(at 0 0.5)+		(size 0.81 0.81)+		(layers "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "1" smd roundrect+		(at -0.25 -1.6875)+		(size 0.25 0.825)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "2" smd roundrect+		(at -1.1875 -1.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "3" smd roundrect+		(at -1.1875 -0.75)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "4" smd roundrect+		(at -1.1875 -0.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "5" smd roundrect+		(at -1.1875 0.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "6" smd roundrect+		(at -1.1875 0.75)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "7" smd roundrect+		(at -1.1875 1.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "8" smd roundrect+		(at -0.25 1.6875)+		(size 0.25 0.825)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "9" smd roundrect+		(at 0.25 1.6875)+		(size 0.25 0.825)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "10" smd roundrect+		(at 1.1875 1.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "11" smd roundrect+		(at 1.1875 0.75)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "12" smd roundrect+		(at 1.1875 0.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "13" smd roundrect+		(at 1.1875 -0.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "14" smd roundrect+		(at 1.1875 -0.75)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "15" smd roundrect+		(at 1.1875 -1.25)+		(size 0.825 0.25)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "16" smd roundrect+		(at 0.25 -1.6875)+		(size 0.25 0.825)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "17" smd rect+		(at 0 0)+		(size 1 2)+		(property pad_prop_heatsink)+		(layers "F.Cu" "F.Mask")+		(zone_connect 2)+	)+	(embedded_fonts no)+	(model "${KICAD10_3DMODEL_DIR}/Package_DFN_QFN.3dshapes/DHVQFN-16-1EP_2.5x3.5mm_P0.5mm_EP1x2mm.step"+		(offset+			(xyz 0 0 0)+		)+		(scale+			(xyz 1 1 1)+		)+		(rotate+			(xyz 0 0 0)+		)+	)+)
examples/74hc595bq-domino/layout.jsonadded+9
@@ -0,0 +1,9 @@+{+ "title": "74HC595BQ molecule: signals off the corner pins (domino, chip turned: top VCC, bottom GND)",+ "plan": "plan.json",+ "machinePinNets": {"MP1": "GND", "MP2": "VCC", "MP3": "VCC", "MP4": "GND"},+ "parts": [+  {"ref": "U1", "footprint": "74hc595bq.kicad_mod", "x": 0, "y": -0.25, "rotation": 0, "label": "74HC595BQ"},+  {"ref": "C1", "footprint": "0402b104j160ct.kicad_mod", "x": 1.4, "y": 2.75, "rotation": 0}+ ]+}
examples/74hc595bq-domino/plan.jsonadded+1
@@ -0,0 +1 @@+{"board": {"width": 10.4, "height": 14, "nominalWidth": 10, "nominalHeight": 10, "center": {"x": 0, "y": 0}, "cornerRadius": 0, "wings": {"left": 0.2, "right": 0.2, "top": 2, "bottom": 2}, "outline": [{"x": 5.2, "y": -7}, {"x": 5.2, "y": 7}, {"x": -5.2, "y": 7}, {"x": -5.2, "y": -7}]}, "machinePins": [{"name": "MP1", "x": -4, "y": -4, "type": "MachinePinMediumShort", "holeID": 1.2, "holeOD": 1.6, "boundingBox": 2}, {"name": "MP2", "x": -4, "y": 4, "type": "MachinePinMediumShort", "holeID": 1.2, "holeOD": 1.6, "boundingBox": 2}, {"name": "MP3", "x": 4, "y": 4, "type": "MachinePinMediumShort", "holeID": 1.2, "holeOD": 1.6, "boundingBox": 2}, {"name": "MP4", "x": 4, "y": -4, "type": "MachinePinMediumShort", "holeID": 1.2, "holeOD": 1.6, "boundingBox": 2}], "contacts": [{"designator": "MC1", "name": "Q6", "net": "Q6", "margin": "leftMargin", "side": "left", "row": 0, "index": 0, "x": -4, "y": -2, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": -4, "y": -2, "width": 2, "height": 2}}, {"designator": "MC2", "name": "Q5", "net": "Q5", "margin": "leftMargin", "side": "left", "row": 0, "index": 1, "x": -4, "y": 0, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": -4, "y": 0, "width": 2, "height": 2}}, {"designator": "MC3", "name": "Q4", "net": "Q4", "margin": "leftMargin", "side": "left", "row": 0, "index": 2, "x": -4, "y": 2, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": -4, "y": 2, "width": 2, "height": 2}}, {"designator": "MC4", "name": "Q3", "net": "Q3", "margin": "topWingMargin", "side": "top", "row": 0, "index": 0, "x": -4, "y": 6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": -4, "y": 6, "width": 2, "height": 2}}, {"designator": "MC5", "name": "Q2", "net": "Q2", "margin": "topWingMargin", "side": "top", "row": 0, "index": 1, "x": -2, "y": 6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": -2, "y": 6, "width": 2, "height": 2}}, {"designator": "MC6", "name": "Q1", "net": "Q1", "margin": "topWingMargin", "side": "top", "row": 0, "index": 2, "x": 0, "y": 6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 0, "y": 6, "width": 2, "height": 2}}, {"designator": "MC7", "name": "VCC", "net": "VCC", "margin": "topWingMargin", "side": "top", "row": 0, "index": 3, "x": 2, "y": 6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 2, "y": 6, "width": 2, "height": 2}}, {"designator": "MC8", "name": "Q0", "net": "Q0", "margin": "topWingMargin", "side": "top", "row": 0, "index": 4, "x": 4, "y": 6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 4, "y": 6, "width": 2, "height": 2}}, {"designator": "MC9", "name": "DS", "net": "DS", "margin": "rightMargin", "side": "right", "row": 0, "index": 0, "x": 4, "y": 2, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 4, "y": 2, "width": 2, "height": 2}}, {"designator": "MC10", "name": "OE", "net": "OE", "margin": "rightMargin", "side": "right", "row": 0, "index": 1, "x": 4, "y": 0, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 4, "y": 0, "width": 2, "height": 2}}, {"designator": "MC11", "name": "STCP", "net": "STCP", "margin": "rightMargin", "side": "right", "row": 0, "index": 2, "x": 4, "y": -2, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 4, "y": -2, "width": 2, "height": 2}}, {"designator": "MC12", "name": "SHCP", "net": "SHCP", "margin": "bottomWingMargin", "side": "bottom", "row": 0, "index": 0, "x": 4, "y": -6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 4, "y": -6, "width": 2, "height": 2}}, {"designator": "MC13", "name": "MR", "net": "MR", "margin": "bottomWingMargin", "side": "bottom", "row": 0, "index": 1, "x": 2, "y": -6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 2, "y": -6, "width": 2, "height": 2}}, {"designator": "MC14", "name": "Q7S", "net": "Q7S", "margin": "bottomWingMargin", "side": "bottom", "row": 0, "index": 2, "x": 0, "y": -6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": 0, "y": -6, "width": 2, "height": 2}}, {"designator": "MC15", "name": "GND", "net": "GND", "margin": "bottomWingMargin", "side": "bottom", "row": 0, "index": 3, "x": -2, "y": -6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": -2, "y": -6, "width": 2, "height": 2}}, {"designator": "MC16", "name": "Q7", "net": "Q7", "margin": "bottomWingMargin", "side": "bottom", "row": 0, "index": 4, "x": -4, "y": -6, "type": "MachineContactMedium", "holeID": 0.78, "holeOD": 1.3, "boundingBox": 2, "gridCell": {"x": -4, "y": -6, "width": 2, "height": 2}}], "channels": [{"between": ["MC1", "MC2"], "axis": "y", "x": -4, "y": -1, "width": 1.3, "height": 0.7, "gapMm": 0.7, "traces": 1}, {"between": ["MC1", "MP1"], "axis": "y", "x": -4, "y": -2.925, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}, {"between": ["MC2", "MC3"], "axis": "y", "x": -4, "y": 1, "width": 1.3, "height": 0.7, "gapMm": 0.7, "traces": 1}, {"between": ["MC3", "MP2"], "axis": "y", "x": -4, "y": 2.925, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}, {"between": ["MC4", "MC5"], "axis": "x", "x": -3, "y": 6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC4", "MP2"], "axis": "y", "x": -4, "y": 5.075, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}, {"between": ["MC5", "MC6"], "axis": "x", "x": -1, "y": 6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC6", "MC7"], "axis": "x", "x": 1, "y": 6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC7", "MC8"], "axis": "x", "x": 3, "y": 6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC8", "MP3"], "axis": "y", "x": 4, "y": 5.075, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}, {"between": ["MC9", "MC10"], "axis": "y", "x": 4, "y": 1, "width": 1.3, "height": 0.7, "gapMm": 0.7, "traces": 1}, {"between": ["MC9", "MP3"], "axis": "y", "x": 4, "y": 2.925, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}, {"between": ["MC10", "MC11"], "axis": "y", "x": 4, "y": -1, "width": 1.3, "height": 0.7, "gapMm": 0.7, "traces": 1}, {"between": ["MC11", "MP4"], "axis": "y", "x": 4, "y": -2.925, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}, {"between": ["MC12", "MC13"], "axis": "x", "x": 3, "y": -6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC12", "MP4"], "axis": "y", "x": 4, "y": -5.075, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}, {"between": ["MC13", "MC14"], "axis": "x", "x": 1, "y": -6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC14", "MC15"], "axis": "x", "x": -1, "y": -6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC15", "MC16"], "axis": "x", "x": -3, "y": -6, "width": 0.7, "height": 1.3, "gapMm": 0.7, "traces": 1}, {"between": ["MC16", "MP1"], "axis": "y", "x": -4, "y": -5.075, "width": 1.3, "height": 0.55, "gapMm": 0.55, "traces": 1}], "moleculePlaceholders": [], "molecules": [], "rules": {"traceMm": 0.2, "clearanceMm": 0.15}}\ No newline at end of file
examples/cd74hc4067/0402.kicad_modadded+6
@@ -0,0 +1,6 @@+(footprint "0402"+  (layer "F.Cu")+  (attr smd)+  (pad "1" smd rect (at -0.5 0) (size 0.6 0.5) (layers "F.Cu" "F.Paste" "F.Mask"))+  (pad "2" smd rect (at 0.5 0) (size 0.6 0.5) (layers "F.Cu" "F.Paste" "F.Mask"))+)
examples/cd74hc4067/a-upright.jsonadded+68
@@ -0,0 +1,68 @@+{+ "title": "A: U1 upright (pin 1 top left)",+ "plan": "plan.json",+ "machinePinNets": {+  "MP1": "GND",+  "MP2": "VCC",+  "MP3": "VCC",+  "MP4": "GND"+ },+ "parts": [+  {+   "ref": "U1",+   "footprint": "cd74hc4067sm96.kicad_mod",+   "x": 0,+   "y": 0,+   "rotation": 0,+   "pins": {+    "1": "COM",+    "2": "I7",+    "3": "I6",+    "4": "I5",+    "5": "I4",+    "6": "I3",+    "7": "I2",+    "8": "I1",+    "9": "I0",+    "10": "S0",+    "11": "S1",+    "12": "GND",+    "13": "S3",+    "14": "S2",+    "15": "E",+    "16": "I15",+    "17": "I14",+    "18": "I13",+    "19": "I12",+    "20": "I11",+    "21": "I10",+    "22": "I9",+    "23": "I8",+    "24": "VCC"+   },+   "label": "CD74HC4067"+  },+  {+   "ref": "C1",+   "footprint": "0402.kicad_mod",+   "x": 4.3,+   "y": 5.4,+   "rotation": 90,+   "pins": {+    "1": "VCC",+    "2": "GND"+   }+  },+  {+   "ref": "R1",+   "footprint": "0402.kicad_mod",+   "x": 4.3,+   "y": -5.4,+   "rotation": 90,+   "pins": {+    "1": "E",+    "2": "GND"+   }+  }+ ]+}\ No newline at end of file
examples/cd74hc4067/b-turned.jsonadded+92
@@ -0,0 +1,92 @@+{+ "title": "B: U1 turned 90 (pin 1 bottom left), contacts unchanged, nets re-ordered",+ "plan": "plan.json",+ "machinePinNets": {+  "MP1": "GND",+  "MP2": "VCC",+  "MP3": "VCC",+  "MP4": "GND"+ },+ "contactNets": {+  "MC16": "S3",+  "MC15": "S2",+  "MC14": "E",+  "MC13": "I15",+  "MC12": "I14",+  "MC11": "I13",+  "MC10": "I12",+  "MC9": "I11",+  "MC8": "I10",+  "MC7": "I9",+  "MC6": "I8",+  "MC5": "COM",+  "MC4": "I7",+  "MC3": "I6",+  "MC2": "I5",+  "MC1": "I4",+  "MC22": "I3",+  "MC21": "I2",+  "MC20": "I1",+  "MC19": "I0",+  "MC18": "S0",+  "MC17": "S1"+ },+ "parts": [+  {+   "ref": "U1",+   "footprint": "cd74hc4067sm96.kicad_mod",+   "x": 0,+   "y": 0,+   "rotation": 90,+   "pins": {+    "1": "COM",+    "2": "I7",+    "3": "I6",+    "4": "I5",+    "5": "I4",+    "6": "I3",+    "7": "I2",+    "8": "I1",+    "9": "I0",+    "10": "S0",+    "11": "S1",+    "12": "GND",+    "13": "S3",+    "14": "S2",+    "15": "E",+    "16": "I15",+    "17": "I14",+    "18": "I13",+    "19": "I12",+    "20": "I11",+    "21": "I10",+    "22": "I9",+    "23": "I8",+    "24": "VCC"+   },+   "label": "CD74HC4067"+  },+  {+   "ref": "C1",+   "footprint": "0402.kicad_mod",+   "x": -4.6,+   "y": 5.6,+   "rotation": 90,+   "pins": {+    "1": "VCC",+    "2": "GND"+   }+  },+  {+   "ref": "R1",+   "footprint": "0402.kicad_mod",+   "x": 1.0,+   "y": 5.6,+   "rotation": 0,+   "pins": {+    "1": "E",+    "2": "GND"+   }+  }+ ]+}\ No newline at end of file
examples/cd74hc4067/cd74hc4067sm96.kicad_modadded+396
@@ -0,0 +1,396 @@+(footprint "SSOP-24_5.3x8.2mm_P0.65mm"+	(version 20260206)+	(generator "kicad-footprint-generator")+	(layer "F.Cu")+	(descr "SSOP, 24 Pin (JEDEC MO-150 variation AG, 1.75mm body thickness, https://www.jedec.org/document_search?search_api_views_fulltext=MO-150, https://ww1.microchip.com/downloads/en/PackagingSpec/00000049BQ.pdf#page=398, https://www.analog.com/media/en/package-pcb-resources/package/pkg_pdf/ltc-legacy-ssop/ssop_24_05-08-1640.pdf)")+	(tags "SSOP SO")+	(property "Reference" "REF**"+		(at 0 -5.05 0)+		(layer "F.SilkS")+		(effects+			(font+				(size 1 1)+				(thickness 0.15)+			)+		)+	)+	(property "Value" "SSOP-24_5.3x8.2mm_P0.65mm"+		(at 0 5.05 0)+		(layer "F.Fab")+		(effects+			(font+				(size 1 1)+				(thickness 0.15)+			)+		)+	)+	(property "KiLib_Generator" "package/gullwing"+		(at 0 0 0)+		(layer "F.SilkS")+		(hide yes)+		(effects+			(font+				(size 1 1)+				(thickness 0.15)+			)+		)+	)+	(attr smd)+	(duplicate_pad_numbers_are_jumpers no)+	(fp_line+		(start -2.76 -4.21)+		(end 2.76 -4.21)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start -2.76 -4.035)+		(end -2.76 -4.21)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start -2.76 4.21)+		(end -2.76 4.035)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start 2.76 -4.21)+		(end 2.76 -4.035)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start 2.76 4.035)+		(end 2.76 4.21)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_line+		(start 2.76 4.21)+		(end -2.76 4.21)+		(stroke+			(width 0.12)+			(type solid)+		)+		(layer "F.SilkS")+	)+	(fp_poly+		(pts+			(xy -3.5 -4.04)+			(xy -3.84 -4.51)+			(xy -3.16 -4.51)+		)+		(stroke+			(width 0.12)+			(type solid)+		)+		(fill yes)+		(layer "F.SilkS")+	)+	(fp_line+		(start -4.7 -4.03)+		(end -2.9 -4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -4.7 4.03)+		(end -4.7 -4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -2.9 -4.35)+		(end 2.9 -4.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -2.9 -4.03)+		(end -2.9 -4.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -2.9 4.03)+		(end -4.7 4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start -2.9 4.35)+		(end -2.9 4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 2.9 -4.35)+		(end 2.9 -4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 2.9 -4.03)+		(end 4.7 -4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 2.9 4.03)+		(end 2.9 4.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 2.9 4.35)+		(end -2.9 4.35)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 4.7 -4.03)+		(end 4.7 4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_line+		(start 4.7 4.03)+		(end 2.9 4.03)+		(stroke+			(width 0.05)+			(type solid)+		)+		(layer "F.CrtYd")+	)+	(fp_poly+		(pts+			(xy -1.65 -4.1)+			(xy 2.65 -4.1)+			(xy 2.65 4.1)+			(xy -2.65 4.1)+			(xy -2.65 -3.1)+		)+		(stroke+			(width 0.1)+			(type solid)+		)+		(fill no)+		(layer "F.Fab")+	)+	(fp_text user "${REFERENCE}"+		(at 0 0 0)+		(layer "F.Fab")+		(effects+			(font+				(size 1 1)+				(thickness 0.15)+			)+		)+	)+	(pad "1" smd roundrect+		(at -3.5 -3.575)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "2" smd roundrect+		(at -3.5 -2.925)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "3" smd roundrect+		(at -3.5 -2.275)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "4" smd roundrect+		(at -3.5 -1.625)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "5" smd roundrect+		(at -3.5 -0.975)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "6" smd roundrect+		(at -3.5 -0.325)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "7" smd roundrect+		(at -3.5 0.325)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "8" smd roundrect+		(at -3.5 0.975)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "9" smd roundrect+		(at -3.5 1.625)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "10" smd roundrect+		(at -3.5 2.275)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "11" smd roundrect+		(at -3.5 2.925)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "12" smd roundrect+		(at -3.5 3.575)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "13" smd roundrect+		(at 3.5 3.575)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "14" smd roundrect+		(at 3.5 2.925)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "15" smd roundrect+		(at 3.5 2.275)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "16" smd roundrect+		(at 3.5 1.625)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "17" smd roundrect+		(at 3.5 0.975)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "18" smd roundrect+		(at 3.5 0.325)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "19" smd roundrect+		(at 3.5 -0.325)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "20" smd roundrect+		(at 3.5 -0.975)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "21" smd roundrect+		(at 3.5 -1.625)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "22" smd roundrect+		(at 3.5 -2.275)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "23" smd roundrect+		(at 3.5 -2.925)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(pad "24" smd roundrect+		(at 3.5 -3.575)+		(size 1.9 0.4)+		(layers "F.Cu" "F.Mask" "F.Paste")+		(roundrect_rratio 0.25)+	)+	(embedded_fonts no)+	(model "${KICAD10_3DMODEL_DIR}/Package_SO.3dshapes/SSOP-24_5.3x8.2mm_P0.65mm.step"+		(offset+			(xyz 0 0 0)+		)+		(scale+			(xyz 1 1 1)+		)+		(rotate+			(xyz 0 0 0)+		)+	)+)
examples/cd74hc4067/molecule.jsonadded+1
@@ -0,0 +1 @@+{"type":"4pin","size":"8x16","pinType":"MachinePinMediumShort","wingLeft":"2mm","wingRight":"2mm"}
examples/cd74hc4067/plan.jsonadded+304
@@ -0,0 +1,304 @@+{+ "board": {+  "width": 14,+  "height": 18,+  "nominalWidth": 10,+  "nominalHeight": 18,+  "center": {+   "x": 0,+   "y": 0+  },+  "cornerRadius": 0,+  "wings": {+   "left": 2,+   "right": 2,+   "top": 0,+   "bottom": 0+  },+  "outline": [+   {+    "x": 7,+    "y": -9+   },+   {+    "x": 7,+    "y": 9+   },+   {+    "x": -7,+    "y": 9+   },+   {+    "x": -7,+    "y": -9+   }+  ]+ },+ "machinePins": [+  {+   "name": "MP1",+   "x": -4,+   "y": -8,+   "type": "MachinePinMediumShort",+   "holeID": 1.2,+   "holeOD": 1.6,+   "boundingBox": 2+  },+  {+   "name": "MP2",+   "x": -4,+   "y": 8,+   "type": "MachinePinMediumShort",+   "holeID": 1.2,+   "holeOD": 1.6,+   "boundingBox": 2+  },+  {+   "name": "MP3",+   "x": 4,+   "y": 8,+   "type": "MachinePinMediumShort",+   "holeID": 1.2,+   "holeOD": 1.6,+   "boundingBox": 2+  },+  {+   "name": "MP4",+   "x": 4,+   "y": -8,+   "type": "MachinePinMediumShort",+   "holeID": 1.2,+   "holeOD": 1.6,+   "boundingBox": 2+  }+ ],+ "contacts": [+  {+   "designator": "MC1",+   "net": "S0",+   "x": -6,+   "y": -8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC2",+   "net": "I0",+   "x": -6,+   "y": -6,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC3",+   "net": "I1",+   "x": -6,+   "y": -4,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC4",+   "net": "I2",+   "x": -6,+   "y": -2,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC5",+   "net": "I3",+   "x": -6,+   "y": 0,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC6",+   "net": "I4",+   "x": -6,+   "y": 2,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC7",+   "net": "I5",+   "x": -6,+   "y": 4,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC8",+   "net": "I6",+   "x": -6,+   "y": 6,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC9",+   "net": "I7",+   "x": -6,+   "y": 8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC10",+   "net": "COM",+   "x": -2,+   "y": 8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC11",+   "net": "I8",+   "x": 2,+   "y": 8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC12",+   "net": "I9",+   "x": 6,+   "y": 8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC13",+   "net": "I10",+   "x": 6,+   "y": 6,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC14",+   "net": "I11",+   "x": 6,+   "y": 4,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC15",+   "net": "I12",+   "x": 6,+   "y": 2,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC16",+   "net": "I13",+   "x": 6,+   "y": 0,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC17",+   "net": "I14",+   "x": 6,+   "y": -2,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC18",+   "net": "I15",+   "x": 6,+   "y": -4,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC19",+   "net": "E",+   "x": 6,+   "y": -6,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC20",+   "net": "S2",+   "x": 6,+   "y": -8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC21",+   "net": "S3",+   "x": 2,+   "y": -8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  },+  {+   "designator": "MC22",+   "net": "S1",+   "x": -2,+   "y": -8,+   "type": "MachineContactMedium",+   "holeID": 0.78,+   "holeOD": 1.3,+   "boundingBox": 2+  }+ ],+ "channels": [],+ "moleculePlaceholders": [],+ "molecules": [],+ "rules": {+  "traceMm": 0.2,+  "clearanceMm": 0.15+ }+}\ No newline at end of file
package.json+20−4
@@ -1,6 +1,6 @@ {   "slug": "adom-2dboard",-  "version": "0.4.1",+  "version": "0.5.0",   "type": "app",   "description": "Interactive 2D board view: your EDA's own PCB render plus live net/trace highlighting and per-pad stock, price and wiki lookup",   "dependencies": {@@ -25,7 +25,13 @@     "make the pcb preview clickable",     "interactive pcb view",     "embed a board view in my app",-    "what part is this on the board"+    "what part is this on the board",+    "mock up the layout",+    "MP MC board size chip",+    "molecule plan",+    "compare layouts",+    "render the board to png",+    "show the circuit.json board"   ],   "discovery_pitch": "Use to view or embed a PCB layout that looks exactly like the user's EDA drew it, with clickable nets, traces and pads plus live stock, price and wiki data per part.",   "sample_prompts": [@@ -44,6 +50,10 @@     {       "label": "Embed it",       "prompt": "replace the flat PCB image in my app with an interactive board view"+    },+    {+      "label": "Mock up a molecule",+      "prompt": "mock up the MP / MC layout for this chip at 8x16 and compare upright vs turned"     }   ],   "tags": [@@ -63,6 +73,12 @@     "fusion",     "eagle",     "pcbdoc",-    "schdoc"-  ]+    "schdoc",+    "molecule",+    "plan",+    "tscircuit",+    "circuit-json",+    "png"+  ],+  "title": "Adom 2D Board" }
page.json+18−3
@@ -4,7 +4,7 @@   "type": "app",   "title": "Adom 2D Board",   "brief": "Interactive 2D board view: your EDA's own PCB render plus live net/trace highlighting and per-pad stock, price and wiki lookup",-  "version": "0.4.1",+  "version": "0.5.0",   "author": {     "name": "barrett-land",     "email": "[email protected]"@@ -26,7 +26,12 @@     "fusion",     "eagle",     "pcbdoc",-    "schdoc"+    "schdoc",+    "molecule",+    "plan",+    "tscircuit",+    "circuit-json",+    "png"   ],   "license": "proprietary",   "visibility": "public",@@ -50,6 +55,10 @@     {       "label": "Embed it",       "prompt": "replace the flat PCB image in my app with an interactive board view"+    },+    {+      "label": "Mock up a molecule",+      "prompt": "mock up the MP / MC layout for this chip at 8x16 and compare upright vs turned"     }   ],   "discovery_triggers": [@@ -62,7 +71,13 @@     "make the pcb preview clickable",     "interactive pcb view",     "embed a board view in my app",-    "what part is this on the board"+    "what part is this on the board",+    "mock up the layout",+    "MP MC board size chip",+    "molecule plan",+    "compare layouts",+    "render the board to png",+    "show the circuit.json board"   ],   "discovery_pitch": "Use to view or embed a PCB layout that looks exactly like the user's EDA drew it, with clickable nets, traces and pads plus live stock, price and wiki data per part.",   "metadata": {},
scripts/acceptance/courtyards.pyadded+50
@@ -0,0 +1,50 @@+"""Acceptance 3: courtyard overlaps across the claude-pcb-f411 boards, checked against shapely.++For each board's committed circuit.json (and design.json) at a given claude-pcb-f411 commit, runs+`adom-2dboard render --circuit ... --json` and compares its overlapping pairs with shapely's positive-area+intersections of the same top-side courtyards. Usage: python3 courtyards.py <binary> <claude-pcb-f411 repo> <commit>"""+import json, subprocess, sys, tempfile+from pathlib import Path+sys.path.insert(0, '/home/adom/project/claude-pcb-f411/.validation-packages')+from shapely.geometry import Point, Polygon+from shapely import affinity++BIN, REPO, COMMIT = sys.argv[1], sys.argv[2], sys.argv[3]+git = lambda *a: subprocess.run(['git', '-C', REPO, *a], capture_output=True, text=True, check=True).stdout+paths = [p for p in git('ls-tree', '-r', '--name-only', COMMIT, '--', 'mcu-self-contained/boards').split('\n')+         if p.endswith('/dist/lib/index/circuit.json') and p.count('/') == 6]+def shapely_pairs(cj):+    name = {c['source_component_id']: c['name'] for c in cj if c['type'] == 'source_component'}+    comp = {c['pcb_component_id']: name.get(c['source_component_id']) for c in cj if c['type'] == 'pcb_component'}+    shapes = []+    for e in cj:+        if e.get('layer') == 'bottom' or e['type'] not in ('pcb_courtyard_outline', 'pcb_courtyard_circle', 'pcb_courtyard_rect'): continue+        o = comp.get(e.get('pcb_component_id'))+        if e['type'] == 'pcb_courtyard_circle': g = Point(e['center']['x'], e['center']['y']).buffer(e['radius'], 256)+        elif e['type'] == 'pcb_courtyard_rect':+            c, w, h = e['center'], e['width'], e['height']+            g = affinity.rotate(Polygon([(c['x'] - w / 2, c['y'] - h / 2), (c['x'] + w / 2, c['y'] - h / 2), (c['x'] + w / 2, c['y'] + h / 2), (c['x'] - w / 2, c['y'] + h / 2)]), e.get('ccw_rotation', 0) or 0, origin=(c['x'], c['y']))+        else: g = Polygon([(p['x'], p['y']) for p in e['outline']])+        shapes.append((o, g))+    out = set()+    for i, (a, ga) in enumerate(shapes):+        for b, gb in shapes[i + 1:]:+            if a != b and ga.intersection(gb).area > 1e-6: out.add(tuple(sorted((a, b))))+    return out+total, agree, excepted = 0, True, []+with tempfile.TemporaryDirectory() as t:+    for p in sorted(paths):+        board = p.split('/')[2]; bd = Path(t) / board; bd.mkdir()+        (bd / 'circuit.json').write_text(git('show', f'{COMMIT}:{p}'))+        args = [BIN, 'render', '--circuit', str(bd / 'circuit.json'), '--out', '/dev/null', '--json', '--title', board]+        try:+            (bd / 'design.json').write_text(git('show', f'{COMMIT}:mcu-self-contained/boards/{board}/design.json')); args += ['--design', str(bd / 'design.json')]+        except subprocess.CalledProcessError: pass+        out = subprocess.run(args, capture_output=True, text=True, check=True).stdout+        ov = json.loads(out[:out.rindex(']') + 1])[0]['courtyardOverlaps']+        mine = {tuple(sorted((o['a'], o['b']))) for o in ov}+        ref = shapely_pairs(json.loads((bd / 'circuit.json').read_text()))+        total += len(mine); agree &= mine == ref+        excepted += [(board, o['a'], o['b']) for o in ov if o['excepted']]+        if mine: print(f'{board}: ' + ', '.join(f"{o['a']}-{o['b']}{' (exception)' if o['excepted'] else ''}" for o in ov) + ('' if mine == ref else f'  SHAPELY: {sorted(ref)}'))+print(f'{len(paths)} boards, {total} overlapping pairs, shapely agrees on every board: {agree}; named exceptions: {excepted}')
scripts/acceptance/hc595_pours.pyadded+23
@@ -0,0 +1,23 @@+"""Acceptance 2: logic-74hc595bq at claude-pcb-f411 tag hc595-domino-v2.3 shows both bottom pours with a 0.30 mm+gap and a 0.40 mm edge pullback, and the 45-degree corner labels.+Usage: python3 hc595_pours.py <adom-2dboard binary> <claude-pcb-f411 repo> [out.png]"""+import json, os, subprocess, sys, tempfile+BIN, REPO = sys.argv[1], sys.argv[2]+OUT = sys.argv[3] if len(sys.argv) > 3 else '/dev/null'+B = 'mcu-self-contained/boards/logic-74hc595bq'+with tempfile.TemporaryDirectory() as t:+    for f, p in (('circuit.json', f'{B}/dist/lib/index/circuit.json'), ('design.json', f'{B}/design.json')):+        open(os.path.join(t, f), 'w').write(subprocess.run(['git', '-C', REPO, 'show', f'hc595-domino-v2.3:{p}'], capture_output=True, text=True, check=True).stdout)+    out = subprocess.run([BIN, 'render', '--circuit', f'{t}/circuit.json', '--design', f'{t}/design.json', '--out', OUT, '--json'], capture_output=True, text=True, check=True).stdout+s = json.loads(out[:out.rindex(']') + 1])[0]+bottom = [p for p in s['pours'] if p['layer'] == 'bottom']+corner = [t for t in s['silk'] if abs(abs(t['ccwRotation']) - 45) < 1e-9 and not t['bottom']]+checks = {+    'bottom pours VCC and GND': len(bottom) == 1 and sorted(bottom[0]['nets']) == ['GND', 'VCC'],+    'pour gap 0.30 mm': bool(bottom) and bottom[0]['gap_mm'] == 0.3,+    'edge pullback 0.40 mm': bool(bottom) and bottom[0]['edge_pullback_mm'] == 0.4,+    '45-degree corner labels (VCC -45, GND +45)': sorted((t['text'], t['ccwRotation']) for t in corner) == [('GND', 45.0), ('VCC', -45.0)],+}+print('pours:', bottom); print('corner labels:', [(t['text'], t['ccwRotation'], t['x'], t['y']) for t in corner])+for k, v in checks.items(): print(('PASS ' if v else 'FAIL ') + k)+sys.exit(0 if all(checks.values()) else 1)
scripts/acceptance/mock_positions.pyadded+76
@@ -0,0 +1,76 @@+"""Acceptance 1: the viewer reproduces the matplotlib mocks' positions exactly.++Recomputes every machine pin, contact and pad centre the way the mock scripts did (claude-pcb-f411's mcu_line /+wiki_pad_geometry helpers, shapely), runs `adom-2dboard render --json` on the matching example layouts, and compares+positions and nets. Usage: python3 mock_positions.py <adom-2dboard binary> <mock scratch dir>"""+import json, math, subprocess, sys+from pathlib import Path+sys.path.insert(0, '/home/adom/project/claude-pcb-f411/scripts'); sys.path.insert(0, '/home/adom/project/claude-pcb-f411/.validation-packages')+import mcu_line as M+from wiki_pad_geometry import footprint_pads+from shapely.geometry import box+from shapely import affinity++BIN, MOCK = sys.argv[1], Path(sys.argv[2])+EX = Path(__file__).resolve().parents[2] / 'examples'+TOL = 1e-4++def viewer(*layouts):+    out = subprocess.run([BIN, 'render', *sum((['--layout', str(l)] for l in layouts), []), '--out', '/dev/null', '--json'],+                         capture_output=True, text=True, check=True).stdout+    return json.loads(out[:out.rindex(']') + 1])++def compare(name, want, got):+    """want/got: {key: (x, y, net-or-None)}"""+    bad = [k for k in want if k not in got or math.dist(want[k][:2], got[k][:2]) > TOL or (want[k][2] is not None and want[k][2] != got[k][2])]+    extra = [k for k in got if k not in want]+    worst = max((math.dist(want[k][:2], got[k][:2]) for k in want if k in got), default=0)+    print(f'{name}: {len(want)} positions, {len(bad)} differ, {len(extra)} extra, worst offset {worst:.2e} mm')+    for k in bad[:5]: print('   ', k, 'mock', want[k], 'viewer', got.get(k))+    return not bad and not extra++def got_of(scene):+    g = {('MP', m['name']): (m['x'], m['y'], m['net']) for m in scene['machinePins']}+    g.update({('MC', c['name']): (c['x'], c['y'], c['net']) for c in scene['contacts']})+    g.update({('pad', p['part'], p['pin']): (p['x'], p['y'], None) for p in scene['pads']})+    return g++ok = True+# 74HC595BQ domino (m595v/mock.py)+plan = json.load(open(MOCK / 'm595v/plan.json'))+roles = {'MP1': 'GND', 'MP2': 'VCC', 'MP3': 'VCC', 'MP4': 'GND'}+want = {('MP', m['name']): (m['x'], m['y'], roles[m['name']]) for m in plan['machinePins']}+want.update({('MC', c['designator']): (c['x'], c['y'], c['net']) for c in plan['contacts']})+for ref, slug, pos in (('U1', '74hc595bq', (0, -0.25)), ('C1', '0402b104j160ct', (1.4, 2.75))):+    want.update({('pad', ref, k): (c[0], c[1], None) for k, (c, g) in M.pad_geoms(slug, pos, 0).items()})+ok &= compare('74HC595BQ domino (m595v)', want, got_of(viewer(EX / '74hc595bq-domino/layout.json')[0]))++# CD74HC4067 A / B (mock4067.py)+U1PINS = {1:'COM',2:'I7',3:'I6',4:'I5',5:'I4',6:'I3',7:'I2',8:'I1',9:'I0',10:'S0',11:'S1',12:'GND',13:'S3',14:'S2',15:'E',16:'I15',17:'I14',18:'I13',19:'I12',20:'I11',21:'I10',22:'I9',23:'I8',24:'VCC'}+plan = json.load(open(MOCK / 'plan4067.json')); slots = {(x, y): k for k, (n, x, y) in plan.items()}+MPS = {'MP1': ((-4, -8), 'GND'), 'MP2': ((-4, 8), 'VCC'), 'MP3': ((4, 8), 'VCC'), 'MP4': ((4, -8), 'GND')}+scenes = viewer(EX / 'cd74hc4067/a-upright.json', EX / 'cd74hc4067/b-turned.json')+for variant, scene in zip(('upright', 'turned'), scenes):+    if variant == 'upright':+        rot = 0; nets = {k: n for k, (n, x, y) in plan.items()}+        parts = [('C1', (4.3, 5.4), 90), ('R1', (4.3, -5.4), 90)]+    else:+        rot = 90+        order_top = [(6, 0), (6, 2), (6, 4), (6, 6), (6, 8), (2, 8), (-2, 8), (-6, 8), (-6, 6), (-6, 4), (-6, 2)]+        order_bot = [(-6, 0), (-6, -2), (-6, -4), (-6, -6), (-6, -8), (-2, -8), (2, -8), (6, -8), (6, -6), (6, -4), (6, -2)]+        nets = {}+        for pn, xy in zip(range(13, 24), order_top): nets[slots[xy]] = U1PINS[pn]+        for pn, xy in zip(range(1, 12), order_bot): nets[slots[xy]] = U1PINS[pn]+        parts = [('C1', (-4.6, 5.6), 90), ('R1', (1.0, 5.6), 0)]+    want = {('MP', k): (xy[0], xy[1], n) for k, (xy, n) in MPS.items()}+    want.update({('MC', k): (x, y, nets.get(k, n)) for k, (n, x, y) in plan.items()})+    for p in footprint_pads(MOCK / 'logic/cd74hc4067sm96/cd74hc4067sm96.kicad_mod'):+        if not any(l.endswith('.Cu') for l in p['layers']): continue+        w, h = p['size']; g = affinity.rotate(box(p['at'][0] - w / 2, -p['at'][1] - h / 2, p['at'][0] + w / 2, -p['at'][1] + h / 2), rot, origin=(0, 0))+        want[('pad', 'U1', str(p['pad']))] = (g.centroid.x, g.centroid.y, None)+    for ref, (cx, cy), r in parts:+        for k, x, y, w, h in (('1', -0.5, 0.0, 0.6, 0.5), ('2', 0.5, 0.0, 0.6, 0.5)):+            g = affinity.translate(affinity.rotate(box(x - w / 2, y - h / 2, x + w / 2, y + h / 2), r, origin=(0, 0)), cx, cy)+            want[('pad', ref, k)] = (g.centroid.x, g.centroid.y, None)+    ok &= compare(f'CD74HC4067 {variant} (mock4067.py)', want, got_of(scene))+print('PASS' if ok else 'FAIL'); sys.exit(0 if ok else 1)
src/main.rs+58−4
@@ -14,6 +14,8 @@ mod sexpr; mod sch_render; mod server; mod enrich;+mod plan_view;+mod png;  use anyhow::{Context, Result}; use clap::{Parser, Subcommand};@@ -29,12 +31,37 @@ struct Cli {  #[derive(Subcommand)] enum Cmd {-    /// Render a `.kicad_pcb` to a themed, identity-tagged SVG (+ optional -meta.json).+    /// Render a board to SVG or PNG (by --out's extension). Inputs: a finished `.kicad_pcb` (--file), molecule+    /// plans before routing (--layout, repeat to compare side by side), or a built tscircuit `circuit.json`+    /// (--circuit, with --design for a claude-pcb-f411 design.json's roles, pours and courtyard exceptions).     Render {+        /// A finished board: `.kicad_pcb` (also Altium / Eagle)         #[arg(long)]-        file: PathBuf,+        file: Option<PathBuf>,+        /// A planning layout (molecule plan + footprints + placements); repeat for side-by-side variants+        #[arg(long)]+        layout: Vec<PathBuf>,+        /// A built board's circuit.json+        #[arg(long)]+        circuit: Option<PathBuf>,+        /// design.json beside the circuit.json (default: <circuit dir>/../../../design.json when it exists)+        #[arg(long)]+        design: Option<PathBuf>,+        /// Title for a circuit.json view (default: the board directory name)+        #[arg(long)]+        title: Option<String>,+        /// Output: .svg or .png         #[arg(long)]         out: PathBuf,+        /// PNG width in pixels+        #[arg(long, default_value_t = 1000)]+        width: u32,+        /// Leave courtyards out (plan / circuit.json views draw them: overlaps red, named exceptions amber)+        #[arg(long)]+        no_courtyards: bool,+        /// Print the plan / circuit.json measurements (clearances, crossings, courtyard overlaps, pours) as JSON+        #[arg(long)]+        json: bool,         /// Also write <out>.meta.json (nets, components, counts)         #[arg(long)]         meta: bool,@@ -99,6 +126,17 @@ pub fn build_embed(svg: &str, meta_json: &str) -> String {     APP_HTML.replace(r#"<script src="viewer.js"></script>"#, &payload) } +/// Write an SVG, or a PNG when `out` ends in .png.+fn write_image(out: &std::path::Path, svg: &str, width: u32) -> Result<()> {+    if out.extension().map_or(false, |e| e.eq_ignore_ascii_case("png")) {+        let png = png::svg_to_png(svg, width)?;+        fs::write(out, &png).with_context(|| format!("write {}", out.display()))?;+    } else {+        fs::write(out, svg).with_context(|| format!("write {}", out.display()))?;+    }+    Ok(())+}+ // CLI contract: every response starts with `OK:` or `ERROR:`, and every error // carries an actionable `Hint:` naming the next command. fn main() {@@ -112,11 +150,27 @@ fn main() { fn run() -> Result<()> {     let cli = Cli::parse();     match cli.command {-        Cmd::Render { file, out, meta, base } => {+        Cmd::Render { file, layout, circuit, design, title, out, width, no_courtyards, json, meta, base } => {+            let given = file.is_some() as u8 + (!layout.is_empty()) as u8 + circuit.is_some() as u8;+            if given != 1 {+                anyhow::bail!("give exactly one input: --file <board.kicad_pcb>, --layout <plan layout>... or --circuit <circuit.json>");+            }+            if file.is_none() {+                let scenes = plan_view::scenes_for(&layout, circuit.as_deref(), design.as_deref(), title.as_deref(), !no_courtyards)?;+                write_image(&out, &plan_view::render_svg(&scenes), width)?;+                if json {+                    println!("{}", serde_json::to_string_pretty(&plan_view::report(&scenes, &out))?);+                } else {+                    for line in plan_view::summary(&scenes) { println!("{line}"); }+                }+                println!("OK: rendered {} view(s) -> {}", scenes.len(), out.display());+                return Ok(());+            }+            let file = file.unwrap();             let raw = fs::read(&file).with_context(|| format!("read {}", file.display()))?;             let base_svg = base.as_ref().and_then(|p| fs::read_to_string(p).ok());             let (svg, m) = pcb_render::render_board_bytes_with(&raw, base_svg.as_deref());-            fs::write(&out, &svg).with_context(|| format!("write {}", out.display()))?;+            write_image(&out, &svg, width)?;             println!(                 "OK: rendered {} -> {} ({} nets, {} comps, {} tracks, {} vias, {} pads, {:.1}x{:.1}mm)",                 file.display(), out.display(), m.net_names.len(), m.components.len(),
src/plan_view.rsadded+1365
@@ -0,0 +1,1365 @@+//! Plan view (#21): a plain, static 2D layout view of a molecule, labelled by net.+//!+//! Draws the board outline (wings included), machine pins and contacts labelled by net with copper sized from the+//! library's hole OD, free contact slots dashed, each footprint's pads with pin numbers and a pin-1 mark at its+//! placement and rotation, passives, pin-to-contact lines (planning) or traces (built board), and the measured+//! minimum copper clearance from every part to the nearest other copper. Courtyards are drawn too (on by default; a+//! placement review hinges on them): overlapping pairs in red, pairs a design names as courtyard exceptions in amber.+//!+//! Two inputs, one look:+//! - `Scene::from_layout`: before routing. The headless molecule plan (`bun scripts/plan.ts` in+//!   adom-inc/adom-tsci-molecule, its `planMolecule` JSON) plus footprints (`.kicad_mod`) and their placements.+//! - `Scene::from_circuit`: a built board's `circuit.json`, with traces.+//!+//! Coordinates are board millimetres, y up; the SVG flips y.++use anyhow::{anyhow, bail, Context, Result};+use serde_json::Value;+use std::collections::{BTreeMap, HashMap};+use std::fmt::Write as _;+use std::path::{Path, PathBuf};++pub type Pt = (f64, f64);++// ─── geometry ──────────────────────────────────────────────────────────────++#[derive(Clone, Debug)]+pub enum Shape {+    Circle { c: Pt, r: f64 },+    Poly(Vec<Pt>),+}++impl Shape {+    pub fn centre(&self) -> Pt {+        match self {+            Shape::Circle { c, .. } => *c,+            Shape::Poly(p) => {+                let n = p.len() as f64;+                (p.iter().map(|q| q.0).sum::<f64>() / n, p.iter().map(|q| q.1).sum::<f64>() / n)+            }+        }+    }+    fn bounds(&self) -> (f64, f64, f64, f64) {+        match self {+            Shape::Circle { c, r } => (c.0 - r, c.1 - r, c.0 + r, c.1 + r),+            Shape::Poly(p) => p.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, q| {+                (b.0.min(q.0), b.1.min(q.1), b.2.max(q.0), b.3.max(q.1))+            }),+        }+    }+}++fn rot(p: Pt, deg: f64) -> Pt {+    let a = deg.to_radians();+    (p.0 * a.cos() - p.1 * a.sin(), p.0 * a.sin() + p.1 * a.cos())+}++fn rect_poly(c: Pt, w: f64, h: f64, deg: f64) -> Vec<Pt> {+    [(-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(|&q| { let r = rot(q, deg); (c.0 + r.0, c.1 + r.1) })+        .collect()+}++/// A stadium (oval / pill pad) as a 16-segment polygon.+fn stadium_poly(c: Pt, w: f64, h: f64, deg: f64) -> Vec<Pt> {+    let r = w.min(h) / 2.0;+    let (ax, ay) = if w >= h { (w / 2.0 - r, 0.0) } else { (0.0, h / 2.0 - r) };+    let mut pts = Vec::new();+    for (sx, sy, a0) in [(ax, ay, -90.0f64), (-ax, -ay, 90.0)] {+        let a0 = if w >= h { a0 } else { a0 + 90.0 };+        for k in 0..=8 {+            let a = (a0 + k as f64 * 22.5).to_radians();+            let q = rot((sx + r * a.cos(), sy + r * a.sin()), deg);+            pts.push((c.0 + q.0, c.1 + q.1));+        }+    }+    pts+}++fn seg_point_dist(p: Pt, a: Pt, b: Pt) -> f64 {+    let (dx, dy) = (b.0 - a.0, b.1 - a.1);+    let l2 = dx * dx + dy * dy;+    let t = if l2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };+    ((p.0 - a.0 - t * dx).powi(2) + (p.1 - a.1 - t * dy).powi(2)).sqrt()+}++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) }++fn segs_cross(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 > 0.0) != (d2 > 0.0)) && ((d3 > 0.0) != (d4 > 0.0)) && d1 != 0.0 && d2 != 0.0 && d3 != 0.0 && d4 != 0.0+}++/// A proper crossing with a tolerance: an endpoint within `eps` (cross product, mm²) of the other line counts as on+/// it. Exported outlines carry float noise (x 3.6000000000000005 at one end of an edge, 3.5999999999999996 at the+/// other), which a strict test reads as two touching courtyards crossing.+fn segs_cross_by(a: Pt, b: Pt, c: Pt, d: Pt, eps: f64) -> bool {+    let (d1, d2, d3, d4) = (cross(c, d, a), cross(c, d, b), cross(a, b, c), cross(a, b, d));+    d1.abs() > eps && d2.abs() > eps && d3.abs() > eps && d4.abs() > eps && ((d1 > 0.0) != (d2 > 0.0)) && ((d3 > 0.0) != (d4 > 0.0))+}++fn inside(p: Pt, poly: &[Pt]) -> bool {+    let mut c = false;+    for i in 0..poly.len() {+        let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);+        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; }+    }+    c+}++/// Distance from a point to a polygon's outline, inside or out.+fn boundary_dist(p: Pt, poly: &[Pt]) -> f64 {+    (0..poly.len()).map(|i| seg_point_dist(p, poly[i], poly[(i + 1) % poly.len()])).fold(f64::MAX, f64::min)+}++/// Distance from a point to a polygon's area: 0 inside.+fn point_poly_dist(p: Pt, poly: &[Pt]) -> f64 {+    if inside(p, poly) { return 0.0; }+    boundary_dist(p, poly)+}++/// Edge-to-edge distance between two copper shapes; 0 when they touch or overlap.+/// Distance between two polygons' boundaries (vertex to edge, both ways): for a pour inside the board outline this+/// is its pullback from the edge; for two disjoint pours, the gap between them.+pub fn poly_gap(a: &[Pt], b: &[Pt]) -> f64 {+    let one = |p: &[Pt], q: &[Pt]| p.iter().map(|&v| boundary_dist(v, q)).fold(f64::MAX, f64::min);+    one(a, b).min(one(b, a))+}++pub fn distance(a: &Shape, b: &Shape) -> f64 {+    match (a, b) {+        (Shape::Circle { c: ca, r: ra }, Shape::Circle { c: cb, r: rb }) => {+            (((ca.0 - cb.0).powi(2) + (ca.1 - cb.1).powi(2)).sqrt() - ra - rb).max(0.0)+        }+        (Shape::Circle { c, r }, Shape::Poly(p)) | (Shape::Poly(p), Shape::Circle { c, r }) => (point_poly_dist(*c, p) - r).max(0.0),+        (Shape::Poly(p), Shape::Poly(q)) => {+            let n = p.len();+            let m = q.len();+            for i in 0..n {+                for j in 0..m {+                    if segs_cross(p[i], p[(i + 1) % n], q[j], q[(j + 1) % m]) { return 0.0; }+                }+            }+            if inside(p[0], q) || inside(q[0], p) { return 0.0; }+            let mut d = f64::MAX;+            for &v in p { d = d.min(point_poly_dist(v, q)); }+            for &v in q { d = d.min(point_poly_dist(v, p)); }+            d+        }+    }+}++/// Whether two shapes share area (KiCad's courtyards_overlap): crossing edges, a vertex strictly inside the other, or+/// circles closer than their radii. Outlines that only touch along an edge or at a point do not overlap.+pub fn overlaps(a: &Shape, b: &Shape) -> bool {+    const EPS: f64 = 1e-6;+    let strictly_inside = |p: Pt, poly: &[Pt]| inside(p, poly) && boundary_dist(p, poly) > EPS;+    match (a, b) {+        (Shape::Circle { c: ca, r: ra }, Shape::Circle { c: cb, r: rb }) => ((ca.0 - cb.0).powi(2) + (ca.1 - cb.1).powi(2)).sqrt() < ra + rb - EPS,+        (Shape::Circle { c, r }, Shape::Poly(p)) | (Shape::Poly(p), Shape::Circle { c, r }) => inside(*c, p) || point_poly_dist(*c, p) < r - EPS,+        (Shape::Poly(p), Shape::Poly(q)) => {+            let (n, m) = (p.len(), q.len());+            (0..n).any(|i| (0..m).any(|j| segs_cross_by(p[i], p[(i + 1) % n], q[j], q[(j + 1) % m], 1e-9)))+                || p.iter().any(|v| strictly_inside(*v, q)) || q.iter().any(|v| strictly_inside(*v, p))+                // equal or nested outlines with no crossing and no strictly-inside vertex: test the centroids+                || strictly_inside(Shape::Poly(p.clone()).centre(), q) || strictly_inside(Shape::Poly(q.clone()).centre(), p)+        }+    }+}++// ─── scene ─────────────────────────────────────────────────────────────────++#[derive(Clone, Debug, PartialEq)]+pub enum CopperKind { MachinePin, Contact, Pad }++#[derive(Clone, Debug)]+pub struct Copper {+    pub owner: String,       // MP1, MC3, U1, C1+    pub pin: Option<String>, // pad number for footprint pads+    pub net: Option<String>,+    pub shape: Shape,+    pub kind: CopperKind,+}++#[derive(Clone, Debug)]+pub struct Part {+    pub refdes: String,+    pub label: Option<String>,+    pub body: Vec<Vec<Pt>>,  // fab outline polygons / polylines, board frame+    pub chip: bool,          // drawn as a chip (body, pin numbers) rather than a passive+    /// fill the body: a footprint's fab outline sits inside the pads; circuit.json only has the component's bounding+    /// box, which covers the pads and the traces under the chip, so it is drawn as an outline+    pub body_fill: bool,+}++#[derive(Clone, Debug)]+pub struct Trace { pub a: Pt, pub b: Pt, pub width: f64, pub bottom: bool }++#[derive(Clone, Debug, Default)]+pub struct Scene {+    pub title: String,+    pub outline: Vec<Pt>,+    pub nominal: Option<(f64, f64, Pt)>,   // nominal (wingless) width, height, centre: dotted+    pub size_note: String,+    pub copper: Vec<Copper>,+    pub parts: Vec<Part>,+    pub traces: Vec<Trace>,+    pub vias: Vec<(Pt, f64)>,+    pub free_slots: Vec<(Pt, f64)>,+    pub lines: Vec<(Pt, Pt)>,              // pin-to-contact assignment+    pub courtyards: Vec<(String, Shape)>,  // top-side courtyard per part (owner, closed outline or circle)+    pub courtyard_exceptions: Vec<CourtyardException>,+    pub show_courtyards: bool,+    /// copper pours (circuit.json `pcb_copper_pour`), drawn under the copper and measured+    pub pours: Vec<Pour>,+    /// silkscreen text (circuit.json `pcb_silkscreen_text`), drawn when `show_silk`+    pub silk: Vec<SilkText>,+    pub show_silk: bool,+    /// nets ringed yellow on contacts: the machine pins' nets plus any the design names as power+    pub power_nets: Vec<String>,+}++#[derive(Clone, Debug)]+pub struct Pour { pub net: Option<String>, pub layer: String, pub outline: Vec<Pt> }++#[derive(Clone, Debug)]+pub struct SilkText { pub text: String, pub at: Pt, pub ccw_rotation: f64, pub size: f64, pub bottom: bool }++/// Measured pour geometry: the narrowest gap between pours of different nets on one layer, and each pour's+/// pullback from the board edge.+#[derive(Clone, Debug, serde::Serialize)]+pub struct PourReport {+    pub layer: String,+    pub nets: Vec<String>,+    #[serde(skip_serializing_if = "Option::is_none")] pub gap_mm: Option<f64>,+    pub edge_pullback_mm: f64,+}++/// A pair of parts whose courtyards may overlap by decision (claude-pcb-f411 design.json `rules.courtyardExceptions`).+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]+pub struct CourtyardException { pub refs: [String; 2], #[serde(default)] pub reason: String }++#[derive(Clone, Debug, serde::Serialize)]+pub struct CourtyardOverlap { pub a: String, pub b: String, pub excepted: bool, #[serde(skip_serializing_if = "String::is_empty")] pub reason: String }++#[derive(Clone, Debug, serde::Serialize)]+pub struct Clearance { pub part: String, pub mm: f64, pub from: String, pub to: String }++impl Scene {+    /// Per layer: the pours' nets, the narrowest gap between pours of different nets, and the smallest pullback of+    /// any pour from the board outline.+    pub fn pour_report(&self) -> Vec<PourReport> {+        let mut layers: Vec<String> = self.pours.iter().map(|p| p.layer.clone()).collect();+        layers.sort(); layers.dedup();+        let r3 = |v: f64| (v * 1000.0).round() / 1000.0;+        layers.into_iter().map(|layer| {+            let ps: Vec<&Pour> = self.pours.iter().filter(|p| p.layer == layer).collect();+            let mut gap: Option<f64> = None;+            for (i, a) in ps.iter().enumerate() {+                for b in ps.iter().skip(i + 1) {+                    if a.net.is_some() && a.net == b.net { continue; }+                    let d = poly_gap(&a.outline, &b.outline);+                    gap = Some(gap.map_or(d, |g: f64| g.min(d)));+                }+            }+            let edge = ps.iter().map(|p| poly_gap(&p.outline, &self.outline)).fold(f64::MAX, f64::min);+            PourReport { layer, nets: ps.iter().map(|p| p.net.clone().unwrap_or_else(|| "?".into())).collect(), gap_mm: gap.map(r3), edge_pullback_mm: r3(edge) }+        }).collect()+    }++    fn is_power(&self, net: &Option<String>) -> bool { net.as_ref().map_or(false, |n| self.power_nets.iter().any(|p| p == n)) }++    /// Minimum copper clearance from each part to the nearest copper of another owner on another (or unknown) net.+    pub fn clearances(&self) -> Vec<Clearance> {+        let mut out = Vec::new();+        for part in &self.parts {+            let mut best: Option<Clearance> = None;+            for a in self.copper.iter().filter(|c| c.owner == part.refdes) {+                for b in self.copper.iter().filter(|c| c.owner != part.refdes) {+                    if a.net.is_some() && a.net == b.net { continue; }+                    let d = distance(&a.shape, &b.shape);+                    if best.as_ref().map_or(true, |x| d < x.mm) {+                        let name = |c: &Copper| match &c.pin { Some(p) => format!("{}.{}", c.owner, p), None => c.owner.clone() };+                        best = Some(Clearance { part: part.refdes.clone(), mm: (d * 1000.0).round() / 1000.0, from: name(a), to: name(b) });+                    }+                }+            }+            out.extend(best);+        }+        out+    }++    /// Pairs of parts whose courtyards share area (touching does not count), each marked if the design names it as an+    /// exception.+    pub fn courtyard_overlaps(&self) -> Vec<CourtyardOverlap> {+        let mut out: Vec<CourtyardOverlap> = Vec::new();+        for (i, (a, sa)) in self.courtyards.iter().enumerate() {+            for (b, sb) in self.courtyards.iter().skip(i + 1) {+                if a == b || !overlaps(sa, sb) { continue; }+                let (x, y) = if a < b { (a, b) } else { (b, a) };+                if out.iter().any(|o| &o.a == x && &o.b == y) { continue; }+                let ex = self.courtyard_exceptions.iter().find(|e| (&e.refs[0] == a && &e.refs[1] == b) || (&e.refs[0] == b && &e.refs[1] == a));+                out.push(CourtyardOverlap { a: x.clone(), b: y.clone(), excepted: ex.is_some(), reason: ex.map(|e| e.reason.clone()).unwrap_or_default() });+            }+        }+        out.sort_by(|p, q| (p.excepted, &p.a, &p.b).cmp(&(q.excepted, &q.a, &q.b)));+        out+    }++    /// Straight pin-to-contact lines that cross each other: a fan-out that will need vias or detours.+    pub fn crossings(&self) -> usize {+        let l = &self.lines;+        (0..l.len()).map(|i| (i + 1..l.len()).filter(|&j| segs_cross(l[i].0, l[i].1, l[j].0, l[j].1)).count()).sum()+    }++    /// Empty grid slots on the board's outer rows and columns (the contact ring), between machine pins and contacts.+    /// The pitch is one grid for the board: the smallest spacing on any of those lines.+    fn find_free_slots(&mut self) {+        let holes: Vec<(Pt, f64)> = self.copper.iter()+            .filter(|c| c.kind != CopperKind::Pad)+            .filter_map(|c| match c.shape { Shape::Circle { c, .. } => Some((c, 0.0)), _ => None })+            .collect();+        let r = self.copper.iter().find(|c| c.kind == CopperKind::Contact)+            .and_then(|c| if let Shape::Circle { r, .. } = c.shape { Some(r) } else { None });+        let Some(r) = r else { return };+        let key = |v: f64| (v * 1000.0).round() as i64;+        let mut rows: Vec<(usize, i64, Vec<f64>)> = Vec::new();+        for axis in 0..2 {+            let mut lines: BTreeMap<i64, Vec<f64>> = BTreeMap::new();+            for (p, _) in &holes {+                let (on, along) = if axis == 0 { (p.1, p.0) } else { (p.0, p.1) };+                lines.entry(key(on)).or_default().push(along);+            }+            // only the outermost row / column on each side carries contact slots; lines across the interior+            // (a wing contact column to the opposite one) are not slots+            let (lo, hi) = (*lines.keys().next().unwrap_or(&0), *lines.keys().last().unwrap_or(&0));+            for (on, mut v) in lines {+                if v.len() < 2 || (on != lo && on != hi) { continue; }+                v.sort_by(|a, b| a.partial_cmp(b).unwrap());+                rows.push((axis, on, v));+            }+        }+        // one grid for the board: the smallest spacing on any row or column (the contact pitch)+        let pitch = rows.iter().flat_map(|(_, _, v)| v.windows(2).map(|w| w[1] - w[0])).filter(|d| *d > 1e-6).fold(f64::MAX, f64::min);+        if pitch == f64::MAX { return; }+        let mut slots = Vec::new();+        for (axis, on, v) in rows {+            {+                for w in v.windows(2) {+                    let n = ((w[1] - w[0]) / pitch).round() as i64;+                    for k in 1..n {+                        let a = w[0] + k as f64 * pitch;+                        let p = if axis == 0 { (a, on as f64 / 1000.0) } else { (on as f64 / 1000.0, a) };+                        if !slots.iter().any(|(q, _): &(Pt, f64)| key(q.0) == key(p.0) && key(q.1) == key(p.1)) { slots.push((p, r)); }+                    }+                }+            }+        }+        self.free_slots = slots;+    }++    /// One line from each contact to the same-net pad of `fanout` (default: the part with the most pads).+    fn assignment_lines(&mut self, fanout: Option<&str>) {+        let mut counts: HashMap<&str, usize> = HashMap::new();+        for c in self.copper.iter().filter(|c| c.kind == CopperKind::Pad) { *counts.entry(&c.owner).or_default() += 1; }+        let chip = fanout.map(str::to_string)+            .or_else(|| counts.iter().max_by_key(|(k, n)| (**n, std::cmp::Reverse(**k))).map(|(k, _)| k.to_string()));+        let Some(chip) = chip else { return };+        let mut lines = Vec::new();+        for c in self.copper.iter().filter(|c| c.kind == CopperKind::Contact) {+            let Some(net) = &c.net else { continue };+            let to = c.shape.centre();+            let pad = self.copper.iter()+                .filter(|p| p.owner == chip && p.net.as_ref() == Some(net))+                .min_by(|a, b| {+                    let d = |s: &Shape| { let q = s.centre(); (q.0 - to.0).hypot(q.1 - to.1) };+                    d(&a.shape).partial_cmp(&d(&b.shape)).unwrap()+                });+            if let Some(p) = pad { lines.push((p.shape.centre(), to)); }+        }+        self.lines = lines;+    }++    fn bounds(&self) -> (f64, f64, f64, f64) {+        let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+        let mut add = |x: f64, y: f64| { b = (b.0.min(x), b.1.min(y), b.2.max(x), b.3.max(y)); };+        for p in &self.outline { add(p.0, p.1); }+        for c in &self.copper { let s = c.shape.bounds(); add(s.0, s.1); add(s.2, s.3); }+        b+    }+}++// ─── KiCad footprints ──────────────────────────────────────────────────────++#[derive(Clone, Debug)]+pub enum Sx { Atom(String), List(Vec<Sx>) }++impl Sx {+    fn head(&self) -> Option<&str> { match self { Sx::List(v) => match v.first() { Some(Sx::Atom(a)) => Some(a), _ => None }, _ => None } }+    fn items(&self) -> &[Sx] { match self { Sx::List(v) => v, _ => &[] } }+    fn child(&self, name: &str) -> Option<&Sx> { self.items().iter().find(|c| c.head() == Some(name)) }+    fn children<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Sx> + 'a { self.items().iter().filter(move |c| c.head() == Some(name)) }+    fn atom(&self, i: usize) -> Option<&str> { match self.items().get(i) { Some(Sx::Atom(a)) => Some(a), _ => None } }+    fn num(&self, i: usize) -> Option<f64> { self.atom(i).and_then(|a| a.parse().ok()) }+    fn atoms(&self) -> Vec<&str> { self.items().iter().skip(1).filter_map(|c| if let Sx::Atom(a) = c { Some(a.as_str()) } else { None }).collect() }+}++pub fn parse_sexpr(text: &str) -> Result<Sx> {+    let mut stack: Vec<Vec<Sx>> = vec![Vec::new()];+    let mut chars = text.chars().peekable();+    while let Some(ch) = chars.next() {+        match ch {+            '(' => stack.push(Vec::new()),+            ')' => {+                let done = stack.pop().ok_or_else(|| anyhow!("unbalanced )"))?;+                stack.last_mut().ok_or_else(|| anyhow!("unbalanced )"))?.push(Sx::List(done));+            }+            '"' => {+                let mut s = String::new();+                while let Some(c) = chars.next() {+                    match c { '\\' => { if let Some(n) = chars.next() { s.push(n); } } '"' => break, _ => s.push(c) }+                }+                stack.last_mut().unwrap().push(Sx::Atom(s));+            }+            c if c.is_whitespace() => {}+            c => {+                let mut s = String::from(c);+                while let Some(&n) = chars.peek() { if n == '(' || n == ')' || n.is_whitespace() { break; } s.push(n); chars.next(); }+                stack.last_mut().unwrap().push(Sx::Atom(s));+            }+        }+    }+    if stack.len() != 1 { bail!("unbalanced ("); }+    stack.pop().unwrap().into_iter().next().ok_or_else(|| anyhow!("empty file"))+}++/// A footprint's copper pads (pin number, shape in the footprint frame, y up) and its fab outline.+pub struct Footprint { pub pads: Vec<(String, Shape)>, pub fab: Vec<Vec<Pt>>, pub courtyard: Vec<Shape> }++/// Join F.CrtYd line segments into closed loops (KiCad footprints draw courtyards as separate fp_lines).+fn chain_loops(mut segs: Vec<(Pt, Pt)>) -> Vec<Vec<Pt>> {+    let near = |a: Pt, b: Pt| (a.0 - b.0).abs() < 1e-4 && (a.1 - b.1).abs() < 1e-4;+    let mut loops = Vec::new();+    while let Some((a, b)) = segs.pop() {+        let mut pts = vec![a, b];+        while let Some(k) = segs.iter().position(|(p, q)| near(*p, *pts.last().unwrap()) || near(*q, *pts.last().unwrap())) {+            let (p, q) = segs.swap_remove(k);+            pts.push(if near(p, *pts.last().unwrap()) { q } else { p });+            if near(*pts.last().unwrap(), pts[0]) { break; }+        }+        if pts.len() > 3 && near(*pts.last().unwrap(), pts[0]) { pts.pop(); loops.push(pts); }+    }+    loops+}++pub fn read_footprint(path: &Path) -> Result<Footprint> {+    let text = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;+    let root = parse_sexpr(&text).with_context(|| format!("parse {}", path.display()))?;+    let xy = |s: &Sx| -> Option<Pt> { Some((s.num(1)?, -s.num(2)?)) };   // KiCad y down -> y up+    let mut pads = Vec::new();+    for pad in root.children("pad") {+        let num = pad.atom(1).unwrap_or("").to_string();+        let shape = pad.atom(3).unwrap_or("rect");+        let layers = pad.child("layers").map(|l| l.atoms().join(" ")).unwrap_or_default();+        if !layers.contains(".Cu") || num.is_empty() { continue; }+        let at = pad.child("at").ok_or_else(|| anyhow!("pad {num} has no (at)"))?;+        let c = xy(at).ok_or_else(|| anyhow!("pad {num}: bad (at)"))?;+        // KiCad pad angles are clockwise in y-down, which is counter-clockwise in y-up+        let deg = at.num(3).unwrap_or(0.0);+        let size = pad.child("size").ok_or_else(|| anyhow!("pad {num} has no (size)"))?;+        let (w, h) = (size.num(1).unwrap_or(0.0), size.num(2).unwrap_or(0.0));+        let s = match shape {+            "circle" => Shape::Circle { c, r: w / 2.0 },+            "oval" => Shape::Poly(stadium_poly(c, w, h, deg)),+            _ => Shape::Poly(rect_poly(c, w, h, deg)),+        };+        pads.push((num, s));+    }+    let mut fab = Vec::new();+    let (mut courtyard, mut crt_segs) = (Vec::new(), Vec::new());+    for item in root.items() {+        let layer = item.child("layer").and_then(|l| l.atom(1));+        if layer == Some("F.CrtYd") {+            let (s, e) = (item.child("start").and_then(|s| xy(s)), item.child("end").and_then(|s| xy(s)));+            match item.head() {+                Some("fp_line") => if let (Some(a), Some(b)) = (s, e) { crt_segs.push((a, b)); },+                Some("fp_rect") => if let (Some(a), Some(b)) = (s, e) { courtyard.push(Shape::Poly(vec![a, (b.0, a.1), b, (a.0, b.1)])); },+                Some("fp_poly") => if let Some(pts) = item.child("pts") { courtyard.push(Shape::Poly(pts.children("xy").filter_map(|p| xy(p)).collect())); },+                Some("fp_circle") => if let (Some(c), Some(e)) = (item.child("center").and_then(|s| xy(s)), e) {+                    courtyard.push(Shape::Circle { c, r: ((e.0 - c.0).powi(2) + (e.1 - c.1).powi(2)).sqrt() });+                },+                _ => {}+            }+            continue;+        }+        let on_fab = layer == Some("F.Fab");+        if !on_fab { continue; }+        match item.head() {+            Some("fp_poly") => if let Some(pts) = item.child("pts") { fab.push(pts.children("xy").filter_map(|p| xy(p)).collect()); },+            Some("fp_line") => if let (Some(a), Some(b)) = (item.child("start").and_then(|s| xy(s)), item.child("end").and_then(|s| xy(s))) { fab.push(vec![a, b]); },+            Some("fp_rect") => if let (Some(a), Some(b)) = (item.child("start").and_then(|s| xy(s)), item.child("end").and_then(|s| xy(s))) {+                fab.push(vec![a, (b.0, a.1), b, (a.0, b.1), a]);+            },+            _ => {}+        }+    }+    courtyard.extend(chain_loops(crt_segs).into_iter().map(Shape::Poly));+    Ok(Footprint { pads, fab, courtyard })+}++fn place(p: Pt, at: Pt, deg: f64) -> Pt { let q = rot(p, deg); (at.0 + q.0, at.1 + q.1) }++fn place_shape(s: &Shape, at: Pt, deg: f64) -> Shape {+    match s {+        Shape::Circle { c, r } => Shape::Circle { c: place(*c, at, deg), r: *r },+        Shape::Poly(p) => Shape::Poly(p.iter().map(|q| place(*q, at, deg)).collect()),+    }+}++// ─── input 1: headless plan + footprints ───────────────────────────────────++/// The planning input: `plan` is `planMolecule`'s JSON (inline, or a path relative to the layout file).+#[derive(serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Layout {+    #[serde(default)] pub title: Option<String>,+    pub plan: Value,+    /// relabel contacts (e.g. a turned chip re-orders which net each slot carries): designator -> net+    #[serde(default)] pub contact_nets: BTreeMap<String, String>,+    /// machine pin nets (e.g. MP1: GND); unlabelled pins show their designator+    #[serde(default)] pub machine_pin_nets: BTreeMap<String, String>,+    #[serde(default)] pub parts: Vec<LayoutPart>,+    /// the part the assignment lines fan out from (default: the part with the most pads)+    #[serde(default)] pub fanout: Option<String>,+    /// pairs whose courtyards may overlap by decision; drawn in amber, not red+    #[serde(default)] pub courtyard_exceptions: Vec<CourtyardException>,+    /// nets ringed yellow on contacts, beyond the machine pins' nets (which are power by the molecule rule)+    #[serde(default)] pub power_nets: Vec<String>,+}++#[derive(serde::Deserialize)]+pub struct LayoutPart {+    #[serde(rename = "ref")] pub refdes: String,+    pub footprint: String,+    #[serde(default)] pub x: f64,+    #[serde(default)] pub y: f64,+    #[serde(default)] pub rotation: f64,+    /// pad number -> net+    #[serde(default)] pub pins: BTreeMap<String, String>,+    #[serde(default)] pub label: Option<String>,+}++impl Scene {+    pub fn from_layout(path: &Path) -> Result<Scene> {+        let base = path.parent().unwrap_or(Path::new(".")).to_path_buf();+        let layout: Layout = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?)+            .with_context(|| format!("{}: not a plan-view layout", path.display()))?;+        Scene::from_layout_value(layout, &base, path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default())+    }++    pub fn from_layout_value(layout: Layout, base: &Path, fallback_title: String) -> Result<Scene> {+        let plan: Value = match &layout.plan {+            Value::String(p) => serde_json::from_str(&std::fs::read_to_string(base.join(p)).with_context(|| format!("read plan {p}"))?)?,+            v => v.clone(),+        };+        let board = plan.get("board").ok_or_else(|| anyhow!("plan has no `board`: expected planMolecule JSON (bun scripts/plan.ts)"))?;+        let f = |v: &Value, k: &str| v.get(k).and_then(Value::as_f64).ok_or_else(|| anyhow!("plan: missing number `{k}`"));+        let mut s = Scene { title: layout.title.clone().unwrap_or(fallback_title), show_courtyards: true, courtyard_exceptions: layout.courtyard_exceptions.clone(), ..Default::default() };+        s.outline = board.get("outline").and_then(Value::as_array).ok_or_else(|| anyhow!("plan: board.outline missing"))?+            .iter().map(|p| Ok((f(p, "x")?, f(p, "y")?))).collect::<Result<_>>()?;+        let centre = board.get("center").map(|c| (f(c, "x").unwrap_or(0.0), f(c, "y").unwrap_or(0.0))).unwrap_or((0.0, 0.0));+        let (w, h) = (f(board, "width")?, f(board, "height")?);+        let (nw, nh) = (f(board, "nominalWidth")?, f(board, "nominalHeight")?);+        let wings = board.get("wings");+        let wing = |k: &str| wings.and_then(|w| w.get(k)).and_then(Value::as_f64).unwrap_or(0.0);+        // the nominal (wingless) board sits inside the wings: centre shifted back by half the wing difference+        let ncentre = (centre.0 - (wing("right") - wing("left")) / 2.0, centre.1 - (wing("top") - wing("bottom")) / 2.0);+        if (nw - w).abs() > 1e-6 || (nh - h).abs() > 1e-6 { s.nominal = Some((nw, nh, ncentre)); }+        let wing_note: Vec<String> = ["left", "right", "top", "bottom"].iter().filter(|k| wing(k) > 1e-6).map(|k| format!("{} {}", k, fmt_mm(wing(k)))).collect();+        s.size_note = format!("{} x {} mm{}", fmt_mm(w), fmt_mm(h), if wing_note.is_empty() { String::new() } else { format!(" (wings: {})", wing_note.join(", ")) });+        for p in plan.get("machinePins").and_then(Value::as_array).into_iter().flatten() {+            let name = p.get("name").and_then(Value::as_str).unwrap_or("MP").to_string();+            let c = (f(p, "x")?, f(p, "y")?);+            // the library's courtyard: a circle of the part's bounding box less 0.01 (r 0.99 on a 2 mm pin)+            if let Some(bb) = p.get("boundingBox").and_then(Value::as_f64) { s.courtyards.push((name.clone(), Shape::Circle { c, r: bb / 2.0 - 0.01 })); }+            s.copper.push(Copper {+                net: layout.machine_pin_nets.get(&name).cloned(), owner: name, pin: None, kind: CopperKind::MachinePin,+                shape: Shape::Circle { c, r: f(p, "holeOD")? / 2.0 },+            });+        }+        for c in plan.get("contacts").and_then(Value::as_array).into_iter().flatten() {+            let d = c.get("designator").and_then(Value::as_str).unwrap_or("MC").to_string();+            let net = layout.contact_nets.get(&d).cloned().or_else(|| c.get("net").and_then(Value::as_str).map(str::to_string));+            let at = (f(c, "x")?, f(c, "y")?);+            if let Some(bb) = c.get("boundingBox").and_then(Value::as_f64) { s.courtyards.push((d.clone(), Shape::Circle { c: at, r: bb / 2.0 - 0.01 })); }+            s.copper.push(Copper { owner: d, pin: None, net, kind: CopperKind::Contact, shape: Shape::Circle { c: at, r: f(c, "holeOD")? / 2.0 } });+        }+        for part in &layout.parts {+            let fp = read_footprint(&base.join(&part.footprint))?;+            let at = (part.x, part.y);+            for cy in &fp.courtyard { s.courtyards.push((part.refdes.clone(), place_shape(cy, at, part.rotation))); }+            for (num, shape) in &fp.pads {+                s.copper.push(Copper { owner: part.refdes.clone(), pin: Some(num.clone()), net: part.pins.get(num).cloned(), kind: CopperKind::Pad, shape: place_shape(shape, at, part.rotation) });+            }+            s.parts.push(Part {+                refdes: part.refdes.clone(), label: part.label.clone(),+                body: fp.fab.iter().map(|p| p.iter().map(|q| place(*q, at, part.rotation)).collect()).collect(),+                chip: fp.pads.len() > 3,+                body_fill: true,+            });+        }+        let mut power: Vec<String> = layout.machine_pin_nets.values().cloned().chain(layout.power_nets.iter().cloned()).collect();+        power.sort(); power.dedup();+        s.power_nets = power;+        s.find_free_slots();+        s.assignment_lines(layout.fanout.as_deref());+        Ok(s)+    }+}++fn fmt_mm(v: f64) -> String { let s = format!("{:.3}", v); s.trim_end_matches('0').trim_end_matches('.').to_string() }++// ─── input 2: a built board's circuit.json ─────────────────────────────────++fn of<'a>(cj: &'a [Value], t: &'a str) -> impl Iterator<Item = &'a Value> + 'a {+    cj.iter().filter(move |e| e.get("type").and_then(Value::as_str) == Some(t))+}++impl Scene {+    pub fn from_circuit(cj: &[Value], title: &str) -> Result<Scene> {+        let s_ = |e: &Value, k: &str| e.get(k).and_then(Value::as_str).map(str::to_string);+        let n_ = |e: &Value, k: &str| e.get(k).and_then(Value::as_f64);+        let pt = |e: &Value| -> Option<Pt> { Some((n_(e, "x")?, n_(e, "y")?)) };++        // nets: union the source ports and nets each source_trace connects; name a group by its source_net+        let mut parent: HashMap<String, String> = HashMap::new();+        fn find(p: &mut HashMap<String, String>, x: &str) -> String {+            let up = p.get(x).cloned().unwrap_or_else(|| x.to_string());+            if up == x { return up; }+            let r = find(p, &up); p.insert(x.to_string(), r.clone()); r+        }+        for t in of(cj, "source_trace") {+            let ids: Vec<String> = ["connected_source_port_ids", "connected_source_net_ids"].iter()+                .flat_map(|k| t.get(*k).and_then(Value::as_array).cloned().unwrap_or_default())+                .filter_map(|v| v.as_str().map(str::to_string)).collect();+            for w in ids.windows(2) { let (a, b) = (find(&mut parent, &w[0]), find(&mut parent, &w[1])); if a != b { parent.insert(a, b); } }+        }+        let mut group_name: HashMap<String, String> = HashMap::new();+        for n in of(cj, "source_net") {+            if let (Some(id), Some(name)) = (s_(n, "source_net_id"), s_(n, "name")) {+                let g = find(&mut parent, &id);+                group_name.entry(g).or_insert(name);+            }+        }+        let mut port_net: HashMap<String, String> = HashMap::new();       // pcb_port_id -> net name+        let src_of_pcb: HashMap<String, String> = of(cj, "pcb_port").filter_map(|p| Some((s_(p, "pcb_port_id")?, s_(p, "source_port_id")?))).collect();+        for (pcb, src) in &src_of_pcb {+            let g = find(&mut parent, src);+            if let Some(n) = group_name.get(&g) { port_net.insert(pcb.clone(), n.clone()); }+        }+        let src_name: HashMap<String, String> = of(cj, "source_component").filter_map(|c| Some((s_(c, "source_component_id")?, s_(c, "name")?))).collect();+        let src_mpn: HashMap<String, String> = of(cj, "source_component").filter_map(|c| Some((s_(c, "source_component_id")?, s_(c, "manufacturer_part_number")?))).collect();+        let comp_name: HashMap<String, String> = of(cj, "pcb_component")+            .filter_map(|c| Some((s_(c, "pcb_component_id")?, src_name.get(&s_(c, "source_component_id")?)?.clone()))).collect();+        let pin_of = |e: &Value| -> Option<String> {+            let hints: Vec<String> = e.get("port_hints").and_then(Value::as_array).cloned().unwrap_or_default().iter().filter_map(|v| v.as_str().map(str::to_string)).collect();+            hints.iter().find(|h| h.chars().all(|c| c.is_ascii_digit())).cloned()+                .or_else(|| hints.iter().find_map(|h| h.strip_prefix("pin").map(str::to_string)))+                .or_else(|| hints.first().cloned())+        };++        let mut s = Scene { title: title.to_string(), show_courtyards: true, ..Default::default() };+        let board = of(cj, "pcb_board").next().ok_or_else(|| anyhow!("circuit.json has no pcb_board"))?;+        let outline: Vec<Pt> = board.get("outline").and_then(Value::as_array).map(|o| o.iter().filter_map(pt).collect()).unwrap_or_default();+        let (w, h) = (n_(board, "width").unwrap_or(0.0), n_(board, "height").unwrap_or(0.0));+        let c = board.get("center").and_then(pt).unwrap_or((0.0, 0.0));+        s.outline = if outline.len() >= 3 { outline } else { rect_poly(c, w, h, 0.0) };+        s.size_note = format!("{} x {} mm", fmt_mm(w), fmt_mm(h));++        let kind_of = |name: &str| if name.starts_with("MP") && name[2..].chars().all(|c| c.is_ascii_digit()) { CopperKind::MachinePin }+            else if name.starts_with("MC") && name[2..].chars().all(|c| c.is_ascii_digit()) { CopperKind::Contact } else { CopperKind::Pad };+        let mut pad_counts: HashMap<String, usize> = HashMap::new();+        let mut push = |s: &mut Scene, e: &Value, shape: Shape| {+            let owner = s_(e, "pcb_component_id").and_then(|id| comp_name.get(&id).cloned()).unwrap_or_else(|| "?".into());+            let kind = kind_of(&owner);+            let net = s_(e, "pcb_port_id").and_then(|p| port_net.get(&p).cloned());+            let pin = if kind == CopperKind::Pad { pin_of(e) } else { None };+            *pad_counts.entry(owner.clone()).or_default() += 1;+            s.copper.push(Copper { owner, pin, net, shape, kind });+        };+        for e in of(cj, "pcb_smtpad") {+            if e.get("layer").and_then(Value::as_str) == Some("bottom") { continue; }+            let Some(c) = pt(e) else { continue };+            let deg = n_(e, "ccw_rotation").or_else(|| n_(e, "rotation")).unwrap_or(0.0);+            let shape = match s_(e, "shape").as_deref() {+                Some("circle") => Shape::Circle { c, r: n_(e, "radius").unwrap_or(0.0) },+                Some("polygon") => Shape::Poly(e.get("points").and_then(Value::as_array).map(|p| p.iter().filter_map(pt).collect()).unwrap_or_default()),+                Some("pill") => Shape::Poly(stadium_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), deg)),+                _ => Shape::Poly(rect_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), deg)),+            };+            push(&mut s, e, shape);+        }+        for e in of(cj, "pcb_plated_hole") {+            let Some(c) = pt(e) else { continue };+            let shape = match s_(e, "shape").as_deref() {+                Some("circle") => Shape::Circle { c, r: n_(e, "outer_diameter").unwrap_or(0.0) / 2.0 },+                Some("pill") | Some("oval") => Shape::Poly(stadium_poly(c, n_(e, "outer_width").unwrap_or(0.0), n_(e, "outer_height").unwrap_or(0.0), n_(e, "ccw_rotation").unwrap_or(0.0))),+                _ => Shape::Poly(rect_poly(c, n_(e, "rect_pad_width").or_else(|| n_(e, "outer_width")).unwrap_or(0.0), n_(e, "rect_pad_height").or_else(|| n_(e, "outer_height")).unwrap_or(0.0), 0.0)),+            };+            push(&mut s, e, shape);+        }+        for comp in of(cj, "pcb_component") {+            let Some(name) = s_(comp, "pcb_component_id").and_then(|id| comp_name.get(&id).cloned()) else { continue };+            if kind_of(&name) != CopperKind::Pad || !pad_counts.contains_key(&name) { continue; }+            let chip = pad_counts[&name] > 3;+            let body = if chip {+                let (cw, ch) = (n_(comp, "width").unwrap_or(0.0), n_(comp, "height").unwrap_or(0.0));+                comp.get("center").and_then(pt).map(|c| vec![rect_poly(c, cw, ch, n_(comp, "rotation").unwrap_or(0.0))]).unwrap_or_default()+            } else { vec![] };+            let label = s_(comp, "source_component_id").and_then(|id| src_mpn.get(&id).cloned());+            s.parts.push(Part { refdes: name, label, body, chip, body_fill: false });+        }+        for t in of(cj, "pcb_trace") {+            let pts: Vec<&Value> = t.get("route").and_then(Value::as_array).map(|r| r.iter().collect()).unwrap_or_default();+            for w in pts.windows(2) {+                let (a, b) = (w[0], w[1]);+                if s_(a, "route_type").as_deref() != Some("wire") || s_(b, "route_type").as_deref() != Some("wire") { continue; }+                if s_(a, "layer") != s_(b, "layer") { continue; }+                if let (Some(pa), Some(pb)) = (pt(a), pt(b)) {+                    s.traces.push(Trace { a: pa, b: pb, width: n_(a, "width").unwrap_or(0.15), bottom: s_(a, "layer").as_deref() == Some("bottom") });+                }+            }+        }+        // courtyards (top side; a bottom-side copy would draw the same outline twice)+        for e in of(cj, "pcb_courtyard_outline").chain(of(cj, "pcb_courtyard_circle")).chain(of(cj, "pcb_courtyard_rect")) {+            if e.get("layer").and_then(Value::as_str) == Some("bottom") { continue; }+            let Some(owner) = s_(e, "pcb_component_id").and_then(|id| comp_name.get(&id).cloned()) else { continue };+            let shape = match s_(e, "type").as_deref() {+                Some("pcb_courtyard_circle") => match (e.get("center").and_then(pt), n_(e, "radius")) { (Some(c), Some(r)) => Shape::Circle { c, r }, _ => continue },+                Some("pcb_courtyard_rect") => match e.get("center").and_then(pt) { Some(c) => Shape::Poly(rect_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), n_(e, "ccw_rotation").unwrap_or(0.0))), None => continue },+                _ => {+                    let pts: Vec<Pt> = e.get("outline").and_then(Value::as_array).map(|o| o.iter().filter_map(pt).collect()).unwrap_or_default();+                    if pts.len() < 3 { continue; }+                    Shape::Poly(pts)+                }+            };+            s.courtyards.push((owner, shape));+        }+        for v in of(cj, "pcb_via") { if let Some(c) = pt(v) { s.vias.push((c, n_(v, "outer_diameter").unwrap_or(0.6) / 2.0)); } }+        let net_name: HashMap<String, String> = of(cj, "source_net").filter_map(|n| Some((s_(n, "source_net_id")?, s_(n, "name")?))).collect();+        for e in of(cj, "pcb_copper_pour") {+            let outline: Vec<Pt> = match s_(e, "shape").as_deref() {+                Some("brep") => e.pointer("/brep_shape/outer_ring/vertices").and_then(Value::as_array).map(|v| v.iter().filter_map(pt).collect()).unwrap_or_default(),+                Some("polygon") => e.get("points").and_then(Value::as_array).map(|v| v.iter().filter_map(pt).collect()).unwrap_or_default(),+                Some("rect") => match e.get("center").and_then(pt) { Some(c) => rect_poly(c, n_(e, "width").unwrap_or(0.0), n_(e, "height").unwrap_or(0.0), n_(e, "rotation").unwrap_or(0.0)), None => vec![] },+                _ => vec![],+            };+            if outline.len() < 3 { continue; }+            let net = s_(e, "source_net_id").and_then(|id| net_name.get(&id).cloned());+            s.pours.push(Pour { net, layer: s_(e, "layer").unwrap_or_else(|| "top".into()), outline });+        }+        for e in of(cj, "pcb_silkscreen_text") {+            let Some(at) = e.get("anchor_position").and_then(pt) else { continue };+            s.silk.push(SilkText {+                text: s_(e, "text").unwrap_or_default(), at, ccw_rotation: n_(e, "ccw_rotation").unwrap_or(0.0),+                size: n_(e, "font_size").unwrap_or(0.4), bottom: s_(e, "layer").as_deref() == Some("bottom"),+            });+        }+        // machine pins carry power only (molecule rule), so their nets are the power nets+        let mut power: Vec<String> = s.copper.iter().filter(|c| c.kind == CopperKind::MachinePin).filter_map(|c| c.net.clone()).collect();+        power.sort(); power.dedup();+        s.power_nets = power;+        s.find_free_slots();+        Ok(s)+    }+}++// ─── SVG ───────────────────────────────────────────────────────────────────++fn esc(t: &str) -> String { t.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;") }++fn path_d(p: &[Pt], close: bool) -> String {+    let mut d = String::new();+    for (i, q) in p.iter().enumerate() { let _ = write!(d, "{}{:.4},{:.4}", if i == 0 { "M" } else { " L" }, q.0, -q.1); }+    if close { d.push_str(" Z"); }+    d+}++fn shape_svg(s: &Shape, attrs: &str) -> String {+    match s {+        Shape::Circle { c, r } => format!(r#"<circle cx="{:.4}" cy="{:.4}" r="{:.4}" {attrs}/>"#, c.0, -c.1, r),+        Shape::Poly(p) => format!(r#"<path d="{}" {attrs}/>"#, path_d(p, true)),+    }+}++fn text_fit(label: &str, width: f64, max: f64) -> f64 { (width / (label.chars().count().max(1) as f64 * 0.62)).min(max) }++/// One scene as an SVG group at the origin, plus its frame (min x, min y in SVG space, width, height).+fn scene_group(s: &Scene) -> (String, (f64, f64, f64, f64)) {+    let (x0, y0, x1, y1) = s.bounds();+    let pad = 1.2;+    let clear = s.clearances();+    let crossings = s.crossings();+    let mut notes = vec![s.size_note.clone()];+    // the tightest clearances by name; on a busy board the rest as one line (the JSON report keeps every part)+    let mut by_mm: Vec<&Clearance> = clear.iter().collect();+    by_mm.sort_by(|a, b| a.mm.partial_cmp(&b.mm).unwrap().then(a.part.cmp(&b.part)));+    let shown = if by_mm.len() > 6 { 4 } else { by_mm.len() };+    for c in &by_mm[..shown] { notes.push(format!("{} to nearest copper: {:.2} mm ({} to {})", c.part, c.mm, c.from, c.to)); }+    if by_mm.len() > shown { notes.push(format!("other {} parts: {:.2} mm or more to the nearest copper", by_mm.len() - shown, by_mm[shown].mm)); }+    if !s.lines.is_empty() { notes.push(format!("straight pin-to-contact lines crossing: {crossings}")); }+    let overlaps = if s.show_courtyards { s.courtyard_overlaps() } else { vec![] };+    for r in s.pour_report() {+        notes.push(format!("{} pours {}: {}edge pullback {:.2} mm", r.layer, r.nets.join(", "),+            r.gap_mm.map(|g| format!("gap {g:.2} mm, ")).unwrap_or_default(), r.edge_pullback_mm));+    }+    if s.show_courtyards && !s.courtyards.is_empty() {+        let bad: Vec<String> = overlaps.iter().filter(|o| !o.excepted).map(|o| format!("{}-{}", o.a, o.b)).collect();+        let ok: Vec<String> = overlaps.iter().filter(|o| o.excepted).map(|o| format!("{}-{}", o.a, o.b)).collect();+        notes.push(format!("courtyard overlaps: {}{}", if bad.is_empty() { "none".to_string() } else { bad.join(", ") },+            if ok.is_empty() { String::new() } else { format!("; named exceptions: {}", ok.join(", ")) }));+    }+    // text scales with the board, so a 70 mm board's captions read like a 10 mm molecule's+    let scale = ((x1 - x0) / 12.0).max(1.0);+    let title_size = text_fit(&s.title, (x1 - x0 + 2.0 * pad) * 0.98, 0.9 * scale);+    // one caption size, the largest at which every line fits the board's width (side-by-side scenes never collide)+    let note_size = notes.iter().map(|n| text_fit(n, x1 - x0 + 2.0 * pad, 0.55 * scale)).fold(0.55 * scale, f64::min);+    let line = note_size * 1.6;+    let top = -y1 - pad - title_size * 1.8;          // title above the board+    let bottom = -y0 + pad + line * notes.len() as f64 + 0.4;+    let frame = (x0 - pad, top - 0.6, (x1 - x0) + 2.0 * pad, bottom - (top - 0.6));+    let mut g = String::new();+    let cx = (x0 + x1) / 2.0;+    let _ = write!(g, r##"<text x="{cx:.3}" y="{:.3}" font-size="{title_size:.3}" text-anchor="middle" fill="#111">{}</text>"##, top + title_size * 0.7, esc(&s.title));+    let _ = write!(g, r##"<path d="{}" fill="#2f4a30" stroke="#999" stroke-width="0.2"/>"##, path_d(&s.outline, true));+    if let Some((w, h, c)) = s.nominal {+        let _ = write!(g, r##"<path d="{}" fill="none" stroke="#9c9" stroke-width="0.06" stroke-dasharray="0.15 0.25"/>"##, path_d(&rect_poly(c, w, h, 0.0), true));+    }+    // pours under everything else: bottom ones as seen through the board+    for pour in &s.pours {+        let style = if pour.layer == "bottom" { r##"fill="#4a7fd0" fill-opacity="0.32" stroke="#8fb4ee" stroke-width="0.05" stroke-dasharray="0.25 0.15""## }+            else { r##"fill="#e05a3a" fill-opacity="0.28" stroke="#f09a80" stroke-width="0.05""## };+        let _ = write!(g, r#"<g class="pour"><title>{} pour, {}</title><path d="{}" {style}/></g>"#, esc(pour.net.as_deref().unwrap_or("?")), esc(&pour.layer), path_d(&pour.outline, true));+    }+    if s.show_courtyards {+        let flagged = |owner: &str, excepted: bool| overlaps.iter().any(|o| o.excepted == excepted && (o.a == owner || o.b == owner));+        for (owner, cy) in &s.courtyards {+            // KiCad's courtyard magenta; red where an unexcused overlap involves the part, amber where only exceptions do+            let style = if flagged(owner, false) { r##"fill="#ff3b3b" fill-opacity="0.12" stroke="#ff3b3b" stroke-width="0.07""## }+                else if flagged(owner, true) { r##"fill="#f5a623" fill-opacity="0.12" stroke="#f5a623" stroke-width="0.07" stroke-dasharray="0.2 0.12""## }+                else { r##"fill="none" stroke="#ff26e2" stroke-width="0.04" opacity="0.8""## };+            let _ = write!(g, r#"<g class="courtyard"><title>{} courtyard</title>{}</g>"#, esc(owner), shape_svg(cy, style));+        }+    }+    for t in &s.traces {+        let col = if t.bottom { "#4a7fd0" } else { "#e05a3a" };+        let _ = write!(g, r#"<line x1="{:.4}" y1="{:.4}" x2="{:.4}" y2="{:.4}" stroke="{col}" stroke-width="{:.4}" stroke-linecap="round" opacity="0.9"/>"#, t.a.0, -t.a.1, t.b.0, -t.b.1, t.width);+    }+    for (a, b) in &s.lines {+        let _ = write!(g, r##"<line x1="{:.4}" y1="{:.4}" x2="{:.4}" y2="{:.4}" stroke="#f99" stroke-width="0.07" opacity="0.85"/>"##, a.0, -a.1, b.0, -b.1);+    }+    // footprint pads, then chip bodies over their centres, then pin numbers+    for c in s.copper.iter().filter(|c| c.kind == CopperKind::Pad) {+        let chip = s.parts.iter().any(|p| p.refdes == c.owner && p.chip);+        g.push_str(&shape_svg(&c.shape, if chip { r##"fill="#e44""## } else { r##"fill="#c9a227""## }));+    }+    for part in &s.parts {+        for poly in &part.body {+            let closed = poly.len() > 2;+            let style = if part.chip && closed && part.body_fill { r##"fill="#222" fill-opacity="0.88" stroke="#aaa" stroke-width="0.08""## } else { r##"fill="none" stroke="#aaa" stroke-width="0.08""## };+            let _ = write!(g, r#"<path d="{}" {style}/>"#, path_d(poly, closed));+        }+    }+    for part in s.parts.iter().filter(|p| p.chip) {+        let pads: Vec<&Copper> = s.copper.iter().filter(|c| c.owner == part.refdes).collect();+        let (mx, my) = { let n = pads.len() as f64; (pads.iter().map(|c| c.shape.centre().0).sum::<f64>() / n, pads.iter().map(|c| c.shape.centre().1).sum::<f64>() / n) };+        for c in &pads {+            let Some(pin) = &c.pin else { continue };+            // pin number just inside the pad's inner end, towards the part centre+            let q = c.shape.centre();+            let (b0, b1, b2, b3) = c.shape.bounds();+            let along_x = (b2 - b0) > (b3 - b1);+            let inner = if along_x { (if q.0 > mx { b0 } else { b2 }, q.1) } else { (q.0, if q.1 > my { b1 } else { b3 }) };+            let off = 0.35;+            let p = if along_x { (inner.0 + if q.0 > mx { -off } else { off }, inner.1) } else { (inner.0, inner.1 + if q.1 > my { -off } else { off }) };+            let size = 0.3_f64.min(if along_x { b3 - b1 } else { b2 - b0 } * 0.9);+            let rotate = if along_x { String::new() } else { format!(r#" transform="rotate(-90 {:.4} {:.4})""#, p.0, -p.1) };+            let _ = write!(g, r##"<text x="{:.4}" y="{:.4}" font-size="{size:.3}" text-anchor="middle" dominant-baseline="central" fill="#ccc"{rotate}>{}</text>"##, p.0, -p.1, esc(pin));+            if pin == "1" {+                let d = if along_x { (p.0 + if q.0 > mx { -0.45 } else { 0.45 }, p.1) } else { (p.0, p.1 + if q.1 > my { -0.45 } else { 0.45 }) };+                let _ = write!(g, r##"<circle cx="{:.4}" cy="{:.4}" r="0.14" fill="white"/>"##, d.0, -d.1);+            }+        }+        // refdes and part name on two lines across the body, inside the pin-number columns+        let b = pads.iter().fold((f64::MAX, f64::MIN, f64::MAX, f64::MIN), |b, c| { let s = c.shape.bounds(); (b.0.min(s.0), b.1.max(s.2), b.2.min(s.1), b.3.max(s.3)) });+        // horizontal unless the chip is clearly tall; the part name only where it stays readable+        let wide = (b.3 - b.2) < 1.6 * (b.1 - b.0);+        let room = if wide { b.1 - b.0 } else { b.3 - b.2 } * 0.5;+        let lines: Vec<String> = std::iter::once(part.refdes.clone())+            .chain(part.label.clone().filter(|l| text_fit(l, room, 0.6) >= 0.28)).collect();+        let size = lines.iter().map(|l| text_fit(l, room, 0.6)).fold(f64::MAX, f64::min);+        let rotate = if wide { String::new() } else { format!(r#" transform="rotate(-90 {mx:.4} {:.4})""#, -my) };+        for (i, l) in lines.iter().enumerate() {+            let dy = (i as f64 - (lines.len() as f64 - 1.0) / 2.0) * size * 1.25;+            let _ = write!(g, r##"<g{rotate}><text x="{mx:.4}" y="{:.4}" font-size="{size:.3}" text-anchor="middle" dominant-baseline="central" fill="white">{}</text></g>"##, -my + dy, esc(l));+        }+    }+    for part in s.parts.iter().filter(|p| !p.chip) {+        let pads: Vec<&Copper> = s.copper.iter().filter(|c| c.owner == part.refdes).collect();+        if pads.is_empty() { continue; }+        let b = pads.iter().fold((f64::MAX, f64::MIN, f64::MAX, f64::MIN), |b, c| { let s = c.shape.bounds(); (b.0.min(s.0), b.1.max(s.2), b.2.min(s.1), b.3.max(s.3)) });+        let _ = write!(g, r##"<text x="{:.4}" y="{:.4}" font-size="0.45" text-anchor="middle" fill="white">{}</text>"##, (b.0 + b.1) / 2.0, -(b.3 + 0.12), esc(&part.refdes));+    }+    for (c, r) in &s.vias {+        let _ = write!(g, r##"<circle cx="{:.4}" cy="{:.4}" r="{r:.4}" fill="#bbb" stroke="#555" stroke-width="0.04"/>"##, c.0, -c.1);+    }+    for (c, r) in &s.free_slots {+        let _ = write!(g, r##"<circle cx="{:.4}" cy="{:.4}" r="{r:.4}" fill="none" stroke="#fc8" stroke-width="0.07" stroke-dasharray="0.18 0.14"/>"##, c.0, -c.1);+    }+    for c in s.copper.iter().filter(|c| c.kind != CopperKind::Pad) {+        let mp = c.kind == CopperKind::MachinePin;+        let style = if mp { r##"fill="#d63" stroke="#fe9" stroke-width="0.13""## }+            else if s.is_power(&c.net) { r##"fill="#c33" stroke="#ffd54a" stroke-width="0.18""## }+            else { r##"fill="#c33" stroke="#111" stroke-width="0.08""## };+        g.push_str(&shape_svg(&c.shape, style));+        let label = c.net.clone().unwrap_or_else(|| c.owner.clone());+        let q = c.shape.centre();+        let (b0, _, b2, _) = c.shape.bounds();+        let size = text_fit(&label, (b2 - b0) * 0.92, if mp { 0.5 } else { 0.42 });+        let _ = write!(g, r##"<text x="{:.4}" y="{:.4}" font-size="{size:.3}" font-weight="bold" text-anchor="middle" dominant-baseline="central" fill="white"><title>{}</title>{}</text>"##, q.0, -q.1, esc(&c.owner), esc(&label));+    }+    if s.show_silk {+        // top silk only: bottom silk reads mirrored through the board and sits under the top-side parts+        for t in s.silk.iter().filter(|t| !t.bottom) {+            let fill = r##"fill="#f4f4f4""##;+            let _ = write!(g, r#"<text x="{:.4}" y="{:.4}" font-size="{:.3}" text-anchor="middle" dominant-baseline="central" {fill} transform="rotate({:.3} {:.4} {:.4})">{}</text>"#,+                t.at.0, -t.at.1, t.size, -t.ccw_rotation, t.at.0, -t.at.1, esc(&t.text));+        }+    }+    for (i, n) in notes.iter().enumerate() {+        let size = note_size;+        let _ = write!(g, r##"<text x="{cx:.3}" y="{:.3}" font-size="{size:.3}" text-anchor="middle" fill="#111">{}</text>"##, -y0 + pad + line * (i as f64 + 0.6), esc(n));+    }+    (g, frame)+}++/// Scenes side by side in one SVG (two orientations of the same chip, for example).+pub fn render_svg(scenes: &[Scene]) -> String {+    let mut body = String::new();+    let mut x = 0.0;+    let mut height: f64 = 0.0;+    let gap = 2.0;+    for s in scenes {+        let (g, (fx, fy, fw, fh)) = scene_group(s);+        let _ = write!(body, r#"<g transform="translate({:.4} {:.4})">{g}</g>"#, x - fx, -fy);+        x += fw + gap;+        height = height.max(fh);+    }+    let width = (x - gap).max(1.0);+    format!(+        r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width:.3} {height:.3}" width="{:.0}" height="{:.0}" font-family="DejaVu Sans, Arial, sans-serif"><rect width="100%" height="100%" fill="white"/>{body}</svg>"##,+        width * 40.0, height * 40.0+    )+}++pub fn circuit_json_scene(path: &Path, title: &str) -> Result<Scene> {+    let cj: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?)+        .with_context(|| format!("{}: not circuit JSON", path.display()))?;+    Scene::from_circuit(&cj, title)+}++pub fn default_circuit_json(project: &Path) -> PathBuf { project.join("dist/lib/index/circuit.json") }++/// Courtyard exceptions from a file: a design.json carrying `rules.courtyardExceptions` (the claude-pcb-f411 board+/// contract), or a bare `[{ "refs": [a, b], "reason": ... }]` list.+pub fn read_courtyard_exceptions(path: &Path) -> Result<Vec<CourtyardException>> {+    let v: Value = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?)?;+    let list = if v.is_array() { v } else { v.pointer("/rules/courtyardExceptions").cloned().unwrap_or(Value::Array(vec![])) };+    Ok(serde_json::from_value(list).with_context(|| format!("{}: courtyard exceptions must be [{{refs: [a, b], reason}}]", path.display()))?)+}++/// The project's own exceptions, when it has a design.json that names any.+pub fn project_courtyard_exceptions(project: &Path) -> Vec<CourtyardException> {+    let p = project.join("design.json");+    if p.exists() { read_courtyard_exceptions(&p).unwrap_or_default() } else { vec![] }+}++/// A claude-pcb-f411 board's design.json applied to its circuit.json scene: courtyard exceptions+/// (`rules.courtyardExceptions`), machine pin roles (`mountingPinRoles`, for pins the circuit leaves unnamed) and+/// extra power nets (`powerNets`) for the yellow rings.+pub fn apply_design(scene: &mut Scene, design: &Path) -> Result<()> {+    let v: Value = serde_json::from_str(&std::fs::read_to_string(design).with_context(|| format!("read {}", design.display()))?)+        .with_context(|| format!("{}: not JSON", design.display()))?;+    scene.courtyard_exceptions = read_courtyard_exceptions(design)?;+    if let Some(roles) = v.get("mountingPinRoles").and_then(Value::as_object) {+        for c in scene.copper.iter_mut().filter(|c| c.kind == CopperKind::MachinePin && c.net.is_none()) {+            if let Some(n) = roles.get(&c.owner).and_then(Value::as_str) { c.net = Some(n.to_string()); }+        }+        scene.power_nets.extend(roles.values().filter_map(Value::as_str).map(str::to_string));+    }+    scene.power_nets.extend(v.get("powerNets").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string));+    scene.power_nets.sort(); scene.power_nets.dedup();+    Ok(())+}++/// The design.json of the board a circuit.json was built from (<board>/dist/lib/index/circuit.json), if any.+pub fn default_design(circuit: &Path) -> Option<PathBuf> {+    let d = circuit.parent()?.parent()?.parent()?.parent()?.join("design.json");+    d.exists().then_some(d)+}++/// Scenes for `render`: planning layouts side by side, or one built board (circuit.json + its design.json).+pub fn scenes_for(layouts: &[PathBuf], circuit: Option<&Path>, design: Option<&Path>, title: Option<&str>, courtyards: bool) -> Result<Vec<Scene>> {+    let mut scenes = if let Some(cj) = circuit {+        let title = title.map(str::to_string).unwrap_or_else(|| {+            cj.parent().and_then(|p| p.parent()).and_then(|p| p.parent()).and_then(|p| p.parent())+                .and_then(|p| p.file_name()).map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "board".into())+        });+        let mut scene = circuit_json_scene(cj, &title)?;+        if let Some(d) = design.map(Path::to_path_buf).or_else(|| default_design(cj)) { apply_design(&mut scene, &d)?; }+        scene.show_silk = true;+        vec![scene]+    } else {+        layouts.iter().map(|p| Scene::from_layout(p)).collect::<Result<Vec<_>>>()?+    };+    if !courtyards { for s in &mut scenes { s.show_courtyards = false; } }+    Ok(scenes)+}++/// The measurements behind a render, as JSON (positions included, so a render can be checked against its source).+pub fn report(scenes: &[Scene], out: &Path) -> Value {+    let r4 = |v: f64| (v * 10000.0).round() / 10000.0;+    Value::Array(scenes.iter().map(|s| serde_json::json!({+        "title": s.title, "size": s.size_note, "out": out,+        "machinePins": s.copper.iter().filter(|c| c.kind == CopperKind::MachinePin).map(|c| { let q = c.shape.centre(); serde_json::json!({"name": c.owner, "net": c.net, "x": r4(q.0), "y": r4(q.1)}) }).collect::<Vec<_>>(),+        "contacts": s.copper.iter().filter(|c| c.kind == CopperKind::Contact).map(|c| { let q = c.shape.centre(); serde_json::json!({"name": c.owner, "net": c.net, "x": r4(q.0), "y": r4(q.1), "power": s.is_power(&c.net)}) }).collect::<Vec<_>>(),+        "pads": s.copper.iter().filter(|c| c.kind == CopperKind::Pad).map(|c| { let q = c.shape.centre(); serde_json::json!({"part": c.owner, "pin": c.pin, "net": c.net, "x": r4(q.0), "y": r4(q.1)}) }).collect::<Vec<_>>(),+        "clearances": s.clearances(), "crossings": s.crossings(),+        "freeSlots": s.free_slots.iter().map(|(p, _)| [p.0, p.1]).collect::<Vec<_>>(),+        "courtyardOverlaps": if s.show_courtyards { s.courtyard_overlaps() } else { vec![] },+        "pours": s.pour_report(),+        "silk": s.silk.iter().map(|t| serde_json::json!({"text": t.text, "x": t.at.0, "y": t.at.1, "ccwRotation": t.ccw_rotation, "size": t.size, "bottom": t.bottom})).collect::<Vec<_>>(),+    })).collect())+}++/// One summary block per scene, as the CLI prints it.+pub fn summary(scenes: &[Scene]) -> Vec<String> {+    let mut out = Vec::new();+    for s in scenes {+        out.push(format!("{}: {}", s.title, s.size_note));+        for c in s.clearances() { out.push(format!("  {} to nearest copper: {:.2} mm ({}-{})", c.part, c.mm, c.from, c.to)); }+        if !s.lines.is_empty() { out.push(format!("  pin-to-contact lines crossing: {}", s.crossings())); }+        for r in s.pour_report() {+            out.push(format!("  {} pours {}: {}edge pullback {:.3} mm", r.layer, r.nets.join(", "), r.gap_mm.map(|g| format!("gap {g:.3} mm, ")).unwrap_or_default(), r.edge_pullback_mm));+        }+        if s.show_courtyards {+            for o in s.courtyard_overlaps() {+                out.push(format!("  courtyards overlap: {}-{}{}", o.a, o.b, if o.excepted { format!(" (named exception: {})", o.reason) } else { String::new() }));+            }+        }+    }+    out+}++#[cfg(test)]+mod tests {+    use super::*;+    use serde_json::json;++    const FP: &str = r#"(footprint "T" (layer "F.Cu")+        (fp_poly (pts (xy -1 -1) (xy 1 -1) (xy 1 1) (xy -1 1)) (stroke (width 0.1) (type solid)) (fill no) (layer "F.Fab"))+        (fp_line (start -2.2 -1.2) (end 2.2 -1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))+        (fp_line (start 2.2 -1.2) (end 2.2 1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))+        (fp_line (start -2.2 1.2) (end 2.2 1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))+        (fp_line (start -2.2 1.2) (end -2.2 -1.2) (stroke (width 0.05) (type solid)) (layer "F.CrtYd"))+        (pad "1" smd rect (at -1.5 -0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))+        (pad "2" smd rect (at -1.5 0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))+        (pad "3" smd rect (at 1.5 0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))+        (pad "4" smd rect (at 1.5 -0.5) (size 1 0.4) (layers "F.Cu" "F.Mask" "F.Paste"))+        (pad "" np_thru_hole circle (at 0 0) (size 0.5 0.5) (drill 0.5) (layers "*.Cu")))"#;++    fn plan() -> Value {+        // planMolecule shape: 8x8 MediumShort, contacts on the left column+        json!({+            "board": {"width": 10, "height": 10, "nominalWidth": 10, "nominalHeight": 10, "center": {"x": 0, "y": 0}, "cornerRadius": 0,+                      "wings": {"left": 0, "right": 0, "top": 0, "bottom": 0},+                      "outline": [{"x": 5, "y": -5}, {"x": 5, "y": 5}, {"x": -5, "y": 5}, {"x": -5, "y": -5}]},+            "machinePins": [{"name": "MP1", "x": -4, "y": -4, "holeOD": 1.6, "boundingBox": 2}, {"name": "MP2", "x": -4, "y": 4, "holeOD": 1.6, "boundingBox": 2},+                            {"name": "MP3", "x": 4, "y": 4, "holeOD": 1.6, "boundingBox": 2}, {"name": "MP4", "x": 4, "y": -4, "holeOD": 1.6, "boundingBox": 2}],+            "contacts": [{"designator": "MC1", "net": "A", "x": -4, "y": -2, "holeOD": 1.3, "boundingBox": 2}, {"designator": "MC2", "net": "B", "x": -4, "y": 2, "holeOD": 1.3, "boundingBox": 2},+                         {"designator": "MC3", "net": "C", "x": 4, "y": 0, "holeOD": 1.3, "boundingBox": 2}]+        })+    }++    fn layout_scene(rotation: f64) -> Scene {+        // one directory per call: the tests run in parallel and must not read each other's half-written files+        static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+        let n = N.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+        let dir = std::env::temp_dir().join(format!("plan-view-test-{}-{}-{n}", std::process::id(), rotation));+        std::fs::create_dir_all(&dir).unwrap();+        std::fs::write(dir.join("t.kicad_mod"), FP).unwrap();+        let layout: Layout = serde_json::from_value(json!({+            "title": "t", "plan": plan(), "machinePinNets": {"MP1": "GND"},+            "parts": [{"ref": "U1", "footprint": "t.kicad_mod", "rotation": rotation, "pins": {"1": "B", "2": "A", "3": "C", "4": "GND"}}]+        })).unwrap();+        Scene::from_layout_value(layout, &dir, "x".into()).unwrap()+    }++    #[test]+    fn parses_pads_fab_and_skips_non_copper_names() {+        let dir = std::env::temp_dir().join(format!("plan-view-fp-{}", std::process::id()));+        std::fs::create_dir_all(&dir).unwrap();+        std::fs::write(dir.join("t.kicad_mod"), FP).unwrap();+        let fp = read_footprint(&dir.join("t.kicad_mod")).unwrap();+        assert_eq!(fp.pads.iter().map(|p| p.0.as_str()).collect::<Vec<_>>(), ["1", "2", "3", "4"]);+        // KiCad y down -> y up: pad 1 at (-1.5, -0.5) is at (-1.5, +0.5)+        assert!((fp.pads[0].1.centre().1 - 0.5).abs() < 1e-9);+        assert_eq!(fp.fab.len(), 1);+    }++    #[test]+    fn distances() {+        let a = Shape::Circle { c: (0.0, 0.0), r: 0.65 };+        let b = Shape::Circle { c: (2.0, 0.0), r: 0.65 };+        assert!((distance(&a, &b) - 0.7).abs() < 1e-9);+        let r = Shape::Poly(rect_poly((3.0, 0.0), 1.0, 1.0, 0.0));+        assert!((distance(&a, &r) - 1.85).abs() < 1e-9);+        // a 1 mm square turned 45 degrees at x 4.5: its left corner is at 4.5 - 0.7071, 0.2929 from the edge at 3.5+        let r2 = Shape::Poly(rect_poly((4.5, 0.0), 1.0, 1.0, 45.0));+        assert!((distance(&r, &r2) - (1.0 - 0.5f64.hypot(0.5))).abs() < 1e-9);+        assert_eq!(distance(&r, &Shape::Poly(rect_poly((3.2, 0.0), 1.0, 1.0, 0.0))), 0.0);+    }++    #[test]+    fn plan_scene_labels_nets_and_measures_clearance() {+        let s = layout_scene(0.0);+        let labels: Vec<_> = s.copper.iter().filter(|c| c.kind != CopperKind::Pad).map(|c| c.net.clone().unwrap_or(c.owner.clone())).collect();+        assert_eq!(labels, ["GND", "MP2", "MP3", "MP4", "A", "B", "C"]);+        let c = s.clearances();+        assert_eq!(c.len(), 1);+        // U1 pad 4 (GND, x 1..2, y 0.3..0.7) to MC3 (C, at 4,0, r 0.65): the nearest other-net copper; pad 3 is on C+        // itself, and the left pads sit 2.4 mm from the other-net contacts+        assert_eq!((c[0].part.as_str(), c[0].from.as_str(), c[0].to.as_str()), ("U1", "U1.4", "MC3"));+        assert!((c[0].mm - ((4.0f64 + 0.09).sqrt() - 0.65)).abs() < 1e-3);+        assert_eq!(s.lines.len(), 3);+    }++    #[test]+    fn crossings_follow_rotation() {+        assert_eq!(layout_scene(0.0).crossings(), 0);+        // turned 180: A and B end up on the right, C on the left, so the lines cross the chip and each other+        assert!(layout_scene(180.0).crossings() > 0);+    }++    #[test]+    fn free_slots_between_contacts() {+        let s = layout_scene(0.0);+        // left column: MP1 -4, MC1 -2, (0 empty), MC2 2, MP2 4 -> one free slot at (-4, 0)+        assert!(s.free_slots.iter().any(|(p, _)| (p.0 + 4.0).abs() < 1e-9 && p.1.abs() < 1e-9));+        // right column: MP4 -4, MC3 0, MP3 4 -> free at (4, -2) and (4, 2); the empty top and bottom rows between the+        // machine pins have three free slots each, on the board's 2 mm grid+        assert!(s.free_slots.iter().any(|(p, _)| (p.0 - 4.0).abs() < 1e-9 && (p.1 - 2.0).abs() < 1e-9));+        assert_eq!(s.free_slots.len(), 9);+    }++    #[test]+    fn circuit_scene_names_nets_and_draws_traces() {+        let cj: Vec<Value> = serde_json::from_value(json!([+            {"type": "pcb_board", "center": {"x": 0, "y": 0}, "width": 10, "height": 10},+            {"type": "source_component", "source_component_id": "s1", "name": "MC1"},+            {"type": "source_component", "source_component_id": "s2", "name": "U1"},+            {"type": "pcb_component", "pcb_component_id": "p1", "source_component_id": "s1", "center": {"x": -4, "y": 0}, "width": 2, "height": 2},+            {"type": "pcb_component", "pcb_component_id": "p2", "source_component_id": "s2", "center": {"x": 0, "y": 0}, "width": 3, "height": 2},+            {"type": "source_port", "source_port_id": "sp1"}, {"type": "source_port", "source_port_id": "sp2"},+            {"type": "pcb_port", "pcb_port_id": "pp1", "source_port_id": "sp1"}, {"type": "pcb_port", "pcb_port_id": "pp2", "source_port_id": "sp2"},+            {"type": "source_net", "source_net_id": "n1", "name": "SDA"},+            {"type": "source_trace", "connected_source_port_ids": ["sp1", "sp2"], "connected_source_net_ids": ["n1"]},+            {"type": "pcb_plated_hole", "pcb_component_id": "p1", "pcb_port_id": "pp1", "shape": "circle", "x": -4, "y": 0, "outer_diameter": 1.3},+            {"type": "pcb_smtpad", "pcb_component_id": "p2", "pcb_port_id": "pp2", "shape": "rect", "x": -1, "y": 0, "width": 0.6, "height": 0.4, "layer": "top", "port_hints": ["1", "pin1"]},+            {"type": "pcb_trace", "route": [{"route_type": "wire", "x": -4, "y": 0, "width": 0.2, "layer": "top"}, {"route_type": "wire", "x": -1, "y": 0, "width": 0.2, "layer": "top"}]}+        ])).unwrap();+        let s = Scene::from_circuit(&cj, "b").unwrap();+        let mc = s.copper.iter().find(|c| c.owner == "MC1").unwrap();+        assert_eq!(mc.net.as_deref(), Some("SDA"));+        assert_eq!(s.copper.iter().find(|c| c.owner == "U1").unwrap().pin.as_deref(), Some("1"));+        assert_eq!(s.traces.len(), 1);+        let svg = render_svg(&[s]);+        assert!(svg.contains(">SDA</text>"));+    }++    /// A 10.4 x 14 board with two bottom pours 0.3 mm apart and 0.4 mm in from the edge (the 74HC595 domino's),+    /// a GND machine pin, a GND contact, a corner label at 45 degrees and one bottom silk line.+    fn poured_board() -> Vec<Value> {+        let rect = |x0: f64, y0: f64, x1: f64, y1: f64| json!([{"x": x0, "y": y0}, {"x": x1, "y": y0}, {"x": x1, "y": y1}, {"x": x0, "y": y1}]);+        serde_json::from_value(json!([+            {"type": "pcb_board", "center": {"x": 0, "y": 0}, "width": 10.4, "height": 14},+            {"type": "source_net", "source_net_id": "n1", "name": "VCC"}, {"type": "source_net", "source_net_id": "n2", "name": "GND"},+            {"type": "pcb_copper_pour", "layer": "bottom", "source_net_id": "n1", "shape": "brep", "brep_shape": {"outer_ring": {"vertices": rect(-4.8, 3.025, 4.8, 6.6)}, "inner_rings": []}},+            {"type": "pcb_copper_pour", "layer": "bottom", "source_net_id": "n2", "shape": "brep", "brep_shape": {"outer_ring": {"vertices": rect(-4.8, -6.6, 4.8, 2.725)}, "inner_rings": []}},+            {"type": "source_component", "source_component_id": "s1", "name": "MP1"}, {"type": "source_component", "source_component_id": "s2", "name": "MC1"},+            {"type": "pcb_component", "pcb_component_id": "p1", "source_component_id": "s1"}, {"type": "pcb_component", "pcb_component_id": "p2", "source_component_id": "s2"},+            {"type": "source_port", "source_port_id": "sp1"}, {"type": "source_port", "source_port_id": "sp2"},+            {"type": "pcb_port", "pcb_port_id": "pp1", "source_port_id": "sp1"}, {"type": "pcb_port", "pcb_port_id": "pp2", "source_port_id": "sp2"},+            {"type": "source_trace", "connected_source_port_ids": ["sp1", "sp2"], "connected_source_net_ids": ["n2"]},+            {"type": "pcb_plated_hole", "pcb_component_id": "p1", "pcb_port_id": "pp1", "shape": "circle", "x": -4, "y": -4, "outer_diameter": 1.6},+            {"type": "pcb_plated_hole", "pcb_component_id": "p2", "pcb_port_id": "pp2", "shape": "circle", "x": 2, "y": -6, "outer_diameter": 1.3},+            {"type": "pcb_silkscreen_text", "text": "GND", "anchor_position": {"x": 3.2, "y": -5.3}, "ccw_rotation": 45, "font_size": 0.4, "layer": "top"},+            {"type": "pcb_silkscreen_text", "text": "UNDER", "anchor_position": {"x": 0, "y": 0}, "ccw_rotation": 0, "font_size": 0.5, "layer": "bottom"}+        ])).unwrap()+    }++    #[test]+    fn pours_measure_gap_and_edge_pullback() {+        let s = Scene::from_circuit(&poured_board(), "b").unwrap();+        let r = s.pour_report();+        assert_eq!(r.len(), 1);+        assert_eq!((r[0].layer.as_str(), r[0].nets.clone()), ("bottom", vec!["VCC".to_string(), "GND".to_string()]));+        assert_eq!(r[0].gap_mm, Some(0.3));+        assert_eq!(r[0].edge_pullback_mm, 0.4);+        // same-net pours are one region: no gap reported between them+        let mut same = s.clone();+        for p in &mut same.pours { p.net = Some("GND".into()); }+        assert_eq!(same.pour_report()[0].gap_mm, None);+    }++    #[test]+    fn silk_keeps_rotation_and_only_top_silk_is_drawn() {+        let mut s = Scene::from_circuit(&poured_board(), "b").unwrap();+        let gnd = s.silk.iter().find(|t| t.text == "GND").unwrap();+        assert_eq!((gnd.ccw_rotation, gnd.size, gnd.bottom), (45.0, 0.4, false));+        assert!(s.silk.iter().any(|t| t.text == "UNDER" && t.bottom));+        s.show_silk = true;+        let svg = render_svg(&[s]);+        // SVG y is down, so a 45 degree counter-clockwise label is rotate(-45)+        assert!(svg.contains(r#"transform="rotate(-45.000 3.2000 5.3000)">GND</text>"#));+        assert!(!svg.contains(">UNDER</text>"));+    }++    #[test]+    fn machine_pin_nets_ring_contacts_yellow() {+        let s = Scene::from_circuit(&poured_board(), "b").unwrap();+        assert_eq!(s.power_nets, vec!["GND".to_string()]);+        let svg = render_svg(&[s]);+        assert!(svg.contains(r##"fill="#c33" stroke="#ffd54a""##), "the GND contact is ringed");+        // a layout: machinePinNets plus powerNets+        let dir = std::env::temp_dir().join(format!("plan-view-power-{}", std::process::id()));+        std::fs::create_dir_all(&dir).unwrap();+        let layout: Layout = serde_json::from_value(json!({"plan": plan(), "machinePinNets": {"MP1": "GND"}, "powerNets": ["B"]})).unwrap();+        let l = Scene::from_layout_value(layout, &dir, "x".into()).unwrap();+        assert_eq!(l.power_nets, vec!["B".to_string(), "GND".to_string()]);+        let svg = render_svg(&[l]);+        assert_eq!(svg.matches(r##"fill="#c33" stroke="#ffd54a""##).count(), 1, "only MC2 (net B) is ringed");+    }++    #[test]+    fn design_json_names_pins_power_nets_and_exceptions() {+        let mut cj = poured_board();+        // the machine pin loses its net: design.json's mountingPinRoles names it+        cj.retain(|e| e.get("type").and_then(Value::as_str) != Some("source_trace"));+        let mut s = Scene::from_circuit(&cj, "b").unwrap();+        assert!(s.power_nets.is_empty());+        let dir = std::env::temp_dir().join(format!("plan-view-design-{}", std::process::id()));+        std::fs::create_dir_all(&dir).unwrap();+        std::fs::write(dir.join("design.json"), json!({+            "mountingPinRoles": {"MP1": "GND"}, "powerNets": ["VIN"],+            "rules": {"courtyardExceptions": [{"refs": ["U1", "MP2"], "reason": "r"}]}+        }).to_string()).unwrap();+        apply_design(&mut s, &dir.join("design.json")).unwrap();+        assert_eq!(s.copper.iter().find(|c| c.owner == "MP1").unwrap().net.as_deref(), Some("GND"));+        assert_eq!(s.power_nets, vec!["GND".to_string(), "VIN".to_string()]);+        assert_eq!(s.courtyard_exceptions.len(), 1);+    }++    fn placed_at(x: f64, exceptions: Value) -> Scene {+        static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+        let n = N.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+        let dir = std::env::temp_dir().join(format!("plan-view-cy-{}-{n}", std::process::id()));+        std::fs::create_dir_all(&dir).unwrap();+        std::fs::write(dir.join("t.kicad_mod"), FP).unwrap();+        let layout: Layout = serde_json::from_value(json!({+            "plan": plan(), "courtyardExceptions": exceptions,+            "parts": [{"ref": "U1", "footprint": "t.kicad_mod", "x": x, "y": 0}]+        })).unwrap();+        Scene::from_layout_value(layout, &dir, "x".into()).unwrap()+    }++    #[test]+    fn courtyard_lines_chain_into_one_closed_outline() {+        let s = placed_at(0.0, json!([]));+        let u1: Vec<_> = s.courtyards.iter().filter(|(o, _)| o == "U1").collect();+        assert_eq!(u1.len(), 1);+        match &u1[0].1 { Shape::Poly(p) => assert_eq!(p.len(), 4), _ => panic!("expected a polygon") }+        // every machine pin and contact gets the library's courtyard circle (r 0.99)+        assert_eq!(s.courtyards.iter().filter(|(_, c)| matches!(c, Shape::Circle { r, .. } if (*r - 0.99).abs() < 1e-9)).count(), 7);+    }++    #[test]+    fn courtyard_overlaps_are_flagged_unless_named() {+        // U1's courtyard spans x -2.2..2.2; at x 0 it is clear of the contact column's circles (edge at -3.01)+        assert!(placed_at(0.0, json!([])).courtyard_overlaps().is_empty());+        // moved left by 1.5 mm its corners (-3.7, ±1.2) sit 0.85 mm from MC1 / MC2 (at -4, ±2), inside their r 0.99+        let o = placed_at(-1.5, json!([])).courtyard_overlaps();+        assert_eq!(o.iter().map(|o| (o.a.as_str(), o.b.as_str(), o.excepted)).collect::<Vec<_>>(), [("MC1", "U1", false), ("MC2", "U1", false)]);+        // a named exception turns its pair amber; the other stays an error+        let s = placed_at(-1.5, json!([{"refs": ["U1", "MC1"], "reason": "checked"}]));+        let o = s.courtyard_overlaps();+        assert_eq!(o.iter().map(|o| (o.a.as_str(), o.b.as_str(), o.excepted)).collect::<Vec<_>>(), [("MC2", "U1", false), ("MC1", "U1", true)]);+        let svg = render_svg(&[s.clone()]);+        assert!(svg.contains("#ff3b3b") && svg.contains("#f5a623"));+        assert!(svg.contains("courtyard overlaps: MC2-U1; named exceptions: MC1-U1"));+        let mut off = s; off.show_courtyards = false;+        assert!(!render_svg(&[off]).contains("class=\"courtyard\""));+    }++    #[test]+    fn rotated_courtyard_rects_turn_with_their_part() {+        // a 1.9 x 1.1 courtyard turned 90 is 1.1 wide: at x 1.6 it clears a circle of r 0.99 at the origin+        // (gap 1.6 - 0.55 - 0.99 = 0.06); unturned it would reach 1.6 - 0.95 = 0.65 and overlap+        let cj: Vec<Value> = serde_json::from_value(json!([+            {"type": "pcb_board", "center": {"x": 0, "y": 0}, "width": 10, "height": 10},+            {"type": "source_component", "source_component_id": "s1", "name": "MC1"},+            {"type": "source_component", "source_component_id": "s2", "name": "C1"},+            {"type": "pcb_component", "pcb_component_id": "p1", "source_component_id": "s1", "center": {"x": 0, "y": 0}},+            {"type": "pcb_component", "pcb_component_id": "p2", "source_component_id": "s2", "center": {"x": 1.6, "y": 0}},+            {"type": "pcb_courtyard_circle", "pcb_component_id": "p1", "layer": "top", "center": {"x": 0, "y": 0}, "radius": 0.99},+            {"type": "pcb_courtyard_rect", "pcb_component_id": "p2", "layer": "top", "center": {"x": 1.6, "y": 0}, "width": 1.9, "height": 1.1, "ccw_rotation": 90}+        ])).unwrap();+        assert!(Scene::from_circuit(&cj, "r").unwrap().courtyard_overlaps().is_empty());+    }++    #[test]+    fn touching_courtyards_do_not_overlap() {+        let a = Shape::Poly(rect_poly((0.0, 0.0), 2.0, 2.0, 0.0));+        assert!(!overlaps(&a, &Shape::Poly(rect_poly((2.0, 0.0), 2.0, 2.0, 0.0))));       // shared edge+        assert!(!overlaps(&a, &Shape::Poly(rect_poly((2.0, 2.0), 2.0, 2.0, 0.0))));       // shared corner+        assert!(overlaps(&a, &Shape::Poly(rect_poly((1.9, 0.5), 2.0, 2.0, 0.0))));        // 0.1 mm in+        assert!(overlaps(&a, &Shape::Poly(rect_poly((0.0, 0.0), 2.0, 2.0, 0.0))));        // identical+        assert!(!overlaps(&Shape::Circle { c: (0.0, 0.0), r: 1.0 }, &Shape::Circle { c: (2.0, 0.0), r: 1.0 }));+        assert!(overlaps(&Shape::Circle { c: (0.0, 0.0), r: 1.0 }, &Shape::Circle { c: (1.9, 0.0), r: 1.0 }));+        assert!(!overlaps(&Shape::Circle { c: (2.0, 0.0), r: 1.0 }, &a));                 // touches the edge+        // float noise on a shared edge (the AMS1117's U1 / C2 courtyards: shapely measures 0 mm² between them)+        let u = Shape::Poly(vec![(2.15, -2.7), (3.5999999999999996, -2.7), (3.6000000000000005, 1.4999999999999996), (2.15, 1.5)]);+        let c2 = Shape::Poly(vec![(5.06, -1.83), (5.06, 1.13), (3.6, 1.13), (3.6, -1.83)]);+        assert!(!overlaps(&u, &c2));+    }++    #[test]+    fn exceptions_read_from_a_design_json_or_a_list() {+        let dir = std::env::temp_dir().join(format!("plan-view-ex-{}", std::process::id()));+        std::fs::create_dir_all(&dir).unwrap();+        std::fs::write(dir.join("design.json"), r#"{"rules": {"courtyardExceptions": [{"refs": ["U1", "MP2"], "reason": "r"}]}}"#).unwrap();+        std::fs::write(dir.join("list.json"), r#"[{"refs": ["C1", "U1"]}]"#).unwrap();+        assert_eq!(project_courtyard_exceptions(&dir)[0].refs, ["U1".to_string(), "MP2".to_string()]);+        assert_eq!(read_courtyard_exceptions(&dir.join("list.json")).unwrap()[0].refs[0], "C1");+        assert!(project_courtyard_exceptions(&dir.join("nowhere")).is_empty());+    }++    #[test]+    fn svg_draws_two_scenes_side_by_side() {+        let svg = render_svg(&[layout_scene(0.0), layout_scene(180.0)]);+        assert_eq!(svg.matches("<g transform").count(), 2);+        assert!(svg.contains("stroke-dasharray=\"0.18 0.14\""));   // free slot+        assert!(svg.contains("to nearest copper"));+    }+}
src/png.rsadded+56
@@ -0,0 +1,56 @@+//! SVG -> PNG through resvg, sized for chat (a fixed pixel width), with the system fonts loaded so labels render.++use anyhow::{anyhow, Context, Result};+use resvg::{tiny_skia, usvg};++pub fn svg_to_png(svg: &str, width_px: u32) -> Result<Vec<u8>> {+    let mut opt = usvg::Options::default();+    opt.fontdb_mut().load_system_fonts();+    let tree = usvg::Tree::from_str(svg, &opt).context("parse SVG for PNG")?;+    let size = tree.size();+    let scale = width_px as f32 / size.width();+    let height_px = (size.height() * scale).ceil().max(1.0) as u32;+    let mut pixmap = tiny_skia::Pixmap::new(width_px, height_px).ok_or_else(|| anyhow!("PNG of {width_px}x{height_px} px"))?;+    pixmap.fill(tiny_skia::Color::WHITE);+    resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());+    // Opaque on white. Boards are a few dozen flat colours plus anti-aliased edges, so a 256-colour palette of the+    // most frequent colours (edges mapped to their nearest) keeps the look and roughly halves the file.+    let rgb: Vec<[u8; 3]> = pixmap.data().chunks_exact(4).map(|p| [p[0], p[1], p[2]]).collect();+    let mut counts: std::collections::HashMap<[u8; 3], u32> = std::collections::HashMap::new();+    for c in &rgb { *counts.entry(*c).or_default() += 1; }+    let mut by_freq: Vec<([u8; 3], u32)> = counts.into_iter().collect();+    by_freq.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));+    let palette: Vec<[u8; 3]> = by_freq.iter().take(256).map(|(c, _)| *c).collect();+    let mut index_of: std::collections::HashMap<[u8; 3], u8> = palette.iter().enumerate().map(|(i, c)| (*c, i as u8)).collect();+    let nearest = |c: [u8; 3]| -> u8 {+        let d = |p: &[u8; 3]| (0..3).map(|k| { let v = p[k] as i32 - c[k] as i32; v * v }).sum::<i32>();+        (0..palette.len()).min_by_key(|&i| d(&palette[i])).unwrap_or(0) as u8+    };+    let indices: Vec<u8> = rgb.iter().map(|c| match index_of.get(c) { Some(i) => *i, None => { let i = nearest(*c); index_of.insert(*c, i); i } }).collect();+    let mut out = Vec::new();+    {+        let mut enc = png::Encoder::new(&mut out, width_px, height_px);+        enc.set_color(png::ColorType::Indexed);+        enc.set_depth(png::BitDepth::Eight);+        enc.set_palette(palette.iter().flatten().copied().collect::<Vec<u8>>());+        enc.set_compression(png::Compression::Best);+        enc.set_adaptive_filter(png::AdaptiveFilterType::NonAdaptive);+        enc.set_filter(png::FilterType::NoFilter);+        let mut w = enc.write_header().context("PNG header")?;+        w.write_image_data(&indices).context("encode PNG")?;+    }+    Ok(out)+}++#[cfg(test)]+mod tests {+    #[test]+    fn png_is_indexed_at_the_requested_width() {+        let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 5" width="400" height="200"><rect width="10" height="5" fill="white"/><circle cx="5" cy="2.5" r="2" fill="#c33"/><text x="5" y="2.5" font-size="1" fill="white">MC1</text></svg>"##;+        let png = super::svg_to_png(svg, 1000).unwrap();+        assert_eq!(&png[1..4], b"PNG");+        let be = |i: usize| u32::from_be_bytes(png[i..i + 4].try_into().unwrap());+        assert_eq!((be(16), be(20)), (1000, 500));+        assert_eq!(png[25], 3, "colour type 3: palette");+    }+}