kicad-splitplane 0.5.0__py3-none-any.whl

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.
kicad_splitplane.py ADDED
@@ -0,0 +1,961 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ kicad-splitplane - split a KiCad power layer into one continuous zone per net.
4
+
5
+ Every via / through-hole pad of the selected power nets is a seed. The tool
6
+ partitions the layer so that
7
+
8
+ * every net gets exactly ONE continuous copper region (connected mode), and
9
+ * each region contains all of its net's vias and none of the other nets',
10
+ * borders lie as far as possible from foreign copper.
11
+
12
+ It reads a .kicad_pcb file (KiCad 7-10 format), writes the zones into a copy
13
+ of the board and renders a preview image. No KiCad installation is needed.
14
+ The same code also runs as a KiCad 9+ plugin (see plugin/).
15
+
16
+ CLI
17
+ ---
18
+ pip install "shapely>=2.0" numpy scipy matplotlib
19
+ python kicad_splitplane.py board.kicad_pcb --layer In2.Cu --nets 5V 3.3V VBUS
20
+ python kicad_splitplane.py board.kicad_pcb --nets 5V 3.3V --json # for scripts / agents
21
+
22
+ Library
23
+ -------
24
+ import kicad_splitplane as sp
25
+ result = sp.process(open("board.kicad_pcb").read(), "In2.Cu", ["5V", "3.3V"])
26
+ result.board_text # modified board
27
+ result.log # list of messages / warnings
28
+ sp.render_png(result, "preview.png")
29
+ sp.summary(result) # dict: ok, zones per net, warnings
30
+
31
+ AI agents
32
+ ---------
33
+ kicad_splitplane_mcp.py is an MCP server around this library
34
+ (pip install "kicad-splitplane[mcp]"; kicad-splitplane-mcp).
35
+
36
+ Author: Aleksandar Tuzlak - MIT License
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import argparse
41
+ import itertools
42
+ import math
43
+ import re
44
+ import sys
45
+ import uuid
46
+ from collections import defaultdict
47
+ from dataclasses import dataclass, field
48
+
49
+ import numpy as np
50
+ from scipy import ndimage
51
+ from scipy.sparse import coo_matrix
52
+ from scipy.sparse.csgraph import dijkstra
53
+ from shapely import contains_xy
54
+ from shapely.affinity import rotate, translate
55
+ from shapely.geometry import LineString, MultiPoint, Point, Polygon, box
56
+ from shapely.ops import nearest_points, polygonize, unary_union, voronoi_diagram
57
+
58
+ __version__ = "0.5.0"
59
+
60
+
61
+ # =============================================================================
62
+ # 1. Minimal S-expression parser (.kicad_pcb is one big S-expression)
63
+ # =============================================================================
64
+ _TOKEN = re.compile(r'\(|\)|"(?:\\.|[^"\\])*"|[^\s()"]+')
65
+
66
+
67
+ def parse_sexpr(text: str):
68
+ stack, cur = [], []
69
+ for m in _TOKEN.finditer(text):
70
+ t = m.group(0)
71
+ if t == "(":
72
+ stack.append(cur)
73
+ cur = []
74
+ elif t == ")":
75
+ done, cur = cur, stack.pop()
76
+ cur.append(done)
77
+ else:
78
+ cur.append(t[1:-1] if t.startswith('"') else t)
79
+ return cur[0]
80
+
81
+
82
+ def children(node, name):
83
+ return [c for c in node if isinstance(c, list) and c and c[0] == name]
84
+
85
+
86
+ def child(node, name):
87
+ c = children(node, name)
88
+ return c[0] if c else None
89
+
90
+
91
+ # =============================================================================
92
+ # 2. Board data
93
+ # =============================================================================
94
+ def net_table(board) -> dict:
95
+ """Top-level (net <num> "<name>") entries (KiCad <= 9). Empty in KiCad 10."""
96
+ return {n[1]: n[2] for n in children(board, "net") if len(n) >= 3}
97
+
98
+
99
+ def net_name(net_node, table):
100
+ """Handles (net 3 "+5V"), (net 3) + lookup table, and KiCad 10's (net "+5V")."""
101
+ if net_node is None or len(net_node) < 2:
102
+ return None
103
+ if len(net_node) >= 3:
104
+ return net_node[2]
105
+ return table.get(net_node[1], net_node[1])
106
+
107
+
108
+ def _pad_abs(fp_at, pad_at):
109
+ """Absolute pad position. KiCad: y down, positive angle = CCW on screen."""
110
+ fx, fy = float(fp_at[1]), float(fp_at[2])
111
+ rot = math.radians(float(fp_at[3])) if len(fp_at) > 3 else 0.0
112
+ px, py = float(pad_at[1]), float(pad_at[2])
113
+ return (fx + px * math.cos(rot) + py * math.sin(rot),
114
+ fy - px * math.sin(rot) + py * math.cos(rot))
115
+
116
+
117
+ def copper_layers(board) -> list[str]:
118
+ lay = child(board, "layers")
119
+ return [l[1] for l in lay[1:] if isinstance(l, list) and l[1].endswith(".Cu")] if lay else []
120
+
121
+
122
+ def collect_seeds(board, layer, nets, include_smd=False):
123
+ """(x, y, net) for every via / THT pad of `nets` that reaches `layer`.
124
+ include_smd=True also uses SMD pads as stand-ins for vias not yet placed."""
125
+ table, seeds = net_table(board), []
126
+ for v in children(board, "via"):
127
+ if "micro" in v:
128
+ continue
129
+ name = net_name(child(v, "net"), table)
130
+ lay = child(v, "layers")
131
+ through = "blind" not in v
132
+ if name in nets and (through or (lay and (layer in lay or "*.Cu" in lay))):
133
+ at = child(v, "at")
134
+ seeds.append((float(at[1]), float(at[2]), name))
135
+ for fp in children(board, "footprint"):
136
+ fp_at = child(fp, "at")
137
+ for pad in children(fp, "pad"):
138
+ if len(pad) < 3 or pad[2] not in ("thru_hole", "smd"):
139
+ continue
140
+ if pad[2] == "smd" and not include_smd:
141
+ continue
142
+ name = net_name(child(pad, "net"), table)
143
+ if name in nets:
144
+ seeds.append((*_pad_abs(fp_at, child(pad, "at")), name))
145
+ return seeds
146
+
147
+
148
+ @dataclass
149
+ class Hole:
150
+ """Copper of a via / THT pad (or an NPTH hole, net None) that pierces the layer."""
151
+ x: float
152
+ y: float
153
+ shape: object
154
+ net: str | None
155
+
156
+ @property
157
+ def r(self) -> float:
158
+ """Circumscribed radius around (x, y)."""
159
+ return Point(self.x, self.y).hausdorff_distance(self.shape.exterior)
160
+
161
+
162
+ def _pad_shape(pad, x, y):
163
+ """Copper outline of a pad (rect, roundrect and others as their bounding box)."""
164
+ size = child(pad, "size")
165
+ w, h = float(size[1]), float(size[2] if len(size) > 2 else size[1])
166
+ kind = pad[3] if len(pad) > 3 else "circle"
167
+ if kind == "circle":
168
+ s = Point(0, 0).buffer(w / 2)
169
+ elif kind == "oval" and w != h:
170
+ d, half = min(w, h), abs(w - h) / 2
171
+ s = LineString([(-half, 0), (half, 0)] if w > h else [(0, -half), (0, half)]).buffer(d / 2)
172
+ else:
173
+ s = box(-w / 2, -h / 2, w / 2, h / 2)
174
+ at = child(pad, "at")
175
+ # Pad angles are absolute in KiCad 6+; y points down, so negate.
176
+ return translate(rotate(s, -float(at[3]) if len(at) > 3 else 0.0, origin=(0, 0)), x, y)
177
+
178
+
179
+ def collect_holes(board, layer) -> list[Hole]:
180
+ """Every via, THT pad and NPTH hole on `layer`, of any net: the copper a zone
181
+ has to keep clear of (or, for its own net, connect to)."""
182
+ table, holes = net_table(board), []
183
+ for v in children(board, "via"):
184
+ lay = child(v, "layers")
185
+ if ("micro" in v or "blind" in v) and not (lay and (layer in lay or "*.Cu" in lay)):
186
+ continue
187
+ at, size = child(v, "at"), child(v, "size")
188
+ x, y = float(at[1]), float(at[2])
189
+ holes.append(Hole(x, y, Point(x, y).buffer(float(size[1]) / 2),
190
+ net_name(child(v, "net"), table)))
191
+ for fp in children(board, "footprint"):
192
+ fp_at = child(fp, "at")
193
+ for pad in children(fp, "pad"):
194
+ if len(pad) < 4 or pad[2] not in ("thru_hole", "np_thru_hole") or child(pad, "size") is None:
195
+ continue
196
+ lay = child(pad, "layers")
197
+ if pad[2] == "thru_hole" and lay and not ("*.Cu" in lay or layer in lay):
198
+ continue
199
+ x, y = _pad_abs(fp_at, child(pad, "at"))
200
+ net = net_name(child(pad, "net"), table) if pad[2] == "thru_hole" else None
201
+ holes.append(Hole(x, y, _pad_shape(pad, x, y), net))
202
+ return holes
203
+
204
+
205
+ def seed_radii(seeds, holes, default=0.3) -> list[float]:
206
+ """Copper radius of each seed (SMD stand-ins get the size of a small via)."""
207
+ at = {(round(h.x, 3), round(h.y, 3), h.net): h.r for h in holes}
208
+ return [at.get((round(x, 3), round(y, 3), n), default) for x, y, n in seeds]
209
+
210
+
211
+ def list_power_candidates(text: str) -> list[tuple[str, int, int]]:
212
+ """Nets that look like supplies: (name, #vias/THT pads, #SMD pads), sorted."""
213
+ pat = re.compile(r"(^[+-]?\d+(\.\d+)?V\d*$)|(^[+-]?\d+V\d+$)|VCC|VDD|VBUS|VBAT|VIN|PWR|^V[A-Z]*$", re.I)
214
+ return [t for t in list_nets(text) if pat.search(t[0])]
215
+
216
+
217
+ def list_nets(text: str) -> list[tuple[str, int, int]]:
218
+ """All named nets with pads/vias: (name, #vias/THT pads, #SMD pads), sorted."""
219
+ board = parse_sexpr(text)
220
+ table = net_table(board)
221
+ tht, smd = defaultdict(int), defaultdict(int)
222
+ for v in children(board, "via"):
223
+ tht[net_name(child(v, "net"), table)] += 1
224
+ for fp in children(board, "footprint"):
225
+ for pad in children(fp, "pad"):
226
+ if len(pad) < 3:
227
+ continue
228
+ n = net_name(child(pad, "net"), table)
229
+ if pad[2] == "thru_hole":
230
+ tht[n] += 1
231
+ elif pad[2] == "smd":
232
+ smd[n] += 1
233
+ names = {n for n in set(tht) | set(smd)
234
+ if n and not n.lower().startswith(("net-", "unconnected"))}
235
+ return sorted(((n, tht[n], smd[n]) for n in names), key=lambda t: -(t[1] + t[2]))
236
+
237
+
238
+ def board_outline(board):
239
+ """Polygon from Edge.Cuts (lines, rects, polys, arcs approximated by 2 chords)."""
240
+ def xy(n):
241
+ return float(n[1]), float(n[2])
242
+ segs = []
243
+ for kind in ("gr_rect", "gr_poly", "gr_line", "gr_arc"):
244
+ for g in children(board, kind):
245
+ if (child(g, "layer") or [None, None])[1] != "Edge.Cuts":
246
+ continue
247
+ if kind == "gr_rect":
248
+ (x0, y0), (x1, y1) = xy(child(g, "start")), xy(child(g, "end"))
249
+ return box(min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1))
250
+ if kind == "gr_poly":
251
+ return Polygon([xy(p) for p in children(child(g, "pts"), "xy")])
252
+ if kind == "gr_line":
253
+ segs.append(LineString([xy(child(g, "start")), xy(child(g, "end"))]))
254
+ else:
255
+ segs.append(LineString([xy(child(g, k)) for k in ("start", "mid", "end")]))
256
+ polys = list(polygonize(unary_union(segs))) if segs else []
257
+ if not polys:
258
+ raise ValueError("Could not build a closed board outline from Edge.Cuts.")
259
+ return max(polys, key=lambda p: p.area)
260
+
261
+
262
+ def _parts(geom):
263
+ return [g for g in getattr(geom, "geoms", [geom]) if not g.is_empty]
264
+
265
+
266
+ # =============================================================================
267
+ # 3a. Plain Voronoi (fast, may create islands)
268
+ # =============================================================================
269
+ def voronoi_partition(seeds, outline, gap, edge, log):
270
+ cells = voronoi_diagram(MultiPoint([(x, y) for x, y, _ in seeds]),
271
+ envelope=outline.buffer(50))
272
+ by_net = defaultdict(list)
273
+ for cell in cells.geoms:
274
+ for x, y, net in seeds:
275
+ if cell.contains(Point(x, y)):
276
+ by_net[net].append(cell)
277
+ break
278
+ usable = outline.buffer(-edge)
279
+ return {n: unary_union(cs).intersection(usable).buffer(-gap / 2, join_style=2)
280
+ for n, cs in by_net.items()}
281
+
282
+
283
+ # =============================================================================
284
+ # 3b. Connected partition: exactly ONE continuous region per net
285
+ # =============================================================================
286
+ # Step 1 "spines": per net, join all its vias by a tree of 45-degree grid paths
287
+ # (Prim + Dijkstra). Paths keep out of other nets' vias and of spines routed
288
+ # earlier and prefer the middle of free space (cost ~ 1/distance).
289
+ # Step 2: split the board by nearest spine, measured around (not through)
290
+ # other nets' pads and vias. A region grown from a connected spine is itself
291
+ # connected, so every net ends up as exactly one zone.
292
+ # Pads and vias are not points: each seed keeps a ring of its own copper, and
293
+ # every other via / pad / hole on the layer is an obstacle. Spines do not pass
294
+ # where less than min_copper of copper would fit (e.g. between header pins) and
295
+ # avoid passages narrower than min_neck.
296
+ # All routing orders of the nets are tried; the best (fewest trapped vias,
297
+ # then shortest spines) wins. A trapped via is topologically enclosed by other
298
+ # nets and has to be moved; a target position is suggested.
299
+ def connected_partition(seeds, outline, gap, edge, log, res=0.5, keepout=0.35,
300
+ max_orders=24, progress=None, holes=(), min_neck=1.0,
301
+ min_copper=0.25, ring=0.5, pretty=True):
302
+ usable = outline.buffer(-edge)
303
+ x0, y0, x1, y1 = outline.bounds
304
+ W, H = int(math.ceil((x1 - x0) / res)), int(math.ceil((y1 - y0) / res))
305
+ cx = x0 + (np.arange(W) + 0.5) * res
306
+ cy = y0 + (np.arange(H) + 0.5) * res
307
+ XX, YY = np.meshgrid(cx, cy)
308
+ inside = contains_xy(usable, XX, YY)
309
+
310
+ def cell(x, y):
311
+ return (min(H - 1, max(0, int((y - y0) / res))),
312
+ min(W - 1, max(0, int((x - x0) / res))))
313
+
314
+ def discs(items, extra):
315
+ """Cells within r + extra of any (x, y, r)."""
316
+ m = np.zeros((H, W), bool)
317
+ for x, y, r in items:
318
+ R = r + extra
319
+ c0, c1 = np.searchsorted(cx, x - R), np.searchsorted(cx, x + R, "right")
320
+ r0, r1 = np.searchsorted(cy, y - R), np.searchsorted(cy, y + R, "right")
321
+ m[r0:r1, c0:c1] |= (XX[r0:r1, c0:c1] - x) ** 2 + (YY[r0:r1, c0:c1] - y) ** 2 <= R * R
322
+ return m
323
+
324
+ nets = sorted({n for *_, n in seeds})
325
+ clear = gap / 2
326
+ radii = seed_radii(seeds, holes)
327
+ pads = {n: [(x, y, r) for (x, y, m), r in zip(seeds, radii) if m == n] for n in nets}
328
+ seed_cells = {n: sorted({cell(x, y) for x, y, _ in pads[n]}) for n in nets}
329
+ other = [(h.x, h.y, h.r) for h in holes if h.net not in nets]
330
+ core = discs(other, clear) # no zone copper at all
331
+ hard_other = discs(other, clear + min_copper) # too narrow for copper
332
+ narrow_other = discs(other, clear + min_neck / 2) # copper, but a neck
333
+ own = {n: discs(pads[n], 0) for n in nets}
334
+ hard_seed = {n: discs([p for m in nets if m != n for p in pads[m]], gap + keepout) for n in nets}
335
+ narrow_seed = {n: discs([p for m in nets if m != n for p in pads[m]], gap + min_neck / 2)
336
+ for n in nets}
337
+ block_r = (gap + keepout) / res
338
+ narrow_r = (gap + min_neck) / res
339
+ idx = np.arange(H * W).reshape(H, W)
340
+ steps = [(0, 1, 1.0), (1, 0, 1.0), (1, 1, math.sqrt(2)), (1, -1, math.sqrt(2))]
341
+
342
+ def grid_graph(free, cost):
343
+ rows, cols, w = [], [], []
344
+ for dr, dc, L in steps:
345
+ a = idx[max(0, -dr):H - max(0, dr), max(0, -dc):W - max(0, dc)].ravel()
346
+ b = idx[max(0, dr):, max(0, dc):][:H - abs(dr), :W - abs(dc)].ravel()
347
+ ok = free.flat[a] & free.flat[b]
348
+ a, b = a[ok], b[ok]
349
+ rows.append(a)
350
+ cols.append(b)
351
+ w.append(L * (cost.flat[a] + cost.flat[b]) / 2)
352
+ return coo_matrix((np.concatenate(w), (np.concatenate(rows), np.concatenate(cols))),
353
+ shape=(H * W, H * W)).tocsr()
354
+
355
+ def route_net(net, blocked, cost):
356
+ free = inside & ~blocked | own[net]
357
+ for r, c in seed_cells[net]:
358
+ free[r, c] = True
359
+ g = grid_graph(free, cost)
360
+ targets = [r * W + c for r, c in seed_cells[net]]
361
+ tree, todo, failed, total = {targets[0]}, set(targets[1:]), [], 0.0
362
+ spine = np.zeros((H, W), bool)
363
+ spine.flat[targets[0]] = True
364
+ while todo:
365
+ dist, pred, _ = dijkstra(g, directed=False, indices=list(tree),
366
+ min_only=True, return_predecessors=True)
367
+ reach = [t for t in todo if np.isfinite(dist[t])]
368
+ if not reach:
369
+ failed += list(todo)
370
+ break
371
+ t = min(reach, key=lambda k: dist[k])
372
+ total += dist[t]
373
+ while t >= 0 and t not in tree:
374
+ tree.add(t)
375
+ spine.flat[t] = True
376
+ t = pred[t]
377
+ todo -= tree
378
+ return spine, failed, total
379
+
380
+ def attempt(order):
381
+ spines, failed, total = {}, [], 0.0
382
+ for net in order:
383
+ foreign = np.zeros((H, W), bool)
384
+ for m in nets:
385
+ if m != net:
386
+ for r, c in seed_cells[m]:
387
+ foreign[r, c] = True
388
+ for sp in spines.values():
389
+ foreign |= sp
390
+ d = ndimage.distance_transform_edt(~foreign)
391
+ blocked = (d <= block_r) | hard_seed[net] | hard_other
392
+ narrow = (d <= narrow_r) | narrow_seed[net] | narrow_other
393
+ sp, f, t = route_net(net, blocked, 1.0 + 4.0 / np.maximum(d, 0.5) + 8.0 * narrow)
394
+ spines[net] = sp
395
+ total += t
396
+ failed += [(net, divmod(k, W)) for k in f]
397
+ return spines, failed, total
398
+
399
+ orders = list(itertools.permutations(nets))
400
+ if len(orders) > max_orders:
401
+ import random
402
+ random.Random(0).shuffle(orders)
403
+ orders = orders[:max_orders]
404
+ best = None
405
+ for i, order in enumerate(orders):
406
+ if progress:
407
+ progress(i, len(orders))
408
+ r = attempt(order)
409
+ key = (len(r[1]), r[2])
410
+ if best is None or key < best[0]:
411
+ best = (key, order, r)
412
+ if key[0] == 0 and len(nets) > 4:
413
+ break
414
+ _, order, (spines, failed, _) = best
415
+ log.append(f"routing order: {' -> '.join(order)}")
416
+
417
+ srcs = np.zeros((H, W), bool)
418
+ owner = np.full((H, W), -1)
419
+ for i, n in enumerate(nets):
420
+ srcs |= spines[n]
421
+ owner[spines[n]] = i
422
+ for n, (r, c) in failed:
423
+ srcs[r, c] = True
424
+ owner[r, c] = nets.index(n)
425
+ # Every pad / via keeps a ring of its own net (where two rings overlap the
426
+ # pads are too close for either; leave those cells to the split below).
427
+ rings = np.zeros((H, W), int)
428
+ ring_owner = np.full((H, W), -1)
429
+ for i, n in enumerate(nets):
430
+ m = discs(pads[n], clear + ring) & ~srcs
431
+ rings += m
432
+ ring_owner[m] = i
433
+ m = rings == 1
434
+ srcs |= m
435
+ owner[m] = ring_owner[m]
436
+
437
+ # Nearest source measured around the other nets' pads and vias, so a region
438
+ # does not reach across a row of them through gaps copper cannot fill.
439
+ _, (ir, ic) = ndimage.distance_transform_edt(~srcs, return_indices=True)
440
+ label = owner[ir, ic]
441
+ g = grid_graph((inside & ~core) | srcs, np.ones((H, W)))
442
+ _, _, nearest = dijkstra(g, directed=False, indices=np.flatnonzero(srcs),
443
+ min_only=True, return_predecessors=True)
444
+ reached = nearest >= 0
445
+ label.flat[reached] = owner.flat[nearest[reached]]
446
+
447
+ cells = {}
448
+ for i, n in enumerate(nets):
449
+ m = label == i
450
+ boxes = []
451
+ for r in range(H):
452
+ run = np.flatnonzero(np.diff(np.r_[0, m[r].astype(np.int8), 0]))
453
+ for a, b in zip(run[::2], run[1::2]):
454
+ boxes.append(box(x0 + a * res, y0 + r * res, x0 + b * res, y0 + (r + 1) * res))
455
+ cells[n] = unary_union(boxes)
456
+ keep = {n: [Point(x, y).buffer(r + clear) for x, y, r in pads[n]] for n in nets}
457
+ regions = tidy(cells, usable, gap, keep, holes, min_neck,
458
+ [16 * res, 12 * res, 8 * res, 4 * res, 2 * res] if pretty else [])
459
+
460
+ for n, (r, c) in failed:
461
+ p = Point(cx[c], cy[r])
462
+ main = max(_parts(regions[n]), key=lambda q: q.area).buffer(-0.6)
463
+ msg = f"! {n}: via at ({p.x:.2f}, {p.y:.2f}) is trapped by other nets"
464
+ if not main.is_empty:
465
+ q = nearest_points(main, p)[0]
466
+ msg += f" -> move it to ~({q.x:.2f}, {q.y:.2f}) ({p.distance(q):.1f} mm fanout)"
467
+ log.append(msg)
468
+ return regions
469
+
470
+
471
+ # =============================================================================
472
+ # 3c. Clean outlines: smooth borders with 0 / 45 / 90 degree edges
473
+ # =============================================================================
474
+ # The grid gives staircase borders. Neighbouring regions share their borders
475
+ # (a polygon coverage), so they are simplified together (shapely's
476
+ # coverage_simplify keeps shared borders identical) and every segment is then
477
+ # bent into a straight + 45-degree pair, like a hand-drawn plane. Each
478
+ # simplification level is only used if it keeps every pad ring, the gap
479
+ # between zones and the connectivity at least as good as the raw grid.
480
+ def _octilinear_ring(coords):
481
+ out = [coords[0]]
482
+ for a, b in zip(coords[:-1], coords[1:]):
483
+ dx, dy = abs(b[0] - a[0]), abs(b[1] - a[1])
484
+ if dx > 1e-6 and dy > 1e-6 and abs(dx - dy) > 1e-6:
485
+ # Bend from the lexicographically smaller end, so both zones that
486
+ # share this segment get the same corner.
487
+ p, q = (a, b) if a < b else (b, a)
488
+ d = min(dx, dy)
489
+ out.append((p[0] + math.copysign(d, q[0] - p[0]), p[1] + math.copysign(d, q[1] - p[1])))
490
+ out.append(b)
491
+ return out
492
+
493
+
494
+ def _polygons(geom):
495
+ return unary_union([g for g in getattr(geom, "geoms", [geom]) if g.geom_type in ("Polygon", "MultiPolygon")])
496
+
497
+
498
+ def _octilinear(geom):
499
+ from shapely import make_valid
500
+ return _polygons(make_valid(unary_union([
501
+ Polygon(_octilinear_ring(list(p.exterior.coords)),
502
+ [_octilinear_ring(list(i.coords)) for i in p.interiors]) for p in _parts(geom)])))
503
+
504
+
505
+ def _defects(regions, keep, holes, gap, min_neck):
506
+ """Count what makes a split worse: islands, pad rings not covered, zones over
507
+ another net's pad, zones closer than the gap, thin necks."""
508
+ n = 0
509
+ for net, r in regions.items():
510
+ parts = _parts(r)
511
+ n += len(parts) - 1
512
+ n += sum(not r.contains(k) for k in keep.get(net, []))
513
+ n += sum(1 for h in holes if h.net in regions and h.net != net
514
+ and r.intersects(h.shape.buffer(gap / 2)))
515
+ if min_neck:
516
+ copper = unary_union(simulate_fill(r, net, holes, gap / 2)) if holes else r
517
+ n += len(_parts(copper.buffer(-min_neck / 2).buffer(min_neck / 2))) > len(_parts(copper))
518
+ nets = sorted(regions)
519
+ n += sum(regions[a].distance(regions[b]) < gap * 0.9
520
+ for i, a in enumerate(nets) for b in nets[i + 1:])
521
+ return n
522
+
523
+
524
+ def _octagon(p, r):
525
+ """Octagon around p with 0 / 45 / 90 degree edges, enclosing the circle of radius r."""
526
+ R = r / math.cos(math.pi / 8)
527
+ return Polygon([(p.x + R * math.cos(a), p.y + R * math.sin(a))
528
+ for a in (math.pi / 8 + k * math.pi / 4 for k in range(8))])
529
+
530
+
531
+ def _bad_spots(regions, keep, holes, gap):
532
+ """Pads whose ring a zone border cuts, and other nets' pads a zone covers."""
533
+ spots = [k.centroid for net, rings in keep.items() for k in rings if not regions[net].contains(k)]
534
+ spots += [Point(h.x, h.y) for net, r in regions.items() for h in holes
535
+ if h.net in regions and h.net != net and r.intersects(h.shape.buffer(gap / 2))]
536
+ return spots
537
+
538
+
539
+ def _clean_cover(cover, keep, zone=None, thin=0.4):
540
+ """Hand pieces of a partition that hold none of their net's pads, and (within
541
+ `zone`) spikes thinner than 2*thin, to the neighbour they share the longest
542
+ border with. Such slivers appear where smooth and exact borders meet."""
543
+ out, loose = {}, []
544
+ for n, g in cover.items():
545
+ rings = keep.get(n, [])
546
+ if zone is not None and not zone.is_empty:
547
+ body = g.buffer(-thin, join_style=2).buffer(thin, join_style=2)
548
+ spikes = g.intersection(zone).difference(body)
549
+ g = _polygons(g.difference(spikes))
550
+ loose += [(p, n) for p in _parts(_polygons(spikes)) if p.area > 1e-6]
551
+ good = [p for p in _parts(g) if any(p.intersects(k) for k in rings)]
552
+ loose += [(p, None) for p in _parts(g) if not any(p.intersects(k) for k in rings)]
553
+ out[n] = unary_union(good) if good else Polygon()
554
+ for q, was in sorted(loose, key=lambda t: t[0].area):
555
+ edge = q.exterior.buffer(1e-3)
556
+ touch = {n: edge.intersection(out[n]).area for n in out if n != was}
557
+ best = max(touch, key=touch.get, default=None)
558
+ if best is not None and touch[best] > 0:
559
+ out[best] = _polygons(out[best].union(q.buffer(1e-6, join_style=2)))
560
+ elif was is not None:
561
+ out[was] = _polygons(out[was].union(q.buffer(1e-6, join_style=2)))
562
+ # Close zero-width slits where two borders met (they would open up when
563
+ # the zone is shrunk by half the gap).
564
+ return {n: _polygons(g.buffer(0.01, join_style=2).buffer(-0.01, join_style=2)) for n, g in out.items()}
565
+
566
+
567
+ def tidy(cells, usable, gap, keep, holes=(), min_neck=1.0, tolerances=(), patch=3.0):
568
+ """Zones from grid regions: smoothed and octilinear where that does no harm.
569
+ Around pads where the smooth border would be worse, the exact grid border
570
+ is kept (within `patch` mm); both are partitions, so the gap stays intact."""
571
+ def shrink(polys):
572
+ return {n: _polygons(g.intersection(usable).buffer(-gap / 2, join_style=2))
573
+ for n, g in polys.items()}
574
+
575
+ nets = list(cells)
576
+ exact = {n: cells[n].simplify(0.01) for n in nets}
577
+ raw = shrink(exact)
578
+ if not tolerances:
579
+ return raw
580
+ try:
581
+ from shapely import coverage_simplify
582
+ except ImportError: # shapely < 2.1
583
+ return raw
584
+ limit = _defects(raw, keep, holes, gap, min_neck)
585
+ for tol in tolerances:
586
+ simple = coverage_simplify([cells[n] for n in nets], tolerance=tol, simplify_boundary=False)
587
+ cover = {n: _octilinear(g) for n, g in zip(nets, simple)}
588
+ area = Polygon()
589
+ for _ in range(3):
590
+ cover = _clean_cover(cover, keep)
591
+ cand = shrink(cover)
592
+ spots = [p for p in _bad_spots(cand, keep, holes, gap) if not area.contains(p)]
593
+ if not spots:
594
+ break
595
+ area = area.union(unary_union([_octagon(p, patch) for p in spots]))
596
+ cover = {n: _polygons(cover[n].difference(area).union(exact[n].intersection(area)))
597
+ for n in nets}
598
+ cand = shrink(_clean_cover(cover, keep, area.buffer(1.0)))
599
+ if _defects(cand, keep, holes, gap, min_neck) <= limit:
600
+ return cand
601
+ return raw
602
+
603
+
604
+ # =============================================================================
605
+ # 4. Checks and output
606
+ # =============================================================================
607
+ def simulate_fill(region, net, holes, clear, thermal_gap=0.5, seeds=()):
608
+ """Roughly what KiCad fills: the zone minus clearance around every other
609
+ net's via / pad / hole, without islands that touch none of the net's pads.
610
+ Seeds without a hole (SMD stand-ins for vias still to be placed) count as pads."""
611
+ foreign = unary_union([h.shape.buffer(clear) for h in holes if h.net != net])
612
+ fill = region.difference(foreign) if not foreign.is_empty else region
613
+ pads = [h.shape.buffer(thermal_gap + 0.1) for h in holes if h.net == net]
614
+ pads += [Point(x, y).buffer(0.3 + thermal_gap + 0.1) for x, y, n in seeds if n == net]
615
+ return [p for p in _parts(fill) if any(p.intersects(q) for q in pads)] if pads else _parts(fill)
616
+
617
+
618
+ def check(regions, seeds, min_neck, log, holes=(), gap=0.5, thermal_gap=0.5):
619
+ ok = True
620
+ for net, r in sorted(regions.items()):
621
+ parts = _parts(r)
622
+ if len(parts) > 1:
623
+ ok = False
624
+ log.append(f"! {net}: split into {len(parts)} islands on this layer")
625
+ copper = r
626
+ if holes:
627
+ for h in holes:
628
+ if h.net in regions and h.net != net and r.intersects(h.shape.buffer(gap / 2)):
629
+ ok = False
630
+ log.append(f"! {net}: zone runs over a {h.net} pad/via at ({h.x:.2f}, {h.y:.2f})")
631
+ filled = simulate_fill(r, net, holes, gap / 2, thermal_gap, seeds)
632
+ copper = unary_union(filled)
633
+ if len(filled) > len(parts):
634
+ ok = False
635
+ log.append(f"! {net}: other nets' pads/vias cut the copper into {len(filled)} pieces"
636
+ " (e.g. no room between header pins)")
637
+ for x, y, n in seeds:
638
+ if n == net and copper.distance(Point(x, y)) > _seed_reach(x, y, net, holes, thermal_gap):
639
+ ok = False
640
+ log.append(f"! {net}: pad/via at ({x:.2f}, {y:.2f}) is not connected to its zone")
641
+ if min_neck and not copper.is_empty:
642
+ opened = copper.buffer(-min_neck / 2).buffer(min_neck / 2)
643
+ if len(_parts(opened)) > len(_parts(copper)):
644
+ ok = False
645
+ log.append(f"! {net}: has a neck narrower than {min_neck} mm")
646
+ if ok:
647
+ log.append("OK: one connected zone per net, no thin necks")
648
+ return ok
649
+
650
+
651
+ def _seed_reach(x, y, net, holes, thermal_gap):
652
+ """How far zone copper may be from a seed centre and still connect via spokes."""
653
+ p = Point(x, y)
654
+ pad = next((h for h in holes if h.net == net and h.shape.contains(p)), None)
655
+ return (pad.r if pad else 0.3) + thermal_gap + 0.05
656
+
657
+
658
+ def strip_old_zones(text, layer, nets):
659
+ """Remove existing zones of `nets` on `layer` (returns new text, count)."""
660
+ out, i, removed = [], 0, 0
661
+ for m in re.finditer(r"\(zone\b", text):
662
+ if m.start() < i:
663
+ continue
664
+ depth, j = 0, m.start()
665
+ while True:
666
+ ch = text[j]
667
+ if ch == '"':
668
+ j = text.index('"', j + 1)
669
+ elif ch == "(":
670
+ depth += 1
671
+ elif ch == ")":
672
+ depth -= 1
673
+ if depth == 0:
674
+ break
675
+ j += 1
676
+ z = parse_sexpr(text[m.start():j + 1])
677
+ lay = child(z, "layer")
678
+ if lay and lay[1] == layer and net_name(child(z, "net"), {}) in nets:
679
+ out.append(text[i:m.start()])
680
+ i = j + 1
681
+ removed += 1
682
+ out.append(text[i:])
683
+ return "".join(out), removed
684
+
685
+
686
+ def _zone_sexpr(poly, net, layer, table, gap, prio):
687
+ num = next((k for k, v in table.items() if v == net), None)
688
+ net_tok = f'(net {num}) (net_name "{net}")' if num is not None else f'(net "{net}")'
689
+ pts = " ".join(f"(xy {x:.4f} {y:.4f})" for x, y in list(poly.exterior.coords)[:-1])
690
+ return (f'\t(zone {net_tok} (layer "{layer}") (uuid "{uuid.uuid4()}")\n'
691
+ f'\t\t(name "splitplane_{net}") (priority {prio}) (hatch edge 0.5)\n'
692
+ f'\t\t(connect_pads yes (clearance {gap / 2:.3f}))\n'
693
+ f'\t\t(min_thickness 0.25) (filled_areas_thickness no)\n'
694
+ f'\t\t(fill (thermal_gap 0.5) (thermal_bridge_width 0.5))\n'
695
+ f'\t\t(polygon (pts {pts}))\n\t)\n')
696
+
697
+
698
+ def zone_parts(regions):
699
+ """[(polygon, net, priority)] to write as zones. Holes are not written;
700
+ smaller zones get higher priority so that an island enclosed by a bigger
701
+ zone always wins the fill."""
702
+ parts = [(p, n) for n, r in regions.items() for p in _parts(r) if p.area > 0.01]
703
+ parts.sort(key=lambda t: t[0].area, reverse=True)
704
+ return [(p.simplify(0.05), n, k) for k, (p, n) in enumerate(parts)]
705
+
706
+
707
+ def insert_zones(text, regions, layer, table, gap):
708
+ zones = "".join(_zone_sexpr(p, n, layer, table, gap, k) for p, n, k in zone_parts(regions))
709
+ end = text.rstrip().rfind(")")
710
+ return text[:end] + zones + ")\n"
711
+
712
+
713
+ @dataclass
714
+ class Result:
715
+ board_text: str
716
+ regions: dict
717
+ seeds: list
718
+ outline: object
719
+ layer: str
720
+ ok: bool
721
+ log: list = field(default_factory=list)
722
+ holes: list = field(default_factory=list)
723
+
724
+
725
+ def compute(text, layer, nets, gap=0.5, edge=0.5, min_neck=1.0, res=0.5,
726
+ include_smd=False, plain=False, progress=None, smooth=True) -> Result:
727
+ """Partition only; result.board_text is None. Raises ValueError on unusable input."""
728
+ log = []
729
+ nets = list(dict.fromkeys(nets))
730
+ if len(nets) < 2:
731
+ raise ValueError("Select at least two nets.")
732
+ board = parse_sexpr(text)
733
+ if layer not in copper_layers(board):
734
+ raise ValueError(f"Layer {layer} not in board ({', '.join(copper_layers(board))}).")
735
+ seeds = collect_seeds(board, layer, set(nets), include_smd)
736
+ counts = {n: sum(s[2] == n for s in seeds) for n in nets}
737
+ log.append(f"{len(seeds)} seeds on {layer}: " + ", ".join(f"{n}={c}" for n, c in counts.items()))
738
+ missing = [n for n, c in counts.items() if c == 0]
739
+ if missing:
740
+ hint = "" if include_smd else " (no vias yet? try 'use SMD pads as stand-in vias')"
741
+ raise ValueError(f"No vias/THT pads found for: {', '.join(missing)}{hint}")
742
+ outline = board_outline(board)
743
+ holes = collect_holes(board, layer)
744
+ if plain:
745
+ regions = voronoi_partition(seeds, outline, gap, edge, log)
746
+ else:
747
+ regions = connected_partition(seeds, outline, gap, edge, log, res=res, progress=progress,
748
+ holes=holes, min_neck=min_neck, pretty=smooth)
749
+ ok = check(regions, seeds, min_neck, log, holes, gap)
750
+ return Result(None, regions, seeds, outline, layer, ok, log, holes)
751
+
752
+
753
+ def process(text, layer, nets, gap=0.5, edge=0.5, min_neck=1.0, res=0.5,
754
+ include_smd=False, plain=False, keep_old=False, progress=None, smooth=True) -> Result:
755
+ """Full pipeline on board text: compute() + write the zones into the text."""
756
+ r = compute(text, layer, nets, gap, edge, min_neck, res, include_smd, plain, progress, smooth)
757
+ if not keep_old:
758
+ text, n_old = strip_old_zones(text, layer, set(nets))
759
+ if n_old:
760
+ r.log.append(f"removed {n_old} existing zone(s) of these nets on {layer}")
761
+ r.board_text = insert_zones(text, r.regions, layer, net_table(parse_sexpr(text)), gap)
762
+ return r
763
+
764
+
765
+ def summary(result: Result) -> dict:
766
+ """Machine-readable result (for scripts and AI agents):
767
+ ok, layer, nets, zones {net: {parts, area_mm2, seeds}}, warnings, log.
768
+ warnings are the log lines that start with "!" (without the "! ")."""
769
+ return {
770
+ "ok": bool(result.ok),
771
+ "layer": result.layer,
772
+ "nets": sorted(result.regions),
773
+ "zones": {n: {"parts": len(_parts(r)),
774
+ "area_mm2": round(r.area, 2),
775
+ "seeds": sum(s[2] == n for s in result.seeds)}
776
+ for n, r in sorted(result.regions.items())},
777
+ "warnings": [line[1:].strip() for line in result.log if line.startswith("!")],
778
+ "log": list(result.log),
779
+ }
780
+
781
+
782
+ PALETTE = ["#2a6fdb", "#e8833a", "#3aa856", "#d64545", "#8a5cc7", "#c2a12b", "#2ab3b3", "#c25599"]
783
+
784
+
785
+ def render_png(result: Result, path_or_buffer, title=None):
786
+ import matplotlib
787
+ matplotlib.use("Agg")
788
+ import matplotlib.pyplot as plt
789
+
790
+ fig, ax = plt.subplots(figsize=(8, 6))
791
+ draw(result, ax, title)
792
+ fig.tight_layout()
793
+ fig.savefig(path_or_buffer, dpi=130, format="png")
794
+ plt.close(fig)
795
+
796
+
797
+ def net_colors(nets) -> dict:
798
+ """{net: '#rrggbb'}, the same colours as the preview."""
799
+ return {n: PALETTE[i % len(PALETTE)] for i, n in enumerate(sorted(nets))}
800
+
801
+
802
+ def write_project(board_path, out_path, nets, colors=True) -> list[str]:
803
+ """Copy the board's .kicad_pro / .kicad_prl next to `out_path`, so the new
804
+ board keeps the project's design rules. With `colors`, every net gets its
805
+ preview colour and KiCad shows net colours on zones (not only ratsnest).
806
+ KiCad reads these files when it opens the board, so the board must not be
807
+ open in KiCad at the same time."""
808
+ import json
809
+ import os
810
+ src, dst = (re.sub(r"\.kicad_pcb$", "", p) for p in (board_path, out_path))
811
+ written = []
812
+ for ext in (".kicad_pro", ".kicad_prl"):
813
+ data = json.load(open(src + ext, encoding="utf-8")) if os.path.exists(src + ext) else {}
814
+ if not data and not colors:
815
+ continue
816
+ if ext == ".kicad_pro":
817
+ data.setdefault("meta", {})["filename"] = os.path.basename(dst + ext)
818
+ if colors:
819
+ ns = data.setdefault("net_settings", {})
820
+ ns["net_colors"] = dict(ns.get("net_colors") or {})
821
+ for n, c in net_colors(nets).items():
822
+ ns["net_colors"][n] = "rgb({}, {}, {})".format(*(int(c[k:k + 2], 16) for k in (1, 3, 5)))
823
+ elif colors:
824
+ data.setdefault("board", {})["net_color_mode"] = 0 # 0 = all, 1 = ratsnest only
825
+ with open(dst + ext, "w", encoding="utf-8") as f:
826
+ json.dump(data, f, indent=2)
827
+ f.write("\n")
828
+ written.append(dst + ext)
829
+ return written
830
+
831
+
832
+ def write_outputs(board_path, out_path, result: Result, colors=True) -> dict:
833
+ """Write the board, the preview PNG and the project files next to
834
+ `out_path`, as the CLI does. Returns {"board", "preview", "project": [...]}."""
835
+ with open(out_path, "w", encoding="utf-8") as f:
836
+ f.write(result.board_text)
837
+ png = re.sub(r"\.kicad_pcb$", "", out_path) + ".png"
838
+ render_png(result, png)
839
+ return {"board": out_path, "preview": png,
840
+ "project": write_project(board_path, out_path, result.regions, colors=colors)}
841
+
842
+
843
+ def draw(result: Result, ax, title=None):
844
+ """Plot zones and seeds onto a matplotlib Axes."""
845
+ ax.plot(*result.outline.exterior.xy, color="#222", lw=1.5)
846
+ for h in result.holes:
847
+ if h.net not in result.regions:
848
+ ax.fill(*h.shape.exterior.xy, color="#999", lw=0, zorder=3)
849
+ for i, (net, r) in enumerate(sorted(result.regions.items())):
850
+ c = PALETTE[i % len(PALETTE)]
851
+ for k, p in enumerate(_parts(r)):
852
+ ax.fill(*p.exterior.xy, color=c, alpha=0.45, lw=0, label=net if k == 0 else None)
853
+ for hole in p.interiors:
854
+ ax.fill(*hole.xy, color="white")
855
+ pts = [(x, y) for x, y, n in result.seeds if n == net]
856
+ ax.plot(*zip(*pts), "o", color=c, mec="#222", ms=4.5)
857
+ ax.legend(loc="upper right", framealpha=0.9)
858
+ ax.set_aspect("equal")
859
+ ax.invert_yaxis()
860
+ ax.set_title(title or f"{result.layer}: one zone per net")
861
+ ax.set_xlabel("x [mm]")
862
+ ax.set_ylabel("y [mm]")
863
+
864
+
865
+ # =============================================================================
866
+ # 5. CLI
867
+ # =============================================================================
868
+ class _Parser(argparse.ArgumentParser):
869
+ """With --json, usage errors are reported as JSON on stdout too (same exit code 2)."""
870
+ json_errors = False
871
+
872
+ def error(self, message):
873
+ if self.json_errors:
874
+ _print_json({"ok": False, "error": message})
875
+ sys.exit(2)
876
+ super().error(message)
877
+
878
+
879
+ def _print_json(obj):
880
+ import json
881
+ print(json.dumps(obj, indent=2, ensure_ascii=False))
882
+
883
+
884
+ def main(argv=None):
885
+ ap = _Parser(
886
+ prog="kicad_splitplane",
887
+ description="Split a KiCad power layer into one continuous zone per net.")
888
+ ap.json_errors = "--json" in (sys.argv[1:] if argv is None else argv)
889
+ ap.add_argument("board", help=".kicad_pcb file")
890
+ ap.add_argument("--layer", default="In2.Cu", help="target copper layer (default In2.Cu)")
891
+ ap.add_argument("--nets", nargs="+", help="power nets to place on the layer")
892
+ ap.add_argument("--list-nets", action="store_true", help="show supply-like nets and exit")
893
+ ap.add_argument("--gap", type=float, default=0.5, help="gap between zones [mm]")
894
+ ap.add_argument("--edge", type=float, default=0.5, help="clearance to board edge [mm]")
895
+ ap.add_argument("--min-neck", type=float, default=1.0, help="warn below this copper width [mm]")
896
+ ap.add_argument("--res", type=float, default=0.5, help="grid resolution [mm]; try 0.3-0.6 if vias get trapped")
897
+ ap.add_argument("--include-smd", action="store_true", help="use SMD pads as stand-in vias (preview before fanout)")
898
+ ap.add_argument("--plain", action="store_true", help="skip connecting the vias (faster, may create islands)")
899
+ ap.add_argument("--no-smooth", action="store_true", help="keep the raw grid outlines instead of smooth 45-degree ones")
900
+ ap.add_argument("--keep-old", action="store_true", help="keep existing zones of these nets on the layer")
901
+ ap.add_argument("--no-colors", action="store_true", help="don't give the nets their preview colours in the project file")
902
+ ap.add_argument("--out", help="output board (default: <board>_splitplane.kicad_pcb)")
903
+ ap.add_argument("--json", action="store_true",
904
+ help="print one JSON object instead of text (same files and exit codes)")
905
+ ap.add_argument("--version", action="version", version=__version__)
906
+ a = ap.parse_args(argv)
907
+ if a.json:
908
+ return _main_json(ap, a)
909
+
910
+ text = open(a.board, encoding="utf-8").read()
911
+ if a.list_nets:
912
+ print(f"{'net':<20} {'vias/THT':>9} {'SMD':>5}")
913
+ for n, t, s in list_power_candidates(text):
914
+ print(f"{n:<20} {t:>9} {s:>5}")
915
+ return 0
916
+ if not a.nets:
917
+ ap.error("--nets is required (use --list-nets to see candidates)")
918
+ try:
919
+ r = process(text, a.layer, a.nets, a.gap, a.edge, a.min_neck, a.res,
920
+ a.include_smd, a.plain, a.keep_old, smooth=not a.no_smooth,
921
+ progress=lambda i, n: print(f" routing order {i + 1}/{n}", end="\r", file=sys.stderr))
922
+ except ValueError as e:
923
+ sys.exit(f"error: {e}")
924
+ print(" " * 40, end="\r", file=sys.stderr)
925
+ for line in r.log:
926
+ print((" " if line.startswith("!") else "") + line)
927
+ out = a.out or re.sub(r"\.kicad_pcb$", "", a.board) + "_splitplane.kicad_pcb"
928
+ files = write_outputs(a.board, out, r, colors=not a.no_colors)
929
+ print(f"wrote {files['board']}\nwrote {files['preview']}")
930
+ for path in files["project"]:
931
+ print(f"wrote {path}" + ("" if a.no_colors else " (net colours as in the preview)"))
932
+ return 0 if r.ok else 1
933
+
934
+
935
+ def _main_json(ap, a):
936
+ """main() with --json: the same work, files and exit codes; stdout is one
937
+ JSON object. Errors give {"ok": false, "error": ...}."""
938
+ try:
939
+ text = open(a.board, encoding="utf-8").read()
940
+ except OSError as e:
941
+ _print_json({"ok": False, "error": str(e)})
942
+ return 1
943
+ if a.list_nets:
944
+ _print_json({"ok": True, "nets": [{"name": n, "vias_tht": t, "smd": s}
945
+ for n, t, s in list_power_candidates(text)]})
946
+ return 0
947
+ if not a.nets:
948
+ ap.error("--nets is required (use --list-nets to see candidates)")
949
+ try:
950
+ r = process(text, a.layer, a.nets, a.gap, a.edge, a.min_neck, a.res,
951
+ a.include_smd, a.plain, a.keep_old, smooth=not a.no_smooth)
952
+ except ValueError as e:
953
+ _print_json({"ok": False, "error": str(e)})
954
+ return 1
955
+ out = a.out or re.sub(r"\.kicad_pcb$", "", a.board) + "_splitplane.kicad_pcb"
956
+ _print_json({**summary(r), "files": write_outputs(a.board, out, r, colors=not a.no_colors)})
957
+ return 0 if r.ok else 1
958
+
959
+
960
+ if __name__ == "__main__":
961
+ sys.exit(main())