@rulecad/pcb 0.3.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +78 -2
  2. package/circuit.mjs +637 -56
  3. package/package.json +3 -1
  4. package/pcb.mjs +878 -55
package/pcb.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
  // Diodes point from the switch to the row (COL2ROW in QMK's terms).
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
16
- import { circuitJson, bounds } from './circuit.mjs';
16
+ import { circuitJson, bounds, smtBounds, slideClear } from './circuit.mjs';
17
17
  export { bounds };
18
18
  import { loadRuleSet } from '@rulecad/cad/rules';
19
19
  import jscad from '@jscad/modeling';
@@ -32,7 +32,7 @@ const hole = (x, y, d) => ({ x, y, d });
32
32
 
33
33
  // An MX switch, PCB mount: two pins, the centre post and the two fixing pegs
34
34
  export function mx(name, x, y, m, sch = {}) {
35
- return { name, ftype: 'simple_switch', mpn: 'Cherry MX (PCB mount)', x, y, layer: 'top', sch,
35
+ return { name, ftype: 'simple_switch', mpn: 'Cherry MX (PCB mount)', package: 'Cherry MX, PCB mount', x, y, layer: 'top', sch,
36
36
  pads: [pad('pin1', m.pcb_pin1_x, m.pcb_pin1_y, m.pcb_pin_drill, m.pcb_pin_pad), pad('pin2', m.pcb_pin2_x, m.pcb_pin2_y, m.pcb_pin_drill, m.pcb_pin_pad)],
37
37
  holes: [hole(0, 0, m.pcb_centre_hole), hole(-m.pcb_peg_x, 0, m.pcb_peg_hole), hole(m.pcb_peg_x, 0, m.pcb_peg_hole)],
38
38
  courtyard: { w: m.pcb_body, h: m.pcb_body } }; // the housing's footprint on the board
@@ -45,7 +45,7 @@ export function pico(name, x, y, p, sch = {}) {
45
45
  const left = n <= 20, i = left ? n - 1 : 40 - n;
46
46
  pins.push(pad(`pin${n}`, (left ? -1 : 1) * p.pin_rows / 2, (19 / 2 - i) * p.pin_pitch, p.pin_hole, p.pin_pad));
47
47
  }
48
- return { name, ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', x, y, layer: 'top', sch, pads: pins, courtyard: { w: p.width, h: p.length } };
48
+ return { name, ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', package: 'Raspberry Pi Pico, 0.1 in header pins', x, y, layer: 'top', sch, pads: pins, courtyard: { w: p.width, h: p.length } };
49
49
  }
50
50
  // Where a Pico pin is, from its centre
51
51
  export const picoPin = (n, p) => { const left = n <= 20, i = left ? n - 1 : 40 - n; return { x: (left ? -1 : 1) * p.pin_rows / 2, y: (19 / 2 - i) * p.pin_pitch }; };
@@ -56,7 +56,7 @@ export const picoGpio = (side) => Object.entries(loadRuleSet('pico').rules[`gpio
56
56
  // Parts for any board, not only keyboards. Each returns a part as circuit.mjs describes it: put them in board.parts, join
57
57
  // their pins with board.nets, and set board.autoroute. o (all optional): { rotation: 0 | 90 | 180 | 270, layer,
58
58
  // mpn, labels: { pin1: 'GND', ... }, sch: { x, y } }. Pin labels name the pins in nets ('U1.GND') and on the schematic.
59
- const chip = (name, x, y, o, more) => ({ name, ftype: 'simple_chip', x, y, layer: o.layer ?? 'top', rotation: o.rotation ?? 0, mpn: o.mpn,
59
+ const chip = (name, x, y, o, more) => ({ name, ftype: 'simple_chip', x, y, layer: o.layer ?? 'top', rotation: o.rotation ?? 0, mpn: o.mpn, ...(o.package ? { package: o.package } : {}),
60
60
  courtyard: o.courtyard ?? null, sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} }, ...more });
61
61
  const pinNo = (p) => Number(p.pin.replace(/\D/g, ''));
62
62
  // A rule set's pin map ({ "1": "GND", ... }) as pin labels ({ pin1: 'GND', ... })
@@ -80,25 +80,25 @@ export function header(name, x, y, r, o = {}) {
80
80
  pads.push(pad(`pin${i + 1}`, two ? -r.row_spacing / 2 : 0, py, r.drill, r.pad));
81
81
  if (two) pads.push(pad(`pin${2 * n - i}`, r.row_spacing / 2, py, r.drill, r.pad));
82
82
  }
83
- return chip(name, x, y, o, { pads: pads.sort((a, b) => pinNo(a) - pinNo(b)) });
83
+ return chip(name, x, y, { package: `${two ? '2 × ' : ''}${n}-pin header, ${r.pitch} mm`, ...o }, { pads: pads.sort((a, b) => pinNo(a) - pinNo(b)) });
84
84
  }
85
85
 
86
86
  /** A Seeed Studio XIAO module (any of the family) on header pins, USB at +y, from the xiao rules; pins labelled D0..D10, 5V, GND, 3V3. */
87
87
  export const xiao = (name, x, y, r, o = {}) =>
88
- header(name, x, y, r, { pins: r.pins / 2, rows: 2, mpn: 'Seeed Studio XIAO', courtyard: { w: r.width, h: r.length }, labels: labelsFrom('xiao', 'pins'), ...o });
88
+ header(name, x, y, r, { pins: r.pins / 2, rows: 2, mpn: 'Seeed Studio XIAO', package: 'Seeed Studio XIAO, 0.1 in header pins', courtyard: { w: r.width, h: r.length }, labels: labelsFrom('xiao', 'pins'), ...o });
89
89
 
90
90
  /** A Qwiic / STEMMA QT socket (JST SH, 4 pins, side entry), from the qwiic rules: the plug goes in from +y, the tabs' side. */
91
91
  export function qwiic(name, x, y, r, o = {}) {
92
92
  const n = r.pins, smd = (k, x, y, w, h) => ({ pin: `pin${k}`, smd: true, hint: String(k), x, y, w, h });
93
93
  const pads = Array.from({ length: n }, (_, i) => smd(i + 1, (i - (n - 1) / 2) * r.pitch, r.pad_y, r.pad_w, r.pad_h))
94
94
  .concat([-1, 1].map((side, i) => smd(n + i + 1, side * r.tab_x, r.tab_y, r.tab_w, r.tab_h)));
95
- return chip(name, x, y, { mpn: 'JST SM04B-SRSS-TB', labels: { ...labelsFrom('qwiic', 'pins'), pin5: 'TAB1', pin6: 'TAB2' }, ...o }, { pads });
95
+ return chip(name, x, y, { mpn: 'JST SM04B-SRSS-TB', package: 'JST SH, 4 pins, side entry', labels: { ...labelsFrom('qwiic', 'pins'), pin5: 'TAB1', pin6: 'TAB2' }, ...o }, { pads });
96
96
  }
97
97
 
98
98
  /** A JST PH socket (2.0 mm, through-hole), from the jstph rules: o.pins pins in a row along x (default 2). */
99
99
  export function jstph(name, x, y, r, o = {}) {
100
100
  const n = o.pins ?? 2;
101
- return chip(name, x, y, { mpn: `JST B${n}B-PH-K-S`, ...o }, { pads: Array.from({ length: n }, (_, i) => pad(`pin${i + 1}`, (i - (n - 1) / 2) * r.pitch, 0, r.drill, r.pad)) });
101
+ return chip(name, x, y, { mpn: `JST B${n}B-PH-K-S`, package: `JST PH, ${n} pins`, ...o }, { pads: Array.from({ length: n }, (_, i) => pad(`pin${i + 1}`, (i - (n - 1) / 2) * r.pitch, 0, r.drill, r.pad)) });
102
102
  }
103
103
 
104
104
  // ---------- the keyboard ----------
@@ -138,6 +138,18 @@ export function fromLayout(list, pitch) {
138
138
  // drawn by rule and the connections to the Pico autorouted
139
139
  // mcu_gap, mcu_side, mcu_row, mount_holes (1: an M2 hole in each corner), thickness
140
140
  // matrix: each key's row and column and the GPIO each row and column uses, for checks and firmware.
141
+ // Lanes beside the Pico, nearest first: each runs from `from` to `to` (its pin's height) and then in to its pin,
142
+ // across every lane nearer than it, so a lane may be given a nearer place only if its run covers none of the other
143
+ // lanes' pins. { id: place }, 0 the nearest. (When no lane qualifies, the shortest run takes the place: the checks say)
144
+ export function laneOrder(lanes) {
145
+ const out = {}, left = [...lanes], covers = (l, y) => y > Math.min(l.from, l.to) - 1e-9 && y < Math.max(l.from, l.to) + 1e-9;
146
+ for (let place = 0; left.length; place++) {
147
+ const next = left.find((l) => left.every((o) => o === l || !covers(l, o.to))) ?? [...left].sort((a, b) => Math.abs(a.to - a.from) - Math.abs(b.to - b.from))[0];
148
+ out[next.id] = place; left.splice(left.indexOf(next), 1);
149
+ }
150
+ return out;
151
+ }
152
+
141
153
  export function keyboard(v, keys) {
142
154
  const m = v.mx, p = v.pico, d = v.sod123, lane = v.track + v.clear, half = m.pitch / 2, under = v.controller === 'under';
143
155
  const rows = [...new Set(keys.map((k) => k.r))].sort((a, b) => a - b), cols = [...new Set(keys.map((k) => k.c))].sort((a, b) => a - b);
@@ -183,12 +195,15 @@ export function keyboard(v, keys) {
183
195
  pinRows.push({ gap, y: ys, xs, keep });
184
196
  }
185
197
  } else {
186
- const cx = keyBox.right + v.mcu_gap + p.width / 2, cy = (keyBox.top + keyBox.bottom) / 2;
198
+ // Beside the keys, mcu_gap off them, or further out when the lanes to its pins (one a column on the front, one a
199
+ // row on the back, a lane apart) wouldn't fit between the keys and its pins
200
+ const lanesWide = Math.max(cols.length, rows.length) * lane, pinsIn = p.width / 2 + picoPin(1, p).x - p.pin_pad / 2 - v.clear - v.track / 2; // the left pins' near edge and clearance, in from the Pico's edge
201
+ const cx = keyBox.right + Math.max(v.mcu_gap, lanesWide + v.clear - pinsIn) + p.width / 2, cy = (keyBox.top + keyBox.bottom) / 2;
187
202
  pinAt = (n) => { const q = picoPin(n, p); return { x: cx + q.x, y: cy + q.y }; };
188
203
  pico0 = { x: cx, y: cy };
189
204
  right = cx + p.width / 2 + v.margin;
190
205
  }
191
- const picoPart = { name: 'U1', ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', x: pico0.x, y: pico0.y, layer: 'top', sch,
206
+ const picoPart = { name: 'U1', ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', package: 'Raspberry Pi Pico, 0.1 in header pins', x: pico0.x, y: pico0.y, layer: 'top', sch,
192
207
  pads: Array.from({ length: 40 }, (_, i) => { const q = pinAt(i + 1); return pad(`pin${i + 1}`, q.x - pico0.x, q.y - pico0.y, p.pin_hole, p.pin_pad); }),
193
208
  courtyard: under ? null : { w: p.width, h: p.length } };
194
209
 
@@ -196,7 +211,7 @@ export function keyboard(v, keys) {
196
211
  const pts = (list) => list.map(([x, y]) => ({ x, y })); // a track's corners between its two pads, on the board
197
212
  for (const k of keys) {
198
213
  parts.push(mx(`K${k.n}`, k.x, k.y, m, { x: k.c * SX, y: -k.r * SY }),
199
- { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
214
+ { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', package: 'SOD-123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
200
215
  traces.push({ from: [`D${k.n}`, 'anode'], to: [`K${k.n}`, 'pin1'], width: v.track, path: pts([[k.x + anodeX, k.y + m.pcb_pin1_y]]) });
201
216
  }
202
217
 
@@ -267,25 +282,40 @@ export function keyboard(v, keys) {
267
282
  traces.push({ from: near.sel, to: ['U1', `pin${best.g.pin}`], width: v.track }); // no path: the autorouter's
268
283
  }
269
284
  } else {
270
- // Beside: rows take the free left-edge pins nearest their row line, columns the lowest of the rest; every track
271
- // drawn: rows right then up or down a lane beside the Pico (back), columns below the keys and up a lane (front),
272
- // the leftmost column lowest and nearest the Pico, so no two cross
285
+ // Beside: rows take the free left-edge pins nearest their row lines, top row first and each below the last's
286
+ // (so none cross), columns the pins nearest the lanes' depth below the keys. Every track drawn: a row right along
287
+ // its line then up or down a lane beside the Pico (back copper) to its pin's height and in; a column down below
288
+ // the keys, right, and up or down a lane (front) to its pin's height and in. Each lane runs in to its pin across
289
+ // the lanes nearer the Pico, so those must end before it: lanes are given out nearest first to whichever would
290
+ // cross none of the rest (laneOrder), and the depths below the keys the same way
273
291
  const nearPins = pinAt(1).x - p.pin_pad / 2 - v.clear - v.track / 2, free = picoGpio('left'), take = (pin) => free.splice(free.findIndex((g) => g.pin === pin), 1)[0];
274
- for (const r of rows) {
275
- const y = rowY(r) + lineY, best = [...free].sort((a, b) => Math.abs(pinAt(a.pin).y - y) - Math.abs(pinAt(b.pin).y - y))[0];
292
+ let above = Infinity; // the last row's pin: the next row's is below it, leaving enough below for the rest
293
+ rows.forEach((r, i) => {
294
+ const y = rowY(r) + lineY, rest = rows.length - 1 - i;
295
+ const best = free.filter((g) => pinAt(g.pin).y < above && free.filter((o) => pinAt(o.pin).y < pinAt(g.pin).y).length >= rest).sort((a, b) => Math.abs(pinAt(a.pin).y - y) - Math.abs(pinAt(b.pin).y - y))[0];
276
296
  if (!best) throw new Error(`the Pico's left edge has no GPIO left for row ${r}`);
277
- rowPin[r] = take(best.pin);
278
- }
279
- const lowest = [...free].sort((a, b) => pinAt(a.pin).y - pinAt(b.pin).y);
280
- if (lowest.length < cols.length) throw new Error(`${cols.length} columns need ${cols.length} more GPIO on the Pico's left edge; ${lowest.length} are left`);
281
- cols.forEach((c, i) => { colPin[c] = lowest[i]; });
297
+ rowPin[r] = take(best.pin); above = pinAt(best.pin).y;
298
+ });
299
+ // The columns' pins: the nearest to the runs below the keys, all above them or all below (lanes up or lanes
300
+ // down, not both: their runs would cross each other's lanes), above when there are enough
301
+ const depthLine = keyBox.bottom - (cols.length + 1) / 2 * lane;
302
+ const byDepth = (list) => [...list].sort((a, b) => Math.abs(pinAt(a.pin).y - depthLine) - Math.abs(pinAt(b.pin).y - depthLine));
303
+ const over = free.filter((g) => pinAt(g.pin).y > depthLine), belowLine = free.filter((g) => pinAt(g.pin).y <= depthLine);
304
+ const nearDepth = byDepth(over.length >= cols.length ? over : belowLine.length >= cols.length ? belowLine : free);
305
+ if (nearDepth.length < cols.length) throw new Error(`${cols.length} columns need ${cols.length} more GPIO on the Pico's left edge; ${nearDepth.length} are left`);
306
+ cols.forEach((c, i) => { colPin[c] = nearDepth[i]; });
307
+ const rowLane = laneOrder(rows.map((r) => ({ id: r, from: rowY(r) + lineY, to: pinAt(rowPin[r].pin).y })));
282
308
  for (const r of rows) {
283
- const last = keys.filter((k) => k.r === r).sort((a, b) => a.x - b.x).at(-1), pinY = pinAt(rowPin[r].pin).y;
309
+ const last = keys.filter((k) => k.r === r).sort((a, b) => a.x - b.x).at(-1), pinY = pinAt(rowPin[r].pin).y, laneX = nearPins - rowLane[r] * lane;
284
310
  traces.push({ from: [`D${last.n}`, 'cathode'], to: ['U1', `pin${rowPin[r].pin}`], width: v.track,
285
- path: pts([[last.x + cathodeX, last.y + lineY], [nearPins - lane, last.y + lineY], [nearPins - lane, pinY]]) });
311
+ path: pts([[last.x + cathodeX, last.y + lineY], [laneX, last.y + lineY], [laneX, pinY]]) });
286
312
  }
287
- cols.forEach((c, i) => {
288
- const last = keys.filter((k) => k.c === c).sort((a, b) => b.r - a.r)[0], depth = keyBox.bottom - (cols.length - i) * lane, laneX = nearPins - i * lane;
313
+ // The depths: a lane's run below the keys crosses the lanes further out on its way in, so where their pins are
314
+ // above the runs the nearer lane runs deeper (and ends lower), where below, shallower
315
+ const pinsAbove = cols.filter((c) => pinAt(colPin[c].pin).y > depthLine).length >= cols.length / 2;
316
+ const colLane = laneOrder(cols.map((c) => ({ id: c, from: depthLine, to: pinAt(colPin[c].pin).y })));
317
+ cols.forEach((c) => {
318
+ const last = keys.filter((k) => k.c === c).sort((a, b) => b.r - a.r)[0], i = colLane[c], depth = keyBox.bottom - (pinsAbove ? cols.length - i : i + 1) * lane, laneX = nearPins - i * lane;
289
319
  traces.push({ from: [`K${last.n}`, 'pin2'], to: ['U1', `pin${colPin[c].pin}`], width: v.track,
290
320
  path: pts([[last.x + jogX, last.y + m.pcb_pin2_y - slant], [last.x + jogX, depth], [laneX, depth], [laneX, pinAt(colPin[c].pin).y]]) });
291
321
  });
@@ -309,6 +339,7 @@ export function keyboard(v, keys) {
309
339
  ...keys.map((k) => rect(k.x + cathodeX + d.pad_w / 2 + silk * 2, k.y + diode.y, silk, d.pad_h, 'bottom')),
310
340
  ...(v.margin >= text * 2 ? [{ text: 'rulecad: diodes point to the rows', x: (keyBox.left + keyBox.right) / 2, y: bottom + v.margin / 2, size: text, layer: 'bottom' }] : [])];
311
341
  const board = { center: { x: cx, y: cy }, width: right - left, height: top - bottom, thickness: v.thickness, autoroute: under,
342
+ silk_line: v.jlcpcb.silk_line, silk_text: v.jlcpcb.silk_text, via_hole: 0.3, via_pad: 0.3 + 2 * v.jlcpcb.annular, fab: v.jlcpcb, // (vias with the ring the fab recommends; the fab's minimums for the router)
312
343
  parts, traces, silk: marks, holes: corners.map(([x, y]) => hole(x, y, v.m2.clearance)) };
313
344
  const matrix = {
314
345
  keys: keys.map((k) => ({ key: `K${k.n}`, ...(k.label ? { label: k.label } : {}), row: k.r, col: k.c })),
@@ -323,25 +354,37 @@ export function keyboard(v, keys) {
323
354
  * A KiCad footprint (.kicad_mod text) as pad data: { pads, courtyard: { w, h } }, in mm, y up (KiCad's y is down).
324
355
  * Keep the result in a rule set's "footprints" (with its source), and place it with footprint(): a design never
325
356
  * reads files. SMD pads: { pin, smd: true, x, y, w, h } (a turned pad's w and h swapped); plated holes: { pin, x, y,
326
- * hole, outer }. Pads named alike (several GND pads) keep their name; unnamed pads (mechanical) are left out.
327
- * @param {string} text @returns {{ pads: object[], courtyard: { w: number, h: number } | null }}
357
+ * hole, outer }, an oval one with rect: { w, h } (its copper) and slot: [w, h] (drilled round at the narrow width);
358
+ * unplated holes in holes: [{ x, y, d }]. Pads named alike (several GND pads) keep their name; unnamed plated pads
359
+ * (mechanical) are left out. Text that isn't a footprint, or one with nothing on it, is refused.
360
+ * @param {string} text @returns {{ pads: object[], holes?: object[], courtyard: { w: number, h: number } | null }}
328
361
  */
329
362
  export function fromKicad(text) {
330
- const num = (s) => Number(s), pads = [];
363
+ if (!/^\s*\((?:footprint|module)\s/.test(text)) throw new Error('fromKicad: not a KiCad footprint (a .kicad_mod starts with "(footprint")');
364
+ const num = (s) => Number(s), pads = [], holes = [];
331
365
  for (const m of text.matchAll(/\(pad\s+"([^"]*)"\s+(smd|thru_hole|np_thru_hole)\s+(\w+)([\s\S]*?)\(layers/g)) {
332
- const [, name, kind, , rest] = m;
333
- if (!name) continue;
366
+ const [, name, kind, shape, rest] = m;
334
367
  const at = rest.match(/\(at\s+([-\d.]+)\s+([-\d.]+)(?:\s+([-\d.]+))?\)/), sz = rest.match(/\(size\s+([-\d.]+)\s+([-\d.]+)\)/);
335
368
  if (!at || !sz) continue;
336
369
  const turn = ((num(at[3] || 0) % 180) + 180) % 180 === 90, w = num(turn ? sz[2] : sz[1]), h = num(turn ? sz[1] : sz[2]);
337
370
  const x = +num(at[1]).toFixed(4), y = +(-num(at[2])).toFixed(4);
371
+ const drill = rest.match(/\(drill\s+(oval\s+)?([-\d.]+)(?:\s+([-\d.]+))?/);
372
+ if (kind === 'np_thru_hole') { if (drill) holes.push({ x, y, d: num(drill[2]) }); continue; } // a locating peg's hole: unplated, nothing to connect
373
+ if (!name) continue; // (an unnamed plated pad: mechanical)
338
374
  if (kind === 'smd') pads.push({ pin: name, smd: true, x, y, w, h });
339
- else if (kind === 'thru_hole') { const d = rest.match(/\(drill\s+(?:oval\s+)?([-\d.]+)/); pads.push({ pin: name, x, y, hole: num(d[1]), outer: Math.max(w, h) }); }
375
+ else if (kind === 'thru_hole') {
376
+ // An oval pad keeps its oval copper; a slot is drilled round at its narrow width (boards here can't carry slots),
377
+ // and says so
378
+ const d = num(drill[2]), slot = drill[1] && drill[3] && num(drill[3]) !== d ? (turn ? [num(drill[3]), d] : [d, num(drill[3])]) : null;
379
+ const oval = shape === 'oval' || (shape === 'rect' || shape === 'roundrect') ? w !== h : false;
380
+ pads.push({ pin: name, x, y, hole: slot ? Math.min(...slot) : d, outer: Math.max(w, h), ...(oval ? { rect: { w, h } } : {}), ...(slot ? { slot } : {}) });
381
+ }
340
382
  }
383
+ if (!pads.length && !holes.length) throw new Error('fromKicad: the footprint has no pads');
341
384
  const pts = text.split(/\n\s*(?=\(fp_|\(pad|\(model|\(zone)/).filter((el) => /^\(fp_(?:line|rect|poly)/.test(el) && /\(layer\s+"F\.CrtYd"\)/.test(el)) // the courtyard's corners
342
385
  .flatMap((el) => [...el.matchAll(/\((?:start|end|xy)\s+([-\d.]+)\s+([-\d.]+)\)/g)].map((m) => [num(m[1]), num(m[2])]));
343
386
  const span = (k) => Math.max(...pts.map((p) => p[k])) - Math.min(...pts.map((p) => p[k]));
344
- return { pads, courtyard: pts.length ? { w: +span(0).toFixed(3), h: +span(1).toFixed(3) } : null };
387
+ return { pads, ...(holes.length ? { holes } : {}), courtyard: pts.length ? { w: +span(0).toFixed(3), h: +span(1).toFixed(3) } : null };
345
388
  }
346
389
 
347
390
  /**
@@ -350,8 +393,618 @@ export function fromKicad(text) {
350
393
  * layer, mpn, labels, sch).
351
394
  */
352
395
  export function footprint(name, data, x, y, o = {}) {
353
- const pads = data.pads.map((p, i) => p.smd ? { pin: `pin${p.pin}`, smd: true, hint: String(p.pin), x: p.x, y: p.y, w: p.w, h: p.h } : pad(`pin${p.pin}`, p.x, p.y, p.hole, p.outer));
354
- return chip(name, x, y, { courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o }, { pads });
396
+ const pads = data.pads.map((p, i) => p.smd ? { pin: `pin${p.pin}`, smd: true, hint: String(p.pin), x: p.x, y: p.y, w: p.w, h: p.h } : { ...pad(`pin${p.pin}`, p.x, p.y, p.hole, p.outer), ...(p.rect ? { rect: p.rect } : {}) });
397
+ return chip(name, x, y, { courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o }, { pads, ...(data.holes?.length ? { holes: data.holes.map((h) => hole(h.x, h.y, h.d)) } : {}) });
398
+ }
399
+
400
+ // ---------- whole boards from KiCad: clones ----------
401
+ // A published board (a .kicad_pcb, KiCad 6 or later) read as a circuit: its parts with their pads, its nets, its planes and
402
+ // its outline. Keep the result in a rule set's "circuit" (cad clone writes it, with the source and its licence), and
403
+ // build boards from it with clone(): the circuit stays the source's, and the layout is redrawn by rules. sameCircuit()
404
+ // checks that a board still joins exactly the pins the source joins.
405
+
406
+ // KiCad's files are S-expressions: (name value (child ...) ...) as nested arrays, strings unquoted
407
+ function sexpr(text) {
408
+ const stack = [[]];
409
+ for (const t of text.match(/"(?:[^"\\]|\\.)*"|\(|\)|[^\s()"]+/g) || []) {
410
+ if (t === '(') stack.push([]);
411
+ else if (t === ')') { const l = stack.pop(); if (!stack.length) throw new Error('not a KiCad file: a ")" closes nothing'); stack.at(-1).push(l); }
412
+ else stack.at(-1).push(t[0] === '"' ? t.slice(1, -1).replace(/\\(.)/g, '$1') : t);
413
+ }
414
+ if (stack.length !== 1) throw new Error('not a KiCad file: a "(" is never closed');
415
+ return stack[0][0];
416
+ }
417
+ const kidsOf = (l, name) => l.filter((c) => Array.isArray(c) && c[0] === name);
418
+ const kidOf = (l, name) => kidsOf(l, name)[0];
419
+ const r4 = (n) => Math.round(n * 1e4) / 1e4 || 0; // 0.1 mm to the micron, and never -0
420
+ const turnOf = (deg) => ((Math.round(deg * 1e3) / 1e3 % 360) + 360) % 360;
421
+
422
+ // Edge.Cuts pieces ({ a, b } lines, arcs already cut into lines) joined end to end into closed loops
423
+ function loops(pieces, tol = 0.005) {
424
+ const same = (p, q) => Math.abs(p.x - q.x) < tol && Math.abs(p.y - q.y) < tol, out = [], left = [...pieces];
425
+ while (left.length) {
426
+ const loop = [left[0].a, left[0].b]; left.shift();
427
+ for (let found = true; found && !same(loop[0], loop.at(-1));) {
428
+ found = false;
429
+ for (let i = 0; i < left.length; i++) {
430
+ const s = left[i], end = loop.at(-1);
431
+ if (same(s.a, end) || same(s.b, end)) { loop.push(same(s.a, end) ? s.b : s.a); left.splice(i, 1); found = true; break; }
432
+ }
433
+ }
434
+ if (same(loop[0], loop.at(-1)) && loop.length > 3) out.push(loop.slice(0, -1));
435
+ else return null; // an open edge: the outline isn't one closed shape
436
+ }
437
+ return out;
438
+ }
439
+ const area = (pts) => pts.reduce((s, p, i) => { const q = pts[(i + 1) % pts.length]; return s + p.x * q.y - q.x * p.y; }, 0) / 2;
440
+
441
+ // The source's own tracks and vias, with their nets, in the circuit's frame: { tracks: [{ a, b, width, layer, net }],
442
+ // vias: [{ x, y, pad, hole, net }] }. Layers as boards here name them (top, inner1, ..., bottom)
443
+ function sourceCopper(root, to) {
444
+ const names = new Map(kidsOf(root, 'net').map((n) => [n[1], n[2]])), layer = (l) => (l === 'F.Cu' ? 'top' : l === 'B.Cu' ? 'bottom' : `inner${l.match(/\d+/)[0]}`);
445
+ const pt = (l) => to({ x: Number(l[1]), y: Number(l[2]) }), netOf = (e) => { const n = kidOf(e, 'net'); return n ? (n[2] ?? names.get(n[1]) ?? null) : null; };
446
+ return {
447
+ tracks: kidsOf(root, 'segment').map((g) => ({ a: pt(kidOf(g, 'start')), b: pt(kidOf(g, 'end')), width: Number(kidOf(g, 'width')[1]), layer: layer(kidOf(g, 'layer')[1]), net: netOf(g) })),
448
+ vias: kidsOf(root, 'via').map((v) => ({ ...pt(kidOf(v, 'at')), pad: Number(kidOf(v, 'size')[1]), hole: Number(kidOf(v, 'drill')[1]), net: netOf(v) }))
449
+ };
450
+ }
451
+
452
+ // The sizes the source uses most: its vias ({ via: { pad, hole } }), its narrowest track, its zones' clearance
453
+ function commonest(root) {
454
+ const most = (list) => { const n = new Map(); for (const k of list) n.set(k, (n.get(k) || 0) + 1); return [...n].sort((a, b) => b[1] - a[1])[0]?.[0]; };
455
+ const via = most(kidsOf(root, 'via').map((v) => `${kidOf(v, 'size')?.[1]} ${kidOf(v, 'drill')?.[1]}`));
456
+ const widths = kidsOf(root, 'segment').map((g) => Number(kidOf(g, 'width')?.[1])).filter((w) => w > 0);
457
+ const clear = most(kidsOf(root, 'zone').map((z) => kidOf(kidOf(z, 'connect_pads') || [], 'clearance')?.[1]).filter(Boolean));
458
+ return { ...(via ? { via: { pad: Number(via.split(' ')[0]), hole: Number(via.split(' ')[1]) } } : {}), ...(widths.length ? { track: Math.min(...widths) } : {}), ...(clear ? { clearance: Number(clear) } : {}) };
459
+ }
460
+
461
+ /**
462
+ * A KiCad board (.kicad_pcb text, KiCad 6 or later) as a circuit, in mm, y up, centred on the outline's bounds:
463
+ * { layers, width, height, outline, parts, nets, planes, holes, source }. Each part keeps its place on the source
464
+ * board ({ ref, footprint, value, mpn, lcsc, x, y, rotation, layer }) and its pads in its own frame, as seen from
465
+ * the side it's on ({ pin, x, y, w, h, angle, smd, shape, net } and, for holes, hole, hole_offset, castellated), and its
466
+ * unplated holes (holes: [{ x, y, d }], a socket's locating pegs). The board's own holes (a mounting hole) are in holes.
467
+ * nets: { name: ['U1.3', 'C4.1'] }, part and pad, for nets joining two pads or more. planes: nets the source fills on
468
+ * whole layers ({ GND: ['In1.Cu', 'B.Cu'] }). routing: the source's own tracks and vias (for keeping its layout of an
469
+ * area: moveGroup with keep). source: what the file says beyond the circuit (counts, its commonest via and clearance).
470
+ * @param {string} text @returns {object}
471
+ */
472
+ export function fromKicadPcb(text) {
473
+ const root = sexpr(text);
474
+ if (root?.[0] !== 'kicad_pcb') throw new Error('not a KiCad board: a .kicad_pcb starts with (kicad_pcb');
475
+ if (!kidOf(root, 'footprint')) throw new Error('no footprints in this board: KiCad 6 or later is needed (older files call them "module": open and save it in KiCad 6+)');
476
+ const layers = kidOf(root, 'layers').slice(1).filter((l) => l[2] === 'signal').map((l) => l[1]);
477
+ const num = Number, pieces = [], holes = [], raw = [];
478
+ const edge = (l, place) => { // a line or an arc on Edge.Cuts, as straight pieces in the board's frame
479
+ if ((kidOf(l, 'layer')?.[1]) !== 'Edge.Cuts') return;
480
+ const pt = (k) => { const p = kidOf(l, k); return p && place(num(p[1]), num(p[2])); };
481
+ const a = pt('start'), b = pt('end'), m = pt('mid');
482
+ if (!a || !b) return;
483
+ if (!m) return pieces.push({ a, b });
484
+ const ax = b.x - a.x, ay = b.y - a.y, bx = m.x - a.x, by = m.y - a.y, d = 2 * (ax * by - ay * bx); // the circle through a, m, b
485
+ const cx = a.x + (by * (ax * ax + ay * ay) - ay * (bx * bx + by * by)) / d, cy = a.y + (ax * (bx * bx + by * by) - bx * (ax * ax + ay * ay)) / d;
486
+ const r = Math.hypot(a.x - cx, a.y - cy), at = (p) => Math.atan2(p.y - cy, p.x - cx), t0 = at(a);
487
+ let t1 = at(b), tm = at(m);
488
+ const norm = (t) => ((t - t0) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI);
489
+ t1 = norm(t1); tm = norm(tm); const sweep = tm < t1 ? t1 : t1 - 2 * Math.PI, n = Math.max(2, Math.ceil(Math.abs(sweep) / (Math.PI / 16)));
490
+ let prev = a;
491
+ for (let i = 1; i <= n; i++) { const t = t0 + (sweep * i) / n, q = i === n ? b : { x: cx + r * Math.cos(t), y: cy + r * Math.sin(t) }; pieces.push({ a: prev, b: q }); prev = q; }
492
+ };
493
+ for (const g of root) if (Array.isArray(g) && ['gr_line', 'gr_arc'].includes(g[0])) edge(g, (x, y) => ({ x, y }));
494
+ for (const g of kidsOf(root, 'gr_rect')) if (kidOf(g, 'layer')?.[1] === 'Edge.Cuts') {
495
+ const s = kidOf(g, 'start'), e = kidOf(g, 'end'), [x0, y0, x1, y1] = [s[1], s[2], e[1], e[2]].map(num);
496
+ pieces.push({ a: { x: x0, y: y0 }, b: { x: x1, y: y0 } }, { a: { x: x1, y: y0 }, b: { x: x1, y: y1 } }, { a: { x: x1, y: y1 }, b: { x: x0, y: y1 } }, { a: { x: x0, y: y1 }, b: { x: x0, y: y0 } });
497
+ }
498
+ for (const f of kidsOf(root, 'footprint')) {
499
+ const at = kidOf(f, 'at'), fx = num(at[1]), fy = num(at[2]), deg = num(at[3] || 0), t = (deg * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
500
+ const bottom = (kidOf(f, 'layer')?.[1]) === 'B.Cu';
501
+ const place = (x, y) => ({ x: fx + x * c + y * s, y: fy - x * s + y * c }); // KiCad's frame: y down, angles counter-clockwise on screen
502
+ for (const l of [...kidsOf(f, 'fp_line'), ...kidsOf(f, 'fp_arc')]) edge(l, place);
503
+ const props = Object.fromEntries(kidsOf(f, 'property').map((p) => [String(p[1]).trim(), p[2]]));
504
+ const ref = props.Reference ?? kidsOf(f, 'fp_text').find((x) => x[1] === 'reference')?.[2];
505
+ const pads = [], own = []; // own: the part's unplated holes (a socket's locating pegs), in its frame
506
+ for (const p of kidsOf(f, 'pad')) {
507
+ const [, name, kind, shape] = p, pa = kidOf(p, 'at'), sz = kidOf(p, 'size'), drill = kidOf(p, 'drill');
508
+ if (kind === 'np_thru_hole') { own.push({ x: r4(bottom ? -num(pa[1]) : num(pa[1])), y: r4(-num(pa[2])), d: num(drill[1]), at: place(num(pa[1]), num(pa[2])) }); continue; }
509
+ if (!name) continue; // unnamed pads are mechanical: no net
510
+ // A pad's place in the part's frame, y up, seen from the side the part is on: (x, -y) on top; a part on the back
511
+ // is stored mirrored by KiCad, and turned the other way, so (-x, -y) with the turn negated (see rotation below)
512
+ const px = num(pa[1]), py = num(pa[2]), angle = turnOf((num(pa[3] || 0) - deg) * (bottom ? -1 : 1));
513
+ const pad = { pin: name, x: r4(bottom ? -px : px), y: r4(-py), w: num(sz[1]), h: num(sz[2]), angle, smd: kind === 'smd', shape, net: kidOf(p, 'net')?.[2] || null };
514
+ const ratio = kidOf(p, 'roundrect_rratio'); // rounded corners, as a share of the shorter side
515
+ if (shape === 'roundrect' && ratio) pad.corner = r4(num(ratio[1]) * Math.min(pad.w, pad.h));
516
+ if (drill) {
517
+ const d = drill.slice(1), oval = d[0] === 'oval', ds = d.filter((x) => !Array.isArray(x) && x !== 'oval').map(num), off = kidOf(drill, 'offset');
518
+ pad.hole = Math.min(...ds);
519
+ if (oval && ds.length > 1 && ds[0] !== ds[1]) pad.hole_size = [ds[0], ds[1]];
520
+ if (off && (num(off[1]) || num(off[2]))) { // KiCad drills at the pad's position and moves its copper by the offset (turned with the pad)
521
+ const t = ((num(pa[3] || 0) - deg) * Math.PI) / 180, ox = num(off[1]), oy = -num(off[2]); // y up
522
+ const o = [(ox * Math.cos(t) - oy * Math.sin(t)) * (bottom ? -1 : 1), ox * Math.sin(t) + oy * Math.cos(t)];
523
+ pad.x = r4(pad.x + o[0]); pad.y = r4(pad.y + o[1]); pad.hole_offset = [r4(-o[0]), r4(-o[1])]; // the copper's centre, and the hole from it
524
+ }
525
+ }
526
+ if (p.some((x) => Array.isArray(x) && x[0] === 'property' && x[1] === 'pad_prop_castellated')) pad.castellated = true;
527
+ pads.push(pad);
528
+ }
529
+ if (!pads.length) { holes.push(...own.map((h) => ({ ...h.at, d: h.d }))); continue; } // a mounting hole (a board's), a logo: nothing to connect
530
+ const attr = kidOf(f, 'attr') || []; // parts the source keeps off its BOM and placement files (edge pads, test points)
531
+ const m3 = kidOf(f, 'model'), xyz = (k) => { const v = kidOf(kidOf(m3, k) || [], 'xyz'); return v ? v.slice(1).map(Number) : null; };
532
+ const model = m3 && { path: m3[1], offset: xyz('offset') || [0, 0, 0], scale: xyz('scale') || [1, 1, 1], rotate: xyz('rotate') || [0, 0, 0] }; // its 3D model, as KiCad finds it
533
+ raw.push({ ref, footprint: f[1], value: props.Value, mpn: props.MPN ?? props['Manufacturer Part Number'], lcsc: props.LCSC, x: fx, y: fy, rotation: turnOf(bottom ? -deg : deg), layer: bottom ? 'bottom' : 'top', pads,
534
+ ...(model ? { model } : {}), ...(attr.includes('exclude_from_bom') ? { bom: false } : {}), ...(attr.includes('exclude_from_pos_files') ? { place: false } : {}),
535
+ ...(own.length ? { holes: own.map(({ at, ...h }) => h) } : {}) });
536
+ }
537
+ // The outline: the loops on Edge.Cuts, the biggest outside (counter-clockwise, y up); without one closed loop, its bounds
538
+ const found = loops(pieces);
539
+ const all = pieces.flatMap((p) => [p.a, p.b]);
540
+ if (!all.length) throw new Error('no board outline: nothing is drawn on Edge.Cuts');
541
+ const xs = all.map((p) => p.x), ys = all.map((p) => p.y), cx = (Math.min(...xs) + Math.max(...xs)) / 2, cy = (Math.min(...ys) + Math.max(...ys)) / 2;
542
+ const to = (p) => ({ x: r4(p.x - cx), y: r4(cy - p.y) }); // into the circuit's frame: centred, y up
543
+ let outline = null, cutouts = [];
544
+ if (found) {
545
+ const shapes = found.map((l) => l.map(to)).map((l) => (area(l) < 0 ? l.reverse() : l)).sort((a, b) => area(b) - area(a));
546
+ [outline, ...cutouts] = shapes;
547
+ }
548
+ const parts = raw.map((p) => ({ ...p, ...to(p) }));
549
+ const nets = {};
550
+ for (const p of parts) for (const q of p.pads) if (q.net) (nets[q.net] ||= new Set()).add(`${p.ref}.${q.pin}`);
551
+ const planes = {};
552
+ for (const z of kidsOf(root, 'zone')) {
553
+ const net = kidOf(z, 'net_name')?.[1], on = [...(kidOf(z, 'layers')?.slice(1) || []), ...(kidOf(z, 'layer') ? [kidOf(z, 'layer')[1]] : [])];
554
+ if (net) planes[net] = [...new Set([...(planes[net] || []), ...on])];
555
+ }
556
+ return {
557
+ layers: layers.length, copper: layers, width: r4(Math.max(...xs) - Math.min(...xs)), height: r4(Math.max(...ys) - Math.min(...ys)),
558
+ thickness: num(kidOf(kidOf(root, 'general') || [], 'thickness')?.[1]) || null,
559
+ outline, cutouts, parts,
560
+ nets: Object.fromEntries(Object.entries(nets).filter(([, s]) => s.size > 1).map(([k, s]) => [k, [...s]])),
561
+ planes, holes: holes.map((h) => ({ ...to(h), d: h.d })),
562
+ routing: sourceCopper(root, to),
563
+ source: { generator: kidOf(root, 'generator')?.[1], version: kidOf(root, 'version')?.[1], tracks: kidsOf(root, 'segment').length + kidsOf(root, 'arc').length, vias: kidsOf(root, 'via').length,
564
+ ...commonest(root) }
565
+ };
566
+ }
567
+
568
+ /**
569
+ * A circuit's parts and nets (fromKicadPcb's, kept in a rule set) for a board, each part where the source put it: put
570
+ * them in board.parts and board.nets. o.planes: nets left out of the routing, for planes to join (default: the nets
571
+ * the source fills on inner layers, when it has them). o.layers: the board's copper layers (default the source's): on 4
572
+ * or more, those nets get planes on inner layers (board.planes). Returns { parts, nets, planes, holes, outline, layers,
573
+ * copper (the source's routing kept with moveGroup), via_pad, via_hole, plane_clearance (the source's), notes }: notes say what this board does with them, and what it can't carry yet (slots are drilled round).
574
+ * @param {object} circuit @param {{ planes?: string[], layers?: number }} [o]
575
+ */
576
+ export function clone(circuit, o = {}) {
577
+ const inner = (l) => /^In\d+\.Cu$/.test(l), layers = o.layers ?? circuit.layers ?? 2;
578
+ const planes = o.planes ?? Object.entries(circuit.planes || {}).filter(([, ls]) => ls.some(inner)).map(([n]) => n);
579
+ const notes = [], castellated = new Set(), oval = new Set();
580
+ const parts = circuit.parts.map((p) => {
581
+ const quarterTurn = p.rotation % 90 === 0, t = (p.rotation * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
582
+ const pads = p.pads.map((q) => {
583
+ const pin = `pin${q.pin}`;
584
+ if (!q.smd) {
585
+ const at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
586
+ if (q.castellated) { castellated.add(p.ref); return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(q.w, q.h), castellated: true }; }
587
+ if (q.hole_size) oval.add(p.ref); // a slot: drilled round, at its narrow width
588
+ if (q.w === q.h && !q.hole_offset) return { pin, hint: q.pin, ...at, hole: q.hole, outer: q.w };
589
+ // an oval pad, or a hole off its centre: a rounded rectangle round the hole, turned with the part (quarter turns)
590
+ const sw = (q.angle + (quarterTurn ? 0 : p.rotation)) % 180 === 90, w = sw ? q.h : q.w, h = sw ? q.w : q.h;
591
+ return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(w, h), rect: { w, h, offset: q.hole_offset || [0, 0] } };
592
+ }
593
+ const turn = q.angle + (quarterTurn ? 0 : p.rotation);
594
+ if (turn % 90 === 0) { // a rectangle, its sides swapped by a quarter turn of its own
595
+ const sw = turn % 180 !== 0, at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
596
+ return { pin, smd: true, hint: q.pin, ...at, w: sw ? q.h : q.w, h: sw ? q.w : q.h, ...(q.shape === 'circle' && q.w === q.h ? { circle: true } : {}), ...(q.corner ? { corner: q.corner } : {}) };
597
+ }
598
+ const a = (turn * Math.PI) / 180, ca = Math.cos(a), sa = Math.sin(a), at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
599
+ const pts = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([u, v]) => [r4(at.x + (u * q.w / 2) * ca - (v * q.h / 2) * sa), r4(at.y + (u * q.w / 2) * sa + (v * q.h / 2) * ca)]);
600
+ return { pin, smd: true, hint: q.pin, ...at, points: pts }; // corners relative to the part, as circuit.mjs takes them
601
+ });
602
+ const holes = (p.holes || []).map((h) => (quarterTurn ? h : { ...h, x: h.x * c - h.y * s, y: h.x * s + h.y * c }));
603
+ return { name: p.ref, ftype: 'simple_chip', x: p.x, y: p.y, layer: p.layer, rotation: quarterTurn ? p.rotation : 0, mpn: p.mpn, lcsc: p.lcsc, value: p.value, ...(p.bom === false ? { bom: false } : {}), ...(p.place === false ? { place: false } : {}), ...(holes.length ? { holes } : {}),
604
+ ...(p.model && circuit.models?.[p.model.path] ? { model: { ...p.model, ...circuit.models[p.model.path], turn: quarterTurn ? 0 : p.rotation } } : {}), courtyard: null, pads }; // no sch: laid out on the schematic in rows, each pin labelled with its net
605
+ }).filter((p) => p.pads.length);
606
+ const have = new Set(parts.flatMap((p) => p.pads.map((q) => `${p.name}.${q.pin}`))), dropped = new Set();
607
+ const nets = Object.fromEntries(Object.entries(circuit.nets).filter(([n]) => !planes.includes(n))
608
+ .map(([n, pins]) => [n, pins.map((x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; })
609
+ .filter((x) => have.has(x) || !dropped.add(x))]).filter(([, pins]) => pins.length > 1));
610
+ const plural = (set, one, many) => `${set.size} ${set.size === 1 ? one : many} (${[...set].join(', ')})`;
611
+ // On 4 layers or more, each plane net fills the inner layer the source gives it (the first, if several), or the next free one
612
+ const onPlanes = {}, free = Array.from({ length: Math.max(0, layers - 2) }, (_, i) => `inner${i + 1}`);
613
+ if (layers >= 4) for (const n of planes) {
614
+ const own = (circuit.planes?.[n] || []).find(inner), want = own ? `inner${own.match(/\d+/)[0]}` : null;
615
+ const layer = want && free.includes(want) ? want : free[0];
616
+ if (!layer) { notes.push(`${n}: no inner layer left for its plane`); continue; }
617
+ free.splice(free.indexOf(layer), 1);
618
+ onPlanes[n] = { layer, pins: (circuit.nets[n] || []).map((x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; }).filter((x) => have.has(x)) };
619
+ }
620
+ if (layers >= 4 && Object.keys(onPlanes).length) notes.push(`planes on inner layers: ${Object.entries(onPlanes).map(([n, q]) => `${n} on ${q.layer} (${q.pins.length} pads)`).join(', ')}`);
621
+ else if (planes.length) notes.push(`left to planes, not routed: ${planes.map((n) => `${n} (${circuit.nets[n]?.length ?? 0} pads)`).join(', ')}. On 2 layers these nets need a pour joined to every pad: build the board with 4 layers ({ layers: 4 }) to give them planes`);
622
+ if (castellated.size) notes.push(`castellated pads on ${plural(castellated, 'part', 'parts')}: half holes on the board's edge, which the fab cuts through (an option when ordering)`);
623
+ if (oval.size) notes.push(`slots drilled round, at their narrow width, on ${plural(oval, 'part', 'parts')}`);
624
+ if (dropped.size) notes.push(`${dropped.size} pins with no pad left on this board are out of their nets: ${[...dropped].slice(0, 5).join(', ')}`);
625
+ const src = circuit.source || {}; // the source's via and clearance, which its layout was made to
626
+ const sizes = { ...(src.via ? { via_pad: src.via.pad, via_hole: src.via.hole } : {}), ...(src.clearance ? { plane_clearance: src.clearance } : {}) };
627
+ // The source's own copper kept with a moved block, its pins named as the board names them
628
+ const named = (x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; };
629
+ const copper = circuit.kept?.islands.length ? { ...circuit.kept, islands: circuit.kept.islands.map((k) => ({ ...k, pins: k.pins.map(named) })),
630
+ stubs: (circuit.kept.stubs || []).map((b) => ({ ...b, pin: named(b.pin) })) } : null;
631
+ if (copper) notes.push(`the source's own routing kept: ${copper.tracks.length} tracks and ${copper.vias.length} vias in ${copper.islands.length} pieces, and ${copper.stubs.length} escapes routed on from where they leave`);
632
+ return { parts, nets, holes: circuit.holes, outline: circuit.outline, layers, ...(Object.keys(onPlanes).length ? { planes: onPlanes } : {}), ...(copper ? { copper } : {}), ...sizes, notes };
633
+ }
634
+
635
+ // A part's pads on the board (the circuit's frame), as render places them: turned, and mirrored in x on the back
636
+ export function padsOnBoard(part) {
637
+ const m = part.layer === 'bottom' ? -1 : 1, t = (part.rotation * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
638
+ return part.pads.map((q) => ({ ...q, bx: r4(part.x + m * (c * q.x - s * q.y)), by: r4(part.y + (s * q.x + c * q.y)) }));
639
+ }
640
+
641
+ /**
642
+ * The circuit with one part on a new footprint: the same pins, so the same nets, with pads where you put them (each
643
+ * { pin, x, y, w, h, angle, smd, hole, ... } as fromKicadPcb gives them, in the part's frame). Every pin the part had must
644
+ * have a pad, and no other: its circuit can't change, only its shape. Returns a new circuit.
645
+ * @param {object} circuit @param {string} ref @param {object[]} pads
646
+ */
647
+ export function withFootprint(circuit, ref, pads) {
648
+ const part = circuit.parts.find((p) => p.ref === ref);
649
+ if (!part) throw new Error(`withFootprint: no part ${ref} in the circuit`);
650
+ const had = new Map(part.pads.map((q) => [q.pin, q.net])), given = new Set(pads.map((q) => q.pin));
651
+ const missing = [...had.keys()].filter((n) => !given.has(n)), extra = [...given].filter((n) => !had.has(n));
652
+ if (missing.length || extra.length) throw new Error(`withFootprint: ${ref}'s new pads must have the same pins as before${missing.length ? `; missing ${missing.join(', ')}` : ''}${extra.length ? `; not on ${ref}: ${extra.join(', ')}` : ''}`);
653
+ return { ...circuit, parts: circuit.parts.map((p) => (p.ref === ref ? { ...p, footprint: `${p.footprint} (reshaped)`, pads: pads.map((q) => ({ angle: 0, smd: false, shape: 'circle', ...q, net: had.get(q.pin) })) } : p)) };
654
+ }
655
+
656
+ /**
657
+ * New pins on a clone's part, declared: each pad { pin, net, ...pad } joins an existing net of the source (a reset line
658
+ * from a test point to the edge), or with `joins: ['U3.13']` a new net to pins the source leaves unconnected (a spare
659
+ * GPIO brought out). The circuit is then the source's plus these; `added` lists them, and sameCircuit (given them)
660
+ * checks the rest is unchanged and names each one. @param {object} circuit @param {string} ref @param {object[]} pads
661
+ */
662
+ export function addPins(circuit, ref, pads) {
663
+ const part = circuit.parts.find((p) => p.ref === ref);
664
+ if (!part) throw new Error(`addPins: no part ${ref} in the circuit`);
665
+ const have = new Set(part.pads.map((q) => q.pin)), nets = { ...circuit.nets }, added = [...(circuit.added || [])];
666
+ for (const q of pads) {
667
+ if (have.has(q.pin)) throw new Error(`addPins: ${ref} already has a pin ${q.pin}`);
668
+ if (!q.joins && !nets[q.net]) throw new Error(`addPins: no net ${q.net} in the source (give joins: [...] for a new net)`);
669
+ if (q.joins) for (const x of q.joins) { const owner = Object.entries(nets).find(([, n]) => n.includes(x)); if (owner) throw new Error(`addPins: ${x} is already on ${owner[0]}`); }
670
+ nets[q.net] = [...(nets[q.net] || q.joins), `${ref}.${q.pin}`];
671
+ added.push({ pin: `${ref}.${q.pin}`, net: q.net, ...(q.joins ? { joins: q.joins } : {}) });
672
+ }
673
+ const extra = pads.map(({ joins, ...q }) => ({ angle: 0, smd: false, shape: 'circle', ...q }));
674
+ return { ...circuit, nets, added, parts: circuit.parts.map((p) => (p.ref === ref ? { ...p, pads: [...p.pads, ...extra] } : p)) };
675
+ }
676
+
677
+ /**
678
+ * Silkscreen labels moved clear of copper and of each other: each slides across its reading direction (a level label up
679
+ * or down, a turned one left or right), a step at a time up to reach, to the nearest place clear of every pad by gap. A
680
+ * label with nowhere clear stays put, marked clash: true. The fab trims silkscreen off copper, so a label on a pad loses
681
+ * letters. A label with `to: { x, y }` (or a list of such, to choose from) points at it: it goes to the nearest place
682
+ * to where it's asked for (within `near` mm) that is clear of pads, of surface-mount parts' bodies and of other labels,
683
+ * inside `area` ({ minX, maxX, minY, maxY }), with a small triangle beside it pointing at the spot: for a pin with no
684
+ * room for its label beside it.
685
+ * o: { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75 (a character's width over its height), area, near = 6 }.
686
+ * @param {object[]} silk { text, x, y, size, rotation, to } @param {object} circuit @param {object} [o]
687
+ */
688
+ export function clearLabels(silk, circuit, { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75, area = null, near = 6 } = {}) {
689
+ const padBoxes = (p) => padsOnBoard(p).map((q) => { const t = turnOf(p.rotation + q.angle) % 180 === 90; return { x: q.bx, y: q.by, w: t ? q.h : q.w, h: t ? q.w : q.h }; });
690
+ const copper = circuit.parts.flatMap((p) => [...padBoxes(p),
691
+ ...padsOnBoard({ ...p, pads: (p.holes || []).map((h) => ({ ...h, w: h.d, h: h.d, angle: 0 })) }).map((h) => ({ x: h.bx, y: h.by, w: h.w, h: h.h }))]);
692
+ // A surface-mount part's body spans its pads: a label with an arrow keeps off it (the part would hide it)
693
+ const bodies = circuit.parts.filter((p) => p.pads.length > 1 && p.pads.every((q) => q.smd)).map((p) => {
694
+ const b = padBoxes(p), x0 = Math.min(...b.map((q) => q.x - q.w / 2)), x1 = Math.max(...b.map((q) => q.x + q.w / 2)), y0 = Math.min(...b.map((q) => q.y - q.h / 2)), y1 = Math.max(...b.map((q) => q.y + q.h / 2));
695
+ return { x: (x0 + x1) / 2, y: (y0 + y1) / 2, w: x1 - x0, h: y1 - y0 };
696
+ });
697
+ return slideClear(silk, copper, { reach, step, gap, char, bodies, area, near });
698
+ }
699
+
700
+ /**
701
+ * Placement rules learnt from the source: each small part (fewer than 4 pads: resistors, capacitors, LEDs) stays near
702
+ * the pad of a bigger part (an anchor: a chip, a connector, a crystal) on its most particular net (the one joining the
703
+ * fewest pins), the nearest such pad on the source board: a decoupling capacitor by its power pin, a crystal's capacitors by the crystal. Each rule:
704
+ * { part, anchor, pin, net, source (mm, pad centre to pad centre on the source), max (mm) }. max allows a quarter more,
705
+ * and at least 0.5 mm: edit it in the rule set to be stricter or freer. o.anchor: the fewest pads an anchor has (4).
706
+ * @param {object} circuit @param {{ anchor?: number }} [o] @returns {object[]}
707
+ */
708
+ export function learnPlacement(circuit, o = {}) {
709
+ const min = o.anchor ?? 4, anchors = circuit.parts.filter((p) => p.pads.length >= min), rules = [];
710
+ const anchorPads = anchors.flatMap((a) => padsOnBoard(a).filter((q) => q.net).map((q) => ({ ...q, ref: a.ref })));
711
+ for (const p of circuit.parts.filter((x) => x.pads.length < min)) {
712
+ let best = null; // on its most particular net (the fewest pins: a crystal's pin before GND), then the nearest pad
713
+ for (const q of padsOnBoard(p)) for (const a of anchorPads) {
714
+ if (!q.net || a.net !== q.net) continue;
715
+ const d = Math.hypot(a.bx - q.bx, a.by - q.by), n = circuit.nets[q.net]?.length ?? Infinity;
716
+ if (!best || n < best.n || (n === best.n && d < best.d)) best = { d, n, q, a };
717
+ }
718
+ if (best) rules.push({ part: p.ref, anchor: best.a.ref, pin: best.a.pin, net: best.q.net, source: r4(best.d), max: r4(Math.max(best.d * 1.25, best.d + 0.5)) });
719
+ }
720
+ return rules;
721
+ }
722
+
723
+ /**
724
+ * The circuit with some parts moved, each small part going with the anchor its placement rule names (turned with it,
725
+ * kept the same way round): moves { U3: { x, y, rotation } } (any of the three; rotation in quarter turns from above).
726
+ * Parts not moved, and not following a moved anchor, stay where the source put them. Returns a new circuit.
727
+ * @param {object} circuit @param {Record<string, { x?: number, y?: number, rotation?: number }>} moves @param {object[]} [rules]
728
+ */
729
+ export function arrange(circuit, moves, rules = circuit.placement || learnPlacement(circuit)) {
730
+ const byRef = new Map(circuit.parts.map((p) => [p.ref, p])), follow = new Map(rules.map((r) => [r.part, r.anchor]));
731
+ for (const ref of Object.keys(moves)) if (!byRef.has(ref)) throw new Error(`arrange: no part ${ref} in the circuit`);
732
+ const moved = (p) => {
733
+ const to = moves[p.ref];
734
+ if (to) { const dr = ((to.rotation ?? p.rotation) - p.rotation + 360) % 360; return { ...p, x: to.x ?? p.x, y: to.y ?? p.y, rotation: (to.rotation ?? p.rotation) % 360, dr }; }
735
+ const a = follow.has(p.ref) && !moves[p.ref] ? byRef.get(follow.get(p.ref)) : null, at = a && moves[a.ref];
736
+ if (!at) return p;
737
+ const turn = ((at.rotation ?? a.rotation) - a.rotation + 360) % 360, t = (turn * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
738
+ const dx = p.x - a.x, dy = p.y - a.y, own = p.layer === a.layer ? turn : -turn; // a part on the other side turns the other way, seen from its side
739
+ return { ...p, x: r4((at.x ?? a.x) + c * dx - s * dy), y: r4((at.y ?? a.y) + s * dx + c * dy), rotation: turnOf(p.rotation + own) };
740
+ };
741
+ const parts = circuit.parts.map(moved).map(({ dr, ...p }) => p);
742
+ const shifted = new Set(parts.filter((p, i) => p.x !== circuit.parts[i].x || p.y !== circuit.parts[i].y || p.rotation !== circuit.parts[i].rotation).map((p) => p.ref)); // a kept island to a part that moved apart is left to routing
743
+ const kept = circuit.kept && { ...circuit.kept, islands: circuit.kept.islands.filter((k) => !k.pins.some((x) => shifted.has(x.split('.')[0]))) };
744
+ if (kept) {
745
+ kept.stubs = (kept.stubs || []).filter((b) => !shifted.has(b.pin.split('.')[0]));
746
+ const ids = new Set([...kept.islands.map((k) => k.id), ...kept.stubs.map((b) => b.id)]);
747
+ kept.tracks = kept.tracks.filter((g) => ids.has(g.island ?? g.stub)); kept.vias = kept.vias.filter((v) => ids.has(v.island ?? v.stub));
748
+ }
749
+ return { ...circuit, ...(kept ? { kept } : {}), parts };
750
+ }
751
+
752
+ /**
753
+ * The circuit with a group of parts moved as one block, every part keeping its place relative to the others: turned
754
+ * about the origin by turn (quarter turns, counter-clockwise from above), then moved by dx, dy. For keeping a source's
755
+ * proven layout of a whole area (a chip with all its small parts) while the board around it changes. With { keep: true }
756
+ * the source's tracks and vias that join only these parts' pads come too (circuit.kept, which clone() hands the board):
757
+ * that area's routing is the source's, proven, and only the connections leaving it are routed. Returns a new circuit.
758
+ * @param {object} circuit @param {string[]} refs @param {{ turn?: number, dx?: number, dy?: number }} move @param {{ keep?: boolean }} [o]
759
+ */
760
+ export function moveGroup(circuit, refs, { turn = 0, dx = 0, dy = 0 } = {}, { keep = false } = {}) {
761
+ const set = new Set(refs), missing = refs.filter((r) => !circuit.parts.some((p) => p.ref === r));
762
+ if (missing.length) throw new Error(`moveGroup: no part ${missing.join(', ')} in the circuit`);
763
+ if (turn % 90) throw new Error(`moveGroup: turn in quarter turns (0, 90, 180, 270), not ${turn}`);
764
+ const t = (turn * Math.PI) / 180, c = Math.round(Math.cos(t)), s = Math.round(Math.sin(t));
765
+ const at = ({ x, y }) => ({ x: r4(c * x - s * y + dx), y: r4(s * x + c * y + dy) });
766
+ let kept = circuit.kept;
767
+ if (keep) { // the source's copper wholly within the group, moved with it
768
+ if (!circuit.routing) throw new Error('moveGroup: keep needs the source\'s tracks (circuit.routing, from fromKicadPcb)');
769
+ const k = islands(circuit, set);
770
+ kept = { tracks: [...(kept?.tracks || []), ...k.tracks.map((g) => ({ ...g, a: at(g.a), b: at(g.b) }))],
771
+ vias: [...(kept?.vias || []), ...k.vias.map((v) => ({ ...v, ...at(v) }))], islands: [...(kept?.islands || []), ...k.islands],
772
+ stubs: [...(kept?.stubs || []), ...k.stubs.map((b) => ({ ...b, end: { ...b.end, ...at(b.end) } }))] };
773
+ }
774
+ return { ...circuit, ...(kept ? { kept } : {}), parts: circuit.parts.map((p) => (!set.has(p.ref) ? p : {
775
+ ...p, ...at(p), rotation: turnOf(p.rotation + (p.layer === 'bottom' ? -turn : turn))
776
+ })) };
777
+ }
778
+
779
+ // The source's copper in islands: tracks and vias joined end to end, through a via, or by touching a pad of their net.
780
+ // Returns the islands that touch only pads of the given parts (at least one): { tracks, vias, islands: [{ id, net,
781
+ // pins, via }] }, each track and via carrying its island's id. Islands touching any other part, or no pad, are left.
782
+ function islands(circuit, refs) {
783
+ const { tracks, vias } = circuit.routing, near = 0.01;
784
+ const pads = circuit.parts.flatMap((p) => padsOnBoard(p).map((q) => {
785
+ const turned = turnOf(p.rotation + q.angle) % 180 === 90;
786
+ return { ref: p.ref, pin: q.pin, net: q.net, x: q.bx, y: q.by, w: turned ? q.h : q.w, h: turned ? q.w : q.h, layer: q.smd ? p.layer : null };
787
+ }));
788
+ const onSeg = (pt, g) => { const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y, l = dx * dx + dy * dy, u = l ? Math.max(0, Math.min(1, ((pt.x - g.a.x) * dx + (pt.y - g.a.y) * dy) / l)) : 0; return Math.hypot(pt.x - g.a.x - u * dx, pt.y - g.a.y - u * dy) <= near; };
789
+ // copper touching copper: a track's end within half its width of the pad (as KiCad joins them), a via within its radius
790
+ const inPad = (pt, q, layer, reach = 0) => (!q.layer || !layer || q.layer === layer) && Math.abs(pt.x - q.x) <= q.w / 2 + reach + near && Math.abs(pt.y - q.y) <= q.h / 2 + reach + near;
791
+ const nodes = [...tracks.map((g, i) => ({ kind: 't', i, g, net: g.net })), ...vias.map((v, i) => ({ kind: 'v', i, v, net: v.net }))];
792
+ const adj = nodes.map(() => []), up = nodes.map((_, i) => i), find = (i) => { while (up[i] !== i) i = up[i] = up[up[i]]; return i; }, join = (i, j) => { up[find(i)] = find(j); };
793
+ const byNet = new Map(); nodes.forEach((n, i) => byNet.set(n.net, [...(byNet.get(n.net) || []), i]));
794
+ for (const list of byNet.values()) for (let x = 0; x < list.length; x++) for (let y = x + 1; y < list.length; y++) {
795
+ const A = nodes[list[x]], B = nodes[list[y]];
796
+ const touch = A.kind === 't' && B.kind === 't' ? A.g.layer === B.g.layer && (onSeg(A.g.a, B.g) || onSeg(A.g.b, B.g) || onSeg(B.g.a, A.g) || onSeg(B.g.b, A.g))
797
+ : A.kind === 'v' && B.kind === 'v' ? Math.hypot(A.v.x - B.v.x, A.v.y - B.v.y) <= (A.v.pad + B.v.pad) / 2
798
+ : (() => { const [t, v] = A.kind === 't' ? [A.g, B.v] : [B.g, A.v]; return Math.hypot(t.a.x - v.x, t.a.y - v.y) <= v.pad / 2 + near || Math.hypot(t.b.x - v.x, t.b.y - v.y) <= v.pad / 2 + near; })();
799
+ if (touch) { join(list[x], list[y]); adj[list[x]].push(list[y]); adj[list[y]].push(list[x]); }
800
+ }
801
+ const touched = new Map(); // island root -> pads it touches
802
+ nodes.forEach((n, i) => {
803
+ const hit = pads.filter((q) => q.net === n.net && (n.kind === 't' ? inPad(n.g.a, q, n.g.layer, n.g.width / 2) || inPad(n.g.b, q, n.g.layer, n.g.width / 2) : inPad(n.v, q, null, n.v.pad / 2)));
804
+ const r = find(i); touched.set(r, [...(touched.get(r) || []), ...hit]);
805
+ });
806
+ const keep = new Map(); // root -> island
807
+ for (const [r, hit] of touched) if (hit.length && hit.every((q) => refs.has(q.ref)))
808
+ keep.set(r, { id: `island${keep.size + 1}`, net: nodes[r].net, pins: [...new Set(hit.map((q) => `${q.ref}.${q.pin}`))], via: false });
809
+ // A kept piece's dead ends (a branch that led somewhere left behind): trimmed, track by track
810
+ const dead = new Set(), ends = (i) => { const g = nodes[i].g; return [g.a, g.b]; };
811
+ for (let again = true; again;) {
812
+ again = false;
813
+ nodes.forEach((n, i) => {
814
+ if (n.kind !== 't' || dead.has(i) || !keep.has(find(i))) return;
815
+ const free = ends(i).some((pt) => !pads.some((q) => q.net === n.net && inPad(pt, q, n.g.layer, n.g.width / 2))
816
+ && !adj[i].some((j) => !dead.has(j) && (nodes[j].kind === 'v' ? Math.hypot(pt.x - nodes[j].v.x, pt.y - nodes[j].v.y) <= nodes[j].v.pad / 2 + near : onSeg(pt, nodes[j].g) || [nodes[j].g.a, nodes[j].g.b].some((e) => Math.hypot(e.x - pt.x, e.y - pt.y) <= near))));
817
+ if (free) { dead.add(i); again = true; }
818
+ });
819
+ }
820
+ // A track's end that stops just short of its pad (its copper overlapping it, as KiCad joins them) is moved onto the pad
821
+ const onto = (pt, net, layer, reach) => { const q = pads.find((d) => d.net === net && inPad(pt, d, layer, reach) && !inPad(pt, d, layer));
822
+ return q ? { x: r4(Math.min(Math.max(pt.x, q.x - q.w / 2 + 0.01), q.x + q.w / 2 - 0.01)), y: r4(Math.min(Math.max(pt.y, q.y - q.h / 2 + 0.01), q.y + q.h / 2 - 0.01)) } : pt; };
823
+ const snapped = (g) => ({ ...g, a: onto(g.a, g.net, g.layer, g.width / 2), b: onto(g.b, g.net, g.layer, g.width / 2) });
824
+ const out = { tracks: [], vias: [], islands: [], stubs: [] };
825
+ nodes.forEach((n, i) => { const k = keep.get(find(i)); if (!k || dead.has(i)) return; if (n.kind === 't') out.tracks.push({ ...snapped(n.g), island: k.id }); else { k.via = true; out.vias.push({ ...n.v, island: k.id }); } });
826
+ out.islands = [...keep.values()];
827
+ // Breakouts: an island from one of the block's pins out to other parts keeps its stretch within the block's bounds,
828
+ // from the pin to where it leaves (a fine-pitch chip's escape, proven); the rest is routed from the stub's end
829
+ const own = pads.filter((q) => refs.has(q.ref));
830
+ if (!own.length) return out;
831
+ const box = { x0: Math.min(...own.map((q) => q.x - q.w / 2)) - 0.3, x1: Math.max(...own.map((q) => q.x + q.w / 2)) + 0.3, y0: Math.min(...own.map((q) => q.y - q.h / 2)) - 0.3, y1: Math.max(...own.map((q) => q.y + q.h / 2)) + 0.3 };
832
+ const inBox = (pt) => pt.x >= box.x0 && pt.x <= box.x1 && pt.y >= box.y0 && pt.y <= box.y1;
833
+ const inside = (n) => (n.kind === 't' ? inBox(n.g.a) && inBox(n.g.b) : inBox(n.v));
834
+ for (const [r, hit] of touched) {
835
+ const mine = [...new Set(hit.filter((q) => refs.has(q.ref)).map((q) => `${q.ref}.${q.pin}`))];
836
+ if (keep.has(r) || mine.length !== 1 || hit.every((q) => refs.has(q.ref))) continue;
837
+ const pin = own.find((q) => `${q.ref}.${q.pin}` === mine[0]);
838
+ const touches = (n) => (n.kind === 't' ? inPad(n.g.a, pin, n.g.layer, n.g.width / 2) || inPad(n.g.b, pin, n.g.layer, n.g.width / 2) : inPad(n.v, pin, null, n.v.pad / 2));
839
+ const start = nodes.map((n, i) => i).filter((i) => find(i) === r && touches(nodes[i]));
840
+ // From the pin outward: whole pieces within the bounds, and the one track that crosses them cut where it does
841
+ const seen = new Set(), cut = [], queue = [];
842
+ const visit = (j, from) => {
843
+ if (seen.has(j)) return;
844
+ const n = nodes[j];
845
+ if (inside(n)) { seen.add(j); queue.push(j); return; }
846
+ if (n.kind !== 't') return cut.push(null); // a via outside: give up on a stub
847
+ const [p, q] = inBox(n.g.a) ? [n.g.a, n.g.b] : inBox(n.g.b) ? [n.g.b, n.g.a] : [null, null];
848
+ if (!p) return cut.push(null);
849
+ let t = 1; // where p -> q leaves the box
850
+ for (const [d, lo, hi, o] of [[q.x - p.x, box.x0, box.x1, p.x], [q.y - p.y, box.y0, box.y1, p.y]]) if (d) t = Math.min(t, ((d > 0 ? hi : lo) - o) / d);
851
+ cut.push({ g: { ...n.g, a: p, b: { x: r4(p.x + (q.x - p.x) * t), y: r4(p.y + (q.y - p.y) * t) } } });
852
+ };
853
+ for (const i of start) visit(i);
854
+ while (queue.length) { const i = queue.shift(); for (const j of adj[i]) visit(j, i); }
855
+ if (cut.length !== 1 || !cut[0]) continue; // no way out, more than one, or not a plain track: routed whole
856
+ const id = `stub${out.stubs.length + 1}`, g = cut[0].g;
857
+ out.stubs.push({ id, net: g.net, pin: mine[0], end: { x: g.b.x, y: g.b.y, layer: g.layer } });
858
+ out.tracks.push({ ...snapped(g), stub: id });
859
+ for (const i of seen) { const n = nodes[i]; if (n.kind === 't') out.tracks.push({ ...snapped(n.g), stub: id }); else out.vias.push({ ...n.v, stub: id }); }
860
+ }
861
+ return out;
862
+ }
863
+
864
+ /**
865
+ * Are the small parts still near their anchors? Findings ({ level, text }): one fail per broken rule, naming the part,
866
+ * the pin and the distances, or a pass.
867
+ * @param {object} circuit @param {object[]} [rules]
868
+ */
869
+ export function placementChecks(circuit, rules = circuit.placement || learnPlacement(circuit)) {
870
+ const byRef = new Map(circuit.parts.map((p) => [p.ref, p])), out = [];
871
+ for (const r of rules) {
872
+ const p = byRef.get(r.part), a = byRef.get(r.anchor);
873
+ if (!p || !a) { out.push({ level: 'fail', text: `placement: ${!p ? r.part : r.anchor} isn't on the board` }); continue; }
874
+ const pin = padsOnBoard(a).filter((q) => q.pin === r.pin), mine = padsOnBoard(p).filter((q) => q.net === r.net);
875
+ const d = Math.min(...mine.flatMap((q) => pin.map((x) => Math.hypot(x.bx - q.bx, x.by - q.by))));
876
+ if (!(d <= r.max + 1e-6)) out.push({ level: 'fail', text: `placement: ${r.part} is ${mm(d)} mm from ${r.anchor} pin ${r.pin} (${r.net}): at most ${mm(r.max)} (${mm(r.source)} on the source)` });
877
+ }
878
+ if (!out.length) out.push({ level: 'pass', text: `placement: all ${rules.length} small parts within reach of their anchors, as the source has them` });
879
+ return out;
880
+ }
881
+
882
+ /**
883
+ * Does the board join exactly the pins the circuit joins? Each of the circuit's nets (but planes) must be one group of
884
+ * pins on the board, with no other net's pins in it. Findings as checks() gives them ({ level, text }).
885
+ * @param {object[]} json Circuit JSON (render's) @param {object} circuit @param {{ planes?: string[] }} [o]
886
+ */
887
+ export function sameCircuit(json, circuit, o = {}, added = []) {
888
+ const onBoard = new Set(json.filter((e) => e.type === 'source_net').map((e) => e.name)); // nets the board has planes for
889
+ const left = { ...clone(circuit, o).nets }, all = { ...circuit.nets };
890
+ for (const a of added) { if (!all[a.net]) left[a.net] = true; all[a.net] = [...(all[a.net] || a.joins), a.pin]; } // declared new pins: expected too
891
+ const nets = Object.fromEntries(Object.entries(all).filter(([n]) => left[n] || onBoard.has(n))
892
+ .map(([n, pins]) => [n, pins.map((x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; })]));
893
+ const up = new Map(), find = (a) => { while (up.get(a) !== a) a = up.get(a); return a; };
894
+ const join = (a, b) => { up.set(find(a), find(b)); };
895
+ const comp = new Map(json.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e]));
896
+ const name = new Map(json.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, `${comp.get(e.source_component_id)?.name}.${e.name}`]));
897
+ for (const id of name.keys()) up.set(id, id);
898
+ for (const c of comp.values()) for (const g of c.internally_connected_source_port_ids || []) g.forEach((id) => join(id, g[0]));
899
+ for (const t of json.filter((e) => e.type === 'source_trace')) {
900
+ t.connected_source_port_ids.forEach((id) => join(id, t.connected_source_port_ids[0]));
901
+ for (const n of t.connected_source_net_ids || []) { if (!up.has(n)) up.set(n, n); join(t.connected_source_port_ids[0], n); } // a pad joined to a plane
902
+ }
903
+ const group = new Map(); // pin name -> group
904
+ for (const [id, n] of name) group.set(n, find(id));
905
+ for (const [n, pins] of Object.entries(nets)) if (!left[n]) nets[n] = pins.filter((p) => group.has(p)); // a pin with no pad here (castellated): out of its plane too
906
+ const out = [], missing = [], split = [], shorted = [];
907
+ const owner = new Map(); // group -> net
908
+ for (const [net, pins] of Object.entries(nets)) {
909
+ const gs = new Set(pins.map((p) => group.get(p)));
910
+ if (gs.has(undefined)) { missing.push(`${net}: ${pins.filter((p) => !group.has(p)).join(', ')}`); continue; }
911
+ if (gs.size > 1) split.push(net);
912
+ for (const g of gs) { if (owner.has(g) && owner.get(g) !== net) shorted.push(`${owner.get(g)} and ${net}`); owner.set(g, net); }
913
+ }
914
+ const extra = []; // board pins in a net's group that the source doesn't put in that net
915
+ for (const [pin, g] of group) { const net = owner.get(g); if (net && !nets[net].includes(pin)) extra.push(`${pin} in ${net}`); }
916
+ if (extra.length) out.push({ level: 'fail', text: `${extra.length} pins joined to nets the source leaves them out of: ${extra.slice(0, 5).join(', ')}` });
917
+ const n = Object.keys(nets).length;
918
+ if (missing.length) out.push({ level: 'fail', text: `${missing.length} nets name pins the board doesn't have: ${missing.slice(0, 3).join('; ')}` });
919
+ if (split.length) out.push({ level: 'fail', text: `${split.length} nets are split in two or more on the board: ${split.slice(0, 5).join(', ')}` });
920
+ if (shorted.length) out.push({ level: 'fail', text: `nets joined that the source keeps apart: ${[...new Set(shorted)].slice(0, 5).join('; ')}` });
921
+ if (!out.length) out.push({ level: 'pass', text: `same circuit as the source: all ${n} nets join the same pins, and no others${Object.keys(all).length > n ? ` (${Object.keys(all).length - n} left to planes)` : ''}${added.length ? `, plus ${added.length} pins added: ${added.map((a) => `${a.pin} (${a.net.replace(/^\//, '')})`).join(', ')}` : ''}` });
922
+ return out;
923
+ }
924
+
925
+ // ---------- 3D models of parts ----------
926
+ /**
927
+ * A VRML model (KiCad's .wrl) as triangles, in mm: [[x, y, z] x3, ...]. KiCad's models are in tenths of an inch, z up
928
+ * out of the board, x and y as the footprint's (y towards its top). Faces with more than three corners are fanned.
929
+ * @param {string} text @param {number} [unit] mm per model unit (KiCad's: 2.54) @returns {number[][][]}
930
+ */
931
+ export function wrlMesh(text, unit = 2.54) {
932
+ const out = [];
933
+ for (const m of text.matchAll(/coordIndex\s*\[([^\]]*)\][\s\S]*?point\s*\[([^\]]*)\]/g)) {
934
+ const pts = m[2].split(',').map((p) => p.trim().split(/\s+/).map((n) => Number(n) * unit)).filter((p) => p.length === 3 && p.every(Number.isFinite));
935
+ let face = [];
936
+ for (const n of m[1].split(',').map((x) => Number(x.trim()))) {
937
+ if (n === -1) { for (let i = 1; i + 1 < face.length; i++) out.push([pts[face[0]], pts[face[i]], pts[face[i + 1]]]); face = []; }
938
+ else if (Number.isInteger(n) && pts[n]) face.push(n);
939
+ }
940
+ }
941
+ return out;
942
+ }
943
+
944
+ /**
945
+ * A STEP model's size: the box round every point it lists ({ min: [x, y, z], max }, mm), with no geometry kernel. For a
946
+ * model whose shape can't be shared (no licence) only its size is used, which is a fact about the part.
947
+ * @param {string} text @returns {{ min: number[], max: number[] } | null}
948
+ */
949
+ export function stepBounds(text) {
950
+ const k = /SI_UNIT\s*\(\s*\.MILLI\.\s*,\s*\.METRE\.\s*\)/i.test(text) ? 1 : /INCH/i.test(text) ? 25.4 : /SI_UNIT\s*\(\s*\$\s*,\s*\.METRE\./i.test(text) ? 1000 : 1;
951
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
952
+ for (const m of text.matchAll(/CARTESIAN_POINT\s*\(\s*'[^']*'\s*,\s*\(\s*([-\d.Ee+]+)\s*,\s*([-\d.Ee+]+)\s*,\s*([-\d.Ee+]+)\s*\)/g))
953
+ for (let i = 0; i < 3; i++) { const v = Number(m[i + 1]) * k; min[i] = Math.min(min[i], v); max[i] = Math.max(max[i], v); }
954
+ return Number.isFinite(min[0]) ? { min: min.map(r4), max: max.map(r4) } : null;
955
+ }
956
+
957
+ // A box as triangles
958
+ /**
959
+ * Pin headers under a board, for its 3D model: at each hole, a square pin through the board and a plastic spacer under
960
+ * it, sized as a standard 2.54 mm male header (pin 0.64 mm square; spacer 2.54 mm square, 2.5 mm tall; 6 mm of pin
961
+ * below it, 3 mm above). Give the result as a part's `model`: { boxes } in the part's frame, z from the board's top.
962
+ * @param {{ x, y }[]} holes in the part's frame @param {object} [o] { thickness = 1.6, pitch = 2.54, pin = 0.64, spacer = 2.5, below = 6, above = 3 }
963
+ */
964
+ export function pinHeaders(holes, { thickness = 1.6, pitch = 2.54, pin = 0.64, spacer = 2.5, below = 6, above = 3 } = {}) {
965
+ const bottom = -thickness - spacer; // the spacer's underside, from the board's top
966
+ return { boxes: holes.flatMap(({ x, y }) => [
967
+ { min: [x - pitch / 2, y - pitch / 2, bottom], max: [x + pitch / 2, y + pitch / 2, -thickness] },
968
+ { min: [x - pin / 2, y - pin / 2, bottom - below], max: [x + pin / 2, y + pin / 2, -thickness + above] }]) };
969
+ }
970
+
971
+ function boxMesh({ min: [x0, y0, z0], max: [x1, y1, z1] }) {
972
+ const v = [[x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0], [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]];
973
+ return [[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7]].map((f) => f.map((i) => v[i]));
974
+ }
975
+
976
+ /**
977
+ * Each part's 3D model on the board, as triangles in the board's frame (board bottom at z = 0, top at thickness): the
978
+ * model's own scale, turn and offset as KiCad applies them, then the part's place; a part on the back hangs below,
979
+ * turned over. meshes: { file: triangles } for models with a mesh; a model with only a box is drawn as that box, and
980
+ * one with boxes (pinHeaders) as those.
981
+ * @param {object[]} json render's @param {{ thickness: number, meshes?: object }} o @returns {number[][][]}
982
+ */
983
+ export function partModels(json, { thickness, meshes = {} }) {
984
+ const rad = Math.PI / 180, out = [];
985
+ for (const c of json.filter((e) => e.type === 'cad_component' && e.rulecad_model)) {
986
+ const m = c.rulecad_model, tris = m.mesh ? meshes[m.mesh] : m.box ? boxMesh(m.box) : m.boxes ? m.boxes.flatMap(boxMesh) : null;
987
+ if (!tris) continue;
988
+ const [sx, sy, sz] = m.scale ?? [1, 1, 1], [rx, ry, rz] = (m.rotate ?? [0, 0, 0]).map((a) => -a * rad), [ox, oy, oz] = m.offset ?? [0, 0, 0];
989
+ const turn = (v) => { // KiCad's model turn: about x, then y, then z
990
+ let [x, y, z] = v;
991
+ [y, z] = [y * Math.cos(rx) - z * Math.sin(rx), y * Math.sin(rx) + z * Math.cos(rx)];
992
+ [x, z] = [x * Math.cos(ry) + z * Math.sin(ry), -x * Math.sin(ry) + z * Math.cos(ry)];
993
+ [x, y] = [x * Math.cos(rz) - y * Math.sin(rz), x * Math.sin(rz) + y * Math.cos(rz)];
994
+ return [x, y, z];
995
+ };
996
+ const back = m.layer === 'bottom', t = (m.rotation * Math.PI) / 180, ct = Math.cos(t), st = Math.sin(t), tt = (m.turn * Math.PI) / 180;
997
+ const place = (v) => {
998
+ let [x, y, z] = turn([v[0] * sx, v[1] * sy, v[2] * sz]);
999
+ x += ox; y += oy; z += oz;
1000
+ if (m.turn) [x, y] = [x * Math.cos(tt) - y * Math.sin(tt), x * Math.sin(tt) + y * Math.cos(tt)]; // a part at an angle that isn't a quarter turn
1001
+ if (back) { x = -x; y = -y; } // the part's own frame on the back is the footprint's turned half round (as its pads are)
1002
+ const m1 = back ? -1 : 1;
1003
+ return [r4(m.x + m1 * (ct * x - st * y)), r4(m.y + (st * x + ct * y)), r4(back ? -z : thickness + z)];
1004
+ };
1005
+ for (const tri of tris) out.push(tri.map(place));
1006
+ }
1007
+ return out;
355
1008
  }
356
1009
 
357
1010
  // ---------- board shapes ----------
@@ -395,13 +1048,15 @@ export const render = (board, options) => circuitJson(board, options); // option
395
1048
  // The board as a solid (previews, fits, the on-screen copy, the model page): the bare board, drilled, bottom at z = 0. Its
396
1049
  // copper is drawn in the 2D views (views), not in 3D. The board is a 2D outline with its holes, extruded: its faces
397
1050
  // triangulate cleanly (cylinders subtracted from a block leave long slivers).
398
- export function solids(json, { thickness, smooth = 16 }) { // smooth: segments per hole (a board without the variable gets 16)
1051
+ export function solids(json, { thickness, smooth = 16, models }) { // models: { file: triangles }, the parts' meshes (cad loads them) // smooth: segments per hole (a board without the variable gets 16)
399
1052
  const { rectangle, circle, polygon } = jscad.primitives, { subtract } = jscad.booleans, { extrudeLinear } = jscad.extrusions;
400
1053
  const b = json.find((e) => e.type === 'pcb_board');
401
1054
  const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via')
402
- .map((e) => circle({ center: [e.x, e.y], radius: (e.hole_diameter ?? e.hole_width) / 2, segments: smooth }));
1055
+ .map((e) => circle({ center: [e.x + (e.hole_offset_x ?? 0), e.y + (e.hole_offset_y ?? 0)], radius: (e.hole_diameter ?? e.hole_width) / 2, segments: smooth })); // a hole off-centre in its pad, where the fab drills it
403
1056
  const outline = b.outline ? polygon({ points: b.outline.map((p) => [p.x, p.y]) }) : rectangle({ center: [b.center.x, b.center.y], size: [b.width, b.height] });
404
- return { board: extrudeLinear({ height: thickness }, drills.length ? subtract(outline, ...drills) : outline) };
1057
+ const board = extrudeLinear({ height: thickness }, drills.length ? subtract(outline, ...drills) : outline);
1058
+ const parts = models ? partModels(json, { thickness, meshes: models }) : [];
1059
+ return { board, ...(parts.length ? { components: jscad.geometries.geom3.fromPoints(parts) } : {}) }; // the parts' 3D models, where there are any
405
1060
  }
406
1061
 
407
1062
  // What a built board tells the parts around it, as numbers an assembly can use (board.pico_y): its outline (centre and
@@ -428,30 +1083,138 @@ export const holes = (json) => json.filter((e) => e.type === 'pcb_hole' && !e.pc
428
1083
 
429
1084
  // ---------- checks ----------
430
1085
  const mm = (x) => String(Number(x.toFixed(3))); // 0.30000000000000004 reads as 0.3
431
- // checks(json, v) -> findings ({ level, text }): tscircuit's own design checks, the fab's limits, and the matrix
432
- export async function checks(json, v, matrix) {
1086
+ // checks(json, v, matrix, source) -> findings ({ level, text }): tscircuit's own design checks, the fab's limits, the
1087
+ // matrix, and for a clone (source: { circuit, arranged }) the source's circuit and placement
1088
+ export async function checks(json, v, matrix, source) { // source: a clone's { circuit, arranged } (its own checks join these)
433
1089
  const { runAllChecks } = await import('@tscircuit/checks');
434
1090
  const out = [], j = v.jlcpcb;
435
1091
  const board = json.find((e) => e.type === 'pcb_board');
436
1092
  // On a shaped board, a part's box can reach past a curved edge when its copper doesn't (a ring on a round disc): that
437
1093
  // part is checked here pad by pad against the outline instead (below)
438
- const padsOf = (id) => json.filter((e) => e.pcb_component_id === id && ['pcb_smtpad', 'pcb_plated_hole'].includes(e.type));
1094
+ // Castellated pads sit on the edge by design: half holes the fab cuts through. They're checked against its rules for them below
1095
+ // (with the other pads of their pins: a header pad beside a half hole runs into it, as on a Pico)
1096
+ const b = board, castellated = json.filter((e) => e.type === 'pcb_plated_hole' && e.port_hints?.includes('castellated'));
1097
+ const pinOf = (e) => `${e.pcb_component_id}:${e.port_hints?.[1]}`, edgePins = new Set(castellated.map(pinOf));
1098
+ const halves = new Set(json.filter((e) => e.type === 'pcb_plated_hole' && edgePins.has(pinOf(e))).map((e) => e.pcb_plated_hole_id));
1099
+ const padsOf = (id) => json.filter((e) => e.pcb_component_id === id && ['pcb_smtpad', 'pcb_plated_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id));
439
1100
  const fits = (id) => board.outline && padsOf(id).every((e) => (e.points || [e]).every((q) => inside(board.outline, q.x, q.y)));
440
- const drc = (await runAllChecks(json)).filter((e) => !(e.type === 'pcb_component_outside_board_error' && fits(e.pcb_component_id)));
1101
+ const onEdge = (e) => { const t = JSON.stringify(e); return [...halves].some((id) => new RegExp(`${id}(?!\\d)`).test(t)); };
1102
+ // A clone's pads as close to the edge as the source has them, and parts that reach past it as they do there, are the
1103
+ // source's design (a mid-mount socket in its notch): said, not failed. Anything else near the edge fails as usual
1104
+ const inherited = [], same = source?.circuit ? asSource(json, source.circuit, source.arranged?.kept) : null, planeNames = new Set(json.filter((e) => e.type === 'source_net').map((e) => e.name));
1105
+ const drc = (await runAllChecks(json)).filter((e) => !(e.type === 'pcb_component_outside_board_error' && fits(e.pcb_component_id)) && !onEdge(e))
1106
+ .filter((e) => !(same?.(e) && inherited.push(e)))
1107
+ .filter((e) => !(planeNames.has(e.message?.match(/is not connected to net \[(.+)\] by a PCB trace/)?.[1]))); // planes join these: checked below, pad by pad
441
1108
  const problems = [...json, ...drc].filter((e) => /_error$/.test(e.type));
442
1109
  const seen = new Set(), errors = problems.filter((e) => !seen.has(e.message) && seen.add(e.message));
443
1110
  out.push(errors.length ? { level: 'fail', text: `${errors.length} design-rule errors: ${errors.slice(0, 3).map((e) => e.message).join('; ')}` } : { level: 'pass', text: 'tscircuit\'s design checks: no errors (traces, clearances, holes, board edge)' });
444
- const traces = json.filter((e) => e.type === 'pcb_trace'), unrouted = json.filter((e) => e.type === 'source_trace').length - traces.length;
1111
+ // Connections between pads: as many tracks as connections (the router names a net's pieces after its connections). To
1112
+ // a plane: a track to a via, or the pad's own hole
1113
+ const traces = json.filter((e) => e.type === 'pcb_trace'), toPlane = json.filter((e) => e.type === 'source_trace' && e.connected_source_net_ids?.length);
1114
+ const planeIds = new Set(toPlane.map((t) => t.source_trace_id)), tracked = new Set(traces.map((t) => t.source_trace_id));
1115
+ const holePorts = new Set(json.filter((e) => e.type === 'pcb_plated_hole').map((e) => json.find((p) => p.type === 'pcb_port' && p.pcb_port_id === e.pcb_port_id)?.source_port_id));
1116
+ const unrouted = json.filter((e) => e.type === 'source_trace').length - planeIds.size - traces.filter((t) => !planeIds.has(t.source_trace_id)).length
1117
+ + toPlane.filter((t) => !tracked.has(t.source_trace_id) && !holePorts.has(t.connected_source_port_ids[0])).length;
445
1118
  out.push(unrouted > 0 ? { level: 'fail', text: `${unrouted} connections have no track` } : { level: 'pass', text: `every connection is routed (${traces.length} tracks, ${json.filter((e) => e.type === 'pcb_via').length} vias)` });
446
- const thin = traces.flatMap((t) => t.route).filter((p) => p.width != null && p.width < j.track_min);
447
- out.push(thin.length ? { level: 'fail', text: `tracks under JLCPCB's ${j.track_min} mm` } : { level: 'pass', text: `tracks ${mm(v.track ?? Math.min(...traces.flatMap((t) => t.route).map((p) => p.width).filter((w) => w != null)))} mm${v.clear != null ? `, gaps ${mm(v.clear)} mm` : ''}: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
448
- const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole').map((e) => e.hole_diameter ?? e.hole_width);
1119
+ out.push(...planeChecks(json));
1120
+ // A clone's own routing, kept: every track and via of it on the board exactly as the source has it (smoothing and
1121
+ // repair move only the router's tracks), but for escapes cut back where a routed track turned straight back on them:
1122
+ // each of those a piece of the source's own track, named with how much went
1123
+ const keptCu = source?.arranged?.kept;
1124
+ if (keptCu?.tracks?.length) {
1125
+ const key = (x, y) => `${x.toFixed(4)},${y.toFixed(4)}`, seg = (layer, width, a, b) => `${layer} ${width} ${key(a.x, a.y)} ${key(b.x, b.y)}`;
1126
+ const tracksAt = new Set(keptCu.tracks.flatMap((g) => [seg(g.layer, g.width, g.a, g.b), seg(g.layer, g.width, g.b, g.a)])), viasAt = new Set(keptCu.vias.map((q) => key(q.x, q.y)));
1127
+ const theirs = (layer, width, a, b) => tracksAt.has(seg(layer, width, a, b));
1128
+ const laid = traces.filter((t) => t.rulecad_kept), isVia = (t) => t.route[1]?.route_type === 'via';
1129
+ const along = (o, p) => { const dx = o.b.x - o.a.x, dy = o.b.y - o.a.y, l = Math.hypot(dx, dy); return Math.abs((p.x - o.a.x) * dy - (p.y - o.a.y) * dx) / l < 1e-4 && ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l > -1e-4 && ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l < l + 1e-4; };
1130
+ const cutBy = [], moved = laid.filter((t) => {
1131
+ if (isVia(t)) return !viasAt.has(key(t.route[0].x, t.route[0].y));
1132
+ const [p, q] = t.route, w = p.width, layer = p.layer;
1133
+ if (t.route.length === 2 && theirs(layer, w, p, q)) return false;
1134
+ const o = t.rulecad_shortened; // a piece of the source's segment, from one of its ends
1135
+ if (o && t.route.length === 2 && theirs(layer, w, o.a, o.b) && along(o, p) && along(o, q) && [p, q].some((r) => [o.a, o.b].some((e) => key(e.x, e.y) === key(r.x, r.y)))) {
1136
+ cutBy.push(Math.hypot(o.b.x - o.a.x, o.b.y - o.a.y) - Math.hypot(q.x - p.x, q.y - p.y)); return false;
1137
+ }
1138
+ return true;
1139
+ });
1140
+ const gone = traces.flatMap((t) => (t.rulecad_trimmed || []).map((g) => ({ ...g, track: t })));
1141
+ const strays = gone.filter((g) => !theirs(g.a.layer, g.a.width, g.a, g.b));
1142
+ cutBy.push(...gone.map((g) => Math.hypot(g.b.x - g.a.x, g.b.y - g.a.y)));
1143
+ const escapes = traces.reduce((n, t) => n + (t.rulecad_cut || 0), 0);
1144
+ const vias = laid.filter(isVia).length, short = laid.filter((t) => t.rulecad_shortened).length, total = cutBy.reduce((n, d) => n + d, 0);
1145
+ out.push(moved.length || strays.length ? { level: 'fail', text: `${moved.length + strays.length} of the source's own tracks and vias aren't where the source has them` }
1146
+ : { level: 'pass', text: `the source's own routing as it was: ${laid.length - vias - short} tracks and ${vias} vias exactly where the source has them${cutBy.length ? `, but for ${escapes} escapes cut back where a routed track turned straight back on them (${gone.length} segments gone, ${short} shortened: ${mm(total)} mm of track in all)` : ''} (only the router's tracks are tidied)` });
1147
+ }
1148
+ // Tracks and the gaps between them, measured from the board as drawn (not the design's variables): the narrowest
1149
+ // track, and the nearest two tracks of different connections come on one layer, edge to edge
1150
+ const segs = traces.flatMap((t) => t.route.slice(1).map((q, i) => ({ a: t.route[i], b: q, id: t.source_trace_id ?? t.pcb_trace_id, w: Math.max(t.route[i].width ?? 0, q.width ?? 0), layer: q.layer ?? t.route[i].layer })))
1151
+ .filter((g) => g.a.route_type !== 'via' && g.b.route_type !== 'via' && g.a.layer === g.b.layer);
1152
+ const widths = segs.map((g) => g.w).filter((w) => w > 0), narrow = widths.length ? Math.min(...widths) : null;
1153
+ let tight = null;
1154
+ const segGap = (g, h) => { const pts = [[g.a, h], [g.b, h], [h.a, g], [h.b, g]].map(([p, o]) => { const dx = o.b.x - o.a.x, dy = o.b.y - o.a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l)) : 0; return Math.hypot(p.x - o.a.x - t * dx, p.y - o.a.y - t * dy); }); return Math.min(...pts) - (g.w + h.w) / 2; };
1155
+ const crosses = (g, h) => { const o = (p, q, r) => Math.sign((q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x)); return o(g.a, g.b, h.a) * o(g.a, g.b, h.b) < 0 && o(h.a, h.b, g.a) * o(h.a, h.b, g.b) < 0; };
1156
+ // (tracks of one net may run close or meet: connections are grouped into nets by the ports and nets they share)
1157
+ const parent = new Map(), root = (x) => { while (parent.get(x) !== x) x = parent.get(x); return x; }, join = (x, y) => { parent.set(root(x), root(y)); };
1158
+ for (const t of json.filter((e) => e.type === 'source_trace')) {
1159
+ const ends = [t.source_trace_id, ...(t.connected_source_port_ids || []), ...(t.connected_source_net_ids || [])];
1160
+ for (const e of ends) if (!parent.has(e)) parent.set(e, e);
1161
+ for (const e of ends.slice(1)) join(ends[0], e);
1162
+ }
1163
+ const netOf = (id) => (parent.has(id) ? root(id) : id);
1164
+ const byLayer = new Map(); for (const g of segs) byLayer.set(g.layer, [...(byLayer.get(g.layer) || []), g]);
1165
+ for (const list of byLayer.values()) for (let x = 0; x < list.length; x++) for (let y = x + 1; y < list.length; y++) {
1166
+ const g = list[x], h = list[y];
1167
+ if (g.id === h.id || netOf(g.id) === netOf(h.id)) continue;
1168
+ const d = crosses(g, h) ? -1 : segGap(g, h);
1169
+ if (d <= 1e-6) continue; // touching: two pieces of one net meeting at a pad (the design checks catch real shorts)
1170
+ if (!tight || d < tight.d) tight = { d, at: [(g.a.x + g.b.x) / 2, (g.a.y + g.b.y) / 2] };
1171
+ }
1172
+ const thinTrack = narrow != null && narrow < j.track_min - 1e-9, closeGap = tight && tight.d < j.gap_min - 1e-9;
1173
+ if (narrow != null) out.push(thinTrack || closeGap
1174
+ ? { level: 'fail', text: [thinTrack && `a track ${mm(narrow)} mm wide, under JLCPCB's ${j.track_min} mm`, closeGap && `two tracks ${mm(tight.d)} mm apart near (${mm(tight.at[0])}, ${mm(tight.at[1])}), under JLCPCB's ${j.gap_min} mm`].filter(Boolean).join('; ') }
1175
+ : { level: 'pass', text: `tracks ${mm(narrow)} mm or wider${tight ? `, ${mm(tight.d)} mm or more apart` : ''}, measured on the board: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
1176
+ // A board that can't be made: no size, a hole through its edge, two parts of one name, a pin in two nets
1177
+ const named = json.filter((e) => e.type === 'source_component').map((e) => e.name), twice = named.filter((n, i) => named.indexOf(n) !== i);
1178
+ const edgeHoles = b.outline ? [] : json.filter((e) => (e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') && !halves.has(e.pcb_plated_hole_id)).filter((e) => { const r = (e.outer_diameter ?? e.hole_diameter ?? e.hole_width ?? 0) / 2; return Math.abs(e.x - b.center.x) + r > b.width / 2 + 1e-6 || Math.abs(e.y - b.center.y) + r > b.height / 2 + 1e-6; });
1179
+ const broken = [!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`, edgeHoles.length && `${edgeHoles.length} holes break through the board's edge`, twice.length && `two parts named ${[...new Set(twice)].join(', ')}`].filter(Boolean); // (a pin in two nets is refused as the board is built)
1180
+ if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
1181
+ // Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
1182
+ // between them (under the recommended ring a warning, under the least a failure). A clone's vias as its source
1183
+ // has them are the source's design: said, not failed
1184
+ const srcVia = source?.circuit?.via, asSrc = (e) => srcVia && Math.abs(e.hole_diameter - srcVia.hole) < 1e-6 && Math.abs(e.outer_diameter - srcVia.pad) < 1e-6;
1185
+ const rings = json.filter((e) => e.type === 'pcb_via' || (e.type === 'pcb_plated_hole' && e.outer_diameter != null && e.hole_diameter != null)).map((e) => ({ e, ring: (e.outer_diameter - e.hole_diameter) / 2, via: e.type === 'pcb_via' }));
1186
+ const least = j.annular_min ?? 0.18, badVias = rings.filter((r) => r.via && !asSrc(r.e) && (r.e.hole_diameter < j.via_hole || r.e.outer_diameter < j.via_pad)), thinRings = rings.filter((r) => !asSrc(r.e) && r.ring < least), smallRings = rings.filter((r) => !asSrc(r.e) && r.ring >= least && r.ring < j.annular);
1187
+ const inherited_ = rings.filter((r) => asSrc(r.e) && r.ring < j.annular).length;
1188
+ if (rings.length) {
1189
+ out.push(badVias.length ? { level: 'fail', text: `${badVias.length} vias under JLCPCB's ${j.via_hole} mm hole in a ${j.via_pad} mm pad (${mm(badVias[0].e.hole_diameter)} in ${mm(badVias[0].e.outer_diameter)})` }
1190
+ : thinRings.length ? { level: 'fail', text: `${thinRings.length} ${thinRings[0].via ? 'vias' : 'plated holes'} with a ${mm(Math.min(...thinRings.map((r) => r.ring)))} mm ring, under JLCPCB's least of ${least} mm` }
1191
+ : smallRings.length ? { level: 'warn', text: `${smallRings.length} ${smallRings.every((r) => r.via) ? 'vias' : 'plated holes'} with a ${mm(Math.min(...smallRings.map((r) => r.ring)))} mm ring: above JLCPCB's least of ${least} mm, under the ${j.annular} mm it recommends` }
1192
+ : { level: 'pass', text: `${rings.filter((r) => r.via).length} vias and ${rings.filter((r) => !r.via).length} plated holes, rings ${mm(Math.min(...rings.map((r) => r.ring)))} mm or more (JLCPCB recommends ${j.annular})${inherited_ ? `; ${inherited_} as the source has them` : ''}` });
1193
+ }
1194
+ // Silkscreen the fab can print: lines no thinner than silk_line, text no smaller than silk_text
1195
+ const silkLines = json.filter((e) => (e.type === 'pcb_silkscreen_path' || e.type === 'pcb_silkscreen_rect' || e.type === 'pcb_silkscreen_line' || e.type === 'pcb_silkscreen_circle') && e.stroke_width != null && e.stroke_width < j.silk_line);
1196
+ const silkTexts = json.filter((e) => e.type === 'pcb_silkscreen_text' && e.font_size != null && e.font_size < j.silk_text);
1197
+ if (json.some((e) => /^pcb_silkscreen_/.test(e.type))) out.push(silkLines.length || silkTexts.length
1198
+ ? { level: 'fail', text: `silkscreen the fab can't print: ${[silkLines.length && `${silkLines.length} lines under ${j.silk_line} mm (${mm(Math.min(...silkLines.map((e) => e.stroke_width)))})`, silkTexts.length && `${silkTexts.length} texts under ${j.silk_text} mm high (${mm(Math.min(...silkTexts.map((e) => e.font_size)))})`].filter(Boolean).join(', ')}` }
1199
+ : { level: 'pass', text: `silkscreen: lines ${j.silk_line} mm or wider, text ${j.silk_text} mm or taller (JLCPCB's least)` });
1200
+ const unplated = json.filter((e) => e.type === 'pcb_hole').map((e) => e.hole_diameter ?? e.hole_width), npth = j.npth_min ?? 0.5;
1201
+ if (unplated.length && Math.min(...unplated) < npth - 1e-9) out.push({ level: 'fail', text: `an unplated hole of ${mm(Math.min(...unplated))} mm, under JLCPCB's ${npth} mm for unplated holes` });
1202
+ const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width);
449
1203
  if (drills.length) out.push(Math.min(...drills) < j.drill_min ? { level: 'fail', text: `a hole under JLCPCB's ${j.drill_min} mm` } : { level: 'pass', text: `${drills.length} holes, smallest ${Math.min(...drills)} mm (JLCPCB: ${j.drill_min} mm)` });
450
- const b = json.find((e) => e.type === 'pcb_board'), size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
1204
+ const size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
451
1205
  if (b.outline) { // a shaped board: every pad and hole inside it
452
- const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
1206
+ const reaching = same ? same.reaching : new Set();
1207
+ const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
453
1208
  out.push(out_.length ? { level: 'fail', text: `${out_.length} pads or holes outside the board's outline (first at ${mm(out_[0].x)}, ${mm(out_[0].y)} mm)` } : { level: 'pass', text: `shaped board (${b.outline.length} points): all ${pads.length} pads and holes inside it` });
454
1209
  }
1210
+ if (castellated.length) { // JLCPCB's rules for half holes: big enough, far enough apart
1211
+ const small = castellated.filter((e) => e.hole_diameter < (j.castellated_drill_min ?? 0.6));
1212
+ let gap = Infinity;
1213
+ for (const a of castellated) for (const c of castellated) if (a !== c) gap = Math.min(gap, Math.hypot(a.x - c.x, a.y - c.y) - (a.hole_diameter + c.hole_diameter) / 2);
1214
+ out.push(small.length || gap < (j.castellated_gap_min ?? 0.6)
1215
+ ? { level: 'fail', text: `castellated holes: ${small.length ? `${small.length} under JLCPCB's ${j.castellated_drill_min ?? 0.6} mm` : `${mm(gap)} mm apart, under JLCPCB's ${j.castellated_gap_min ?? 0.6} mm`}` }
1216
+ : { level: 'pass', text: `${castellated.length} castellated holes on the edge, ${mm(Math.min(...castellated.map((e) => e.hole_diameter)))} mm or more, ${mm(gap)} mm apart (JLCPCB: ${j.castellated_drill_min ?? 0.6} / ${j.castellated_gap_min ?? 0.6} mm). Order with castellated holes` });
1217
+ }
455
1218
  out.push(Math.max(b.width, b.height) <= j.cheap_size ? { level: 'pass', text: `${size}: within JLCPCB's lowest price (${j.cheap_size} × ${j.cheap_size} mm)` } : { level: 'info', text: `${size}: over ${j.cheap_size} × ${j.cheap_size} mm, priced by quote` });
456
1219
  if (matrix) {
457
1220
  const cells = new Set(matrix.keys.map((k) => `${k.row},${k.col}`)), gpio = [...Object.values(matrix.rows), ...Object.values(matrix.cols)];
@@ -459,11 +1222,69 @@ export async function checks(json, v, matrix) {
459
1222
  ? { level: 'pass', text: `matrix: ${matrix.keys.length} keys on ${Object.keys(matrix.rows).length} rows × ${Object.keys(matrix.cols).length} columns, ${gpio.length} GPIO (rows ${Object.values(matrix.rows).join(' ')}; columns ${Object.values(matrix.cols).join(' ')})` }
460
1223
  : { level: 'fail', text: 'matrix: two keys share a row and column, or a GPIO is used twice' });
461
1224
  }
1225
+ if (inherited.length) out.push({ level: 'info', text: `as the source has them, so not failed: ${[...new Set(inherited.map((e) => e.message.replace(/ \(.*$/, '').replace(/\. Try moving.*$/, '')))].slice(0, 4).join('; ')}${inherited.length > 4 ? ` (${inherited.length} in all)` : ''}` });
1226
+ if (source?.circuit) out.push(...sameCircuit(json, source.circuit, {}, source.arranged?.added || []), ...placementChecks(source.arranged || source.circuit, source.circuit.placement || learnPlacement(source.circuit)));
462
1227
  const notes = new Set([...json, ...drc].filter((e) => /_warning$/.test(e.type)).map((e) => e.type.replace(/^(source|pcb)_|_warning$/g, '').replace(/_/g, ' ')));
463
1228
  if (notes.size) out.push({ level: 'info', text: `tscircuit notes, none about the copper: ${[...notes].join(', ')}` });
464
1229
  return out;
465
1230
  }
466
1231
 
1232
+ // A clone's findings that the source has too: a pad whose centre is as far from the edge as on the source (to 0.02 mm),
1233
+ // a part that reaches past the outline there too, and the source's own vias, kept, where they touch its pads. Returns a test for a design-rule error, with .reaching:
1234
+ // the board's components that reach past it as on the source.
1235
+ function asSource(json, circuit, kept) {
1236
+ const toEdge = (pts, x, y) => { let d = Infinity; for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length], dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0; d = Math.min(d, Math.hypot(x - a.x - t * dx, y - a.y - t * dy)); } return d; };
1237
+ const src = new Map(), past = new Set(), so = circuit.outline;
1238
+ if (!so) return null;
1239
+ for (const p of circuit.parts) {
1240
+ for (const q of padsOnBoard(p)) { src.set(`${p.ref}.pin${q.pin}`, toEdge(so, q.bx, q.by)); if (!inside(so, q.bx, q.by)) past.add(p.ref); }
1241
+ for (const h of padsOnBoard({ ...p, pads: p.holes || [] })) if (!inside(so, h.bx, h.by)) past.add(p.ref); // its unplated holes too
1242
+ }
1243
+ const b = json.find((e) => e.type === 'pcb_board'), bo = b.outline;
1244
+ const comp = new Map(json.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, json.find((c) => c.source_component_id === e.source_component_id && c.type === 'source_component')?.name]));
1245
+ const reaching = new Set([...comp].filter(([, n]) => past.has(n)).map(([id]) => id));
1246
+ const sp = new Map(json.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
1247
+ const at = new Map();
1248
+ for (const e of json.filter((x) => (x.type === 'pcb_smtpad' || x.type === 'pcb_plated_hole') && x.pcb_port_id)) {
1249
+ const port = json.find((x) => x.type === 'pcb_port' && x.pcb_port_id === e.pcb_port_id), name = `${comp.get(e.pcb_component_id)}.${sp.get(port?.source_port_id)?.name}`;
1250
+ const c = e.type === 'pcb_smtpad' ? smtBounds(e) : e; if (!at.has(name)) at.set(name, c);
1251
+ }
1252
+ const test = (e) => {
1253
+ const m = e.message?.match(/^(?:SMT pad|Plated hole) (\S+) violates copper-to-board-edge/);
1254
+ if (m) { const c = at.get(m[1]), d = src.get(m[1]); return c != null && d != null && bo && Math.abs(toEdge(bo, c.x, c.y) - d) <= 0.02; }
1255
+ const k = e.message?.match(/^Component (\S+) extends outside board/);
1256
+ if (k) return past.has(k[1]);
1257
+ const v = e.message?.match(/^Via hole at \(([-\d.]+)mm, ([-\d.]+)mm\)/); // the source's own via, kept where it was
1258
+ return !!(v && kept?.vias.some((q) => Math.abs(q.x - Number(v[1])) < 0.01 && Math.abs(q.y - Number(v[2])) < 0.01));
1259
+ };
1260
+ test.reaching = reaching;
1261
+ return test;
1262
+ }
1263
+
1264
+ // Each plane net's vias and holes inside its plane's copper (the pour leaves a clear ring round the others)
1265
+ function planeChecks(json) {
1266
+ const nets = json.filter((e) => e.type === 'source_net'), out = [];
1267
+ if (!nets.length) return out;
1268
+ const inRing = (ring, p) => inside(ring.vertices, p.x, p.y);
1269
+ const covered = (pours, p) => pours.some((q) => inRing(q.brep_shape.outer_ring, p) && !q.brep_shape.inner_rings.some((r) => inRing(r, p)));
1270
+ const port = new Map(json.filter((e) => e.type === 'pcb_port').map((e) => [e.source_port_id, e.pcb_port_id]));
1271
+ for (const n of nets) {
1272
+ const pours = json.filter((e) => e.type === 'pcb_copper_pour' && e.source_net_id === n.source_net_id);
1273
+ const st = json.filter((e) => e.type === 'source_trace' && e.connected_source_net_ids?.includes(n.source_net_id));
1274
+ const ids = new Set(st.map((t) => t.source_trace_id)), pts = [];
1275
+ for (const t of json.filter((e) => e.type === 'pcb_trace' && ids.has(e.source_trace_id))) for (const v of json.filter((e) => e.type === 'pcb_via' && e.pcb_trace_id === t.pcb_trace_id)) pts.push(v);
1276
+ for (const t of st) { // a pin's hole (a castellated pin's header pad, not its half hole on the edge)
1277
+ const h = json.find((e) => e.type === 'pcb_plated_hole' && e.pcb_port_id === port.get(t.connected_source_port_ids[0]) && !e.port_hints?.includes('castellated'));
1278
+ if (h) pts.push(h);
1279
+ }
1280
+ const miss = pts.filter((p) => !covered(pours, p));
1281
+ out.push(!pours.length ? { level: 'fail', text: `plane ${n.name}: no copper drawn` }
1282
+ : miss.length ? { level: 'fail', text: `plane ${n.name}: ${miss.length} of its vias and holes are outside its copper (first at ${mm(miss[0].x)}, ${mm(miss[0].y)} mm)` }
1283
+ : { level: 'pass', text: `plane ${n.name} on ${pours[0].layer}: all ${st.length} pads reach it (${pts.length} vias and holes inside its copper)` });
1284
+ }
1285
+ return out;
1286
+ }
1287
+
467
1288
  // ---------- files ----------
468
1289
  // The fab files: Gerbers (KiCad's Protel names, which JLCPCB reads), drill files, BOM and placement -> { name: text }
469
1290
  const PROTEL = { F_Cu: 'GTL', B_Cu: 'GBL', F_Mask: 'GTS', B_Mask: 'GBS', F_SilkScreen: 'GTO', B_SilkScreen: 'GBO', F_Paste: 'GTP', B_Paste: 'GBP', Edge_Cuts: 'GKO' };
@@ -471,7 +1292,7 @@ export async function fabFiles(json, name) {
471
1292
  const { convertSoupToGerberCommands, stringifyGerberCommandLayers, convertSoupToExcellonDrillCommands, stringifyExcellonDrill } = await import('circuit-json-to-gerber');
472
1293
  const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
473
1294
  const out = {};
474
- for (const [layer, text] of Object.entries(stringifyGerberCommandLayers(convertSoupToGerberCommands(json)))) if (PROTEL[layer]) out[`${name}.${PROTEL[layer]}`] = text; // fab notes (B_Fab) stay out
1295
+ for (const [layer, text] of Object.entries(stringifyGerberCommandLayers(convertSoupToGerberCommands(json)))) { const ext = PROTEL[layer] ?? (layer.match(/^In(\d+)_Cu$/) ? `G${layer.match(/\d+/)[0]}` : null); if (ext) out[`${name}.${ext}`] = text; } // fab notes (B_Fab) stay out
475
1296
  out[`${name}-PTH.DRL`] = stringifyExcellonDrill(convertSoupToExcellonDrillCommands({ circuitJson: json, is_plated: true }));
476
1297
  out[`${name}-NPTH.DRL`] = stringifyExcellonDrill(convertSoupToExcellonDrillCommands({ circuitJson: json, is_plated: false }));
477
1298
  out[`${name}-bom.csv`] = bom(json);
@@ -479,17 +1300,19 @@ export async function fabFiles(json, name) {
479
1300
  return out;
480
1301
  }
481
1302
 
482
- // The BOM in JLCPCB's columns (Comment, Designator, Footprint, LCSC Part #), one line per kind of part. The LCSC
483
- // numbers are blank until parts are chosen for assembly; a hand-soldered board doesn't need them.
484
- const FOOTPRINT = { K: 'Cherry MX, PCB mount', U: 'Raspberry Pi Pico, 0.1 in header pins', D: 'SOD-123' };
1303
+ // The BOM in JLCPCB's columns (Comment, Designator, Footprint, LCSC Part #), one line per kind of part. A part's LCSC
1304
+ // number comes with it when it has one (a clone's parts keep the source's); otherwise it's blank until parts are chosen
1305
+ // for assembly, and a hand-soldered board doesn't need them.
485
1306
  function bom(json) {
486
1307
  const lines = new Map(), q = (x) => `"${String(x).replace(/"/g, '""')}"`;
487
- for (const c of json.filter((e) => e.type === 'source_component')) {
488
- const comment = c.manufacturer_part_number || c.name, footprint = FOOTPRINT[c.name[0]] || '', key = `${comment}|${footprint}`;
489
- if (!lines.has(key)) lines.set(key, { comment, footprint, refs: [] });
1308
+ for (const c of json.filter((e) => e.type === 'source_component' && !e.exclude_from_bom)) {
1309
+ const lcsc = c.supplier_part_numbers?.jlcpcb?.[0] ?? '', comment = c.display_value || c.manufacturer_part_number || c.name;
1310
+ const footprint = lcsc ? '' : c.rulecad_package || ''; // the part's own package (a part with an LCSC number is known by that)
1311
+ const key = `${comment}|${footprint}|${lcsc}`;
1312
+ if (!lines.has(key)) lines.set(key, { comment, footprint, lcsc, refs: [] });
490
1313
  lines.get(key).refs.push(c.name);
491
1314
  }
492
- return ['Comment,Designator,Footprint,LCSC Part #', ...[...lines.values()].map((l) => [l.comment, l.refs.join(','), l.footprint, ''].map(q).join(','))].join('\n') + '\n';
1315
+ return ['Comment,Designator,Footprint,LCSC Part #', ...[...lines.values()].map((l) => [l.comment, l.refs.join(','), l.footprint, l.lcsc].map(q).join(','))].join('\n') + '\n';
493
1316
  }
494
1317
 
495
1318
  // KiCad's own files, to check with kicad-cli or finish by hand: { 'name.kicad_pcb': text, 'name.kicad_sch': text }