@rulecad/pcb 0.5.0 → 0.5.3
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.
- package/README.md +16 -0
- package/circuit.mjs +197 -22
- package/kicad.mjs +249 -0
- package/package.json +8 -3
- package/pcb.mjs +105 -20
package/README.md
CHANGED
|
@@ -88,6 +88,22 @@ export function main(v) {
|
|
|
88
88
|
track the design checks then find in a new error goes back as it was, and a board where a cut causes one is smoothed
|
|
89
89
|
again without cuts. For a clone that keeps its source's routing, the checks confirm every kept track and via is still
|
|
90
90
|
exactly where the source has it, and name each escape cut back and how much track went.
|
|
91
|
+
- **A pin with pads apart:** a part whose footprint gives one pin two pads apart from each other (a USB-C socket's two
|
|
92
|
+
VBUS pads, both its A4) gets a track between them, as its net joins the first. Pads that touch (a half hole in its
|
|
93
|
+
header pad) are one copper already, and a plane net's pads each reach the plane.
|
|
94
|
+
- **Fab checks for vias:** a via's ring is measured against JLCPCB's figures for vias (`via_annular_min`, `via_annular`:
|
|
95
|
+
its pad 0.1 mm wider than its hole, 0.15 preferred), a plated hole's against those for holes. Each via's hole is
|
|
96
|
+
measured edge to edge to the nearest track of another net (`via_hole_track`, 0.2 mm): JLCPCB measures from the hole,
|
|
97
|
+
so a small via's thin ring leaves less room than the copper clearance suggests.
|
|
98
|
+
- **Fab files, plotted by KiCad where they must be:** the Gerber writer plots a rounded pad square, so beside a copper
|
|
99
|
+
plane its corners would short to it, and it can't drill a slot. For a board with either, `fabFiles` has KiCad plot the
|
|
100
|
+
Gerbers and drill files from the very board its design-rule check has just passed, and refuses if the check finds an
|
|
101
|
+
error or the drill files aren't the design's holes, slots included. Without KiCad such a board's fab files aren't
|
|
102
|
+
made. The plots share the design's origin with the placement file. A source's slotted holes are kept as slots.
|
|
103
|
+
- **KiCad, as a second opinion:** `kicadFiles` writes the board as KiCad reads it (kicad.mjs: every pad, track and via
|
|
104
|
+
on its named net, a hole set off-centre in its pad where KiCad drills it, castellated pins marked, rounded pads round,
|
|
105
|
+
and a `.kicad_pro` and `.kicad_dru` with the board's rules). Where KiCad is installed, `checks` also runs its
|
|
106
|
+
design-rule check (`kicad-cli`, `KICAD_CLI` to name another), KiCad pouring the planes itself.
|
|
91
107
|
- **Labels clear of copper:** `clearLabels(silk, circuit)` slides each silkscreen label across its reading direction to
|
|
92
108
|
the nearest place clear of every pad and of the labels before it (the fab trims silkscreen off copper, so a label
|
|
93
109
|
on a pad loses letters). A label for a pin hemmed in by its neighbours (`to`: where the pin is) goes to the nearest
|
package/circuit.mjs
CHANGED
|
@@ -22,9 +22,15 @@
|
|
|
22
22
|
// width or board.track; pins are named part.pin, by the pin's label, its name or its number
|
|
23
23
|
// silk { rect: { x, y, w, h }, layer } | { text, x, y, size, layer, rotation } (rotation: degrees, counter-clockwise)
|
|
24
24
|
// effort how hard the autorouter searches (default its own, 1): more for a crowded board, at more time
|
|
25
|
+
// pipeline the autorouter's pipeline to try first (a class it exports, e.g. 'AutoroutingPipelineSolver4'); unset, its
|
|
26
|
+
// own. If one fails, the next in PIPELINES is tried
|
|
25
27
|
// holes [{ x, y, d, keepout }] in the board (mounting holes; keepout: a radius the router keeps tracks out of, for a screw head)
|
|
26
28
|
// layers 2 (default), 4 or 6 copper layers: tracks on the outer two, planes inside
|
|
27
29
|
// clearance (mm) the router keeps from everything in its way (a clone: the source's); unset, the router's own
|
|
30
|
+
// route_via { pad, hole } (mm): the vias the router makes, when not via_pad and via_hole (the planes' vias)
|
|
31
|
+
// join_pads false: a pin's pads apart aren't joined by a track (see samePin)
|
|
32
|
+
// track_gap (mm) routed tracks closer than this (a fab's least gap) are necked to neck where they pass
|
|
33
|
+
// via_hole_gap (mm) a routed track closer to a via's hole than this is bowed out round it (JLCPCB: 0.2)
|
|
28
34
|
// smooth true: routed tracks pulled tight once routed (@rulecad/smooth), where the straight run keeps clearance
|
|
29
35
|
// neck (mm) a routed track still too close to another after repair is narrowed to this where they pass (the fab's smallest)
|
|
30
36
|
// planes { GND: { layer: 'inner1', pins: ['U1.GND', ...] } }: nets joined by copper filling an inner layer. Each SMD pad
|
|
@@ -32,7 +38,8 @@
|
|
|
32
38
|
// either is routed to the nearest pad of its net that reaches the plane. via_pad, via_hole, plane_clearance
|
|
33
39
|
// (mm, defaults 0.6, 0.3, 0.2) size them
|
|
34
40
|
// copper { tracks: [{ a, b, width, layer, island }], vias: [{ x, y, pad, hole, island }], islands: [{ id, net, pins, via }] }:
|
|
35
|
-
// a source's own routing, kept (moveGroup's keep): laid as it is; its pins count as joined
|
|
41
|
+
// a source's own routing, kept (moveGroup's keep): laid as it is; its pins count as joined. An island marked
|
|
42
|
+
// after: true is laid once the rest is routed, unseen by the router
|
|
36
43
|
// pads may be castellated ({ castellated: true }: a half hole on the edge, joined at its inner edge) or a rounded
|
|
37
44
|
// rectangle round their hole ({ rect: { w, h, offset: [x, y] } }: an oval pad, a hole off-centre)
|
|
38
45
|
// All positions are in mm, in the board's own frame. A part on the bottom is seen from above: mirrored in x.
|
|
@@ -110,6 +117,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
|
|
|
110
117
|
// ---- parts: source records, then their footprints on the board ----
|
|
111
118
|
const copper = copperLayers(board.layers ?? 2); // a hole or a via goes through all of them
|
|
112
119
|
const ports = new Map(); // `${part}.${port name or hint}` -> { source, pcb, x, y, layers }
|
|
120
|
+
const pinPads = new Map(); // `${part}.${pin name}` -> each of its pads: { key (in ports), x, y, reach (its copper's half size) }
|
|
113
121
|
const placed = [];
|
|
114
122
|
for (const part of board.parts) {
|
|
115
123
|
const comp = add('source_component', { ftype: part.ftype, name: part.name, manufacturer_part_number: part.mpn,
|
|
@@ -150,7 +158,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
|
|
|
150
158
|
add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length,
|
|
151
159
|
width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS,
|
|
152
160
|
...(board.fab ? { min_trace_width: board.fab.track_min, min_trace_to_pad_edge_clearance: board.fab.gap_min, min_pad_edge_to_pad_edge_clearance: board.fab.gap_min, min_via_hole_edge_to_via_hole_edge_clearance: board.fab.gap_min } : {}), // (the fab's own, when the board names its rules)
|
|
153
|
-
min_via_hole_diameter: board.via_hole ?? 0.3, min_via_pad_diameter: board.via_pad ?? 0.8 });
|
|
161
|
+
min_via_hole_diameter: board.route_via?.hole ?? board.via_hole ?? 0.3, min_via_pad_diameter: board.route_via?.pad ?? board.via_pad ?? 0.8 });
|
|
154
162
|
|
|
155
163
|
for (const { part, comp, pads, sourcePorts, fpEls, at, mirror, size } of placed) {
|
|
156
164
|
// The component sits at the middle of its pads and holes (as tscircuit places it: pick-and-place reads this)
|
|
@@ -171,7 +179,8 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
|
|
|
171
179
|
add('pcb_solder_paste', { layer: part.layer, shape: 'rect', width: p.w * PASTE, height: p.h * PASTE, x: p.x, y: p.y, pcb_component_id: pc.pcb_component_id, pcb_smtpad_id: pad.pcb_smtpad_id, subcircuit_id: SUB });
|
|
172
180
|
} else if (p.rect) { // an oval pad or a hole off-centre: a rounded rectangle, its hole offset turned with the part
|
|
173
181
|
const sz = size(p.rect.w, p.rect.h), o0 = at(0, 0), o1 = at(p.rect.offset[0], p.rect.offset[1]);
|
|
174
|
-
|
|
182
|
+
const slot = p.rect.slot && size(p.rect.slot[0], p.rect.slot[1]); // (a slotted hole, as a USB-C socket's shell legs need)
|
|
183
|
+
add('pcb_plated_hole', { ...own, pcb_port_id: port.pcb_port_id, ...(slot ? { shape: 'pill_hole_with_rect_pad', hole_shape: 'pill', hole_width: slot.w, hole_height: slot.h } : { shape: 'circular_hole_with_rect_pad', hole_shape: 'circle', hole_diameter: p.hole }), pad_shape: 'rect',
|
|
175
184
|
rect_pad_width: sz.w, rect_pad_height: sz.h, rect_border_radius: Math.min(sz.w, sz.h) / 2, hole_offset_x: Math.round((o1.x - o0.x) * 1e6) / 1e6, hole_offset_y: Math.round((o1.y - o0.y) * 1e6) / 1e6,
|
|
176
185
|
port_hints: [`unnamed_platedhole${i + 1}`, p.pin], x: p.x, y: p.y, layers, is_covered_with_solder_mask: false });
|
|
177
186
|
} else {
|
|
@@ -184,6 +193,11 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
|
|
|
184
193
|
const join = p.castellated ? inward(board, p.x, p.y, (p.outer + (p.hole ?? p.outer)) / 4) : { x: p.x, y: p.y };
|
|
185
194
|
if (p.castellated) Object.assign(port, join);
|
|
186
195
|
for (const key of [sourcePorts[i].name, ...sourcePorts[i].port_hints]) ports.set(`${part.name}.${key}`, { source: sourcePorts[i], pcb: port, x: join.x, y: join.y, layers });
|
|
196
|
+
// one pin: one name and one number (a module's GND pins share a name, each its own number, and join inside it)
|
|
197
|
+
const pin = `${part.name}.${sourcePorts[i].name}#${sourcePorts[i].pin_number}`, list = pinPads.get(pin) || [];
|
|
198
|
+
ports.set(`${pin}#${list.length}`, { source: sourcePorts[i], pcb: port, x: join.x, y: join.y, layers }); // each pad of a pin by itself
|
|
199
|
+
list.push({ key: `${sourcePorts[i].name}#${sourcePorts[i].pin_number}#${list.length}`, names: [sourcePorts[i].name, ...sourcePorts[i].port_hints].map((n) => `${part.name}.${n}`),
|
|
200
|
+
x: p.x, y: p.y, reach: Math.max(p.w ?? 0, p.h ?? 0, p.outer ?? 0, p.rect?.w ?? 0, p.rect?.h ?? 0) / 2 }); pinPads.set(pin, list);
|
|
187
201
|
});
|
|
188
202
|
for (const h of part.holes || []) { const q = at(h.x, h.y); add('pcb_hole', { ...own, hole_shape: 'circle', hole_diameter: h.d, x: q.x, y: q.y, is_covered_with_solder_mask: false }); }
|
|
189
203
|
if (part.courtyard) { const c = size(part.courtyard.w, part.courtyard.h); add('pcb_courtyard_rect', { ...own, layer: part.layer, center: { x: part.x, y: part.y }, width: c.w, height: c.h }); }
|
|
@@ -225,11 +239,21 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
|
|
|
225
239
|
add('pcb_via', { pcb_trace_id: tr.pcb_trace_id, x: v.x, y: v.y, hole_diameter: v.hole, outer_diameter: v.pad, layers: copper, from_layer: 'top', to_layer: 'bottom', subcircuit_id: SUB });
|
|
226
240
|
}
|
|
227
241
|
};
|
|
228
|
-
|
|
242
|
+
// A pin with pads apart from each other (a USB-C socket's two VBUS pads, both its A4): joined by a track, as its net
|
|
243
|
+
// joins the pin's first pad. Pads that touch (a half hole in its header pad) are one copper already, and a plane net's
|
|
244
|
+
// pads each reach the plane
|
|
245
|
+
const netNamed = (names) => Object.entries(board.nets || {}).find(([, spec]) => (Array.isArray(spec) ? spec : spec.pins).some((p) => names.includes(p)))?.[0];
|
|
246
|
+
const samePin = [...pinPads].flatMap(([pin, pads]) => {
|
|
247
|
+
const net = pads.length > 1 && netNamed(pads[0].names), part = pin.slice(0, pin.indexOf('.'));
|
|
248
|
+
if (pads.length < 2 || !net || board.planes?.[net] || board.join_pads === false || pads[0].names.some((n) => joined.has(n))) return []; // (or the source's kept copper joins them)
|
|
249
|
+
return pads.slice(1).filter((q, i) => Math.hypot(q.x - pads[i].x, q.y - pads[i].y) > q.reach + pads[i].reach)
|
|
250
|
+
.map((q) => ({ from: [part, pads[0].key], to: [part, q.key], width: board.track, net }));
|
|
251
|
+
});
|
|
252
|
+
const toRoute = [], traces = [...(board.traces || []), ...netTraces(board, port, joined), ...links, ...samePin];
|
|
229
253
|
for (const t of traces) {
|
|
230
254
|
const a = port(...t.from), b = port(...t.to);
|
|
231
255
|
const st = add('source_trace', { connected_source_port_ids: [a.source.source_port_id, b.source.source_port_id], connected_source_net_ids: [], subcircuit_id: SUB,
|
|
232
|
-
display_name: `.${t.from.join(' > .')} to .${t.to.join(' > .')}`, min_trace_thickness: t.width });
|
|
256
|
+
display_name: `.${t.from.join(' > .')} to .${t.to.join(' > .')}`, min_trace_thickness: t.width, ...(t.net ? { rulecad_net: t.net } : {}) }); // (the net's name: KiCad's files carry it)
|
|
233
257
|
if (!t.path) { // a kept escape (stub) from either pin: laid as part of this connection, which is routed from its end
|
|
234
258
|
const ends = [a, b].map((q, i) => { const stub = stubOf.get([t.from, t.to][i].join('.')); if (!stub) return q; stubOf.delete([t.from, t.to][i].join('.'));
|
|
235
259
|
layStub(stub, st.source_trace_id); return { ...q, x: stub.end.x, y: stub.end.y, layers: [stub.end.layer] }; });
|
|
@@ -259,7 +283,12 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
|
|
|
259
283
|
const t = add('pcb_trace', { route: r.route, source_trace_id: r.source_trace_id, subcircuit_id: SUB, rulecad_routed: true });
|
|
260
284
|
for (const v of r.vias) add('pcb_via', { pcb_trace_id: t.pcb_trace_id, ...v, layers: copper, subcircuit_id: SUB }); // whose via it is: the checks need it
|
|
261
285
|
}
|
|
286
|
+
// kept copper laid once routed (an island marked after): unseen by the router, so the rest routes as it would
|
|
287
|
+
// without it; smoothing and the checks see it
|
|
288
|
+
if (board.copper?.islands.some((k) => k.after)) keptCopper(out, add, board, copper, planeNets || {}, true);
|
|
262
289
|
if (board.smooth) await smoothRouted(out, board);
|
|
290
|
+
if (board.via_hole_gap) await viaHoleRepair(out, board.via_hole_gap, board.neck);
|
|
291
|
+
if (board.track_gap && board.neck) await gapRepair(out, board.track_gap, board.neck);
|
|
263
292
|
}
|
|
264
293
|
if (planeNets) await pours(out, add, board, planeNets, netOf);
|
|
265
294
|
if (board.silk?.length) clearSilkAfter(out, add, board);
|
|
@@ -320,6 +349,133 @@ export async function smoothRouted(out, board) {
|
|
|
320
349
|
}
|
|
321
350
|
}
|
|
322
351
|
|
|
352
|
+
// Each via's hole against the tracks of other nets near it: { via, gap (hole edge to track edge, mm), at, kept (the
|
|
353
|
+
// via and the track both a source's own copper), trace, seg (the segment's index) }: the nearest track for each via,
|
|
354
|
+
// or (all) every track segment closer than under
|
|
355
|
+
export function viaHoleGaps(json, { all = false, under = Infinity } = {}) {
|
|
356
|
+
const up = new Map(), find = (a) => { while (up.get(a) !== a) { up.set(a, up.get(up.get(a))); a = up.get(a); } return a; };
|
|
357
|
+
const join = (a, b) => { for (const x of [a, b]) if (!up.has(x)) up.set(x, x); up.set(find(a), find(b)); };
|
|
358
|
+
for (const e of json) if (e.type === 'source_trace') { join(e.source_trace_id, e.source_trace_id); for (const id of [...(e.connected_source_port_ids || []), ...(e.connected_source_net_ids || [])]) join(e.source_trace_id, id); }
|
|
359
|
+
const traceOf = new Map(json.filter((e) => e.type === 'pcb_trace').map((t) => [t.pcb_trace_id, t]));
|
|
360
|
+
const netOf = (t) => (t?.source_trace_id && up.has(t.source_trace_id) ? find(t.source_trace_id) : null);
|
|
361
|
+
const segs = json.filter((e) => e.type === 'pcb_trace').flatMap((t) => t.route.slice(1).map((q, i) => [t.route[i], q, t, i]).filter(([p, q]) => p.route_type === 'wire' && q.route_type === 'wire' && p.layer === q.layer));
|
|
362
|
+
const toSeg = (c, a, b) => { const dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((c.x - a.x) * dx + (c.y - a.y) * dy) / l)) : 0; return { d: Math.hypot(c.x - a.x - t * dx, c.y - a.y - t * dy), p: { x: a.x + t * dx, y: a.y + t * dy } }; };
|
|
363
|
+
const out = [];
|
|
364
|
+
for (const v of json.filter((e) => e.type === 'pcb_via')) {
|
|
365
|
+
const vt = traceOf.get(v.pcb_trace_id), net = netOf(vt);
|
|
366
|
+
let best = null;
|
|
367
|
+
for (const [a, b, t, i] of segs) {
|
|
368
|
+
if (t === vt || (net != null && netOf(t) === net)) continue;
|
|
369
|
+
if (Math.min(a.x, b.x) - 2 > v.x || Math.max(a.x, b.x) + 2 < v.x || Math.min(a.y, b.y) - 2 > v.y || Math.max(a.y, b.y) + 2 < v.y) continue;
|
|
370
|
+
const { d, p } = toSeg(v, a, b), gap = d - v.hole_diameter / 2 - Math.max(a.width ?? 0, b.width ?? 0) / 2;
|
|
371
|
+
const found = { via: v, gap, at: p, kept: !!(vt?.rulecad_kept && t.rulecad_kept), trace: t, seg: i };
|
|
372
|
+
if (all) { if (gap < under) out.push(found); } else if (!best || gap < best.gap) best = found;
|
|
373
|
+
}
|
|
374
|
+
if (best) out.push(best);
|
|
375
|
+
}
|
|
376
|
+
return out;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// A routed track closer to a via's hole than the fab allows (JLCPCB measures from the hole, so a small via's thin ring
|
|
380
|
+
// leaves less room than the copper clearance): necked down where it passes (to neck, the fab's smallest track) if
|
|
381
|
+
// that's room enough, else bowed out round the via by what it lacks, the segment's middle stretch moved off, its ends
|
|
382
|
+
// where they were; last, a via still a little close moved away by what it lacks. A change the design checks then find in
|
|
383
|
+
// a new error goes back
|
|
384
|
+
export async function viaHoleRepair(out, gapMin, neck = 0) {
|
|
385
|
+
const { runAllChecks } = await import('@tscircuit/checks');
|
|
386
|
+
const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
|
|
387
|
+
.map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
|
|
388
|
+
const before = new Set(await errors()), tried = new Set();
|
|
389
|
+
const short = () => viaHoleGaps(out, { all: true, under: gapMin - 1e-6 }).filter((g) => g.trace.rulecad_routed);
|
|
390
|
+
const width = (g) => Math.max(g.trace.route[g.seg].width ?? 0, g.trace.route[g.seg + 1].width ?? 0);
|
|
391
|
+
const necked = (r, i) => r.map((q, k) => (k === i || k === i + 1 ? { ...q, width: Math.min(q.width ?? neck, neck) } : q));
|
|
392
|
+
// First, necked down where they pass (nothing moves, so nothing new comes close): every segment that's then far enough
|
|
393
|
+
if (neck) for (const g of short()) if (width(g) > neck && g.gap + (width(g) - neck) / 2 >= gapMin) g.trace.route = necked(g.trace.route, g.seg);
|
|
394
|
+
// Then the rest bowed out round the via (and necked, so the bow is smaller), one per track a round, each checked
|
|
395
|
+
for (let round = 0; round < 6; round++) {
|
|
396
|
+
const was = new Map(), done = new Set();
|
|
397
|
+
for (const g of short().sort((x, y) => x.gap - y.gap)) {
|
|
398
|
+
const t = g.trace, key = `${t.pcb_trace_id}:${g.via.pcb_via_id}`;
|
|
399
|
+
if (done.has(t.pcb_trace_id) || tried.has(key)) continue; // (one bow a track a round: its segments' places change)
|
|
400
|
+
let r = t.route;
|
|
401
|
+
const w = width(g), thin = neck && w > neck ? neck : w, a = r[g.seg], b = r[g.seg + 1], len = Math.hypot(b.x - a.x, b.y - a.y);
|
|
402
|
+
if (len < 1e-6) continue;
|
|
403
|
+
if (thin < w) r = necked(r, g.seg);
|
|
404
|
+
const u = { x: (b.x - a.x) / len, y: (b.y - a.y) / len }, off = { x: g.at.x - g.via.x, y: g.at.y - g.via.y }, d = Math.hypot(off.x, off.y);
|
|
405
|
+
const n = d > 1e-9 ? { x: off.x / d, y: off.y / d } : { x: -u.y, y: u.x }, need = gapMin - g.gap - (w - thin) / 2 + 0.01;
|
|
406
|
+
const along = (g.at.x - a.x) * u.x + (g.at.y - a.y) * u.y, half = g.via.outer_diameter / 2 + need + 0.15; // the stretch beside the via
|
|
407
|
+
const s0 = Math.max(0, along - half), s1 = Math.min(len, along + half), ramp = Math.min(need * 2, s0, len - s1);
|
|
408
|
+
const pt = (s, k) => { const { start_pcb_port_id, end_pcb_port_id, ...q } = { ...r[g.seg], width: thin, x: a.x + u.x * s + n.x * k, y: a.y + u.y * s + n.y * k }; return q; };
|
|
409
|
+
const bow = [ramp > 0 ? pt(s0 - ramp, 0) : null, pt(s0, need), pt(s1, need), ramp > 0 ? pt(s1 + ramp, 0) : null].filter(Boolean)
|
|
410
|
+
.filter((q) => Math.hypot(q.x - a.x, q.y - a.y) > 1e-6 && Math.hypot(q.x - b.x, q.y - b.y) > 1e-6);
|
|
411
|
+
was.set(t.pcb_trace_id, { route: t.route, key });
|
|
412
|
+
t.route = [...r.slice(0, g.seg + 1), ...bow, ...r.slice(g.seg + 1)];
|
|
413
|
+
done.add(t.pcb_trace_id);
|
|
414
|
+
}
|
|
415
|
+
if (!was.size) break;
|
|
416
|
+
// a bow in a new error: the track as it was before it, and that bow not tried again
|
|
417
|
+
for (const e of (await errors()).filter((x) => !before.has(x))) for (const [id, w] of was) if (e.includes(`"${id}"`)) {
|
|
418
|
+
out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = w.route; tried.add(w.key); was.delete(id);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
// Last, a router's via still a little close (its track can't bow: no room): the via nudged (with its own track's ends
|
|
422
|
+
// there) a few hundredths of a millimetre, the first way round that clears every track near it, each move checked
|
|
423
|
+
const vias = new Map(out.filter((e) => e.type === 'pcb_via').map((v) => [v.pcb_via_id, v]));
|
|
424
|
+
for (const g of short()) {
|
|
425
|
+
const v = vias.get(g.via.pcb_via_id), own = out.find((e) => e.type === 'pcb_trace' && e.pcb_trace_id === v.pcb_trace_id);
|
|
426
|
+
if (!own?.rulecad_routed || tried.has(`via:${v.pcb_via_id}`)) continue;
|
|
427
|
+
tried.add(`via:${v.pcb_via_id}`);
|
|
428
|
+
const was_ = { x: v.x, y: v.y, route: own.route }, at = (q) => Math.hypot(q.x - was_.x, q.y - was_.y) < 1e-6;
|
|
429
|
+
const place = (x, y) => { v.x = x; v.y = y; own.route = was_.route.map((q) => (at(q) ? { ...q, x, y } : q)); };
|
|
430
|
+
const worst = () => Math.min(gapMin, ...viaHoleGaps(out, { all: true, under: gapMin }).filter((h) => h.via === v).map((h) => h.gap));
|
|
431
|
+
let fixed = false;
|
|
432
|
+
for (const step of [0.01, 0.02, 0.03, 0.05]) {
|
|
433
|
+
for (let k = 0; k < 16 && !fixed; k++) {
|
|
434
|
+
const t = (k / 16) * 2 * Math.PI;
|
|
435
|
+
place(was_.x + Math.cos(t) * step, was_.y + Math.sin(t) * step);
|
|
436
|
+
if (worst() >= gapMin - 1e-6 && !(await errors()).some((x) => !before.has(x))) fixed = true;
|
|
437
|
+
}
|
|
438
|
+
if (fixed) break;
|
|
439
|
+
}
|
|
440
|
+
if (!fixed) place(was_.x, was_.y);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Routed tracks of different nets a hair closer than the fab's least gap (the design checks allow a little; a fab's
|
|
445
|
+
// rule doesn't): each routed segment of the pair necked down where they pass (to neck), which opens the gap by half the
|
|
446
|
+
// width it loses, each change checked
|
|
447
|
+
export async function gapRepair(out, gapMin, neck) {
|
|
448
|
+
const { runAllChecks } = await import('@tscircuit/checks');
|
|
449
|
+
const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
|
|
450
|
+
.map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
|
|
451
|
+
const parent = new Map(), root = (x) => { while (parent.get(x) !== x) x = parent.get(x); return x; };
|
|
452
|
+
for (const t of out.filter((e) => e.type === 'source_trace')) {
|
|
453
|
+
const ends = [t.source_trace_id, ...(t.connected_source_port_ids || []), ...(t.connected_source_net_ids || [])];
|
|
454
|
+
for (const e of ends) if (!parent.has(e)) parent.set(e, e);
|
|
455
|
+
for (const e of ends.slice(1)) parent.set(root(e), root(ends[0]));
|
|
456
|
+
}
|
|
457
|
+
const netOf = (t) => (parent.has(t.source_trace_id) ? root(t.source_trace_id) : t.pcb_trace_id);
|
|
458
|
+
const ps = (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); };
|
|
459
|
+
const segs = out.filter((e) => e.type === 'pcb_trace').flatMap((t) => t.route.slice(1).map((q, i) => ({ t, i, a: t.route[i], b: q }))
|
|
460
|
+
.filter((g) => g.a.route_type === 'wire' && g.b.route_type === 'wire' && g.a.layer === g.b.layer));
|
|
461
|
+
const w = (g) => Math.max(g.a.width ?? 0, g.b.width ?? 0), before = new Set(await errors()), was = new Map();
|
|
462
|
+
for (let x = 0; x < segs.length; x++) for (let y = x + 1; y < segs.length; y++) {
|
|
463
|
+
const g = segs[x], h = segs[y];
|
|
464
|
+
if (g.t === h.t || g.a.layer !== h.a.layer || netOf(g.t) === netOf(h.t)) continue;
|
|
465
|
+
if (Math.min(g.a.x, g.b.x) > Math.max(h.a.x, h.b.x) + 1 || Math.min(h.a.x, h.b.x) > Math.max(g.a.x, g.b.x) + 1) continue;
|
|
466
|
+
const d = Math.min(ps(g.a, h), ps(g.b, h), ps(h.a, g), ps(h.b, g)) - w(g) / 2 - w(h) / 2;
|
|
467
|
+
if (d <= 1e-6 || d >= gapMin - 1e-9) continue;
|
|
468
|
+
for (const s of [g, h]) if (s.t.rulecad_routed && w(s) > neck) {
|
|
469
|
+
if (!was.has(s.t.pcb_trace_id)) was.set(s.t.pcb_trace_id, s.t.route);
|
|
470
|
+
s.t.route = s.t.route.map((q, k) => (k === s.i || k === s.i + 1 ? { ...q, width: Math.min(q.width ?? neck, neck) } : q));
|
|
471
|
+
s.a = s.t.route[s.i]; s.b = s.t.route[s.i + 1];
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
for (const e of (await errors()).filter((x) => !before.has(x))) for (const [id, route] of was) if (e.includes(`"${id}"`)) {
|
|
475
|
+
out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = route; was.delete(id);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
323
479
|
// Each routed track's kept escape at either end: the stub of the source's track it carries on from (its end not on a
|
|
324
480
|
// pad), followed back from the joint segment by segment while it's a single line on one layer, stopping at a via or a
|
|
325
481
|
// branch. -> Map(pcb_trace_id -> { start, end }), each { lead: points from the stub's root to the joint, segs: the stub's
|
|
@@ -359,13 +515,13 @@ export const holeSize = (e) => (e.outer_diameter != null ? { w: e.outer_diameter
|
|
|
359
515
|
|
|
360
516
|
// The source's copper kept with a block of parts (moveGroup's keep): its tracks and vias as they were, each island a
|
|
361
517
|
// source trace joining its pins (and its plane, if its via reaches one), so nothing routes them again
|
|
362
|
-
function keptCopper(out, add, board, copper, planeNets) {
|
|
518
|
+
function keptCopper(out, add, board, copper, planeNets, later = false) {
|
|
363
519
|
const pins = padsByPin(out);
|
|
364
|
-
for (const k of board.copper.islands) { // (stubs are laid with the connection they start: see the traces below)
|
|
520
|
+
for (const k of board.copper.islands.filter((x) => !!x.after === later)) { // (stubs are laid with the connection they start: see the traces below)
|
|
365
521
|
const ports = [...new Set(k.pins.flatMap((p) => (pins.get(p) || []).map((f) => f.sp.source_port_id)))];
|
|
366
522
|
const plane = k.via && planeNets[k.net];
|
|
367
523
|
if (!ports.length || (ports.length < 2 && !plane)) continue; // nothing left to join
|
|
368
|
-
const st = add('source_trace', { connected_source_port_ids: ports, connected_source_net_ids: plane ? [plane.id] : [], subcircuit_id: SUB, display_name: `${k.pins.join(', ')}: the source's own copper
|
|
524
|
+
const st = add('source_trace', { connected_source_port_ids: ports, connected_source_net_ids: plane ? [plane.id] : [], subcircuit_id: SUB, display_name: `${k.pins.join(', ')}: the source's own copper`, ...(k.net ? { rulecad_net: k.net } : {}) });
|
|
369
525
|
for (const g of board.copper.tracks.filter((t) => t.island === k.id))
|
|
370
526
|
add('pcb_trace', { route: [{ route_type: 'wire', x: g.a.x, y: g.a.y, width: g.width, layer: g.layer }, { route_type: 'wire', x: g.b.x, y: g.b.y, width: g.width, layer: g.layer }], source_trace_id: st.source_trace_id, subcircuit_id: SUB, rulecad_kept: true });
|
|
371
527
|
for (const v of board.copper.vias.filter((x) => x.island === k.id)) {
|
|
@@ -488,8 +644,9 @@ function planeVias(out, add, board, copper) {
|
|
|
488
644
|
...out.filter((e) => e.type === 'pcb_hole').map((e) => ({ id: e.pcb_hole_id, x: e.x, y: e.y, r: e.hole_diameter / 2 }))];
|
|
489
645
|
const segs = [], sameNet = Object.fromEntries(Object.keys(board.planes).map((n) => [n, []])); // plane tracks drawn so far; each net's vias
|
|
490
646
|
const kept = board.copper || { tracks: [], vias: [], islands: [] }; // the source's copper, kept: in the way, and some pads already reach their plane by it
|
|
491
|
-
|
|
492
|
-
for (const
|
|
647
|
+
const laterIds = new Set((kept.islands || []).filter((k) => k.after).map((k) => k.id)); // (laid once routed: not in the router's way)
|
|
648
|
+
for (const g of kept.tracks) if ((g.layer === 'top' || g.layer === 'bottom') && !laterIds.has(g.island)) segs.push({ a: g.a, b: g.b, layer: g.layer, w: g.width });
|
|
649
|
+
for (const v of kept.vias) if (!laterIds.has(v.island)) circles.push({ id: `kept${circles.length}`, x: v.x, y: v.y, r: v.pad / 2 });
|
|
493
650
|
const reachedBy = new Set(kept.islands.filter((k) => k.via && board.planes[k.net]).flatMap((k) => k.pins));
|
|
494
651
|
const toRect = (x, y, q) => Math.hypot(Math.max(Math.abs(x - q.x) - q.w / 2, 0), Math.max(Math.abs(y - q.y) - q.h / 2, 0));
|
|
495
652
|
const toSeg = (x, y, a, c) => { const dx = c.x - a.x, dy = c.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; return Math.hypot(x - a.x - t * dx, y - a.y - t * dy); };
|
|
@@ -810,14 +967,14 @@ export function layerChanges(route, holes) {
|
|
|
810
967
|
const pieces = [[]];
|
|
811
968
|
for (const p of route) {
|
|
812
969
|
if (p.route_type !== 'through_obstacle') { pieces.at(-1).push(p); continue; }
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
});
|
|
817
|
-
if (!
|
|
970
|
+
// The router sees a hole or via as a square round its copper, so it may mark the change anywhere in that square,
|
|
971
|
+
// corners included: in it counts, and the track is taken on to the hole's centre on each side, so it joins its copper
|
|
972
|
+
const at = p.start, inSquare = (q, h, r) => Math.abs(q.x - h.x) <= r + 1e-6 && Math.abs(q.y - h.y) <= r + 1e-6;
|
|
973
|
+
const hole = holes.find((h) => { const r = Math.max(holeSize(h).w, holeSize(h).h) / 2; return inSquare(at, h, r) && inSquare(p.end, h, r); });
|
|
974
|
+
if (!hole) throw new Error(`the autorouter ran a track through a part at (${at.x.toFixed(2)}, ${at.y.toFixed(2)}) mm: move the parts apart or give it more room`);
|
|
818
975
|
const width = p.width ?? pieces.at(-1).at(-1)?.width;
|
|
819
|
-
pieces.at(-1).push({ route_type: 'wire', x: at.x, y: at.y, width, layer: p.from_layer });
|
|
820
|
-
pieces.push([{ route_type: 'wire', x: p.end.x, y: p.end.y, width, layer: p.to_layer }]);
|
|
976
|
+
pieces.at(-1).push({ route_type: 'wire', x: at.x, y: at.y, width, layer: p.from_layer }, { route_type: 'wire', x: hole.x, y: hole.y, width, layer: p.from_layer });
|
|
977
|
+
pieces.push([{ route_type: 'wire', x: hole.x, y: hole.y, width, layer: p.to_layer }, { route_type: 'wire', x: p.end.x, y: p.end.y, width, layer: p.to_layer }]);
|
|
821
978
|
}
|
|
822
979
|
return pieces.filter((q) => q.length > 1);
|
|
823
980
|
}
|
|
@@ -918,15 +1075,33 @@ export async function neckDown(json, traces, neck) {
|
|
|
918
1075
|
return out;
|
|
919
1076
|
}
|
|
920
1077
|
|
|
1078
|
+
// The autorouter's pipelines, tried in order until one routes the board: its own, then its others, each a different search
|
|
1079
|
+
const PIPELINES = ['AutoroutingPipelineSolver', 'AutoroutingPipelineSolver4', 'AutoroutingPipelineSolver5', 'AutoroutingPipelineSolver6', 'AutoroutingPipelineSolver8'];
|
|
1080
|
+
|
|
921
1081
|
async function routeOnce(json, toRoute, board, limit = 0) {
|
|
922
1082
|
// The autorouter uses JavaScript features from Node 22 (iterator helpers): say so, rather than fail inside it
|
|
923
1083
|
if (Number(process.versions.node.split('.')[0]) < 22) throw new Error(`routing a board's remaining connections needs Node 22 or newer (this is Node ${process.versions.node}); boards drawn wholly by rule build on Node 20`);
|
|
924
|
-
const
|
|
1084
|
+
const router = await import('@tscircuit/capacity-autorouter');
|
|
925
1085
|
const srj = await routeInput(json, toRoute, board);
|
|
926
|
-
|
|
927
|
-
//
|
|
928
|
-
|
|
929
|
-
|
|
1086
|
+
// The router's own pipeline first. If it gives up, one of its later stages throws (its via clean-up can, on a crowded
|
|
1087
|
+
// two-sided board: "a layer transition without a via"), or what it hands back fails here (a pad left without a
|
|
1088
|
+
// track, a track through a part), the next one: a different search from the start
|
|
1089
|
+
const pipelines = [...new Set([board.pipeline || PIPELINES[0], ...PIPELINES])], tried = [];
|
|
1090
|
+
for (const name of pipelines) {
|
|
1091
|
+
if (!router[name]) continue;
|
|
1092
|
+
const solver = new router[name](srj, { cacheProvider: null, ...(board.effort ? { effort: board.effort } : {}) }); // effort: how hard it searches (1, the router's own)
|
|
1093
|
+
// stepped by hand, so a repair can be given a time limit (a first route has none)
|
|
1094
|
+
try { while (!solver.solved && !solver.failed) { solver.step(); if (limit && Date.now() > limit) throw Object.assign(new Error('a repair took too long'), { late: true }); } }
|
|
1095
|
+
catch (e) { if (e.late) throw e; solver.failed = true; solver.error = solver.error || e.message; }
|
|
1096
|
+
if (solver.failed) { tried.push(`${name}: ${solver.error || 'no reason given'}`); continue; }
|
|
1097
|
+
try { return routedTraces(solver, srj, json); } catch (e) { tried.push(`${name}: ${e.message}`); }
|
|
1098
|
+
}
|
|
1099
|
+
throw new Error(tried.length > 1 ? `the autorouter couldn't route every connection, with any of its pipelines (${tried.join('; ')})` : tried[0]?.replace(/^\w+: /, '') || 'the autorouter has none of its pipelines');
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// What a solved pipeline hands back, as tracks on the board: throws if a pad is left without a track or a track runs
|
|
1103
|
+
// through a part
|
|
1104
|
+
function routedTraces(solver, srj, json) {
|
|
930
1105
|
// The routes for the connections asked for (the solver also hands back the fixed ones), each from its first pad to
|
|
931
1106
|
// its second, as tscircuit records them
|
|
932
1107
|
const traces = [], asked = new Map(srj.connections.map((c) => [c.name, c.pointsToConnect]));
|
package/kicad.mjs
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// A board in KiCad's own files, as KiCad reads them: tscircuit's converter (circuit-json-to-kicad) writes the board,
|
|
2
|
+
// and this makes up what it leaves out or reads differently, so KiCad's design-rule check sees the board our checks see.
|
|
3
|
+
// - nets: the converter takes each pad's, track's and via's net from a connectivity key that tscircuit's own core
|
|
4
|
+
// writes and a board built here doesn't. kicadNets() works the nets out (the ports each source trace joins, and the
|
|
5
|
+
// copper laid for it) and names each: its source net's name (GND), the net the board gave the trace (/USB+), else
|
|
6
|
+
// after its first pad (Net-(R4-Pad1))
|
|
7
|
+
// - a hole set off-centre in its pad: KiCad puts the pad at its hole and moves its copper by the drill's offset;
|
|
8
|
+
// tscircuit puts the pad at its copper, the hole moved by hole_offset. The converter writes the copper's place, so
|
|
9
|
+
// the hole lands off by the offset: patchKicadPcb() moves each such pad to its hole
|
|
10
|
+
// - castellated pads (a half hole on the edge) marked as KiCad's castellated pads, which may cross the board's edge
|
|
11
|
+
// - a via laid twice at one place (a kept via and the track that names it) written once
|
|
12
|
+
// - the rules: kicadProject() writes the project file KiCad reads them from, with the board's own minimums (pcb_board's
|
|
13
|
+
// min_* values, which our checks use), and a custom rule file for exceptions the source has (pads by its edge)
|
|
14
|
+
// - kicadDrc(): KiCad's own design-rule check on all of that, when KiCad is installed
|
|
15
|
+
// - kicadFab(): the Gerber and drill files, plotted by KiCad from the board that check has just passed
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import os from 'node:os';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import { execFileSync } from 'node:child_process';
|
|
20
|
+
|
|
21
|
+
const KICAD_CENTRE = 100; // where the converter puts the design's (0, 0) on KiCad's page (mm)
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Circuit JSON with every source port, source trace, pcb trace and via keyed to its net, and a named source net for
|
|
25
|
+
* each, as circuit-json-to-kicad reads them. A copy; the input is unchanged.
|
|
26
|
+
* @param {object[]} json @returns {object[]}
|
|
27
|
+
*/
|
|
28
|
+
export function kicadNets(json) {
|
|
29
|
+
const out = structuredClone(json);
|
|
30
|
+
const up = new Map(), find = (a) => { while (up.get(a) !== a) { up.set(a, up.get(up.get(a))); a = up.get(a); } return a; };
|
|
31
|
+
const join = (a, b) => { for (const x of [a, b]) if (!up.has(x)) up.set(x, x); up.set(find(a), find(b)); };
|
|
32
|
+
for (const e of out) if (e.type === 'source_trace') {
|
|
33
|
+
const ids = [...(e.connected_source_port_ids || []), ...(e.connected_source_net_ids || [])];
|
|
34
|
+
join(e.source_trace_id, e.source_trace_id);
|
|
35
|
+
for (const id of ids) join(e.source_trace_id, id);
|
|
36
|
+
}
|
|
37
|
+
for (const e of out) if (e.type === 'source_net' || e.type === 'source_port') join(e.source_net_id || e.source_port_id, e.source_net_id || e.source_port_id);
|
|
38
|
+
// a pin with more than one pad (a half hole and a header hole) has a port for each: one net. (Pins sharing only a name,
|
|
39
|
+
// as a module's GND pins do, are joined only where the board joins them)
|
|
40
|
+
const pin = new Map();
|
|
41
|
+
for (const e of out) if (e.type === 'source_port') { const k = `${e.source_component_id}:${e.name}:${e.pin_number}`; if (pin.has(k)) join(pin.get(k), e.source_port_id); else pin.set(k, e.source_port_id); }
|
|
42
|
+
const key = (id) => `net_${find(id)}`;
|
|
43
|
+
// each net's name: its source net's, the board's name for one of its traces, else after its first pad
|
|
44
|
+
const names = new Map();
|
|
45
|
+
for (const e of out) if (e.type === 'source_net') names.set(key(e.source_net_id), e.name);
|
|
46
|
+
for (const e of out) if (e.type === 'source_trace' && e.rulecad_net && !names.has(key(e.source_trace_id))) names.set(key(e.source_trace_id), e.rulecad_net);
|
|
47
|
+
const part = new Map(out.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
|
|
48
|
+
for (const e of out) if (e.type === 'source_port' && !names.has(key(e.source_port_id))) names.set(key(e.source_port_id), `Net-(${part.get(e.source_component_id) ?? '?'}-Pad${String(e.name ?? e.pin_number).replace(/^pin/, '')})`);
|
|
49
|
+
// one name, one net: KiCad joins nets that share a name (a USB-C socket's A5 and B5 are both its pin 5)
|
|
50
|
+
const taken = new Map();
|
|
51
|
+
for (const [k, n] of names) { const c = (taken.get(n) || 0) + 1; taken.set(n, c); if (c > 1) names.set(k, `${n}_${c}`); }
|
|
52
|
+
// a net no trace joins is a pin on its own: no KiCad net (net 0), as KiCad leaves an unconnected pad
|
|
53
|
+
const joined = new Set(out.filter((e) => e.type === 'source_trace').map((e) => key(e.source_trace_id)));
|
|
54
|
+
for (const k of pin.values()) if ([...pin.values()].filter((x) => key(x) === key(k)).length > 1 || out.some((e) => e.type === 'source_port' && e.source_port_id !== k && key(e.source_port_id) === key(k))) joined.add(key(k)); // (two pads of one pin: a net of their own)
|
|
55
|
+
const nets = new Map(out.filter((e) => e.type === 'source_net').map((e) => [key(e.source_net_id), e]));
|
|
56
|
+
for (const k of joined) if (!nets.has(k)) {
|
|
57
|
+
const n = { type: 'source_net', source_net_id: `rulecad_${k}`, name: names.get(k), member_source_group_ids: [], subcircuit_connectivity_map_key: k };
|
|
58
|
+
out.push(n); nets.set(k, n);
|
|
59
|
+
}
|
|
60
|
+
for (const [k, n] of nets) n.subcircuit_connectivity_map_key = k;
|
|
61
|
+
const traceKey = new Map();
|
|
62
|
+
for (const e of out) {
|
|
63
|
+
if (e.type === 'source_trace') { e.subcircuit_connectivity_map_key = key(e.source_trace_id); }
|
|
64
|
+
else if (e.type === 'source_port' && joined.has(key(e.source_port_id))) e.subcircuit_connectivity_map_key = key(e.source_port_id);
|
|
65
|
+
}
|
|
66
|
+
for (const e of out) if (e.type === 'pcb_trace' && e.source_trace_id && up.has(e.source_trace_id)) { e.subcircuit_connectivity_map_key = key(e.source_trace_id); traceKey.set(e.pcb_trace_id, e.subcircuit_connectivity_map_key); }
|
|
67
|
+
for (const e of out) if (e.type === 'pcb_via' && traceKey.has(e.pcb_trace_id)) e.subcircuit_connectivity_map_key = traceKey.get(e.pcb_trace_id);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The converter's .kicad_pcb made right for KiCad (see the top of this file): pads with an off-centre hole moved to
|
|
73
|
+
* their hole, castellated pads marked, a via laid twice written once.
|
|
74
|
+
* @param {string} text @param {object[]} json @returns {string}
|
|
75
|
+
*/
|
|
76
|
+
export function patchKicadPcb(text, json) {
|
|
77
|
+
const r4 = (n) => Math.round(n * 1e4) / 1e4;
|
|
78
|
+
// a pad with a drill offset: at its hole (the copper keeps its place: the offset is now from the hole to it)
|
|
79
|
+
text = text.replace(/(\(pad "[^"]*" thru_hole \w+\s*\(at )(-?[\d.e-]+) (-?[\d.e-]+)((?: -?[\d.e-]+)?\)(?:(?!\(pad )[\s\S])*?\(drill [^()]*\(offset (-?[\d.e-]+) (-?[\d.e-]+)\))/g,
|
|
80
|
+
(all, head, x, y, rest, dx, dy) => `${head}${r4(Number(x) - Number(dx))} ${r4(Number(y) - Number(dy))}${rest}`);
|
|
81
|
+
// Pads found by where their footprint puts them (the hole, now), in footprint coordinates
|
|
82
|
+
const comp = new Map(json.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, e]));
|
|
83
|
+
const at = (e) => { const c = comp.get(e.pcb_component_id); return c && { x: e.x + (e.hole_offset_x ?? 0) - c.center.x, y: -(e.y + (e.hole_offset_y ?? 0) - c.center.y), e }; };
|
|
84
|
+
const holes = json.filter((e) => e.type === 'pcb_plated_hole').map(at).filter(Boolean);
|
|
85
|
+
const find = (x, y) => holes.find((p) => Math.abs(p.x - Number(x)) < 1e-3 && Math.abs(p.y - Number(y)) < 1e-3)?.e;
|
|
86
|
+
// castellated: the half hole and every other pad of its pin (a header pad joined to it reaches the edge with it), as
|
|
87
|
+
// KiCad's castellated pads, which may cross the board's edge
|
|
88
|
+
const edgePins = new Set(holes.filter((p) => p.e.port_hints?.includes('castellated')).map((p) => `${p.e.pcb_component_id}:${p.e.port_hints?.[1]}`));
|
|
89
|
+
// a rectangular pad with rounded corners (rect_border_radius): KiCad's rounded rectangle, which the converter leaves square
|
|
90
|
+
text = text.replace(/\(pad "[^"]*" thru_hole (\w+)\s*\(at (-?[\d.e-]+) (-?[\d.e-]+)[^)]*\)/g, (all, shape, x, y) => {
|
|
91
|
+
const e = find(x, y); if (!e) return all;
|
|
92
|
+
let out = all;
|
|
93
|
+
if (shape === 'rect' && e.rect_border_radius) out = out.replace(' thru_hole rect', ' thru_hole roundrect') + `\n (roundrect_rratio ${r4(e.rect_border_radius / Math.min(e.rect_pad_width, e.rect_pad_height))})`;
|
|
94
|
+
if (edgePins.has(`${e.pcb_component_id}:${e.port_hints?.[1]}`)) out += '\n (property pad_prop_castellated)';
|
|
95
|
+
return out;
|
|
96
|
+
});
|
|
97
|
+
// the drill and place origin at the design's own (0, 0), so plots and our placement file share one frame
|
|
98
|
+
text = text.replace(/\(setup\b/, `(setup\n\t\t(aux_axis_origin ${KICAD_CENTRE} ${KICAD_CENTRE})`);
|
|
99
|
+
// a via twice at one place, the same size, layers and net: once
|
|
100
|
+
const seen = new Set();
|
|
101
|
+
text = text.replace(/\n \(via\s*\(at (-?[\d.e-]+) (-?[\d.e-]+)\)\s*\(size ([\d.]+)\)\s*\(drill ([\d.]+)\)\s*\(layers ([^)]*)\)\s*(\(net \d+\))?[\s\S]*?\n \)/g, (all, x, y, size, drill, layers, net) => {
|
|
102
|
+
const k = [r4(Number(x)), r4(Number(y)), size, drill, layers, net].join(' ');
|
|
103
|
+
if (seen.has(k)) return '';
|
|
104
|
+
seen.add(k); return all;
|
|
105
|
+
});
|
|
106
|
+
return text;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* KiCad's project file (.kicad_pro) with the board's own design rules, and a custom rules file (.kicad_dru):
|
|
111
|
+
* minimums from pcb_board's min_* values (what our checks use), the default net class at the board's clearance and
|
|
112
|
+
* track. edgeExempt: parts whose pads may come as close to the board's edge as the source has them ({ ref, edge }).
|
|
113
|
+
* @param {object[]} json @param {{ clearance?: number, track?: number, edgeExempt?: { ref: string, edge: number }[] }} [o]
|
|
114
|
+
* @returns {{ pro: string, dru: string }}
|
|
115
|
+
*/
|
|
116
|
+
export function kicadProject(json, { clearance, track, edgeExempt = [] } = {}) {
|
|
117
|
+
const b = json.find((e) => e.type === 'pcb_board') || {};
|
|
118
|
+
const via = json.find((e) => e.type === 'pcb_via');
|
|
119
|
+
const vias = json.filter((e) => e.type === 'pcb_via'), holes = json.filter((e) => e.type === 'pcb_plated_hole' || e.type === 'pcb_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width).filter(Boolean);
|
|
120
|
+
const viaPad = Math.min(b.min_via_pad_diameter ?? 0.3, ...vias.map((v) => v.outer_diameter)), viaHole = Math.min(b.min_via_hole_diameter ?? 0.2, ...vias.map((v) => v.hole_diameter));
|
|
121
|
+
const gap = clearance ?? b.min_trace_to_pad_edge_clearance ?? 0.1;
|
|
122
|
+
const rules = {
|
|
123
|
+
min_clearance: gap, min_track_width: Math.min(b.min_trace_width ?? 0.1, ...json.filter((e) => e.type === 'pcb_trace').flatMap((t) => t.route.map((p) => p.width ?? Infinity))),
|
|
124
|
+
min_via_diameter: viaPad, min_through_hole_diameter: Math.min(viaHole, ...holes), min_via_annular_width: Math.min(...vias.map((v) => (v.outer_diameter - v.hole_diameter) / 2), (viaPad - viaHole) / 2),
|
|
125
|
+
min_copper_edge_clearance: b.min_board_edge_clearance ?? 0.2, min_hole_clearance: b.min_trace_to_hole_edge_clearance ?? 0.2,
|
|
126
|
+
min_hole_to_hole: b.min_via_hole_edge_to_via_hole_edge_clearance ?? 0.1, min_silk_clearance: 0, min_microvia_diameter: 0.2, min_microvia_drill: 0.1,
|
|
127
|
+
allow_blind_buried_vias: false, allow_microvias: false, max_error: 0.005, use_height_for_length_calcs: true };
|
|
128
|
+
const pro = { board: { design_settings: { defaults: {}, rules, track_widths: [0], via_dimensions: [{ diameter: 0, drill: 0 }], rule_severities: {} } },
|
|
129
|
+
meta: { filename: 'board.kicad_pro', version: 3 },
|
|
130
|
+
net_settings: { classes: [{ name: 'Default', clearance: gap, track_width: track ?? 0.15, via_diameter: via?.outer_diameter ?? viaPad, via_drill: via?.hole_diameter ?? viaHole,
|
|
131
|
+
microvia_diameter: 0.2, microvia_drill: 0.1, diff_pair_gap: 0.2, diff_pair_width: 0.2, diff_pair_via_gap: 0.25, wire_width: 6, bus_width: 12, line_style: 0, pcb_color: 'rgba(0, 0, 0, 0.000)', schematic_color: 'rgba(0, 0, 0, 0.000)', priority: 2147483647 }], meta: { version: 3 } } };
|
|
132
|
+
const dru = ['(version 1)', ...edgeExempt.map((x) => `(rule "${x.ref}: its pads by the edge, as the source has them"\n (condition "A.Parent == '${x.ref}' && A.Type == 'Pad'")\n (constraint edge_clearance (min ${x.edge}mm)))`)].join('\n') + '\n';
|
|
133
|
+
return { pro: JSON.stringify(pro, null, 2) + '\n', dru };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// kicad-cli, where KiCad installs it (KICAD_CLI names another), or null when KiCad isn't installed
|
|
137
|
+
export function kicadCli(env = process.env) {
|
|
138
|
+
const candidates = [env.KICAD_CLI, '/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli', '/usr/bin/kicad-cli', '/usr/local/bin/kicad-cli', 'C:\\Program Files\\KiCad\\bin\\kicad-cli.exe'].filter(Boolean);
|
|
139
|
+
return candidates.find((p) => fs.existsSync(p)) ?? null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The board written where KiCad reads it, for fn({ cli, dir, board }); gone afterwards
|
|
143
|
+
async function onKicadBoard(json, o, fn) {
|
|
144
|
+
const cli = kicadCli();
|
|
145
|
+
if (!cli) return null;
|
|
146
|
+
const { CircuitJsonToKicadPcbConverter } = await import('circuit-json-to-kicad');
|
|
147
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rulecad-kicad-'));
|
|
148
|
+
try {
|
|
149
|
+
const netted = kicadNets(json), pcb = new CircuitJsonToKicadPcbConverter(netted); pcb.runUntilFinished();
|
|
150
|
+
const { pro, dru } = kicadProject(netted, o), board = path.join(dir, 'board.kicad_pcb');
|
|
151
|
+
fs.writeFileSync(board, patchKicadPcb(pcb.getOutputString(), netted));
|
|
152
|
+
fs.writeFileSync(path.join(dir, 'board.kicad_pro'), pro); fs.writeFileSync(path.join(dir, 'board.kicad_dru'), dru);
|
|
153
|
+
return await fn({ cli, dir, board });
|
|
154
|
+
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// kicad-cli's design-rule check, KiCad pouring the planes (extra: more arguments, as --save-board)
|
|
158
|
+
function runDrc(cli, dir, board, extra = []) {
|
|
159
|
+
const version = execFileSync(cli, ['version'], { encoding: 'utf8' }).trim();
|
|
160
|
+
execFileSync(cli, ['pcb', 'drc', '--refill-zones', ...extra, '--format', 'json', '--severity-all', '-o', path.join(dir, 'drc.json'), board], { stdio: 'pipe' });
|
|
161
|
+
const d = JSON.parse(fs.readFileSync(path.join(dir, 'drc.json'), 'utf8'));
|
|
162
|
+
const all = [...d.violations, ...d.unconnected_items].filter((x) => x.type !== 'lib_footprint_issues'); // (KiCad's library has no "tscircuit" footprints: nothing about the board)
|
|
163
|
+
return { version, errors: all.filter((x) => x.severity === 'error'), warnings: all.filter((x) => x.severity !== 'error') };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* KiCad's own design-rule check on the board, as a second opinion: its files written as kicadFiles() writes them
|
|
168
|
+
* (KiCad pours the planes itself, by its rules), checked by kicad-cli. -> { version, errors: [{ type, description,
|
|
169
|
+
* items }], warnings } or null when KiCad isn't installed.
|
|
170
|
+
* @param {object[]} json @param {{ clearance?: number, track?: number, edgeExempt?: { ref: string, edge: number }[] }} [o]
|
|
171
|
+
*/
|
|
172
|
+
export async function kicadDrc(json, o = {}) {
|
|
173
|
+
return onKicadBoard(json, o, ({ cli, dir, board }) => runDrc(cli, dir, board));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Whether a board's fab files must come from KiCad: slotted holes (the Gerber writer can't drill one), or rounded pads
|
|
178
|
+
* beside a copper plane (it plots them square, so their corners reach into a plane cut round the true shape).
|
|
179
|
+
* @param {object[]} json @returns {boolean}
|
|
180
|
+
*/
|
|
181
|
+
export function needsKicadFab(json) {
|
|
182
|
+
const plated = json.filter((e) => e.type === 'pcb_plated_hole');
|
|
183
|
+
return plated.some((e) => e.hole_width != null && e.hole_height != null && e.hole_width !== e.hole_height) || (plated.some((e) => e.rect_border_radius) && json.some((e) => e.type === 'pcb_copper_pour'));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Every hole the board's design has, found in KiCad's drill files: its place, its size, and a slot's length. Excellon text
|
|
188
|
+
* in mm with its zero at the design's. -> what's wrong, in words ([] when they agree).
|
|
189
|
+
* @param {object[]} json @param {string} pth @param {string} npth @returns {string[]}
|
|
190
|
+
*/
|
|
191
|
+
export function drillMismatches(json, pth, npth) {
|
|
192
|
+
const read = (text) => {
|
|
193
|
+
const tools = new Map(), out = []; let size = null;
|
|
194
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
195
|
+
const line = raw.trim(), tool = line.match(/^T(\d+)(?:[A-Z]\S*?)?C([\d.]+)/), pick = line.match(/^T(\d+)$/), at = line.match(/^X(-?[\d.]+)Y(-?[\d.]+)(?:G85X(-?[\d.]+)Y(-?[\d.]+))?/);
|
|
196
|
+
if (tool) tools.set(tool[1], Number(tool[2])); else if (pick) size = tools.get(pick[1]);
|
|
197
|
+
else if (at) out.push({ x: (Number(at[1]) + (at[3] != null ? Number(at[3]) : Number(at[1]))) / 2, y: (Number(at[2]) + (at[4] != null ? Number(at[4]) : Number(at[2]))) / 2, d: size, run: at[3] != null ? Math.hypot(Number(at[3]) - Number(at[1]), Number(at[4]) - Number(at[2])) : 0, used: false });
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
};
|
|
201
|
+
const near = 0.011, wrong = [];
|
|
202
|
+
const compare = (text, all, kind) => {
|
|
203
|
+
const found = read(text), seen = new Set(), wanted = all.filter((h) => { const k = [h.x.toFixed(3), h.y.toFixed(3), h.d, h.run].join(); return !seen.has(k) && seen.add(k); }); // (a via laid twice is drilled once)
|
|
204
|
+
for (const h of wanted) {
|
|
205
|
+
const f = found.find((q) => !q.used && Math.hypot(q.x - h.x, q.y - h.y) < near);
|
|
206
|
+
if (!f) { wrong.push(`no ${kind} hole at (${h.x.toFixed(3)}, ${h.y.toFixed(3)})`); continue; }
|
|
207
|
+
f.used = true;
|
|
208
|
+
if (Math.abs(f.d - h.d) > near || Math.abs(f.run - h.run) > near) wrong.push(`${kind} hole at (${h.x.toFixed(3)}, ${h.y.toFixed(3)}): ${f.d} mm${f.run ? ' slot' : ''} in the file, ${h.d} mm${h.run ? ` slot running ${h.run.toFixed(3)} mm` : ''} in the design`);
|
|
209
|
+
}
|
|
210
|
+
for (const f of found.filter((q) => !q.used)) wrong.push(`a ${kind} hole at (${f.x.toFixed(3)}, ${f.y.toFixed(3)}) the design doesn't have`);
|
|
211
|
+
};
|
|
212
|
+
const hole = (e) => { const w = e.hole_width, h = e.hole_height, slot = e.hole_diameter == null && w != null && h != null; return { x: e.x + (e.hole_offset_x ?? 0), y: e.y + (e.hole_offset_y ?? 0), d: slot ? Math.min(w, h) : e.hole_diameter ?? w, run: slot ? Math.abs(w - h) : 0 }; };
|
|
213
|
+
compare(pth, json.filter((e) => e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map(hole), 'plated');
|
|
214
|
+
compare(npth, json.filter((e) => e.type === 'pcb_hole').map(hole), 'unplated');
|
|
215
|
+
return wrong;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The Gerber and drill files, plotted by KiCad from the very board its design-rule check has just passed, planes poured,
|
|
220
|
+
* named as a fab expects: { 'name.GTL': text, ..., 'name-PTH.DRL': text, 'name-NPTH.DRL': text }. Throws if the check
|
|
221
|
+
* finds an error (allow(finding): one that's accepted, the source's own) or the drill files aren't the design's holes;
|
|
222
|
+
* null when KiCad isn't installed.
|
|
223
|
+
* @param {object[]} json @param {string} name @param {{ clearance?: number, track?: number, edgeExempt?: object[], allow?: (x: any) => boolean }} [o]
|
|
224
|
+
*/
|
|
225
|
+
export async function kicadFab(json, name, o = {}) {
|
|
226
|
+
return onKicadBoard(json, o, ({ cli, dir, board }) => {
|
|
227
|
+
const drc = runDrc(cli, dir, board, ['--save-board']), errors = drc.errors.filter((x) => !o.allow?.(x));
|
|
228
|
+
if (errors.length) throw new Error(`no fab files: KiCad's design-rule check found ${errors.length} errors on the board it would plot (first: ${errors[0].description})`);
|
|
229
|
+
const copper = json.find((e) => e.type === 'pcb_board')?.num_layers ?? 2, inner = Array.from({ length: copper - 2 }, (_, i) => `In${i + 1}.Cu`);
|
|
230
|
+
const layers = ['F.Cu', ...inner, 'B.Cu', 'F.Paste', 'B.Paste', 'F.SilkS', 'B.SilkS', 'F.Mask', 'B.Mask', 'Edge.Cuts'];
|
|
231
|
+
const plots = path.join(dir, 'plots'), drills = path.join(dir, 'drills');
|
|
232
|
+
fs.mkdirSync(plots); fs.mkdirSync(drills);
|
|
233
|
+
execFileSync(cli, ['pcb', 'export', 'gerbers', '--layers', layers.join(','), '--use-drill-file-origin', '--no-x2', '--no-netlist', '-o', `${plots}/`, board], { stdio: 'pipe' });
|
|
234
|
+
execFileSync(cli, ['pcb', 'export', 'drill', '--format', 'excellon', '--excellon-separate-th', '--excellon-units', 'mm', '--excellon-zeros-format', 'decimal', '--excellon-oval-format', 'alternate', '--drill-origin', 'plot', '-o', `${drills}/`, board], { stdio: 'pipe' });
|
|
235
|
+
const ext = { F_Cu: 'GTL', B_Cu: 'GBL', F_Paste: 'GTP', B_Paste: 'GBP', F_Silkscreen: 'GTO', B_Silkscreen: 'GBO', F_Mask: 'GTS', B_Mask: 'GBS', Edge_Cuts: 'GKO' };
|
|
236
|
+
const out = {};
|
|
237
|
+
for (const f of fs.readdirSync(plots)) {
|
|
238
|
+
if (f.endsWith('.gbrjob')) continue;
|
|
239
|
+
const layer = f.replace(/^board-/, '').replace(/\.[^.]+$/, ''), inn = layer.match(/^In(\d+)_Cu$/), e = inn ? `G${inn[1]}` : ext[layer];
|
|
240
|
+
if (!e) throw new Error(`no fab files: KiCad plotted a layer we can't name (${f})`);
|
|
241
|
+
out[`${name}.${e}`] = fs.readFileSync(path.join(plots, f), 'utf8');
|
|
242
|
+
}
|
|
243
|
+
if (Object.keys(out).length !== layers.length) throw new Error(`no fab files: KiCad plotted ${Object.keys(out).length} of ${layers.length} layers`);
|
|
244
|
+
const pth = fs.readFileSync(path.join(drills, 'board-PTH.drl'), 'utf8'), npth = fs.readFileSync(path.join(drills, 'board-NPTH.drl'), 'utf8');
|
|
245
|
+
const wrong = drillMismatches(json, pth, npth);
|
|
246
|
+
if (wrong.length) throw new Error(`no fab files: KiCad's drill files aren't the design's holes (${wrong.length}; first: ${wrong[0]})`);
|
|
247
|
+
return { ...out, [`${name}-PTH.DRL`]: pth, [`${name}-NPTH.DRL`]: npth };
|
|
248
|
+
});
|
|
249
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/pcb",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
4
4
|
"description": "Circuit boards from rules: parts from rule sets or any standard footprint, quarter-turn rotation, nets and autorouting; keyboards with every matrix track drawn by rule. Gerbers, KiCad files and a JLCPCB BOM. Circuit JSON written directly: no React.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": "./pcb.mjs",
|
|
7
7
|
"files": [
|
|
8
8
|
"pcb.mjs",
|
|
9
9
|
"circuit.mjs",
|
|
10
|
+
"kicad.mjs",
|
|
10
11
|
"README.md",
|
|
11
12
|
"LICENSE"
|
|
12
13
|
],
|
|
@@ -29,12 +30,16 @@
|
|
|
29
30
|
"url": "git+https://github.com/JoniBach/rulecad.git",
|
|
30
31
|
"directory": "packages/pcb"
|
|
31
32
|
},
|
|
33
|
+
"homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/pcb#readme",
|
|
34
|
+
"bugs": {
|
|
35
|
+
"url": "https://github.com/JoniBach/rulecad/issues"
|
|
36
|
+
},
|
|
32
37
|
"dependencies": {
|
|
33
38
|
"@flatten-js/core": "1.6.14",
|
|
34
39
|
"@jscad/modeling": "^2.12.0",
|
|
40
|
+
"@rulecad/rules": "^0.3.7",
|
|
35
41
|
"@resvg/resvg-js": "2.6.2",
|
|
36
|
-
"@rulecad/
|
|
37
|
-
"@rulecad/smooth": "^0.1.0",
|
|
42
|
+
"@rulecad/smooth": "^0.1.2",
|
|
38
43
|
"@tscircuit/capacity-autorouter": "0.0.982",
|
|
39
44
|
"@tscircuit/checks": "0.0.264",
|
|
40
45
|
"@tscircuit/circuit-json-util": "0.0.122",
|
package/pcb.mjs
CHANGED
|
@@ -13,9 +13,13 @@
|
|
|
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, smtBounds, slideClear } from './circuit.mjs';
|
|
16
|
+
import { circuitJson, bounds, smtBounds, slideClear, viaHoleGaps } from './circuit.mjs';
|
|
17
17
|
export { bounds };
|
|
18
|
-
import {
|
|
18
|
+
import { createRequire } from 'node:module';
|
|
19
|
+
// The published rule sets a footprint's pins come from (a Pico's GPIO, a XIAO's labels): read from @rulecad/rules as
|
|
20
|
+
// published, not through @rulecad/cad, which pcb would then depend on (and cad names pcb: a loop), and which copies a
|
|
21
|
+
// set into the current folder when it reads one
|
|
22
|
+
const loadRuleSet = (name) => createRequire(import.meta.url)(`@rulecad/rules/${name}.json`);
|
|
19
23
|
import jscad from '@jscad/modeling';
|
|
20
24
|
|
|
21
25
|
// A rows × cols grid of keys at the key pitch, centred on the origin: [{ r, c, x, y, n }], n counting from 1, row 0
|
|
@@ -55,9 +59,10 @@ export const picoGpio = (side) => Object.entries(loadRuleSet('pico').rules[`gpio
|
|
|
55
59
|
// ---------- any board ----------
|
|
56
60
|
// Parts for any board, not only keyboards. Each returns a part as circuit.mjs describes it: put them in board.parts, join
|
|
57
61
|
// their pins with board.nets, and set board.autoroute. o (all optional): { rotation: 0 | 90 | 180 | 270, layer,
|
|
58
|
-
// mpn, labels: { pin1: 'GND', ... }, sch: { x, y }
|
|
62
|
+
// mpn, labels: { pin1: 'GND', ... }, sch: { x, y }, model: { boxes: [{ min, max }] } (its 3D body in its own frame, z up
|
|
63
|
+
// from the board's face, mm) }. Pin labels name the pins in nets ('U1.GND') and on the schematic.
|
|
59
64
|
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
|
-
courtyard: o.courtyard ?? null, sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} }, ...more });
|
|
65
|
+
courtyard: o.courtyard ?? null, sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} }, ...(o.model ? { model: o.model } : {}), ...more });
|
|
61
66
|
const pinNo = (p) => Number(p.pin.replace(/\D/g, ''));
|
|
62
67
|
// A rule set's pin map ({ "1": "GND", ... }) as pin labels ({ pin1: 'GND', ... })
|
|
63
68
|
const labelsFrom = (set, rule) => Object.fromEntries(Object.entries(loadRuleSet(set).rules[rule].pins).map(([n, l]) => [`pin${n}`, l]));
|
|
@@ -513,6 +518,7 @@ export function fromKicadPcb(text) {
|
|
|
513
518
|
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
519
|
const ratio = kidOf(p, 'roundrect_rratio'); // rounded corners, as a share of the shorter side
|
|
515
520
|
if (shape === 'roundrect' && ratio) pad.corner = r4(num(ratio[1]) * Math.min(pad.w, pad.h));
|
|
521
|
+
if (shape === 'oval' && pad.w !== pad.h) pad.corner = r4(Math.min(pad.w, pad.h) / 2); // an oval: round ends, a rectangle's corners rounded all the way
|
|
516
522
|
if (drill) {
|
|
517
523
|
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
524
|
pad.hole = Math.min(...ds);
|
|
@@ -576,7 +582,7 @@ export function fromKicadPcb(text) {
|
|
|
576
582
|
export function clone(circuit, o = {}) {
|
|
577
583
|
const inner = (l) => /^In\d+\.Cu$/.test(l), layers = o.layers ?? circuit.layers ?? 2;
|
|
578
584
|
const planes = o.planes ?? Object.entries(circuit.planes || {}).filter(([, ls]) => ls.some(inner)).map(([n]) => n);
|
|
579
|
-
const notes = [], castellated = new Set()
|
|
585
|
+
const notes = [], castellated = new Set();
|
|
580
586
|
const parts = circuit.parts.map((p) => {
|
|
581
587
|
const quarterTurn = p.rotation % 90 === 0, t = (p.rotation * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
|
|
582
588
|
const pads = p.pads.map((q) => {
|
|
@@ -584,11 +590,10 @@ export function clone(circuit, o = {}) {
|
|
|
584
590
|
if (!q.smd) {
|
|
585
591
|
const at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
|
|
586
592
|
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
593
|
if (q.w === q.h && !q.hole_offset) return { pin, hint: q.pin, ...at, hole: q.hole, outer: q.w };
|
|
589
594
|
// an oval pad, or a hole off its centre: a rounded rectangle round the hole, turned with the part (quarter turns)
|
|
590
595
|
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] } };
|
|
596
|
+
return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(w, h), rect: { w, h, offset: q.hole_offset || [0, 0], ...(q.hole_size ? { slot: sw ? [q.hole_size[1], q.hole_size[0]] : q.hole_size } : {}) } }; // (slot: a slotted hole's width and height)
|
|
592
597
|
}
|
|
593
598
|
const turn = q.angle + (quarterTurn ? 0 : p.rotation);
|
|
594
599
|
if (turn % 90 === 0) { // a rectangle, its sides swapped by a quarter turn of its own
|
|
@@ -620,7 +625,6 @@ export function clone(circuit, o = {}) {
|
|
|
620
625
|
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
626
|
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
627
|
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
628
|
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
629
|
const src = circuit.source || {}; // the source's via and clearance, which its layout was made to
|
|
626
630
|
const sizes = { ...(src.via ? { via_pad: src.via.pad, via_hole: src.via.hole } : {}), ...(src.clearance ? { plane_clearance: src.clearance } : {}) };
|
|
@@ -1085,6 +1089,37 @@ export const holes = (json) => json.filter((e) => e.type === 'pcb_hole' && !e.pc
|
|
|
1085
1089
|
const mm = (x) => String(Number(x.toFixed(3))); // 0.30000000000000004 reads as 0.3
|
|
1086
1090
|
// checks(json, v, matrix, source) -> findings ({ level, text }): tscircuit's own design checks, the fab's limits, the
|
|
1087
1091
|
// matrix, and for a clone (source: { circuit, arranged }) the source's circuit and placement
|
|
1092
|
+
export { viaHoleGaps }; // (in circuit.mjs, which repairs by it)
|
|
1093
|
+
|
|
1094
|
+
// A source board's nearest track to its edge, copper to edge (mm): what its own layout allows there
|
|
1095
|
+
export function sourceEdgeGap(circuit) {
|
|
1096
|
+
const edges = [circuit.outline, ...(circuit.cutouts || [])].filter((o) => o?.length).flatMap((o) => o.map((p, i) => [p, o[(i + 1) % o.length]]));
|
|
1097
|
+
const ps = (p, a, b) => { const dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0; return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy); };
|
|
1098
|
+
const gaps = (circuit.routing?.tracks || []).map((g) => Math.min(...edges.map(([a, b]) => Math.min(ps(g.a, a, b), ps(g.b, a, b), ps(a, g.a, g.b), ps(b, g.a, g.b)))) - g.width / 2);
|
|
1099
|
+
return gaps.length && edges.length ? Math.min(...gaps) : null;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// The rules KiCad checks a board by: its own clearance, and a clone's pads by the edge where the source has them
|
|
1103
|
+
// (inherited: the design-rule errors already said to be the source's)
|
|
1104
|
+
function kicadRules(json, inherited) {
|
|
1105
|
+
const edgeExempt = [...new Set(inherited.map((e) => e.message?.match(/^SMT pad (\w+)\./)?.[1]).filter(Boolean))].map((ref) => ({ ref, edge: 0 }));
|
|
1106
|
+
return { clearance: json.find((e) => e.type === 'pcb_board')?.min_trace_to_pad_edge_clearance, edgeExempt };
|
|
1107
|
+
}
|
|
1108
|
+
// A KiCad finding that is the source's own: a kept track by the edge no nearer than the source's nearest (KiCad's place
|
|
1109
|
+
// is 100 mm in, y down)
|
|
1110
|
+
function kicadSourceEdge(json, source) {
|
|
1111
|
+
const srcEdge = source?.circuit ? sourceEdgeGap(source.circuit) : null;
|
|
1112
|
+
const keptSegs = json.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept).flatMap((t) => t.route.slice(1).map((q, i) => [t.route[i], q]));
|
|
1113
|
+
const onKept = (pos) => keptSegs.some(([a, b]) => { const p = { x: pos.x - 100, y: 100 - pos.y }, dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0; return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy) < 0.02; });
|
|
1114
|
+
return (x) => x.type === 'copper_edge_clearance' && srcEdge != null && x.items.some((i) => /^Track /.test(i.description) && onKept(i.pos)) && Number(x.description.match(/actual ([\d.]+) mm/)?.[1]) >= srcEdge - 1e-3;
|
|
1115
|
+
}
|
|
1116
|
+
// The design-rule errors a clone has where its source has them, for kicadRules
|
|
1117
|
+
async function sourceErrors(json, source) {
|
|
1118
|
+
if (!source?.circuit) return [];
|
|
1119
|
+
const { runAllChecks } = await import('@tscircuit/checks'), same = asSource(json, source.circuit, source.arranged?.kept);
|
|
1120
|
+
return (await runAllChecks(structuredClone(json))).filter((e) => same(e));
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1088
1123
|
export async function checks(json, v, matrix, source) { // source: a clone's { circuit, arranged } (its own checks join these)
|
|
1089
1124
|
const { runAllChecks } = await import('@tscircuit/checks');
|
|
1090
1125
|
const out = [], j = v.jlcpcb;
|
|
@@ -1102,8 +1137,15 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
|
|
|
1102
1137
|
// 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
1138
|
// source's design (a mid-mount socket in its notch): said, not failed. Anything else near the edge fails as usual
|
|
1104
1139
|
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));
|
|
1140
|
+
// A clone's own kept tracks as near the edge as the source's own come (its tracks by its USB-C notch): the source's
|
|
1141
|
+
// nearest track to its edge, copper to edge, measured on the source
|
|
1142
|
+
const srcEdge = source?.circuit ? sourceEdgeGap(source.circuit) : null, keptIds = new Set(json.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept).map((e) => e.pcb_trace_id));
|
|
1143
|
+
const keptByEdge = (e) => { const m = e.message?.match(/^Trace too close to board edge \(([\d.]+)mm/), id = JSON.stringify(e).match(/pcb_trace_\d+/)?.[0];
|
|
1144
|
+
if (!m || srcEdge == null || !keptIds.has(id)) return false;
|
|
1145
|
+
const t = json.find((x) => x.pcb_trace_id === id), w = Math.max(...t.route.map((q) => q.width ?? 0));
|
|
1146
|
+
return Number(m[1]) - w / 2 >= srcEdge - 1e-3; };
|
|
1105
1147
|
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)))
|
|
1148
|
+
.filter((e) => !((same?.(e) || keptByEdge(e)) && inherited.push(e)))
|
|
1107
1149
|
.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
|
|
1108
1150
|
const problems = [...json, ...drc].filter((e) => /_error$/.test(e.type));
|
|
1109
1151
|
const seen = new Set(), errors = problems.filter((e) => !seen.has(e.message) && seen.add(e.message));
|
|
@@ -1179,17 +1221,32 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
|
|
|
1179
1221
|
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
1222
|
if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
|
|
1181
1223
|
// 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
|
|
1224
|
+
// between them (under the recommended ring a warning, under the least a failure). A via's ring and a plated hole's
|
|
1225
|
+
// have their own figures (JLCPCB asks a via's pad only 0.1 mm wider than its hole). A clone's vias as its source
|
|
1183
1226
|
// has them are the source's design: said, not failed
|
|
1184
1227
|
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
|
-
|
|
1186
|
-
|
|
1187
|
-
const
|
|
1228
|
+
// (a plated hole sharing its pin with a surface pad of its part is a via in that pad, such as a chip's thermal vias
|
|
1229
|
+
// under its exposed pad: a via's figures)
|
|
1230
|
+
const padPins = new Set(json.filter((e) => e.type === 'pcb_smtpad').map((e) => `${e.pcb_component_id}:${e.port_hints?.[0]}`));
|
|
1231
|
+
const inPad = (e) => e.type === 'pcb_plated_hole' && e.port_hints?.slice(1).some((h) => padPins.has(`${e.pcb_component_id}:${String(h).replace(/^pin/, '')}`));
|
|
1232
|
+
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' || inPad(e) }));
|
|
1233
|
+
const leastOf = (r) => (r.via ? j.via_annular_min ?? j.annular_min ?? 0.18 : j.annular_min ?? 0.18), wantOf = (r) => (r.via ? j.via_annular ?? j.annular : j.annular);
|
|
1234
|
+
const 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 < leastOf(r) - 1e-9), smallRings = rings.filter((r) => !asSrc(r.e) && r.ring >= leastOf(r) - 1e-9 && r.ring < wantOf(r) - 1e-9);
|
|
1235
|
+
const inherited_ = rings.filter((r) => asSrc(r.e) && r.ring < wantOf(r)).length, kind = (list) => (list.every((r) => r.via) ? 'vias' : list.every((r) => !r.via) ? 'plated holes' : 'vias and plated holes');
|
|
1236
|
+
const least = (list) => mm(Math.min(...list.map((r) => r.ring))), figures = (list) => [...new Set(list.map((r) => (r.via ? 'vias' : 'plated holes')))].map((k) => k === 'vias' ? `${j.via_annular_min ?? j.annular_min} mm for vias` : `${j.annular_min} mm for plated holes`).join(', ');
|
|
1188
1237
|
if (rings.length) {
|
|
1189
1238
|
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
|
|
1191
|
-
: smallRings.length ? { level: 'warn', text: `${smallRings.length} ${smallRings
|
|
1192
|
-
: { level: 'pass', text: `${rings.filter((r) => r.via).length} vias and ${rings.filter((r) => !r.via).length} plated holes
|
|
1239
|
+
: thinRings.length ? { level: 'fail', text: `${thinRings.length} ${kind(thinRings)} with a ${least(thinRings)} mm ring, under JLCPCB's least (${figures(thinRings)})` }
|
|
1240
|
+
: smallRings.length ? { level: 'warn', text: `${smallRings.length} ${kind(smallRings)} with a ${least(smallRings)} mm ring: above JLCPCB's least, under what it recommends (${[...new Set(smallRings.map((r) => (r.via ? `${j.via_annular ?? j.annular} mm for vias` : `${j.annular} mm for plated holes`)))].join(', ')})` }
|
|
1241
|
+
: { level: 'pass', text: `${rings.filter((r) => r.via).length} vias (rings ${rings.some((r) => r.via) ? least(rings.filter((r) => r.via)) : '-'} mm or more) and ${rings.filter((r) => !r.via).length} plated holes (${rings.some((r) => !r.via) ? least(rings.filter((r) => !r.via)) : '-'} mm or more): JLCPCB recommends ${j.via_annular ?? j.annular} and ${j.annular}${inherited_ ? `; ${inherited_} as the source has them` : ''}` });
|
|
1242
|
+
}
|
|
1243
|
+
// A via's hole to a track of another net (JLCPCB measures it from the hole's edge, not the via's pad: a small via's
|
|
1244
|
+
// thin ring leaves less room than the copper clearance suggests)
|
|
1245
|
+
if (j.via_hole_track && json.some((e) => e.type === 'pcb_via')) {
|
|
1246
|
+
const close = viaHoleGaps(json).filter((g) => g.gap < j.via_hole_track - 1e-6);
|
|
1247
|
+
const own = close.filter((g) => !(g.kept && asSrc(g.via)));
|
|
1248
|
+
out.push(own.length ? { level: 'fail', text: `${own.length} tracks closer than JLCPCB's ${j.via_hole_track} mm to a via's hole (${mm(Math.min(...own.map((g) => g.gap)))} mm at ${mm(own[0].at.x)}, ${mm(own[0].at.y)})` }
|
|
1249
|
+
: { level: 'pass', text: `every via's hole ${j.via_hole_track} mm or more from tracks of other nets${close.length ? `, but ${close.length} as the source has them` : ''}` });
|
|
1193
1250
|
}
|
|
1194
1251
|
// Silkscreen the fab can print: lines no thinner than silk_line, text no smaller than silk_text
|
|
1195
1252
|
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);
|
|
@@ -1222,6 +1279,20 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
|
|
|
1222
1279
|
? { 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(' ')})` }
|
|
1223
1280
|
: { level: 'fail', text: 'matrix: two keys share a row and column, or a GPIO is used twice' });
|
|
1224
1281
|
}
|
|
1282
|
+
// KiCad's own design-rule check, when KiCad is installed: the board as KiCad reads it, its planes poured by KiCad. A
|
|
1283
|
+
// clone's pads by the edge where the source has them are allowed there, as in our checks
|
|
1284
|
+
const { kicadDrc } = await import('./kicad.mjs');
|
|
1285
|
+
const kicad = await kicadDrc(json, kicadRules(json, inherited)).catch((e) => ({ failed: e }));
|
|
1286
|
+
if (!kicad) out.push({ level: 'info', text: 'KiCad isn\'t installed: its design-rule check, a second opinion, skipped' });
|
|
1287
|
+
else if (kicad.failed) out.push({ level: 'warn', text: `KiCad's design-rule check didn't run: ${String(kicad.failed.message || kicad.failed).split('\n')[0]}` });
|
|
1288
|
+
else {
|
|
1289
|
+
const asSrcEdge = kicadSourceEdge(json, source), srcEdgeHits = kicad.errors.filter(asSrcEdge);
|
|
1290
|
+
kicad.errors = kicad.errors.filter((x) => !asSrcEdge(x));
|
|
1291
|
+
if (srcEdgeHits.length) inherited.push(...srcEdgeHits.map((x) => ({ message: `KiCad: ${x.description}` })));
|
|
1292
|
+
const by = (list) => Object.entries(list.reduce((m, x) => ((m[x.type.replace(/_/g, ' ')] = (m[x.type.replace(/_/g, ' ')] || 0) + 1), m), {})).map(([t, n]) => `${n} ${t}`).join(', ');
|
|
1293
|
+
out.push(kicad.errors.length ? { level: 'fail', text: `KiCad ${kicad.version}'s design-rule check: ${kicad.errors.length} errors (${by(kicad.errors)}); first: ${kicad.errors[0].description}` }
|
|
1294
|
+
: { level: 'pass', text: `KiCad ${kicad.version}'s design-rule check, its own planes poured: no errors${kicad.warnings.length ? ` (warnings: ${by(kicad.warnings)})` : ''}` });
|
|
1295
|
+
}
|
|
1225
1296
|
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
1297
|
if (source?.circuit) out.push(...sameCircuit(json, source.circuit, {}, source.arranged?.added || []), ...placementChecks(source.arranged || source.circuit, source.circuit.placement || learnPlacement(source.circuit)));
|
|
1227
1298
|
const notes = new Set([...json, ...drc].filter((e) => /_warning$/.test(e.type)).map((e) => e.type.replace(/^(source|pcb)_|_warning$/g, '').replace(/_/g, ' ')));
|
|
@@ -1288,7 +1359,17 @@ function planeChecks(json) {
|
|
|
1288
1359
|
// ---------- files ----------
|
|
1289
1360
|
// The fab files: Gerbers (KiCad's Protel names, which JLCPCB reads), drill files, BOM and placement -> { name: text }
|
|
1290
1361
|
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' };
|
|
1291
|
-
export async function fabFiles(json, name) {
|
|
1362
|
+
export async function fabFiles(json, name, { source } = {}) {
|
|
1363
|
+
// Rounded pads and slots are more than the Gerber writer draws: it plots a rounded pad square, so its corners reach
|
|
1364
|
+
// into a plane cut round the true shape, and it can't drill a slot. KiCad plots those boards, and checks the very copper
|
|
1365
|
+
// it plots first; without KiCad they aren't made at all
|
|
1366
|
+
const { kicadFab, needsKicadFab } = await import('./kicad.mjs');
|
|
1367
|
+
if (needsKicadFab(json)) {
|
|
1368
|
+
const made = await kicadFab(json, name, { ...kicadRules(json, await sourceErrors(json, source)), allow: kicadSourceEdge(json, source) });
|
|
1369
|
+
if (!made) throw new Error('this board has slotted holes, or rounded pads beside a copper plane: its fab files need KiCad (install it, or name kicad-cli in KICAD_CLI)');
|
|
1370
|
+
const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
|
|
1371
|
+
return { ...made, [`${name}-bom.csv`]: bom(json), [`${name}-cpl.csv`]: convertCircuitJsonToPickAndPlaceCsv(json) };
|
|
1372
|
+
}
|
|
1292
1373
|
const { convertSoupToGerberCommands, stringifyGerberCommandLayers, convertSoupToExcellonDrillCommands, stringifyExcellonDrill } = await import('circuit-json-to-gerber');
|
|
1293
1374
|
const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
|
|
1294
1375
|
const out = {};
|
|
@@ -1316,11 +1397,15 @@ function bom(json) {
|
|
|
1316
1397
|
}
|
|
1317
1398
|
|
|
1318
1399
|
// KiCad's own files, to check with kicad-cli or finish by hand: { 'name.kicad_pcb': text, 'name.kicad_sch': text }
|
|
1319
|
-
export async function kicadFiles(json, name) {
|
|
1400
|
+
export async function kicadFiles(json, name, { clearance, track, edgeExempt: exempt, source } = {}) {
|
|
1401
|
+
const edgeExempt = exempt ?? kicadRules(json, await sourceErrors(json, source)).edgeExempt;
|
|
1320
1402
|
const { CircuitJsonToKicadPcbConverter, CircuitJsonToKicadSchConverter } = await import('circuit-json-to-kicad');
|
|
1321
|
-
const
|
|
1403
|
+
const { kicadNets, patchKicadPcb, kicadProject } = await import('./kicad.mjs');
|
|
1404
|
+
const netted = kicadNets(json); // (see kicad.mjs: what the converter leaves out, made up)
|
|
1405
|
+
const pcb = new CircuitJsonToKicadPcbConverter(netted); pcb.runUntilFinished();
|
|
1322
1406
|
const sch = new CircuitJsonToKicadSchConverter(json); sch.runUntilFinished();
|
|
1323
|
-
|
|
1407
|
+
const { pro, dru } = kicadProject(netted, { clearance, track, edgeExempt });
|
|
1408
|
+
return { [`${name}.kicad_pcb`]: patchKicadPcb(pcb.getOutputString(), netted), [`${name}.kicad_sch`]: sch.getOutputString(), [`${name}.kicad_pro`]: pro, [`${name}.kicad_dru`]: dru };
|
|
1324
1409
|
}
|
|
1325
1410
|
|
|
1326
1411
|
// The 2D views for the model page, as SVG drawings: [[name, svg]]. "Group: view" names group into one tab with a
|