aboutsummaryrefslogtreecommitdiff
path: root/tools/router/pcbroute.py
blob: 24f932eda46c1e7d80f2fa602fc3c327a07aea47 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"""Grid maze router for 2-layer boards (Python side; the search runs in astar.c).

The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu). Clearance uses exact
distance fields: for every cell the distance to the nearest copper (d1, its net n1)
and to the nearest copper of any other net (d2). A track of width w fits where the
distance to foreign copper is >= w/2 + CLR. Necks (narrower width) are allowed only
near pads, so fine-pitch pins can be entered.


Call setup(x0, y0, x1, y1) with the board extents before creating a Board.
"""
import ctypes, json, math, os, subprocess
import numpy as np
import shapely
from shapely.geometry import Polygon, Point, box, LineString
from scipy import ndimage

HERE = os.path.dirname(os.path.abspath(__file__))
_LIB = os.path.join(HERE, "libastar.dylib")
if not os.path.exists(_LIB) or os.path.getmtime(_LIB) < os.path.getmtime(os.path.join(HERE, "astar.c")):
    subprocess.run(["cc", "-O3", "-shared", "-fPIC", "-o", _LIB, os.path.join(HERE, "astar.c")], check=True)
lib = ctypes.CDLL(_LIB)
fp = np.ctypeslib.ndpointer
lib.init.argtypes = [ctypes.c_int, ctypes.c_int]
lib.route.restype = ctypes.c_int
lib.route.argtypes = [fp(np.float32), fp(np.int32), fp(np.float32), fp(np.float32), fp(np.float32),
    ctypes.c_int, fp(np.int32), ctypes.c_int, fp(np.uint8), ctypes.c_int,
    ctypes.c_int, ctypes.c_int,
    ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float,
    fp(np.int32), ctypes.c_int,
    ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_int, ctypes.c_int,
    fp(np.int32), fp(np.uint8), ctypes.c_int, ctypes.c_int]

RES = 0.05
X0 = Y0 = X1 = Y1 = 0.0
NX = NY = N = 0


def setup(x0, y0, x1, y1):
    """Set the grid to the board extents (mm). Call before Board()."""
    global X0, Y0, X1, Y1, NX, NY, N
    X0, Y0, X1, Y1 = x0, y0, x1, y1
    NX = int(round((X1 - X0) / RES)) + 1
    NY = int(round((Y1 - Y0) / RES)) + 1
    N = NX * NY
CAP = 1.5
CLR = 0.2
M = 0.015       # numeric margin on clearance checks
RDIAG = 0.02    # extra margin on diagonal steps
EDGE_CLR = 0.5   # copper to board edge
HOLE_CLR = 0.3   # copper to NPTH hole edge

def cell_xy(i, j): return X0 + i * RES, Y0 + j * RES
def xy_cell(x, y): return int(round((x - X0) / RES)), int(round((y - Y0) / RES))

class Item:
    __slots__ = ("kind", "net", "layers", "geom", "bbox", "w", "owner")
    def __init__(self, kind, net, layers, geom, w=0.0, owner=None):
        self.kind, self.net, self.layers, self.geom, self.w, self.owner = kind, net, layers, geom, w, owner
        if kind == "pad":
            self.bbox = geom.bounds
        elif kind == "seg":
            (x1, y1), (x2, y2) = geom
            self.bbox = (min(x1, x2) - w / 2, min(y1, y2) - w / 2, max(x1, x2) + w / 2, max(y1, y2) + w / 2)
        elif kind == "via":
            x, y = geom; r = w / 2
            self.bbox = (x - r, y - r, x + r, y + r)

    def dist(self, X, Y):
        if self.kind == "pad":
            return shapely.distance(shapely.points(X, Y), self.geom).astype(np.float32)
        if self.kind == "seg":
            (x1, y1), (x2, y2) = self.geom
            dx, dy = x2 - x1, y2 - y1
            L2 = dx * dx + dy * dy
            if L2 == 0: t = np.zeros_like(X)
            else: t = np.clip(((X - x1) * dx + (Y - y1) * dy) / L2, 0, 1)
            return (np.hypot(X - (x1 + t * dx), Y - (y1 + t * dy)) - self.w / 2).astype(np.float32)
        if self.kind == "via":
            x, y = self.geom
            return (np.hypot(X - x, Y - y) - self.w / 2).astype(np.float32)


class Board:
    def __init__(self, board_json, netclass_of, domains, plane_nets=("GND",)):
        d = json.load(open(board_json)) if isinstance(board_json, str) else board_json
        self.plane_nets = set(plane_nets)
        self.fpcopper = d.get("fpcopper", [])
        self.keepouts = [Polygon(k) for k in d.get("keepouts", [])]
        self.fps = d["fps"]
        self.netid = {"": -1}
        self.netname = {-1: ""}
        self.pads = []   # dicts with poly, net id, layers, ref, num, center
        for p in d["pads"]:
            layers = tuple(L for L, k in ((0, "F"), (1, "B")) if p[k])
            if not layers: continue
            name = p["net"]
            if not name or name.startswith("unconnected"):
                nid = -1
            else:
                if name not in self.netid:
                    k = len(self.netid); self.netid[name] = k; self.netname[k] = name
                nid = self.netid[name]
            poly = Polygon(p["F"] or p["B"])
            self.pads.append(dict(ref=p["ref"], num=p["num"], net=nid, layers=layers, poly=poly,
                                  x=p["x"], y=p["y"], drill=p["drill"], tht=len(layers) == 2))
        self.npth = [(p["x"], p["y"], p["drill"]) for p in d["pads"] if p.get("npth")]
        self.netclass_of = netclass_of
        self.domains = domains
        self.items = []
        self.d1 = np.full((2, NY, NX), CAP, np.float32)
        self.n1 = np.zeros((2, NY, NX), np.int32)
        self.d2 = np.full((2, NY, NX), CAP, np.float32)
        self.padd = np.full((2, NY, NX), CAP, np.float32)
        self.cost = np.zeros((2, NY, NX), np.float32)
        self.base = np.full((2, NY, NX), CAP, np.float32)
        gx = X0 + np.arange(NX) * RES; gy = Y0 + np.arange(NY) * RES
        self.GX, self.GY = np.meshgrid(gx, gy)
        lib.init(NX, NY)
        self.tgt = np.zeros(2 * N, np.uint8)
        self.out = np.zeros(400000, np.int32); self.outneck = np.zeros(400000, np.uint8)
        self.routes = {}   # net id -> list of route records (segments/vias)

    # ---------- static obstacles ----------
    def build_static(self, keepouts=(), domain_seeds=()):
        keepouts = list(keepouts) + self.keepouts
        GX, GY = self.GX, self.GY
        edge = np.minimum.reduce([GX - X0, X1 - GX, GY - Y0, Y1 - GY])
        base = edge - (EDGE_CLR - CLR)
        for (x, y, dr) in self.npth:
            r = dr / 2 + HOLE_CLR
            base = np.minimum(base, np.hypot(GX - x, GY - y) - r + CLR)
        for poly in keepouts:
            dd = shapely.distance(shapely.points(GX.ravel(), GY.ravel()), poly).reshape(GX.shape)
            base = np.minimum(base, dd + CLR)
        # isolation domains (e.g. isolated RS485): voronoi to domain pad copper, eroded by
        # 1.55 mm each side. Skipped when the board has none.
        dom_ids = sorted(set(self.domains.values()) | {"LOGIC"})
        if len(dom_ids) == 1:
            dom_ids = []
        dist_stack = []
        for dmn in dom_ids:
            mask = np.zeros((NY, NX), bool)
            for p in self.pads:
                if p["net"] < 0: continue
                if self.domains.get(self.netname[p["net"]], "LOGIC") != dmn: continue
                b = p["poly"].bounds
                i0, j0 = xy_cell(b[0], b[1]); i1, j1 = xy_cell(b[2], b[3])
                sub = shapely.contains_xy(p["poly"], GX[j0:j1+1, i0:i1+1], GY[j0:j1+1, i0:i1+1])
                mask[j0:j1+1, i0:i1+1] |= sub
                ci, cj = xy_cell(p["x"], p["y"]); mask[cj, ci] = True
            for (sd, sx, sy) in domain_seeds:
                if sd == dmn:
                    ci, cj = xy_cell(sx, sy); mask[cj, ci] = True
            dist_stack.append(ndimage.distance_transform_edt(~mask) * RES)
        if dom_ids:
            dist_stack = np.array(dist_stack)
            owner = np.argmin(dist_stack, axis=0)
            self.dom_owner = owner; self.dom_ids = dom_ids
            allowed = np.zeros((NY, NX), bool)
            for k in range(len(dom_ids)):
                m = owner == k
                dout = ndimage.distance_transform_edt(m) * RES   # distance to nearest non-m cell
                allowed |= m & (dout >= 1.55)
            dforb = ndimage.distance_transform_edt(allowed) * RES   # distance from allowed cell to forbidden
            base = np.minimum(base, np.where(allowed, dforb + CLR - RES, -1.0))
            self.allowed = allowed
        base = base.astype(np.float32)
        self.base[0] = base; self.base[1] = base
        self.reset_region(None)
        # pad distance field for via-in-pad avoidance (SMD pads, not exposed pads)
        for p in self.pads:
            if p["tht"]: continue
            b = p["poly"].bounds
            if (b[2] - b[0]) > 2.5 and (b[3] - b[1]) > 2.5 and p["net"] >= 0 and self.netname[p["net"]] in self.plane_nets:
                continue  # exposed GND pad: vias allowed
            sl, X, Y = self.window(b, 1.0)
            dd = shapely.distance(shapely.points(X, Y), p["poly"]).astype(np.float32)
            for L in p["layers"]:
                v = self.padd[L][sl]; np.minimum(v, dd, out=v)
        for p in self.pads:
            it = Item("pad", p["net"], p["layers"], p["poly"], owner=("pad", p["ref"], p["num"]))
            p["item"] = it
            self.items.append(it)
            self.insert(it)
        if True:
            # footprint copper that is not a pad (net-tie bridges, antenna graphics)
            for g in self.fpcopper:
                poly = Polygon(g["poly"]).buffer(0)
                for p in self.pads:
                    if p["ref"] == g["ref"]: poly = poly.difference(p["poly"])
                if poly.is_empty: continue
                # a net tie's bridge is GND copper (it joins the AGND pad to GND)
                nid = self.netid.get("GND", -1) if g["ref"].startswith("NT") else -1
                it = Item("pad", nid, (0,) if g["layer"] == "F" else (1,), poly, owner=("fpcopper", g["ref"]))
                self.items.append(it); self.insert(it)
                # KiCad sees this graphic as net-less for hole clearance (0.3 mm to the via hole)
                sl, X, Y = self.window(poly.bounds, 1.0)
                dd = shapely.distance(shapely.points(X, Y), poly).astype(np.float32) - 0.1
                for L in (0, 1):
                    v = self.padd[L][sl]; np.minimum(v, dd, out=v)

    def window(self, b, pad):
        i0 = max(0, int(math.floor((b[0] - pad - X0) / RES))); j0 = max(0, int(math.floor((b[1] - pad - Y0) / RES)))
        i1 = min(NX - 1, int(math.ceil((b[2] + pad - X0) / RES))); j1 = min(NY - 1, int(math.ceil((b[3] + pad - Y0) / RES)))
        sl = (slice(j0, j1 + 1), slice(i0, i1 + 1))
        return sl, self.GX[sl], self.GY[sl]

    def reset_region(self, b):
        if b is None:
            sl = (slice(None), slice(None))
        else:
            sl, _, _ = self.window(b, 0)
        for L in (0, 1):
            bd = self.base[L][sl]
            self.d1[L][sl] = np.minimum(bd, CAP)
            self.n1[L][sl] = np.where(bd < CAP, -1, 0)
            self.d2[L][sl] = CAP

    def insert(self, it, clip=None):
        b = it.bbox
        if clip is not None:
            b2 = (max(b[0] - CAP, clip[0]), max(b[1] - CAP, clip[1]), min(b[2] + CAP, clip[2]), min(b[3] + CAP, clip[3]))
            if b2[0] > b2[2] or b2[1] > b2[3]: return
            sl, X, Y = self.window(b2, 0)
        else:
            sl, X, Y = self.window(b, CAP)
        dd = it.dist(X, Y)
        net = it.net
        for L in it.layers:
            d1 = self.d1[L][sl]; n1 = self.n1[L][sl]; d2 = self.d2[L][sl]
            same = n1 == net
            np.minimum(d1, dd, out=d1, where=same)
            m = (~same) & (dd < d1)
            d2[m] = d1[m]; d1[m] = dd[m]; n1[m] = net
            o = (~same) & (~m)
            np.minimum(d2, dd, out=d2, where=o)

    def remove_items(self, items):
        if not items: return
        ids = set(id(i) for i in items)
        self.items = [i for i in self.items if id(i) not in ids]
        for it in items:
            b = (it.bbox[0] - CAP, it.bbox[1] - CAP, it.bbox[2] + CAP, it.bbox[3] + CAP)
            self.reset_region(b)
            for o in self.items:
                ob = o.bbox
                if ob[0] - CAP > b[2] or ob[2] + CAP < b[0] or ob[1] - CAP > b[3] or ob[3] + CAP < b[1]: continue
                self.insert(o, clip=b)

    # ---------- routing ----------
    def cells_of(self, items, layers=(0, 1)):
        out = []
        for it in items:
            sl, X, Y = self.window(it.bbox, 0.05)
            dd = it.dist(X, Y)
            jj, ii = np.nonzero(dd <= 0.0)
            j0, i0 = sl[0].start, sl[1].start
            c = (jj + j0) * NX + (ii + i0)
            for L in it.layers:
                if L in layers: out.append(L * N + c)
        if not out: return np.zeros(0, np.int32)
        return np.unique(np.concatenate(out)).astype(np.int32)

    def route(self, net, src_items, tgt_items=None, goal_layer1=False, w=0.2, wneck=0.0, via_d=0.6,
              via_cost=40.0, via_cmult=0.0, bmult=3.0, turn=4.0, allow_via=True, layer_mask=3, neck_items=(), max_expand=4000000,
              hxy=None, extra_tgt_cells=None):
        src = self.cells_of(src_items)
        if len(src) == 0: return None
        if tgt_items:
            tc = self.cells_of(tgt_items)
        else:
            tc = np.zeros(0, np.int32)
        if extra_tgt_cells is not None and len(extra_tgt_cells):
            tc = np.concatenate([tc, extra_tgt_cells]).astype(np.int32)
        self.tgt[tc] = 1
        if hxy is None:
            if tgt_items:
                g0 = tgt_items[0]
                c = g0.geom.centroid if g0.kind == "pad" else (Point(g0.geom) if g0.kind == "via" else Point(g0.geom[0]))
                hxy = (c.x, c.y)
            else:
                hxy = (X0, Y0)
        hx, hy = xy_cell(*hxy)
        boxes = []
        for it in neck_items:
            b = it.bbox
            i0, j0 = xy_cell(b[0] - 1.0, b[1] - 1.0); i1, j1 = xy_cell(b[2] + 1.0, b[3] + 1.0)
            boxes += [i0, j0, i1, j1]
        boxes = np.array(boxes or [0, 0, -1, -1], np.int32)
        r_nom = w / 2 + CLR + M
        r_neck = (wneck / 2 + CLR + M) if wneck else 0.0
        r_via = via_d / 2 + CLR + M
        r_vpad = via_d / 2 + 0.05
        n = lib.route(self.d1.ravel(), self.n1.ravel(), self.d2.ravel(), self.padd.ravel(), self.cost.ravel(),
                      net, src, len(src), self.tgt, int(goal_layer1), hx, hy,
                      r_nom, r_neck, r_via, r_vpad, RDIAG, boxes, len(boxes) // 4,
                      via_cost, via_cmult, bmult, turn, int(allow_via), max_expand,
                      self.out, self.outneck, len(self.out), layer_mask)
        self.tgt[tc] = 0
        if n < 0: return None
        path = self.out[:n][::-1].copy(); neck = self.outneck[:n][::-1].copy()
        return path, neck

    def path_to_geom(self, net, path, neck, w, wneck, via_d):
        """Convert a cell path into segments and vias (lists)."""
        pts = []
        for s, nk in zip(path, neck):
            L = int(s // N); c = int(s % N)
            pts.append((L, c % NX, c // NX, int(nk)))
        segs, vias = [], []
        run = [pts[0]]
        def flush(run):
            if len(run) < 2: return
            # widths per step
            k = 0
            while k < len(run) - 1:
                L, i, j, nk = run[k]
                wd = wneck if (wneck and (run[k][3] or run[k + 1][3])) else w
                # extend while direction and width constant
                di, dj = run[k + 1][1] - i, run[k + 1][2] - j
                m = k + 1
                while m < len(run) - 1:
                    w2 = wneck if (wneck and (run[m][3] or run[m + 1][3])) else w
                    if (run[m + 1][1] - run[m][1], run[m + 1][2] - run[m][2]) != (di, dj) or w2 != wd: break
                    m += 1
                segs.append((L, cell_xy(i, j), cell_xy(run[m][1], run[m][2]), wd))
                k = m
        for p in pts[1:]:
            if p[0] != run[-1][0]:
                flush(run)
                vias.append(cell_xy(p[1], p[2]))
                run = [p]
            else:
                run.append(p)
        flush(run)
        return segs, vias

    def commit(self, net, segs, vias, via_d, tag):
        items = []
        for (L, a, b, wd) in segs:
            it = Item("seg", net, (L,), (a, b), w=wd, owner=tag)
            items.append(it)
        for v in vias:
            items.append(Item("via", net, (0, 1), v, w=via_d, owner=tag))
        for it in items:
            self.items.append(it); self.insert(it)
        return items

    def stub(self, net, cell_xy_pt, L, target_item, w):
        """Straight stub from a path end to the centre of the pad it ends in (if inside)."""
        if target_item.kind != "pad": return None
        c = target_item.geom.centroid
        if target_item.geom.contains(Point(cell_xy_pt)) and (abs(c.x - cell_xy_pt[0]) > 1e-6 or abs(c.y - cell_xy_pt[1]) > 1e-6):
            return (L, cell_xy_pt, (c.x, c.y), w)
        return None