diff options
Diffstat (limited to 'tools')
55 files changed, 12845 insertions, 0 deletions
diff --git a/tools/compose_board.py b/tools/compose_board.py new file mode 100644 index 0000000..71b0f04 --- /dev/null +++ b/tools/compose_board.py @@ -0,0 +1,236 @@ +"""Compose a base board from routed module boards: each module's footprints, tracks, vias, pours and +drawings are copied onto the base board as one tile, turned and moved, with references and nets +renamed to the base board's schematic. + +The base board's schematic uses the modules' block sheets with references offset per sheet +(e.g. U1 -> U101 on the first sheet). The net of every copied pad and +track comes from the base board's netlist through the pads: a module net takes the base net of its +pads (all its pads must agree, except pads listed under "repin", whose net the root sheet changed, +e.g. an address strap). Module-only footprints such as housing posts (`skip`) are left out, since +the base board's housing footprint carries the posts. + +Spec (JSON): + {"board": base .kicad_pcb (template copy), "netlist": base netlist, + "modules": [{"board": module .kicad_pcb, "sheet": "RS485 1", "offset": 600, + "block": [x0, y0, x1, y1] (module coordinates), "rot": 0 | 180, + "at": [x0, y0] (block's top-left corner on the base board, after turning), + "skip": ["P1"], "repin": ["U2.1"]}], + "parts": {"R1": [x, y, rot]}, base-sheet parts: footprint from the netlist, placed here + "tabs": {"bottom": ["J101"], "top": ["J301"]}, connectors that get a board tab (connector_tab) + "tab_merge": 2.0} bodies closer than this share one tab (default connector_tab.MERGE, 3 mm) + +usage (KiCad's Python, from the repo root, board closed in KiCad): + .../Python.framework/Versions/3.9/bin/python3 tools/compose_board.py SPEC.json +then tools/sync_board.py NETLIST BOARD for paths, values and fields, and DRC with parity. +Notes: knowledge/tooling/compose-board.md +""" +import json +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import pcbnew # noqa: E402 +from connector_tab import MERGE, add_tabs # noqa: E402 +from sexpr import find, first, parse # noqa: E402 + +from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 +KFP = FOOTPRINTS +HWFP = os.path.join(ROOT, "libraries/footprints/HW.pretty") +mm = pcbnew.FromMM + + +def renum(ref, off): + m = re.fullmatch(r"(#?[A-Za-z_]+)(\d+)", ref) + assert m, ref + return "%s%d" % (m.group(1), int(m.group(2)) + off) + + +def read_netlist(path): + net = parse(open(path).read()) + pinnet, fpid = {}, {} + for n in find(first(net, "nets"), "net"): + for nd in find(n, "node"): + pinnet[(first(nd, "ref")[1], first(nd, "pin")[1])] = first(n, "name")[1] + for c in find(first(net, "components"), "comp"): + fpid[first(c, "ref")[1]] = first(c, "footprint")[1] + return pinnet, fpid + + +def dup(item): + """Copy of a board item (FOOTPRINT::Duplicate takes addToParentGroup, the others nothing).""" + try: + return item.Duplicate(False) + except TypeError: + return item.Duplicate() + + +def branch(mb, pad): + """Tracks of the pad's (module) net that run from the pad up to the first via or junction: the + copper a repinned pad must lose. Other pads do not stop the walk: a branch that crosses a + neighbour's pad end (e.g. an address-strap track running over the next strap pad) would otherwise stay too close to the + repinned pad. A pad that loses its only link shows up in DRC as unconnected.""" + tracks = [t for t in mb.GetTracks() if t.GetNetCode() == pad.GetNetCode()] + vias = [t for t in tracks if t.GetClass() == "PCB_VIA"] + segs = [t for t in tracks if t.GetClass() != "PCB_VIA"] + + def ends(t): + return (t.GetStart(), t.GetEnd()) + + out = [] + todo = [(t, t.GetEnd() if pad.HitTest(t.GetStart()) else t.GetStart()) + for t in segs if pad.IsOnLayer(t.GetLayer()) and any(pad.HitTest(e) for e in ends(t))] + while todo: + t, far = todo.pop() + if t in out: + continue + out.append(t) + nxt = [u for u in segs if u not in out and far in ends(u)] + if len(nxt) != 1 or any(v.GetPosition() == far for v in vias): + continue + u = nxt[0] + todo.append((u, u.GetEnd() if u.GetStart() == far else u.GetStart())) + return out + + +def rect_to_segments(b): + """Edge.Cuts rectangles -> four segments (add_tabs splits straight segments).""" + for d in list(b.GetDrawings()): + if d.GetLayer() == pcbnew.Edge_Cuts and d.GetShape() == pcbnew.SHAPE_T_RECTANGLE: + p, q = d.GetStart(), d.GetEnd() + pts = [(p.x, p.y), (q.x, p.y), (q.x, q.y), (p.x, q.y), (p.x, p.y)] + for a, c in zip(pts, pts[1:]): + s = pcbnew.PCB_SHAPE(b) + s.SetShape(pcbnew.SHAPE_T_SEGMENT) + s.SetStart(pcbnew.VECTOR2I(*a)) + s.SetEnd(pcbnew.VECTOR2I(*c)) + s.SetLayer(pcbnew.Edge_Cuts) + s.SetWidth(d.GetWidth()) + b.Add(s) + b.Remove(d) + + +def main(spec_path): + spec = json.load(open(spec_path)) + pinnet, fpid = read_netlist(spec["netlist"]) + pro = spec["board"][:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro).read() if os.path.exists(pro) else None + b = pcbnew.LoadBoard(spec["board"]) + assert not [f for f in b.GetFootprints() if not f.IsBoardOnly()], "base board already has parts" + rect_to_segments(b) + + nets = {str(k): v for k, v in b.GetNetsByName().items()} + + def getnet(name): + if name not in nets: + ni = pcbnew.NETINFO_ITEM(b, name) + b.Add(ni) + nets[name] = ni + return nets[name] + + for prio, m in enumerate(spec["modules"], start=1): + mb = pcbnew.LoadBoard(m["board"]) + off, skip, repin = m["offset"], set(m.get("skip", [])), set(m.get("repin", [])) + x0, y0, x1, y1 = m["block"] + rot = m.get("rot", 0) + w, h = (x1 - x0, y1 - y0) if rot in (0, 180) else (y1 - y0, x1 - x0) + centre = pcbnew.VECTOR2I(mm((x0 + x1) / 2), mm((y0 + y1) / 2)) + target = pcbnew.VECTOR2I(mm(m["at"][0] + w / 2), mm(m["at"][1] + h / 2)) + angle = pcbnew.EDA_ANGLE(rot, pcbnew.DEGREES_T) + + # module net -> base net, through the pads + nmap, clash = {}, [] + for fp in mb.GetFootprints(): + if fp.GetReference() in skip: + continue + ref = renum(fp.GetReference(), off) + for pad in fp.Pads(): + old, new = pad.GetNetname(), pinnet.get((ref, pad.GetNumber())) + if not old or new is None or "%s.%s" % (fp.GetReference(), pad.GetNumber()) in repin: + continue + if nmap.setdefault(old, new) != new: + clash.append("%s.%s %s: %s / %s" % (ref, pad.GetNumber(), old, nmap[old], new)) + assert not clash, "module nets that split on the base board (add to repin?):\n " + "\n ".join(clash) + + # copper that tied a repinned pad to its old net stays behind + drop = set() + for pr in repin: + ref, num = pr.split(".") + pad = [p for p in mb.FindFootprintByReference(ref).Pads() if p.GetNumber() == num][0] + for t in branch(mb, pad): + drop.add(t.m_Uuid.AsString()) + print(" %s: %d %s tracks left out" % (pr, len(drop), pad.GetNetname())) + + group = pcbnew.PCB_GROUP(b) + group.SetName(m["sheet"]) + b.Add(group) + + def place(item): + if rot: + item.Rotate(centre, angle) + item.Move(target - centre) + b.Add(item) + group.AddItem(item) + + n = {"fp": 0, "track": 0, "zone": 0, "drawing": 0} + for fp in mb.GetFootprints(): + if fp.GetReference() in skip: + continue + c = pcbnew.Cast_to_FOOTPRINT(dup(fp)) + ref = renum(fp.GetReference(), off) + c.SetReference(ref) + place(c) + for pad in c.Pads(): + name = pinnet.get((ref, pad.GetNumber())) + pad.SetNet(getnet(name) if name else b.FindNet(0)) + n["fp"] += 1 + for t in mb.GetTracks(): + if t.m_Uuid.AsString() in drop: + continue + c = dup(t).Cast() + place(c) + c.SetNet(getnet(nmap[t.GetNetname()])) + n["track"] += 1 + for z in mb.Zones(): + c = pcbnew.Cast_to_ZONE(dup(z)) + # butting tiles' pours touch: each tile gets its own priority (DRC zones_intersect) + c.SetAssignedPriority(z.GetAssignedPriority() + prio) + place(c) + if z.GetNetname(): + c.SetNet(getnet(nmap[z.GetNetname()])) + n["zone"] += 1 + for d in mb.GetDrawings(): + if d.GetLayer() == pcbnew.Edge_Cuts: + continue + place(dup(d).Cast()) + n["drawing"] += 1 + print("%-14s rot %3d at (%.2f, %.2f) %s" % (m["sheet"], rot, m["at"][0], m["at"][1], + ", ".join("%d %ss" % (v, k) for k, v in n.items()))) + + for ref, (x, y, r) in spec.get("parts", {}).items(): + nick, name = fpid[ref].split(":") + fp = pcbnew.FootprintLoad(HWFP if nick == "HW" else os.path.join(KFP, nick + ".pretty"), name) + assert fp, fpid[ref] + fp.SetFPID(pcbnew.LIB_ID(nick, name)) + b.Add(fp) + fp.SetReference(ref) + fp.SetPosition(pcbnew.VECTOR2I(mm(x), mm(y))) + fp.SetOrientationDegrees(r) + fp.Reference().SetTextSize(pcbnew.VECTOR2I(mm(0.8), mm(0.8))) + fp.Reference().SetTextThickness(mm(0.12)) + for pad in fp.Pads(): + name = pinnet.get((ref, pad.GetNumber())) + pad.SetNet(getnet(name) if name else b.FindNet(0)) + print("part", ref, fpid[ref], "at", x, y, r) + + for side, refs in spec.get("tabs", {}).items(): + add_tabs(b, refs, side=side, merge=spec.get("tab_merge", MERGE)) + + pcbnew.ZONE_FILLER(b).Fill(b.Zones()) + pcbnew.SaveBoard(spec["board"], b) + if keep is not None: + open(pro, "w").write(keep) # SaveBoard resets the project's net settings + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/tools/connector_tab.py b/tools/connector_tab.py new file mode 100644 index 0000000..7fbd932 --- /dev/null +++ b/tools/connector_tab.py @@ -0,0 +1,141 @@ +"""Put edge connectors onto a connector tab: on a finished board (keeping the routing), or from a +module's gen_pcb.py (add_tabs). + +DIN housing rule (knowledge/topics/din-rail-format.md, edge connectors): where a connector sits at +the bottom edge, the PCB runs out as a tab (2.0 mm) into the shell's wall notch, as wide as the +connector bodies, and the mating face or wire entry ends flush with the tab edge. + +As a script, for each given footprint this moves it by --dy (+ = outward, toward the bottom edge), +extends every track that ended on one of its pads by a straight stub along the move (same layer and +width), then replaces the straight bottom edge under the connectors with a tab TAB deep: one tab per +group of connector bodies (F.Fab extent) closer than --merge. The zones are refilled and the +.kicad_pro that SaveBoard rewrites is restored. Tracks that ran where the pads now are show up in +DRC: run it. + +usage (KiCad's Python, from the repo root, board closed in KiCad): + .../Python.framework/Versions/3.9/bin/python3 tools/connector_tab.py BOARD.kicad_pcb REF [REF ...] \ + --dy 2.0 [--tab 2.0] [--merge 3.0] +--dy is how far the connector moves: 2.0 for a face that was flush with the edge, 0 with --tab 2.5 +for one that already sticks out 2.5 mm (e.g. an RJ45 jack). + +From gen_pcb.py: draw the plain rectangular outline, place the connectors with their faces TAB past +the block edge, then `add_tabs(board, ["J1", ...], TAB)` before saving. +Notes: knowledge/tooling/connector-tab.md +""" +import argparse +import os + +import pcbnew + +TAB, MERGE = 2.0, 3.0 +EPS = pcbnew.FromMM(0.001) + + +def add_tabs(b, refs, tab=TAB, merge=MERGE, side="bottom"): + """Split the board's straight bottom (or top) edge into a tab under the bodies of footprints `refs`.""" + mm, tomm = pcbnew.FromMM, pcbnew.ToMM + fps = {f.GetReference(): f for f in b.GetFootprints()} + missing = [r for r in refs if r not in fps] + assert not missing, "not on the board: %s" % missing + + # body extents (F.Fab), merged into tab intervals: bodies closer than `merge` share one tab and + # one wall notch, so the printed shell gets no thin webs + spans = [] + for r in refs: + # bounding boxes include half the line width: take it off, the body edge is the line's centre + xs = [x for g in fps[r].GraphicalItems() if g.GetLayer() == pcbnew.F_Fab and g.GetClass() != "PCB_TEXT" + for x in (g.GetBoundingBox().GetLeft() + g.GetWidth() // 2, + g.GetBoundingBox().GetRight() - g.GetWidth() // 2)] + assert xs, "%s has no F.Fab outline" % r + spans.append([min(xs), max(xs)]) + spans.sort() + tabs = [spans[0]] + for x0, x1 in spans[1:]: + if x0 - tabs[-1][1] < mm(merge): + tabs[-1][1] = max(tabs[-1][1], x1) + else: + tabs.append([x0, x1]) + + # the bottom edge: the lowest horizontal Edge.Cuts segment(s); each tab splits the one it lies on + # (other outline shapes, e.g. rounded corners, stay as they are). side="top": the highest one, + # for the top row of a base board, with the tab going up + edges = [d for d in b.GetDrawings() if d.GetLayer() == pcbnew.Edge_Cuts and d.GetShape() == pcbnew.SHAPE_T_SEGMENT] + if side == "top": + yb = min(min(d.GetStart().y, d.GetEnd().y) for d in edges) + T = -mm(tab) + else: + yb = max(max(d.GetStart().y, d.GetEnd().y) for d in edges) + T = mm(tab) + for x0, x1 in tabs: + seg = [d for d in edges if abs(d.GetStart().y - yb) < EPS and abs(d.GetEnd().y - yb) < EPS + and min(d.GetStart().x, d.GetEnd().x) <= x0 + EPS and max(d.GetStart().x, d.GetEnd().x) >= x1 - EPS] + assert len(seg) == 1, "no single %s edge segment under %.2f..%.2f mm" % (side, tomm(x0), tomm(x1)) + d = seg[0] + xa, xb = sorted((d.GetStart().x, d.GetEnd().x)) + pts = [(xa, yb), (x0, yb), (x0, yb + T), (x1, yb + T), (x1, yb), (xb, yb)] + width = d.GetWidth() + b.Remove(d) + edges.remove(d) + for p, q in zip(pts, pts[1:]): + if p == q: + continue + s = pcbnew.PCB_SHAPE(b) + s.SetShape(pcbnew.SHAPE_T_SEGMENT) + s.SetStart(pcbnew.VECTOR2I(p[0], p[1])) + s.SetEnd(pcbnew.VECTOR2I(q[0], q[1])) + s.SetLayer(pcbnew.Edge_Cuts) + s.SetWidth(width) + b.Add(s) + edges.append(s) + print("tab x %.2f..%.2f, y %.2f..%.2f" % (tomm(x0), tomm(x1), tomm(min(yb, yb + T)), tomm(max(yb, yb + T)))) + + +def move_with_stubs(b, refs, dy): + """Move footprints `refs` by dy mm; extend each track that ended on one of their pads.""" + DY = pcbnew.FromMM(dy) + fps = {f.GetReference(): f for f in b.GetFootprints()} + stubs = {} # one stub per end point and layer (several tracks can meet on a pad), the widest + for r in refs: + for pad in fps[r].Pads(): + for t in b.GetTracks(): + if t.GetClass() != "PCB_TRACK" or t.GetNetCode() != pad.GetNetCode(): + continue + for end in (t.GetStart(), t.GetEnd()): + if pad.IsOnLayer(t.GetLayer()) and pad.HitTest(end): + k = (end.x, end.y, t.GetLayer()) + if k not in stubs or t.GetWidth() > stubs[k][1]: + stubs[k] = (t.GetNet(), t.GetWidth()) + for r in refs: + fps[r].Move(pcbnew.VECTOR2I(0, DY)) + if not DY: + return 0 + for (x, y, layer), (net, width) in stubs.items(): + s = pcbnew.PCB_TRACK(b) + s.SetStart(pcbnew.VECTOR2I(x, y)) + s.SetEnd(pcbnew.VECTOR2I(x, y + DY)) + s.SetLayer(layer) + s.SetWidth(width) + s.SetNet(net) + b.Add(s) + return len(stubs) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("board") + ap.add_argument("refs", nargs="+") + ap.add_argument("--dy", type=float, required=True) + ap.add_argument("--tab", type=float, default=TAB) + ap.add_argument("--merge", type=float, default=MERGE, help="bodies closer than this share one tab") + a = ap.parse_args() + + pro = a.board[:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro).read() if os.path.exists(pro) else None + b = pcbnew.LoadBoard(a.board) + n = move_with_stubs(b, a.refs, a.dy) + add_tabs(b, a.refs, a.tab, a.merge) + pcbnew.ZONE_FILLER(b).Fill(b.Zones()) + pcbnew.SaveBoard(a.board, b) + if keep is not None: + open(pro, "w").write(keep) # SaveBoard resets the project's net settings + print("moved %s by %.2f mm, %d stubs" % (" ".join(a.refs), a.dy, n)) diff --git a/tools/din_base.kicad_pro b/tools/din_base.kicad_pro new file mode 100644 index 0000000..33e20a0 --- /dev/null +++ b/tools/din_base.kicad_pro @@ -0,0 +1,691 @@ +{ + "board": { + "3dviewports": [], + "design_settings": { + "defaults": { + "apply_defaults_to_fp_barcodes": false, + "apply_defaults_to_fp_dimensions": false, + "apply_defaults_to_fp_fields": false, + "apply_defaults_to_fp_shapes": false, + "apply_defaults_to_fp_text": false, + "board_outline_line_width": 0.05, + "copper_line_width": 0.2, + "copper_text_italic": false, + "copper_text_size_h": 1.5, + "copper_text_size_v": 1.5, + "copper_text_thickness": 0.3, + "copper_text_upright": false, + "courtyard_line_width": 0.05, + "dimension_precision": 4, + "dimension_units": 3, + "dimensions": { + "arrow_length": 1270000, + "extension_offset": 500000, + "keep_text_aligned": true, + "suppress_zeroes": true, + "text_position": 0, + "units_format": 0 + }, + "fab_line_width": 0.1, + "fab_text_italic": false, + "fab_text_size_h": 1.0, + "fab_text_size_v": 1.0, + "fab_text_thickness": 0.15, + "fab_text_upright": false, + "other_line_width": 0.1, + "other_text_italic": false, + "other_text_size_h": 1.0, + "other_text_size_v": 1.0, + "other_text_thickness": 0.15, + "other_text_upright": false, + "pads": { + "drill": 0.8, + "height": 1.27, + "width": 1.27 + }, + "silk_line_width": 0.1, + "silk_text_italic": false, + "silk_text_size_h": 1.0, + "silk_text_size_v": 1.0, + "silk_text_thickness": 0.1, + "silk_text_upright": false, + "zones": { + "border_display_style": 2, + "border_hatch_pitch": 0.5, + "corner_radius": 0.0, + "corner_smoothing": 0, + "fill_mode": 0, + "hatch_gap": 1.5, + "hatch_orientation": 0.0, + "hatch_smoothing_level": 0, + "hatch_smoothing_value": 0.1, + "hatch_thickness": 1.0, + "min_clearance": 0.5, + "min_island_area": 10.0, + "min_thickness": 0.25, + "pad_connection": 1, + "remove_islands": 0, + "thermal_relief_gap": 0.5, + "thermal_relief_spoke_width": 0.5 + } + }, + "diff_pair_dimensions": [ + { + "gap": 0, + "via_gap": 0, + "width": 0 + }, + { + "gap": 0.2, + "via_gap": 0.25, + "width": 0.25 + } + ], + "drc_exclusions": [], + "meta": { + "version": 2 + }, + "rule_severities": { + "annular_width": "error", + "clearance": "error", + "connection_width": "warning", + "copper_edge_clearance": "error", + "copper_sliver": "warning", + "courtyards_overlap": "error", + "creepage": "error", + "diff_pair_gap_out_of_range": "error", + "diff_pair_uncoupled_length_too_long": "error", + "drill_out_of_range": "error", + "duplicate_footprints": "warning", + "extra_footprint": "warning", + "footprint": "error", + "footprint_filters_mismatch": "ignore", + "footprint_symbol_field_mismatch": "warning", + "footprint_symbol_mismatch": "warning", + "footprint_type_mismatch": "ignore", + "hole_clearance": "error", + "hole_to_hole": "warning", + "holes_co_located": "warning", + "invalid_outline": "error", + "isolated_copper": "warning", + "item_on_disabled_layer": "error", + "items_not_allowed": "error", + "length_out_of_range": "error", + "lib_footprint_issues": "warning", + "lib_footprint_mismatch": "warning", + "malformed_courtyard": "error", + "microvia_drill_out_of_range": "error", + "mirrored_text_on_front_layer": "warning", + "missing_courtyard": "ignore", + "missing_footprint": "warning", + "missing_tuning_profile": "warning", + "net_conflict": "warning", + "nonmirrored_text_on_back_layer": "warning", + "npth_inside_courtyard": "error", + "padstack": "warning", + "pth_inside_courtyard": "error", + "shorting_items": "error", + "silk_edge_clearance": "warning", + "silk_over_copper": "warning", + "silk_overlap": "warning", + "skew_out_of_range": "error", + "solder_mask_bridge": "error", + "starved_thermal": "error", + "text_height": "warning", + "text_on_edge_cuts": "error", + "text_thickness": "warning", + "through_hole_pad_without_hole": "error", + "too_many_vias": "error", + "track_angle": "error", + "track_dangling": "warning", + "track_not_centered_on_via": "ignore", + "track_on_post_machined_layer": "error", + "track_segment_length": "error", + "track_width": "error", + "tracks_crossing": "error", + "tuning_profile_track_geometries": "ignore", + "unconnected_items": "error", + "unresolved_variable": "error", + "via_dangling": "warning", + "zones_intersect": "error" + }, + "rules": { + "max_error": 0.005, + "min_clearance": 0.0, + "min_connection": 0.0, + "min_copper_edge_clearance": 0.5, + "min_groove_width": 0.0, + "min_hole_clearance": 0.25, + "min_hole_to_hole": 0.25, + "min_microvia_diameter": 0.2, + "min_microvia_drill": 0.1, + "min_resolved_spokes": 2, + "min_silk_clearance": 0.0, + "min_text_height": 0.8, + "min_text_thickness": 0.08, + "min_through_hole_diameter": 0.3, + "min_track_width": 0.2, + "min_via_annular_width": 0.1, + "min_via_diameter": 0.5, + "solder_mask_to_copper_clearance": 0.0, + "use_height_for_length_calcs": true + }, + "teardrop_options": [ + { + "td_onpthpad": true, + "td_onroundshapesonly": false, + "td_onsmdpad": true, + "td_ontrackend": false, + "td_onvia": true + } + ], + "teardrop_parameters": [ + { + "td_allow_use_two_tracks": true, + "td_curve_segcount": 0, + "td_height_ratio": 1.0, + "td_length_ratio": 0.5, + "td_maxheight": 2.0, + "td_maxlen": 1.0, + "td_on_pad_in_zone": false, + "td_target_name": "td_round_shape", + "td_width_to_size_filter_ratio": 0.9 + }, + { + "td_allow_use_two_tracks": true, + "td_curve_segcount": 0, + "td_height_ratio": 1.0, + "td_length_ratio": 0.5, + "td_maxheight": 2.0, + "td_maxlen": 1.0, + "td_on_pad_in_zone": false, + "td_target_name": "td_rect_shape", + "td_width_to_size_filter_ratio": 0.9 + }, + { + "td_allow_use_two_tracks": true, + "td_curve_segcount": 0, + "td_height_ratio": 1.0, + "td_length_ratio": 0.5, + "td_maxheight": 2.0, + "td_maxlen": 1.0, + "td_on_pad_in_zone": false, + "td_target_name": "td_track_end", + "td_width_to_size_filter_ratio": 0.9 + } + ], + "track_widths": [ + 0, + 0.2, + 0.25, + 0.3, + 0.4, + 0.5, + 0.6, + 0.8, + 1.0 + ], + "tuning_pattern_settings": { + "diff_pair_defaults": { + "corner_radius_percentage": 80, + "corner_style": 1, + "max_amplitude": 1.0, + "min_amplitude": 0.2, + "single_sided": false, + "spacing": 1.0 + }, + "diff_pair_skew_defaults": { + "corner_radius_percentage": 80, + "corner_style": 1, + "max_amplitude": 1.0, + "min_amplitude": 0.2, + "single_sided": false, + "spacing": 0.6 + }, + "single_track_defaults": { + "corner_radius_percentage": 80, + "corner_style": 1, + "max_amplitude": 1.0, + "min_amplitude": 0.2, + "single_sided": false, + "spacing": 0.6 + } + }, + "via_dimensions": [ + { + "diameter": 0, + "drill": 0 + }, + { + "diameter": 0.6, + "drill": 0.3 + } + ], + "zones_allow_external_fillets": false + }, + "ipc2581": { + "bom_rev": "", + "dist": "", + "distpn": "", + "internal_id": "", + "mfg": "", + "mpn": "", + "sch_revision": "" + }, + "layer_pairs": [], + "layer_presets": [], + "viewports": [] + }, + "boards": [], + "component_class_settings": { + "assignments": [], + "meta": { + "version": 0 + }, + "sheet_component_classes": { + "enabled": false + } + }, + "cvpcb": { + "equivalence_files": [] + }, + "erc": { + "erc_exclusions": [], + "meta": { + "version": 0 + }, + "pin_map": [ + [ + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 2 + ], + [ + 0, + 2, + 0, + 1, + 0, + 0, + 1, + 0, + 2, + 2, + 2, + 2 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 1, + 2 + ], + [ + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 2, + 1, + 1, + 2 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 2 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2 + ], + [ + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 2 + ], + [ + 0, + 0, + 0, + 1, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 2 + ], + [ + 0, + 2, + 1, + 2, + 0, + 0, + 1, + 0, + 2, + 2, + 2, + 2 + ], + [ + 0, + 2, + 0, + 1, + 0, + 0, + 1, + 0, + 2, + 0, + 0, + 2 + ], + [ + 0, + 2, + 1, + 1, + 0, + 0, + 1, + 0, + 2, + 0, + 0, + 2 + ], + [ + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2 + ] + ], + "rule_severities": { + "bus_definition_conflict": "error", + "bus_entry_needed": "error", + "bus_to_bus_conflict": "error", + "bus_to_net_conflict": "error", + "different_unit_footprint": "error", + "different_unit_net": "error", + "duplicate_reference": "error", + "duplicate_sheet_names": "error", + "endpoint_off_grid": "warning", + "extra_units": "error", + "field_name_whitespace": "warning", + "footprint_filter": "ignore", + "footprint_link_issues": "warning", + "four_way_junction": "ignore", + "ground_pin_not_ground": "warning", + "hier_label_mismatch": "error", + "isolated_pin_label": "warning", + "label_dangling": "error", + "label_multiple_wires": "warning", + "lib_symbol_issues": "warning", + "lib_symbol_mismatch": "warning", + "missing_bidi_pin": "warning", + "missing_input_pin": "warning", + "missing_power_pin": "error", + "missing_unit": "warning", + "multiple_net_names": "warning", + "net_not_bus_member": "warning", + "no_connect_connected": "warning", + "no_connect_dangling": "warning", + "pin_not_connected": "error", + "pin_not_driven": "error", + "pin_to_pin": "warning", + "power_pin_not_driven": "error", + "same_local_global_label": "warning", + "similar_label_and_power": "warning", + "similar_labels": "warning", + "similar_power": "warning", + "simulation_model_issue": "ignore", + "single_global_label": "ignore", + "stacked_pin_name": "warning", + "unannotated": "error", + "unconnected_wire_endpoint": "warning", + "undefined_netclass": "error", + "unit_value_mismatch": "error", + "unresolved_variable": "error", + "wire_dangling": "error" + } + }, + "libraries": { + "pinned_footprint_libs": [], + "pinned_symbol_libs": [] + }, + "meta": { + "filename": "base.kicad_pro", + "version": 3 + }, + "net_settings": { + "classes": [ + { + "bus_width": 12, + "clearance": 0.2, + "diff_pair_gap": 0.25, + "diff_pair_via_gap": 0.25, + "diff_pair_width": 0.2, + "line_style": 0, + "microvia_diameter": 0.3, + "microvia_drill": 0.1, + "name": "Default", + "pcb_color": "rgba(0, 0, 0, 0.000)", + "priority": 2147483647, + "schematic_color": "rgba(0, 0, 0, 0.000)", + "track_width": 0.2, + "tuning_profile": "", + "via_diameter": 0.6, + "via_drill": 0.3, + "wire_width": 6 + } + ], + "meta": { + "version": 5 + }, + "net_colors": null, + "netclass_assignments": null, + "netclass_patterns": [] + }, + "pcbnew": { + "page_layout_descr_file": "" + }, + "schematic": { + "annotate_start_num": 0, + "annotation": { + "method": 0, + "sort_order": 0 + }, + "bom_export_filename": "${PROJECTNAME}.csv", + "bom_fmt_presets": [], + "bom_fmt_settings": { + "field_delimiter": ",", + "keep_line_breaks": false, + "keep_tabs": false, + "name": "CSV", + "ref_delimiter": ",", + "ref_range_delimiter": "", + "string_delimiter": "\"" + }, + "bom_presets": [], + "bom_settings": { + "exclude_dnp": false, + "fields_ordered": [ + { + "group_by": false, + "label": "Reference", + "name": "Reference", + "show": true + }, + { + "group_by": false, + "label": "Qty", + "name": "${QUANTITY}", + "show": true + }, + { + "group_by": true, + "label": "Value", + "name": "Value", + "show": true + }, + { + "group_by": true, + "label": "DNP", + "name": "${DNP}", + "show": true + }, + { + "group_by": true, + "label": "Exclude from BOM", + "name": "${EXCLUDE_FROM_BOM}", + "show": true + }, + { + "group_by": true, + "label": "Exclude from Board", + "name": "${EXCLUDE_FROM_BOARD}", + "show": true + }, + { + "group_by": true, + "label": "Exclude from Simulation", + "name": "${EXCLUDE_FROM_SIM}", + "show": true + }, + { + "group_by": true, + "label": "Exclude from Position Files", + "name": "${EXCLUDE_FROM_POS_FILES}", + "show": true + }, + { + "group_by": true, + "label": "Footprint", + "name": "Footprint", + "show": true + }, + { + "group_by": false, + "label": "Datasheet", + "name": "Datasheet", + "show": true + } + ], + "filter_string": "", + "group_symbols": true, + "include_excluded_from_bom": true, + "name": "Default Editing", + "sort_asc": true, + "sort_field": "Reference" + }, + "bus_aliases": {}, + "connection_grid_size": 50.0, + "drawing": { + "dashed_lines_dash_length_ratio": 12.0, + "dashed_lines_gap_length_ratio": 3.0, + "default_line_thickness": 6.0, + "default_text_size": 50.0, + "field_names": [], + "hop_over_size_choice": 0, + "intersheets_ref_own_page": false, + "intersheets_ref_prefix": "", + "intersheets_ref_short": false, + "intersheets_ref_show": false, + "intersheets_ref_suffix": "", + "junction_size_choice": 3, + "label_size_ratio": 0.375, + "operating_point_overlay_i_precision": 3, + "operating_point_overlay_i_range": "~A", + "operating_point_overlay_v_precision": 3, + "operating_point_overlay_v_range": "~V", + "overbar_offset_ratio": 1.23, + "pin_symbol_size": 25.0, + "text_offset_ratio": 0.15 + }, + "legacy_lib_dir": "", + "legacy_lib_list": [], + "meta": { + "version": 1 + }, + "page_layout_descr_file": "", + "plot_directory": "", + "reuse_designators": true, + "subpart_first_id": 65, + "subpart_id_separator": 0, + "top_level_sheets": [], + "used_designators": "", + "variants": [] + }, + "sheets": [], + "text_variables": {}, + "tuning_profiles": { + "meta": { + "version": 0 + }, + "tuning_profiles_impedance_geometric": [] + } +} diff --git a/tools/din_template.py b/tools/din_template.py new file mode 100644 index 0000000..e7cb874 --- /dev/null +++ b/tools/din_template.py @@ -0,0 +1,226 @@ +"""Generate DIN-rail board templates: housing footprint + KiCad project per TE. + +Run with KiCad's bundled Python (needs pcbnew): + $KICAD_PYTHON tools/din_template.py 4 5 6 (see tools/kicad_env.sh) + +Writes, for each TE count k: + libraries/footprints/HW.pretty/DIN_Housing_<k>TE.kicad_mod + libraries/templates/DIN_<k>TE/ (project template for KiCad's "New Project from Template") +The 3D model libraries/3dmodels/HW.3dshapes/DIN_Housing_<k>TE.step must be exported +from the DIN housing model at TE = k (bodies Shell, Plate, FrontCap, Spacer_*); the model is +not part of the toolchain, the footprint and templates work without it. + +Dimensions mirror the housing model's parameters; keep the two in sync. +""" +import json +import math +import os +import sys +import uuid + +import netclasses + +from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 +PRETTY = os.path.join(ROOT, "libraries/footprints/HW.pretty") +TEMPLATES = os.path.join(ROOT, "libraries/templates") +PRO_SOURCE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "din_base.kicad_pro") # design rules; net classes from netclasses.py + +# Housing parameters (SolidCraft names) +PITCH, H, WALL, FIT, PCB_GAP = 18.0, 90.0, 2.0, 0.2, 0.5 +D_SH, D_TOT, LIP_T, LIP_H = 45.0, 58.0, 1.2, 3.0 +FRONT_W = 44.5 +PLATE_T, SPACER_H, PCB_T = 4.6, 4.0, 1.6 +POST_D, RIB_W, POST_EX, POST_EY = 7.0, 3.0, 4.5, 14.0 +SPACER_D, HOLE_D = 6.0, 3.2 +TERM_H, STEP_W = 8.5, 10.0 # shoulder step: tallest edge connector, end face to riser +CY = 0.25 # courtyard margin + +Z_PCB = PLATE_T + SPACER_H + PCB_T # top of PCB above the back plane +SH_E = Z_PCB + TERM_H + 0.5 + WALL * (math.sqrt(2) - 1) # end-wall top; 45 deg slope up to the riser +CENTRE = (150.0, 100.0) # board centre on the A4 sheet + + +def dims(k): + w = k * PITCH - 0.5 + pcb_w, pcb_h = w - 2 * WALL - 2 * PCB_GAP, H - 2 * WALL - 2 * PCB_GAP + return { + "W": w, "pcb_w": pcb_w, "pcb_h": pcb_h, + "x_post": pcb_w / 2 - POST_EX, "y_post": pcb_h / 2 - POST_EY, + # inside of the front-cap lip: full height only within this box + "tall_x": w / 2 - WALL - FIT - LIP_T, "tall_y": FRONT_W / 2 - WALL - FIT - LIP_T, + "h_tall": D_TOT - WALL - Z_PCB, # to the inside of the front cap + "h_low": D_SH - LIP_H - Z_PCB, # to the bottom of the lip (the shoulder is higher) + "h_bot": SPACER_H, + # under the 45 deg shoulder step: limit at the PCB edge, rising 1:1 inward up to the riser + "y_step": H / 2 - STEP_W - WALL, # inner face of the riser + "h_edge": SH_E - WALL * math.sqrt(2) + (H / 2 - pcb_h / 2) - Z_PCB, + } + + +def f(v): + return ("%.4f" % v).rstrip("0").rstrip(".") + + +def line(layer, a, b, width=0.05): + return ('\t(fp_line (start %s %s) (end %s %s) (stroke (width %s) (type solid)) (layer "%s"))\n' + % (f(a[0]), f(a[1]), f(b[0]), f(b[1]), f(width), layer)) + + +def arc(layer, a, m, b, width=0.05): + return ('\t(fp_arc (start %s %s) (mid %s %s) (end %s %s) (stroke (width %s) (type solid)) (layer "%s"))\n' + % (f(a[0]), f(a[1]), f(m[0]), f(m[1]), f(b[0]), f(b[1]), f(width), layer)) + + +def circle(layer, c, r, width=0.05): + return ('\t(fp_circle (center %s %s) (end %s %s) (stroke (width %s) (type solid)) (fill no) (layer "%s"))\n' + % (f(c[0]), f(c[1]), f(c[0] + r), f(c[1]), f(width), layer)) + + +def rect(layer, a, b, width=0.1, dash=False): + return ('\t(fp_rect (start %s %s) (end %s %s) (stroke (width %s) (type %s)) (fill no) (layer "%s"))\n' + % (f(a[0]), f(a[1]), f(b[0]), f(b[1]), f(width), "dash" if dash else "solid", layer)) + + +def text(layer, s, at, size=1.0, hidden=False): + return ('\t(fp_text user "%s" (at %s %s 0) (layer "%s")%s (effects (font (size %s %s) (thickness %s)) (justify left)))\n' + % (s, f(at[0]), f(at[1]), layer, " (hide yes)" if hidden else "", f(size), f(size), f(size * 0.15))) + + +def footprint(k): + d = dims(k) + hx, hy = d["pcb_w"] / 2, d["pcb_h"] / 2 + name = "DIN_Housing_%dTE" % k + out = ['(footprint "%s"\n\t(version 20260206)\n\t(generator "din_template.py")\n\t(layer "F.Cu")\n' % name, + '\t(descr "Mounting and keep-outs for the printed DIN-rail housing, %d TE (outer %s mm wide), ' + 'PCB %s x %s mm. Origin = board centre. Generated by tools/din_template.py; see knowledge/topics/din-rail-format.md")\n' + % (k, f(d["W"]), f(d["pcb_w"]), f(d["pcb_h"])), + '\t(tags "DIN rail housing enclosure")\n', + '\t(property "Reference" "ENC1" (at 0 %s 0) (layer "F.Fab") (effects (font (size 1 1) (thickness 0.15))))\n' % f(-hy + 2), + '\t(property "Value" "%s" (at 0 %s 0) (layer "F.Fab") (effects (font (size 1 1) (thickness 0.15))))\n' % (name, f(hy - 2)), + '\t(attr board_only exclude_from_pos_files exclude_from_bom)\n'] + a = math.sqrt((POST_D / 2 + CY) ** 2 - (RIB_W / 2 + CY) ** 2) + rp, rh = POST_D / 2 + CY, RIB_W / 2 + CY + for sx in (1, -1): + for sy in (1, -1): + x0, y0 = sx * d["x_post"], sy * d["y_post"] + # top: post (Ø7) plus the rib that runs from it to the side wall + p1, p2 = (x0 + sx * a, y0 - rh), (x0 + sx * a, y0 + rh) + out += [line("F.CrtYd", p2, (sx * hx, y0 + rh)), line("F.CrtYd", (sx * hx, y0 + rh), (sx * hx, y0 - rh)), + line("F.CrtYd", (sx * hx, y0 - rh), p1), arc("F.CrtYd", p1, (x0 - sx * rp, y0), p2)] + # bottom: spacer + out.append(circle("B.CrtYd", (x0, y0), SPACER_D / 2 + CY)) + out.append(circle("Cmts.User", (x0, y0), POST_D / 2, 0.1)) + out.append('\t(pad "" np_thru_hole circle (at %s %s) (size %s %s) (drill %s) (layers "*.Cu" "*.Mask"))\n' + % (f(x0), f(y0), f(HOLE_D), f(HOLE_D), f(HOLE_D))) + # height zones and notes + tx, ty = min(d["tall_x"], hx), d["tall_y"] + out.append(rect("Dwgs.User", (-tx, -ty), (tx, ty), 0.15, dash=True)) + for sy in (1, -1): # shoulder step: the 45 deg slope starts above these lines + out.append('\t(fp_line (start %s %s) (end %s %s) (stroke (width 0.15) (type dash)) (layer "Dwgs.User"))\n' + % (f(-hx), f(sy * d["y_step"]), f(hx), f(sy * d["y_step"]))) + h_step = d["h_edge"] + hy - d["y_step"] + notes = ["%d TE: top parts max %s mm above PCB, max %s mm inside dashed box" % (k, f(math.floor(d["h_low"])), f(math.floor(d["h_tall"]))), + "outside the dashed step lines: 45 deg slope, max %s mm at the line down to %s mm at the edge" + % (f(math.floor(h_step * 10) / 10), f(math.floor(d["h_edge"] * 10) / 10)), + "bottom parts and THT leads max %s mm (spacers %s mm)" % (f(d["h_bot"] - 1), f(d["h_bot"])), + "no connectors past the edge without a notch in the shell"] + for i, s in enumerate(notes): + out.append(text("Dwgs.User", s, (-hx + 1, -ty + 2.5 + 1.6 * i), 1.0)) + out.append('\t(model "${HW_LIB}/3dmodels/HW.3dshapes/%s.step"\n\t\t(opacity 0.35)\n' + '\t\t(offset (xyz 0 0 %s))\n\t\t(scale (xyz 1 1 1))\n\t\t(rotate (xyz 0 0 0))\n\t)\n' % (name, f(-Z_PCB))) + out.append('\t(embedded_fonts no)\n)\n') + path = os.path.join(PRETTY, name + ".kicad_mod") + with open(path, "w") as fh: + fh.write("".join(out)) + return name + + +def project_json(proj): + with open(PRO_SOURCE) as fh: + d = json.load(fh) + d["meta"]["filename"] = proj + ".kicad_pro" + d["sheets"], d["boards"], d["text_variables"] = [["%s" % uuid.uuid4(), "Root"]], [], {} + d["schematic"]["top_level_sheets"] = [{"filename": proj + ".kicad_sch", "name": proj, "uuid": d["sheets"][0][0]}] + d["board"]["design_settings"]["drc_exclusions"] = [] + d["net_settings"]["netclass_assignments"] = None + netclasses.apply(d) # shared classes, patterns and width/via palettes + d.get("pcbnew", {}).pop("last_paths", None) + return d + + +def schematic(proj, k, d, sheet_uuid): + note = ("DIN-rail board, %d TE: housing %s x 90 mm, PCB %s x %s mm.\\n" + "Mounting holes and keep-outs: footprint DIN_Housing_%dTE on the PCB (not in schematic).\\n" + "Format and rules: knowledge/topics/din-rail-format.md" % (k, f(d["W"]), f(d["pcb_w"]), f(d["pcb_h"]), k)) + return ('(kicad_sch\n\t(version 20250610)\n\t(generator "eeschema")\n\t(generator_version "10.0")\n' + '\t(uuid "%s")\n\t(paper "A4")\n\t(title_block\n\t\t(title "${PROJECTNAME}")\n' + '\t\t(comment 1 "DIN-rail board %d TE")\n\t)\n\t(lib_symbols)\n' + '\t(text "%s"\n\t\t(exclude_from_sim no)\n\t\t(at 25.4 25.4 0)\n' + '\t\t(effects (font (size 1.27 1.27)) (justify left top))\n\t\t(uuid "%s")\n\t)\n' + '\t(sheet_instances\n\t\t(path "/" (page "1"))\n\t)\n\t(embedded_fonts no)\n)\n' + % (sheet_uuid, k, note, uuid.uuid4())) + + +def board(proj, k, d, fp_name, path): + import pcbnew # only here, so tools/height_check.py can import dims() without KiCad's Python + + b = pcbnew.NewBoard(path) + M, V = pcbnew.FromMM, pcbnew.VECTOR2I + cx, cy = CENTRE + hx, hy = d["pcb_w"] / 2, d["pcb_h"] / 2 + edge = pcbnew.PCB_SHAPE(b, pcbnew.SHAPE_T_RECTANGLE) + edge.SetStart(V(M(cx - hx), M(cy - hy))) + edge.SetEnd(V(M(cx + hx), M(cy + hy))) + edge.SetLayer(pcbnew.Edge_Cuts) + edge.SetWidth(M(0.05)) + b.Add(edge) + fp = pcbnew.FootprintLoad(PRETTY, fp_name) + fp.SetFPID(pcbnew.LIB_ID("HW", fp_name)) + fp.SetPosition(V(M(cx), M(cy))) + fp.SetLocked(True) + b.Add(fp) + ds = b.GetDesignSettings() + ds.SetBoardThickness(M(PCB_T)) + ds.SetAuxOrigin(V(M(cx), M(cy))) + ds.SetGridOrigin(V(M(cx), M(cy))) + tb = b.GetTitleBlock() + tb.SetTitle("${PROJECTNAME}") + tb.SetComment(0, "DIN-rail board %d TE, PCB %s x %s mm, origin = board centre" % (k, f(d["pcb_w"]), f(d["pcb_h"]))) + pcbnew.SaveBoard(path, b) + + +def info_html(k, d): + return ("<html>\n<head><title>DIN-rail board %d TE</title></head>\n<body>\n<h1>DIN-rail board %d TE</h1>\n" + "<p>Base PCB for the printed DIN-rail housing : outer width %s mm, " + "PCB %s × %s mm, 1.6 mm thick, four M3 holes at the corners. " + "Footprint <code>HW:DIN_Housing_%dTE</code> carries the holes, post and spacer courtyards, height zones " + "and the housing 3D model (hide it with the 3D viewer's 'Unspecified' toggle).</p>\n" + "<p>Top parts: max %d mm, or %d mm inside the dashed box. Outside the dashed step lines " + "(outer %s mm of the PCB) the shoulder slopes at 45°: max %s mm at the PCB edge, 1 mm more per mm inward. " + "Bottom parts: max %s mm.</p>\n" + "<p>Rules and decisions: knowledge/topics/din-rail-format.md</p>\n</body>\n</html>\n" + % (k, k, f(d["W"]), f(d["pcb_w"]), f(d["pcb_h"]), k, math.floor(d["h_low"]), math.floor(d["h_tall"]), + f(d["pcb_h"] / 2 - d["y_step"]), f(math.floor(d["h_edge"] * 10) / 10), f(d["h_bot"] - 1))) + + +def main(ks): + for k in ks: + d = dims(k) + fp_name = footprint(k) + proj = "DIN_%dTE" % k + tdir = os.path.join(TEMPLATES, proj) + os.makedirs(os.path.join(tdir, "meta"), exist_ok=True) + pro = project_json(proj) + board(proj, k, d, fp_name, os.path.join(tdir, proj + ".kicad_pcb")) + with open(os.path.join(tdir, proj + ".kicad_pro"), "w") as fh: # overwrite NewBoard's default + json.dump(pro, fh, indent=2) + fh.write("\n") + with open(os.path.join(tdir, proj + ".kicad_sch"), "w") as fh: + fh.write(schematic(proj, k, d, pro["sheets"][0][0])) + with open(os.path.join(tdir, "meta", "info.html"), "w") as fh: + fh.write(info_html(k, d)) + print("%s: PCB %s x %s, holes at +-%s/+-%s" % (proj, f(d["pcb_w"]), f(d["pcb_h"]), f(d["x_post"]), f(d["y_post"]))) + + +if __name__ == "__main__": + main([int(a) for a in sys.argv[1:]] or [4, 5, 6]) diff --git a/tools/height_check.py b/tools/height_check.py new file mode 100644 index 0000000..fa1e6e8 --- /dev/null +++ b/tools/height_check.py @@ -0,0 +1,173 @@ +"""Check part heights on a DIN-rail board against the printed housing. + + tools/router/.venv/bin/python tools/height_check.py projects/<name>/kicad/<name>.kicad_pcb + +Finds the HW:DIN_Housing_<k>TE footprint (its position is the housing centre), loads every +top-side footprint's 3D model (STEP vertices, transformed like KiCad does) and compares each +vertex with the height limit at its place, from tools/din_template.py dims(): +- inside the front-cap box: h_tall; elsewhere h_low (bottom of the front-cap lip); +- outside the step lines (|y| > y_step): the 45 deg shoulder slope, h_edge at the PCB edge + and 1 mm more per mm inward. +Parts that reach past the PCB edge are edge connectors: their notch runs up through the slope +(DIN housing model), so they are listed but not judged against the slope. +Bottom-side parts are not checked. Assembly STEP files (e.g. Phoenix's) cannot be placed +without their transforms: for them the F.CrtYd outline at the model's top height is used and the +result is flagged "approx". +""" +import math +import os +import re +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import din_template # noqa: E402 +import model_check # noqa: E402 +import sexpr # noqa: E402 + +from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 +ENV = { + "HW_LIB": os.path.join(ROOT, "libraries"), + "KICAD10_3DMODEL_DIR": MODELS3D, + "KICAD9_3DMODEL_DIR": MODELS3D, +} +_cache = {} + + +def vertices(path): + """(points, exact) for a STEP file; assemblies fall back to all their points.""" + if path not in _cache: + try: + _cache[path] = (model_check.step_vertices(path), True) + except SystemExit: + txt = open(path, encoding="latin-1").read() + pts = re.findall(r"CARTESIAN_POINT\s*\(\s*'[^']*'\s*,\s*\(\s*([-\d.eE+]+)\s*,\s*([-\d.eE+]+)\s*,\s*([-\d.eE+]+)", txt) + _cache[path] = (np.array(pts, dtype=float), False) + return _cache[path] + + +def resolve(path): + path = re.sub(r"\$\{(\w+)\}", lambda m: ENV.get(m.group(1), m.group(0)), path) + if not os.path.exists(path): + for ext in (".step", ".stp"): + alt = os.path.splitext(path)[0] + ext + if os.path.exists(alt): + return alt + return None + return path + + +def xyz(node, key): + n = sexpr.first(node, key) + v = sexpr.first(n, "xyz") if n else None + return np.array([float(a) for a in v[1:4]]) if v else np.zeros(3) if key != "scale" else np.ones(3) + + +def courtyard(fp): + """F.CrtYd corner points in footprint coordinates.""" + pts = [] + for kind in ("fp_line", "fp_rect", "fp_poly"): + for g in sexpr.find(fp, kind): + if str(sexpr.first(g, "layer")[1]) != "F.CrtYd": + continue + for key in ("start", "end"): + n = sexpr.first(g, key) + if n: + pts.append([float(n[1]), float(n[2])]) + if kind == "fp_rect": + a, b = sexpr.first(g, "start"), sexpr.first(g, "end") + pts += [[float(a[1]), float(b[2])], [float(b[1]), float(a[2])]] + n = sexpr.first(g, "pts") + pts += [[float(q[1]), float(q[2])] for q in sexpr.find(n, "xy")] if n else [] + return np.array(pts) + + +def model_points(fp): + """Model vertices of a footprint in board coordinates (x, y down, z above the board).""" + at = sexpr.first(fp, "at") + fx, fy = float(at[1]), float(at[2]) + fa = math.radians(float(at[3])) if len(at) > 3 else 0.0 + c, s = math.cos(fa), math.sin(fa) + out, exact = [], True + for m in sexpr.find(fp, "model"): + if sexpr.first(m, "hide"): + continue + path = resolve(str(m[1])) + if not path or not path.lower().endswith((".step", ".stp")): + continue + P, ok = vertices(path) + if not ok: # assembly: courtyard outline at the model's top height + exact = False + cy = courtyard(fp) + if not len(cy): + continue + top = (P * xyz(m, "scale"))[:, 2].max() + xyz(m, "offset")[2] + P = np.column_stack([cy[:, 0], -cy[:, 1], np.full(len(cy), top)]) + rt = np.zeros(3) + m = [None] + else: + rt = xyz(m, "rotate") + R = model_check.rot(2, -rt[2]) @ model_check.rot(1, -rt[1]) @ model_check.rot(0, -rt[0]) + if ok: + P = (P * xyz(m, "scale")) @ R.T + xyz(m, "offset") + P[:, 1] = -P[:, 1] + x = P[:, 0] * c + P[:, 1] * s + fx + y = -P[:, 0] * s + P[:, 1] * c + fy + out.append(np.column_stack([x, y, P[:, 2]])) + return (np.vstack(out) if out else None), exact + + +def limit(d, u, v): + """Height limit above the PCB at housing coordinates u, v (arrays).""" + au, av = np.abs(u), np.abs(v) + lim = np.where((au <= d["tall_x"]) & (av <= d["tall_y"]), d["h_tall"], d["h_low"]) + slope = d["h_edge"] + d["pcb_h"] / 2 - av + return np.where(av > d["y_step"], np.minimum(lim, slope), lim) + + +def main(): + board = sexpr.parse(open(sys.argv[1]).read()) + fps = sexpr.find(board, "footprint") + housing = [f for f in fps if re.match(r"HW:DIN_Housing_(\d+)TE$", str(f[1]))] + if not housing: + sys.exit("no HW:DIN_Housing_<k>TE footprint on the board") + k = int(re.match(r"HW:DIN_Housing_(\d+)TE$", str(housing[0][1])).group(1)) + at = sexpr.first(housing[0], "at") + cx, cy = float(at[1]), float(at[2]) + d = din_template.dims(k) + edge = d["pcb_h"] / 2 + print("%d TE, centre (%.2f, %.2f): h_tall %.1f, h_low %.1f, step at |y| > %.1f: %.1f at the line to %.1f at the edge" + % (k, cx, cy, d["h_tall"], d["h_low"], d["y_step"], d["h_edge"] + edge - d["y_step"], d["h_edge"])) + bad, nomodel = 0, [] + for fp in fps: + if fp is housing[0] or str(sexpr.first(fp, "layer")[1]) != "F.Cu": + continue + ref = next((str(p[2]) for p in sexpr.find(fp, "property") if str(p[1]) == "Reference"), "?") + P, exact = model_points(fp) + if P is None: + nomodel.append(ref) + continue + P = P[P[:, 2] > 0.05] + if not len(P): + continue + u, v = P[:, 0] - cx, P[:, 1] - cy + note = "" if exact else " (approx: assembly)" + if np.abs(v).max() > edge + 0.05: + print(" %-6s edge connector, %.1f mm tall, |y| %.1f..%.1f: needs a notch through the slope%s" + % (ref, P[:, 2].max(), np.abs(v).min(), np.abs(v).max(), note)) + continue + over = P[:, 2] - limit(d, u, v) + if over.max() > 0: + bad += 1 + i = over.argmax() + print(" %-6s TOO TALL by %.1f mm: %.1f mm at (%.1f, %.1f) from the centre%s" + % (ref, over[i], P[i, 2], u[i], -v[i], note)) + if nomodel: + print(" not checked (no STEP model): %s" % " ".join(sorted(nomodel))) + print("%d part(s) too tall" % bad) + sys.exit(1 if bad else 0) + + +if __name__ == "__main__": + main() diff --git a/tools/housing_inputs.py b/tools/housing_inputs.py new file mode 100644 index 0000000..c6361db --- /dev/null +++ b/tools/housing_inputs.py @@ -0,0 +1,147 @@ +"""Numbers for a project's DIN-rail housing: notches, pockets, spacer-frame tongues and pin cutouts. + + tools/router/.venv/bin/python tools/housing_inputs.py projects/<name>/kicad/<name>.kicad_pcb + +Prints, in housing coordinates (X along the rail, Y up = board -y, origin at the +HW:DIN_Housing_<k>TE footprint), what the per-project changes of the DIN housing model need: +- per PCB tab on Edge.Cuts: its X range and the edge connectors on it, each with the back of its + body (|y|, from the 3D model; assembly models use the courtyard, flagged "approx"), its height + above the PCB and the notch kind the README rules give (screw terminal, side-entry window, + notch from the riser); +- the spacer frame's pin cutouts: per footprint with through-hole pads under the frame, the pad + rectangle grown by PIN_CLR, and cutouts closer than MERGE_GAP that should be merged; +- bottom-side footprints, which the frame does not account for. +""" +import math +import os +import re +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import din_template # noqa: E402 +import height_check # noqa: E402 +import sexpr # noqa: E402 + +# Same values as the DIN housing model's parameters +TAB = 2.0 # PCB tab under an edge connector +STEP_W = 10.0 # shoulder step: riser at |y| = H/2 - STEP_W +TERM_H = 8.5 # tallest terminal under the step; the slope underside clears it by 0.5 at the wall +NOTCH_BACK_CLR = 0.5 # screw terminal: notch starts this far behind the body +WINDOW_CLR = 1.0 # side-entry window: this far above the body +FRAME_Y0 = 27.5 # spacer frame: inner edge of the end bars +FRAME_RAIL = 4.0 # spacer frame: side rail width +PIN_CLR = 1.5 # spacer frame: cutout margin around through-hole pads +MERGE_GAP = 1.0 # cutouts closer than this leave a sliver: merge them + + +def ref_of(fp): + return next((str(p[2]) for p in sexpr.find(fp, "property") if str(p[1]) == "Reference"), "?") + + +def tabs(board, cx, cy, edge): + """X ranges (housing) of the Edge.Cuts segments that run along |y| = edge + TAB, per side.""" + out = {1: [], -1: []} + for g in sexpr.find(board, "gr_line"): + if str(sexpr.first(g, "layer")[1]) != "Edge.Cuts": + continue + a, b = sexpr.first(g, "start"), sexpr.first(g, "end") + y1, y2 = cy - float(a[2]), cy - float(b[2]) + if abs(y1 - y2) < 1e-3 and abs(abs(y1) - (edge + TAB)) < 0.05: + xs = sorted([float(a[1]) - cx, float(b[1]) - cx]) + out[1 if y1 > 0 else -1].append(tuple(xs)) + return {s: sorted(v) for s, v in out.items()} + + +def pads(fp): + """Through-hole pad centres in board coordinates.""" + at = sexpr.first(fp, "at") + fx, fy = float(at[1]), float(at[2]) + a = math.radians(float(at[3])) if len(at) > 3 else 0.0 + out = [] + for p in sexpr.find(fp, "pad"): + if str(p[2]) not in ("thru_hole", "np_thru_hole"): + continue + pa = sexpr.first(p, "at") + lx, ly = float(pa[1]), float(pa[2]) + out.append((fx + lx * math.cos(a) + ly * math.sin(a), fy - lx * math.sin(a) + ly * math.cos(a))) + return out + + +def main(): + board = sexpr.parse(open(sys.argv[1]).read()) + fps = sexpr.find(board, "footprint") + housing = [f for f in fps if re.match(r"HW:DIN_Housing_(\d+)TE$", str(f[1]))] + if not housing: + sys.exit("no HW:DIN_Housing_<k>TE footprint on the board") + k = int(re.match(r"HW:DIN_Housing_(\d+)TE$", str(housing[0][1])).group(1)) + at = sexpr.first(housing[0], "at") + cx, cy = float(at[1]), float(at[2]) + d = din_template.dims(k) + edge = d["pcb_h"] / 2 + riser = din_template.H / 2 - STEP_W + window_max = TERM_H + 0.5 # slope underside at the inner end-wall face, above the PCB + print("%d TE, centre (%.2f, %.2f); housing X = board x - %.2f, Y = %.2f - board y; riser at |y| %.1f" + % (k, cx, cy, cx, cy, riser)) + + conns = [] + for fp in fps: + if fp is housing[0] or str(sexpr.first(fp, "layer")[1]) != "F.Cu": + continue + P, exact = height_check.model_points(fp) + if P is None: + continue + P = P[P[:, 2] > 0.05] + if not len(P) or np.abs(P[:, 1] - cy).max() <= edge + 0.05: + continue + u, v = P[:, 0] - cx, cy - P[:, 1] + conns.append((ref_of(fp), str(fp[1]), 1 if v.mean() > 0 else -1, u.min(), u.max(), + np.abs(v).min(), P[:, 2].max(), exact)) + + print("\nPCB tabs and edge connectors (notch X = tab +- notch_clr, tongue X = tab +- (notch_clr - fit)):") + for side, ranges in tabs(board, cx, cy, edge).items(): + for x1, x2 in ranges: + print(" %s tab X %.2f .. %.2f (length %.2f)" % ("top " if side > 0 else "bottom", x1, x2, x2 - x1)) + for ref, name, s, u1, u2, back, h, exact in conns: + if s != side or u2 < x1 or u1 > x2: + continue + if "TerminalBlock" in name: + kind = "screw terminal: notch from |y| %.2f (body back - %.1f), pocket back wall there" % ( + back - NOTCH_BACK_CLR, NOTCH_BACK_CLR) + elif h + WINDOW_CLR <= window_max: + kind = "side-entry: slope stays closed, end-wall window up to %.1f above the PCB" % (h + WINDOW_CLR) + else: + kind = "notch from the riser (|y| %.1f)%s" % ( + riser, ", back wall above the body" if back < riser else "") + print(" %-6s body back |y| %.2f, %.1f mm tall%s; %s" + % (ref, back, h, "" if exact else " (approx: assembly)", kind)) + + # spacer frame region: end bars |y| >= FRAME_Y0, side rails |x| >= inner edge of the rail + rail_x = d["W"] / 2 - din_template.WALL - din_template.FIT - FRAME_RAIL + rects = [] + for fp in fps: + if fp is housing[0]: + continue + P = [(x - cx, cy - y) for x, y in pads(fp)] + P = [(u, v) for u, v in P if abs(v) >= FRAME_Y0 - PIN_CLR or abs(u) >= rail_x - PIN_CLR] + if P: + us, vs = [p[0] for p in P], [p[1] for p in P] + rects.append((ref_of(fp), min(us) - PIN_CLR, max(us) + PIN_CLR, min(vs) - PIN_CLR, max(vs) + PIN_CLR)) + print("\nSpacer-frame pin cutouts (pad rectangle +- %.1f, through the frame):" % PIN_CLR) + for ref, a, b, c, e in sorted(rects, key=lambda r: (r[3] < 0, r[1])): + print(" %-6s X %.2f .. %.2f, Y %.2f .. %.2f" % (ref, a, b, c, e)) + for i, r in enumerate(rects): + for q in rects[i + 1:]: + gx = max(q[1] - r[2], r[1] - q[2]) + gy = max(q[3] - r[4], r[3] - q[4]) + if max(gx, gy) < MERGE_GAP: + print(" merge %s and %s: %.2f mm apart" % (r[0], q[0], max(gx, gy, 0))) + + bottom = [ref_of(f) for f in fps if str(sexpr.first(f, "layer")[1]) == "B.Cu"] + print("\nBottom-side footprints (the frame ignores them; cut them free by hand): %s" + % (" ".join(sorted(bottom)) if bottom else "none")) + + +if __name__ == "__main__": + main() diff --git a/tools/kicad_env.sh b/tools/kicad_env.sh new file mode 100644 index 0000000..f4947f0 --- /dev/null +++ b/tools/kicad_env.sh @@ -0,0 +1,22 @@ +# Sourced by the shell scripts in tools/: sets KPY (a Python that can `import pcbnew`) and +# KC (kicad-cli). Set either in the environment to override the detection. +# +# KICAD_PYTHON=/usr/bin/python3 KICAD_CLI=/usr/bin/kicad-cli sh tools/pnr.sh run board_dir + +_mac=/Applications/KiCad/KiCad.app/Contents +if [ -z "$KICAD_PYTHON" ]; then + if [ -x "$_mac/Frameworks/Python.framework/Versions/Current/bin/python3" ]; then + KICAD_PYTHON=$_mac/Frameworks/Python.framework/Versions/Current/bin/python3 + elif [ -x "$_mac/Frameworks/Python.framework/Versions/3.9/bin/python3" ]; then + KICAD_PYTHON=$_mac/Frameworks/Python.framework/Versions/3.9/bin/python3 + else + KICAD_PYTHON=python3 # Linux: the system Python has pcbnew when KiCad is installed from packages + fi +fi +if [ -z "$KICAD_CLI" ]; then + if command -v kicad-cli >/dev/null 2>&1; then KICAD_CLI=kicad-cli + else KICAD_CLI=$_mac/MacOS/kicad-cli; fi +fi +KPY=$KICAD_PYTHON +KC=$KICAD_CLI +export KPY KC diff --git a/tools/kicad_paths.py b/tools/kicad_paths.py new file mode 100644 index 0000000..2f46052 --- /dev/null +++ b/tools/kicad_paths.py @@ -0,0 +1,55 @@ +"""Where things live: the hardware repo root and KiCad's stock libraries. + +ROOT is the hardware repo the tools work on, the directory that holds libraries/ (your HW +symbol, footprint and 3D model libraries). It is HW_ROOT if set, else the nearest directory +at or above the current one that has a libraries/ folder, else the parent of tools/. + +KiCad's own environment variables win (KICAD10_SYMBOL_DIR, KICAD10_FOOTPRINT_DIR, +KICAD10_3DMODEL_DIR), then KICAD_SHARE (the directory that holds symbols/, footprints/, +3dmodels/), then the usual install locations on macOS, Linux and Windows. + + from kicad_paths import ROOT, SYMBOLS, FOOTPRINTS, MODELS3D +""" +import os + + +def repo_root(): + env = os.environ.get("HW_ROOT") + if env: + return os.path.abspath(env) + d = os.getcwd() + while True: + if os.path.isdir(os.path.join(d, "libraries")): + return d + up = os.path.dirname(d) + if up == d: + break + d = up + return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +ROOT = repo_root() + +_CANDIDATES = [ + "/Applications/KiCad/KiCad.app/Contents/SharedSupport", # macOS + "/usr/share/kicad", # Linux packages + "/usr/local/share/kicad", + "/app/share/kicad", # Flatpak + r"C:\Program Files\KiCad\10.0\share\kicad", # Windows +] + + +def share_dir(): + env = os.environ.get("KICAD_SHARE") + if env: + return env + for c in _CANDIDATES: + if os.path.isdir(os.path.join(c, "footprints")) or os.path.isdir(os.path.join(c, "symbols")): + return c + return _CANDIDATES[0] + + +SHARE = share_dir() +SYMBOLS = os.environ.get("KICAD10_SYMBOL_DIR") or os.path.join(SHARE, "symbols") +FOOTPRINTS = os.environ.get("KICAD10_FOOTPRINT_DIR") or os.path.join(SHARE, "footprints") +MODELS3D = os.environ.get("KICAD10_3DMODEL_DIR") or os.path.join(SHARE, "3dmodels") diff --git a/tools/konnect b/tools/konnect new file mode 160000 +Subproject c7e87cd8a7d440bfd6912025bc4370c7ebc00a0 diff --git a/tools/model_check.py b/tools/model_check.py new file mode 100644 index 0000000..4a3dcf2 --- /dev/null +++ b/tools/model_check.py @@ -0,0 +1,99 @@ +"""Check a footprint's 3D model placement against its pads. + + python3 tools/model_check.py libraries/footprints/HW.pretty/<name>.kicad_mod [-D HW_LIB=...] + +Reads the footprint's (model ...) entry, loads the STEP file's vertices (single-part STEP +only: no assembly transforms), applies KiCad's model transform (scale, rotate X/Y/Z, offset; +3D Y is footprint -Y) and reports: +- the model's extent in footprint coordinates and its height range above the board; +- every drilled pad (THT and NPTH) with the nearest model feature below the board surface + (pin tips, pegs, shell legs). A good placement has every hole matched within ~0.1 mm and + the body bottom at z ~ 0. + +A model whose features are all above z = 0 is upside down or floating; one with the body +below z = 0 is sunk into the board. +""" +import math +import os +import re +import sys + +import numpy as np + +from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 + + +def step_vertices(path): + txt = open(path, encoding="latin-1").read().replace("\r", "").replace("\n", "") + ents = dict(re.findall(r"#(\d+)\s*=\s*(.*?);(?=\s*#\d+\s*=|\s*ENDSEC)", txt)) + if any(v.startswith("NEXT_ASSEMBLY_USAGE_OCCURRENCE") for v in ents.values()): + sys.exit("%s is an assembly; transforms are not supported" % path) + pts = [] + for v in ents.values(): + m = re.match(r"VERTEX_POINT\s*\(\s*'[^']*'\s*,\s*#(\d+)", v) + if m: + nums = re.search(r"\(\s*([^()]*)\)\s*\)\s*$", ents[m.group(1)]).group(1) + pts.append([float(x) for x in nums.split(",")]) + return np.array(pts) + + +def xyz(block, key): + m = re.search(r"\(%s\s*\(xyz\s+([-\d.e]+)\s+([-\d.e]+)\s+([-\d.e]+)\s*\)" % key, block) + return np.array([float(v) for v in m.groups()]) if m else None + + +def rot(axis, deg): + c, s = math.cos(math.radians(deg)), math.sin(math.radians(deg)) + i, j = [(1, 2), (2, 0), (0, 1)][axis] + R = np.eye(3) + R[i, i], R[i, j], R[j, i], R[j, j] = c, -s, s, c + return R + + +def main(): + fp = sys.argv[1] + env = {"HW_LIB": os.path.join(ROOT, "libraries")} + for a, b in zip(sys.argv[2:], sys.argv[3:]): + if a == "-D": + k, v = b.split("=", 1) + env[k] = v + src = open(fp).read() + mb = src[src.index("(model "):] + path = re.match(r'\(model\s+"([^"]+)"', mb).group(1) + path = re.sub(r"\$\{(\w+)\}", lambda m: env[m.group(1)], path) + off, sc, rt = xyz(mb, "offset"), xyz(mb, "scale"), xyz(mb, "rotate") + P = step_vertices(path) * sc + # KiCad: translate(offset) * rotZ(-z) * rotY(-y) * rotX(-x) * scale + R = rot(2, -rt[2]) @ rot(1, -rt[1]) @ rot(0, -rt[0]) + P = P @ R.T + off + P[:, 1] = -P[:, 1] # 3D Y up -> footprint Y down + print("model", os.path.basename(path), "offset", off, "rotate", rt) + print("extent x %.2f..%.2f y %.2f..%.2f z %.2f..%.2f" % ( + P[:, 0].min(), P[:, 0].max(), P[:, 1].min(), P[:, 1].max(), P[:, 2].min(), P[:, 2].max())) + below = P[P[:, 2] < -0.05] + holes = [] + for m in re.finditer(r'\(pad\s+"([^"]*)"\s+(thru_hole|np_thru_hole)\b(.*?)\(drill\s+(?:oval\s+)?([\d.]+)', src, re.S): + at = re.search(r"\(at\s+([-\d.]+)\s+([-\d.]+)", m.group(3)) + holes.append((m.group(1) or "NPTH", float(at.group(1)), float(at.group(2)), float(m.group(4)))) + if not holes: + print("no drilled pads") + return + if not len(below): + print("nothing of the model reaches below the board surface: upside down or floating?") + return + worst = 0.0 + for name, x, y, d in holes: + near = below[np.hypot(below[:, 0] - x, below[:, 1] - y) < d / 2 + 1.0] + if len(near): + c = near[:, :2].mean(0) + e = math.hypot(c[0] - x, c[1] - y) + worst = max(worst, e) + print(" %-5s (%7.3f, %7.3f) drill %.2f: model feature centre off by %.2f mm" % (name, x, y, d, e)) + else: + worst = math.inf + print(" %-5s (%7.3f, %7.3f) drill %.2f: no model feature below the board within 1 mm" % (name, x, y, d)) + print("worst hole mismatch %.2f mm" % worst) + + +if __name__ == "__main__": + main() diff --git a/tools/netclasses.py b/tools/netclasses.py new file mode 100644 index 0000000..3f1b6df --- /dev/null +++ b/tools/netclasses.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""One net-class table for every board in a repo: modules, templates, base boards. + + python3 tools/netclasses.py PROJECT.kicad_pro [...] write the table + python3 tools/netclasses.py --check PROJECT.kicad_pro [...] report drift, exit 1 if any + python3 tools/netclasses.py --table my.json PROJECT.kicad_pro + +The table is netclasses.json at the repo root (see kicad_paths.ROOT) when it exists, else +the generic default below. + +Writes net_settings.classes, net_settings.netclass_patterns and the track-width, via and +diff-pair palettes. All other project settings stay as they are. Close the project in +KiCad first: an open editor writes its own copy back when it saves. + +Patterns are sheet-independent (*/NET), so the same list works in a module's test +project and on a base board where the module sits under another sheet name. A pattern +that matches no net does nothing, so module-specific classes can live here too; their +names are then reserved for all modules. Lower priority numbers win when several +patterns match one net. + +Class widths are routing defaults, not minimums: short narrower escapes stay legal. +Rationale and sizing: knowledge/topics/netclasses.md +""" +import argparse +import copy +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from kicad_paths import ROOT # noqa: E402 + +# Generic default table. A netclasses.json at the repo root (or --table FILE) replaces it: +# {"clearance": 0.2, "via": 0.6, "drill": 0.3, "default_width": 0.2, +# "track_widths": [0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0], +# "classes": {"Power": [0.5, null, null, ["+3V3", "*/VBUS"]], ...}} +# Each class is [track width, diff pair width, diff pair gap, patterns], in priority order. +CLEARANCE, VIA, DRILL = 0.2, 0.6, 0.3 + +CLASSES = { + "Ethernet": (0.25, 0.25, 0.2, ["*/ETH_TX?", "*/ETH_RX?"]), + "USB": (0.25, 0.25, 0.2, ["*/USB_DP", "*/USB_DN"]), + "Power": (0.5, None, None, ["+3V3", "+5V", "*/3V3", "*/VBUS", "Net-(*-SW)"]), + "Ground": (0.4, None, None, ["GND"]), +} +DEFAULT_WIDTH = 0.2 +TRACK_WIDTHS = [0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0] + + +def load_table(path): + """Replace the module's table with a JSON file's (see the comment above CLASSES).""" + global CLEARANCE, VIA, DRILL, DEFAULT_WIDTH, TRACK_WIDTHS, CLASSES, VIAS, DIFF_PAIRS + with open(path) as fh: + d = json.load(fh) + CLEARANCE = d.get("clearance", CLEARANCE) + VIA, DRILL = d.get("via", VIA), d.get("drill", DRILL) + DEFAULT_WIDTH = d.get("default_width", DEFAULT_WIDTH) + TRACK_WIDTHS = d.get("track_widths", TRACK_WIDTHS) + CLASSES = {k: tuple(v) for k, v in d["classes"].items()} + _palettes() + BASE.update(clearance=CLEARANCE, track_width=DEFAULT_WIDTH, via_diameter=VIA, via_drill=DRILL) + + +def _palettes(): + global VIAS, DIFF_PAIRS + VIAS = [{"diameter": 0, "drill": 0}, {"diameter": VIA, "drill": DRILL}] + pairs = sorted({(dw, g) for _, dw, g, _ in CLASSES.values() if dw}) + DIFF_PAIRS = [{"gap": 0, "via_gap": 0, "width": 0}] + [{"gap": g, "via_gap": 0.25, "width": w} for w, g in pairs] + + +_palettes() + +BASE = { + "bus_width": 12, "clearance": CLEARANCE, "diff_pair_gap": 0.25, "diff_pair_via_gap": 0.25, + "diff_pair_width": 0.2, "line_style": 0, "microvia_diameter": 0.3, "microvia_drill": 0.1, + "name": "Default", "pcb_color": "rgba(0, 0, 0, 0.000)", "priority": 2147483647, + "schematic_color": "rgba(0, 0, 0, 0.000)", "track_width": DEFAULT_WIDTH, "tuning_profile": "", + "via_diameter": VIA, "via_drill": DRILL, "wire_width": 6, +} + + +if os.path.exists(os.path.join(ROOT, "netclasses.json")): + load_table(os.path.join(ROOT, "netclasses.json")) + + +def table(): + classes, patterns = [copy.deepcopy(BASE)], [] + for prio, (name, (width, dp_width, dp_gap, pats)) in enumerate(CLASSES.items()): + c = copy.deepcopy(BASE) + c.update(name=name, priority=prio, track_width=width) + if dp_width: + c.update(diff_pair_width=dp_width, diff_pair_gap=dp_gap) + classes.append(c) + patterns += [{"netclass": name, "pattern": p} for p in pats] + return classes, patterns + + +def apply(project): + """Write the shared table into a parsed .kicad_pro (dict), in place.""" + classes, patterns = table() + project["net_settings"]["classes"] = classes + project["net_settings"]["netclass_patterns"] = patterns + ds = project["board"]["design_settings"] + ds["track_widths"], ds["via_dimensions"], ds["diff_pair_dimensions"] = [0] + [w for w in TRACK_WIDTHS if w], copy.deepcopy(VIAS), copy.deepcopy(DIFF_PAIRS) + return project + + +def drift(project): + want = apply(copy.deepcopy(project)) + out = [] + for path in (("net_settings", "classes"), ("net_settings", "netclass_patterns"), ("board", "design_settings", "track_widths"), + ("board", "design_settings", "via_dimensions"), ("board", "design_settings", "diff_pair_dimensions")): + a, b = project, want + for k in path: + a, b = a.get(k), b.get(k) + if path[-1] == "classes": # KiCad saves the classes sorted by name; priority carries the order + a, b = (sorted(x or [], key=lambda c: c["name"]) for x in (a, b)) + if a != b: + out.append("/".join(path)) + return out + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("projects", nargs="+") + ap.add_argument("--check", action="store_true", help="only report projects that differ from the table") + ap.add_argument("--table", help="net-class table (JSON); default: netclasses.json at the repo root if present") + a = ap.parse_args() + if a.table: + load_table(a.table) + bad = 0 + for p in a.projects: + with open(p) as fh: + d = json.load(fh) + diff = drift(d) + if a.check: + print("%s: %s" % (p, "differs in " + ", ".join(diff) if diff else "ok")) + bad += bool(diff) + elif diff: + with open(p, "w") as fh: + fh.write(json.dumps(apply(d), indent=2) + "\n") + print("%s: updated %s" % (p, ", ".join(diff))) + else: + print("%s: already up to date" % p) + sys.exit(1 if bad else 0) + + +if __name__ == "__main__": + main() diff --git a/tools/placement_check.py b/tools/placement_check.py new file mode 100644 index 0000000..198a24c --- /dev/null +++ b/tools/placement_check.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +"""Rate the component placement of a KiCad board before routing. + +Run with KiCad's bundled Python (pcbnew module): + + $KICAD_PYTHON tools/placement_check.py board.kicad_pcb [--svg out.svg] [--json out.json] \ + [--fill GND] [--pair U2:J2] [--apply-rotations out.kicad_pcb] + +Checks (fill nets such as GND are left out of the ratsnest: they reach their pads +through a pour and a via, so their lines say nothing about routability): + + crossings ratsnest lines of different nets that cross. On two layers each + one costs a via or a detour. + length total ratsnest length (MST per net), and per net class. + decoupling capacitors with one pad on a fill net: distance from the other pad + to the nearest pin of that net on an IC (>= 4 pads; bulk caps >= 4.7 uF + may also sit at an inductor or ferrite), and IC power pins with no + capacitor within 3 mm (crystal nets excluded). The ground pad must be + within the limit + 2 mm of a ground pin of the same part (loop area). + rotation 2-pad parts whose ratsnest gets shorter or crosses less when the + part is turned by 90/180/270 degrees in place, without its courtyard + hitting another part. + courtyards front/back courtyard overlaps, and THT pads inside another + footprint's back courtyard (e.g. the DIN housing spacers). + pairs courtyard gap between named footprints (--pair A:B), for parts + that must sit close together. + +The score starts at 100 and loses points per finding; the breakdown is printed. +""" +import argparse, json, math, re, sys +import pcbnew + +MM = 1e6 +DEFAULT_FILL = r"^(/.*/)?(GND|GNDA|GNDD|AGND|DGND|VSS|PGND)$" + + +def mm(v): + return v / MM + + +class Pad: + __slots__ = ("ref", "num", "net", "x", "y", "fp", "pad", "tht") + + def __init__(self, fp, pad): + p = pad.GetPosition() + self.ref, self.num, self.net = fp.GetReference(), pad.GetNumber(), pad.GetNetname() + self.x, self.y, self.fp, self.pad = mm(p.x), mm(p.y), fp, pad + self.tht = pad.GetAttribute() in (pcbnew.PAD_ATTRIB_PTH, pcbnew.PAD_ATTRIB_NPTH) + + +def mst(points): + """Prim's MST over [(x, y, tag)], returns [(i, j, length)].""" + n = len(points) + if n < 2: + return [] + inside = [False] * n + best = [math.inf] * n + link = [-1] * n + best[0] = 0 + edges = [] + for _ in range(n): + i = min((k for k in range(n) if not inside[k]), key=lambda k: best[k]) + inside[i] = True + if link[i] >= 0: + edges.append((link[i], i, best[i])) + for k in range(n): + if not inside[k]: + d = math.hypot(points[i][0] - points[k][0], points[i][1] - points[k][1]) + if d < best[k]: + best[k], link[k] = d, i + return edges + + +def cross(a, b, c, d, eps=1e-6): + """Proper intersection of segments ab and cd (shared endpoints do not count).""" + def orient(p, q, r): + return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) + for p in (a, b): + for q in (c, d): + if abs(p[0] - q[0]) < eps and abs(p[1] - q[1]) < eps: + return None + o1, o2, o3, o4 = orient(a, b, c), orient(a, b, d), orient(c, d, a), orient(c, d, b) + if o1 * o2 < 0 and o3 * o4 < 0: + t = o1 / (o1 - o2) + return (c[0] + t * (d[0] - c[0]), c[1] + t * (d[1] - c[1])) + return None + + +def rotate_about(px, py, cx, cy, deg): + a = math.radians(deg) + dx, dy = px - cx, py - cy + # KiCad: positive angles turn counter-clockwise on screen (y points down) + return (cx + dx * math.cos(a) + dy * math.sin(a), cy - dx * math.sin(a) + dy * math.cos(a)) + + +def cap_value_uf(v): + m = re.match(r"\s*([\d.]+)\s*([pnuµm]?)F?", v) + if not m: + return None + f = {"p": 1e-6, "n": 1e-3, "u": 1, "µ": 1, "m": 1e3, "": 1}[m.group(2)] + return float(m.group(1)) * f + + +class Check: + def __init__(self, board, fill_re, ignore_refs=()): + self.board = board + self.fill = re.compile(fill_re) + fps = [f for f in board.GetFootprints() if f.GetReference() not in ignore_refs] + self.fps = fps + self.pads = [Pad(f, p) for f in fps for p in f.Pads() if p.GetNetname()] + self.nets = {} + for p in self.pads: + self.nets.setdefault(p.net, []).append(p) + # nets with a copper zone count as fill nets too + zone_nets = {z.GetNetname() for z in board.Zones() if not z.GetIsRuleArea() and z.GetNetname()} + self.fill_nets = {n for n in self.nets if self.fill.search(n) or n in zone_nets} + self.netclass = {} + for n in board.GetNetInfo().NetsByName().values(): + self.netclass[n.GetNetname()] = n.GetNetClassName() + + def is_fill(self, net): + return net in self.fill_nets + + # --- ratsnest ------------------------------------------------------------ + def ratsnest(self, override=None): + """[(net, (x1, y1), (x2, y2), length, pad_a, pad_b)]; override maps pad -> (x, y).""" + out = [] + for net, pads in self.nets.items(): + if self.is_fill(net) or len(pads) < 2: + continue + pts = [(override.get(p, (p.x, p.y)) if override else (p.x, p.y)) for p in pads] + for i, j, d in mst([(x, y, None) for x, y in pts]): + out.append((net, pts[i], pts[j], d, pads[i], pads[j])) + return out + + @staticmethod + def crossings(rats): + res = [] + for i in range(len(rats)): + a = rats[i] + for b in rats[i + 1:]: + if a[0] == b[0]: + continue + pt = cross(a[1], a[2], b[1], b[2]) + if pt: + res.append((a[0], b[0], pt, a, b)) + return res + + # --- decoupling ---------------------------------------------------------- + def decoupling(self): + ic_pads, src_pads = {}, {} + for p in self.pads: + if len(p.fp.Pads()) >= 4 and not p.ref.startswith(("J", "P", "TP")): + ic_pads.setdefault(p.net, []).append(p) + elif p.ref.startswith(("L", "FB")): + src_pads.setdefault(p.net, []).append(p) + xtal_nets = {p.net for p in self.pads if p.ref.startswith("Y")} + caps, covered = [], set() + for f in self.fps: + ps = [p for p in self.pads if p.fp is f] + if not f.GetReference().startswith("C") or len(f.Pads()) != 2 or len(ps) != 2: + continue + g = [p for p in ps if self.is_fill(p.net)] + s = [p for p in ps if not self.is_fill(p.net)] + if len(g) != 1 or len(s) != 1: + continue + s = s[0] + uf = cap_value_uf(f.GetValue()) or 0 + # bulk caps may sit at the IC or at the inductor/ferrite that feeds the rail + cand = ic_pads.get(s.net, []) + (src_pads.get(s.net, []) if uf >= 4.7 else []) + if not cand: + continue + near = min(cand, key=lambda q: math.hypot(q.x - s.x, q.y - s.y)) + d = math.hypot(near.x - s.x, near.y - s.y) + # return side: cap ground pad to the nearest ground pin of the same part + gp = [q for q in self.pads if q.ref == near.ref and q.net == g[0].net] + dg = min((math.hypot(q.x - g[0].x, q.y - g[0].y) for q in gp), default=None) + limit = 8.0 if uf >= 4.7 else 3.0 + ok = d <= limit and (dg is None or dg <= limit + 2.0) + caps.append(dict(ref=f.GetReference(), value=f.GetValue(), net=s.net, ic=near.ref, pin=near.num, + dist=round(d, 2), gnd=None if dg is None else round(dg, 2), limit=limit, ok=ok)) + for q in ic_pads.get(s.net, []): + if math.hypot(q.x - s.x, q.y - s.y) <= 3.0: + covered.add((q.ref, q.num)) + # power pins of ICs: pins on nets that carry a decoupling cap (crystal load caps excluded) + dnets = {c["net"] for c in caps} - xtal_nets + uncovered = sorted({(p.ref, p.num, p.net) for net in dnets for p in ic_pads.get(net, []) + if (p.ref, p.num) not in covered and not p.ref.startswith(("Y", "L", "FB"))}) + return caps, uncovered + + # --- rotation ------------------------------------------------------------- + def rotation(self, rats): + base_x = self.crossings(rats) + sugg = [] + for f in self.fps: + if len(f.Pads()) != 2 or f.IsLocked(): + continue + mine = [p for p in self.pads if p.fp is f and not self.is_fill(p.net)] + if not mine: + continue + c = f.GetPosition() + cx, cy = mm(c.x), mm(c.y) + results = [] + for rot in (0, 90, 180, 270): + ov = {p: rotate_about(p.x, p.y, cx, cy, rot) for p in mine} + r = self.ratsnest(ov) if rot else rats + nets = {p.net for p in mine} + length = sum(e[3] for e in r if e[0] in nets) + local = [e for e in r if e[0] in nets] + others = [e for e in r if e[0] not in nets] + nx = sum(1 for a in local for b in others if cross(a[1], a[2], b[1], b[2])) + results.append((rot, nx, length)) + cur = results[0] + results = [r for r in results if not r[0] or self.fits(f, r[0])] + best = min(results, key=lambda t: (t[1], t[2])) + if best[0] and (best[1] < cur[1] or cur[2] - best[2] > 0.5): + sugg.append(dict(ref=f.GetReference(), turn=best[0], + to=(f.GetOrientationDegrees() + best[0]) % 360, + crossings=(cur[1], best[1]), length=(round(cur[2], 2), round(best[2], 2)))) + return sugg + + def fits(self, f, turn): + """True if footprint f, turned by `turn` degrees in place, hits no other courtyard.""" + old = f.GetOrientation() + f.SetOrientation(old + pcbnew.EDA_ANGLE(turn, pcbnew.DEGREES_T)) + ok = True + for layer in (pcbnew.F_CrtYd, pcbnew.B_CrtYd): + mine = f.GetCourtyard(layer) + if not mine.OutlineCount(): + continue + if any(g is not f and g.GetCourtyard(layer).OutlineCount() and mine.Collide(g.GetCourtyard(layer)) + for g in self.board.GetFootprints()): + ok = False + f.SetOrientation(old) + return ok + + # --- mechanics ----------------------------------------------------------- + def courtyards(self): + res = [] + for side, layer in (("front", pcbnew.F_CrtYd), ("back", pcbnew.B_CrtYd)): + polys = [(f, f.GetCourtyard(layer)) for f in self.fps] + polys = [(f, p) for f, p in polys if p.OutlineCount()] + for i, (a, pa) in enumerate(polys): + for b, pb in polys[i + 1:]: + if pa.Collide(pb): + res.append(dict(side=side, a=a.GetReference(), b=b.GetReference())) + for f in self.fps: + bc = f.GetCourtyard(pcbnew.B_CrtYd) + if not bc.OutlineCount(): + continue + for g in self.fps: + if g is f: + continue + for p in g.Pads(): + if p.GetAttribute() == pcbnew.PAD_ATTRIB_PTH and bc.Collide(p.GetPosition(), int(p.GetSize().x / 2)): + res.append(dict(side="back", a=f.GetReference(), b="%s.%s (THT)" % (g.GetReference(), p.GetNumber()))) + return res + + def gap(self, ra, rb): + fa = next(f for f in self.fps if f.GetReference() == ra) + fb = next(f for f in self.fps if f.GetReference() == rb) + a, b = fa.GetCourtyard(pcbnew.F_CrtYd).BBox(), fb.GetCourtyard(pcbnew.F_CrtYd).BBox() + dx = max(a.GetLeft() - b.GetRight(), b.GetLeft() - a.GetRight(), 0) + dy = max(a.GetTop() - b.GetBottom(), b.GetTop() - a.GetBottom(), 0) + return round(mm(math.hypot(dx, dy)), 2) + + +def svg(path, chk, rats, xs, flagged): + bb = chk.board.GetBoardEdgesBoundingBox() + x0, y0, w, h = mm(bb.GetLeft()) - 2, mm(bb.GetTop()) - 2, mm(bb.GetWidth()) + 4, mm(bb.GetHeight()) + 4 + o = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="%.2f %.2f %.2f %.2f" width="%dmm" height="%dmm">' % (x0, y0, w, h, w * 4, h * 4), + '<rect x="%.2f" y="%.2f" width="%.2f" height="%.2f" fill="white"/>' % (x0, y0, w, h)] + for d in chk.board.GetDrawings(): + if d.GetLayer() == pcbnew.Edge_Cuts and d.GetShape() == pcbnew.SHAPE_T_SEGMENT: + s, e = d.GetStart(), d.GetEnd() + o.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="black" stroke-width="0.15"/>' % (mm(s.x), mm(s.y), mm(e.x), mm(e.y))) + for f in chk.fps: + for layer, col in ((pcbnew.F_CrtYd, "#b0b0b0"), (pcbnew.B_CrtYd, "#c9a0dc")): + cy = f.GetCourtyard(layer) + for k in range(cy.OutlineCount()): + ol = cy.Outline(k) + pts = " ".join("%.3f,%.3f" % (mm(ol.CPoint(i).x), mm(ol.CPoint(i).y)) for i in range(ol.PointCount())) + fill = "#ffe0b0" if f.GetReference() in flagged else "none" + o.append('<polygon points="%s" fill="%s" stroke="%s" stroke-width="0.05"/>' % (pts, fill, col)) + for p in f.Pads(): + q = p.GetPosition(); sz = p.GetSize() + col = "#2e7d32" if chk.is_fill(p.GetNetname()) else "#c62828" + o.append('<circle cx="%.3f" cy="%.3f" r="%.3f" fill="%s" opacity="0.6"/>' % (mm(q.x), mm(q.y), max(0.15, mm(min(sz.x, sz.y)) / 2), col)) + c = f.GetPosition() + o.append('<text x="%.3f" y="%.3f" font-size="0.7" text-anchor="middle" font-family="sans-serif">%s</text>' % (mm(c.x), mm(c.y) + 0.25, f.GetReference())) + for e in rats: + o.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="#1565c0" stroke-width="0.06"/>' % (e[1][0], e[1][1], e[2][0], e[2][1])) + for x in xs: + o.append('<circle cx="%.3f" cy="%.3f" r="0.35" fill="none" stroke="#d50000" stroke-width="0.1"/>' % x[2]) + o.append("</svg>") + open(path, "w").write("\n".join(o)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("board") + ap.add_argument("--fill", default=DEFAULT_FILL, help="regex for fill nets left out of the ratsnest (default: GND-like names; nets with zones are added)") + ap.add_argument("--ignore", default="", help="comma-separated references to leave out (e.g. an off-board connector)") + ap.add_argument("--pair", action="append", default=[], help="A:B[:max_mm] report the courtyard gap between two footprints") + ap.add_argument("--svg", help="write an SVG overlay: courtyards, ratsnest, crossings (red), flagged parts (orange)") + ap.add_argument("--json", help="write the findings as JSON") + ap.add_argument("--apply-rotations", metavar="OUT", help="write a copy of the board with the suggested rotations applied") + a = ap.parse_args() + + board = pcbnew.LoadBoard(a.board) + chk = Check(board, a.fill, [r for r in a.ignore.split(",") if r]) + rats = chk.ratsnest() + xs = chk.crossings(rats) + caps, uncovered = chk.decoupling() + rot = chk.rotation(rats) + cy = chk.courtyards() + pairs = [] + for spec in a.pair: + parts = spec.split(":") + g = chk.gap(parts[0], parts[1]) + lim = float(parts[2]) if len(parts) > 2 else None + pairs.append(dict(a=parts[0], b=parts[1], gap=g, limit=lim, ok=lim is None or g <= lim)) + + total = sum(e[3] for e in rats) + by_class = {} + for e in rats: + k = chk.netclass.get(e[0], "?") + by_class[k] = by_class.get(k, 0) + e[3] + bad_caps = [c for c in caps if not c["ok"]] + penalties = { + "crossings": 1.0 * len(xs), + "decoupling": sum(min(5.0, max(c["dist"] - c["limit"], (c["gnd"] or 0) - c["limit"] - 2.0, 0.5)) for c in bad_caps) + + 1.0 * len(uncovered), + "rotation": 2.0 * len(rot), + "courtyards": 10.0 * len(cy), + "pairs": sum(5.0 for p in pairs if not p["ok"]), + } + score = max(0.0, 100.0 - sum(penalties.values())) + + print("board: %s" % a.board) + print("fill nets (not in ratsnest): %s" % ", ".join(sorted(chk.fill_nets))) + print("ratsnest: %.1f mm total; %s" % (total, ", ".join("%s %.1f" % kv for kv in sorted(by_class.items())))) + print("\ncrossings: %d" % len(xs)) + pairs_x = {} + for n1, n2, pt, ea, eb in xs: + pairs_x.setdefault(tuple(sorted((n1, n2))), []).append((pt, ea, eb)) + for (n1, n2), lst in sorted(pairs_x.items(), key=lambda kv: -len(kv[1])): + ea, eb = lst[0][1], lst[0][2] + print(" %-26s x %-26s %d (%s.%s-%s.%s / %s.%s-%s.%s)" % (n1, n2, len(lst), ea[4].ref, ea[4].num, ea[5].ref, ea[5].num, + eb[4].ref, eb[4].num, eb[5].ref, eb[5].num)) + print("\ndecoupling (cap pad to nearest IC pin of its net, limit 3 mm, 8 mm for >= 4.7 uF;") + print(" cap ground pad to that part's nearest ground pin, limit + 2 mm):") + for c in sorted(caps, key=lambda c: -c["dist"] + c["limit"]): + print(" %s %-6s %-6s %-22s %s.%s %5.2f mm gnd %s%s" % (" " if c["ok"] else "!!", c["ref"], c["value"], c["net"], c["ic"], c["pin"], c["dist"], + " - " if c["gnd"] is None else "%5.2f" % c["gnd"], "" if c["ok"] else " > %.0f" % c["limit"])) + if uncovered: + print(" IC power pins without a small cap within 3 mm: %s" % ", ".join("%s.%s (%s)" % u for u in uncovered)) + print("\nrotation suggestions: %d" % len(rot)) + for r in rot: + print(" %-5s turn %3d -> %3d deg crossings %d -> %d, length %.1f -> %.1f mm" % (r["ref"], r["turn"], r["to"], r["crossings"][0], r["crossings"][1], r["length"][0], r["length"][1])) + print("\ncourtyard conflicts: %d" % len(cy)) + for c in cy: + print(" %s: %s / %s" % (c["side"], c["a"], c["b"])) + if pairs: + print("\npairs (courtyard gap):") + for p in pairs: + print(" %s %s-%s %.2f mm%s" % (" " if p["ok"] else "!!", p["a"], p["b"], p["gap"], "" if p["limit"] is None else " (max %.1f)" % p["limit"])) + print("\nscore %.1f / 100 (penalties: %s)" % (score, ", ".join("%s %.1f" % kv for kv in penalties.items() if kv[1]))) + + flagged = {c["ref"] for c in bad_caps} | {r["ref"] for r in rot} + if a.svg: + svg(a.svg, chk, rats, xs, flagged) + if a.json: + json.dump(dict(score=score, penalties=penalties, ratsnest_mm=total, by_class=by_class, + crossings=[dict(a=n1, b=n2, at=pt) for n1, n2, pt, _, _ in xs], decoupling=caps, + uncovered=uncovered, rotation=rot, courtyards=cy, pairs=pairs), open(a.json, "w"), indent=1) + if a.apply_rotations: + for r in rot: + f = board.FindFootprintByReference(r["ref"]) + f.SetOrientationDegrees(r["to"]) + pcbnew.SaveBoard(a.apply_rotations, board) + + +if __name__ == "__main__": + main() diff --git a/tools/placement_slots.py b/tools/placement_slots.py new file mode 100644 index 0000000..ec49adb --- /dev/null +++ b/tools/placement_slots.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Assign same-size parts to fixed slots by hill-climbing placement_check's penalties. + +Hand placement sets the slots (a row of 0603s under an IC, a cap column); this script only +decides which part sits in which slot and which way it faces. Run with KiCad's Python: + + $KPY tools/placement_slots.py board.kicad_pcb slots.json [--out moved.kicad_pcb] + +slots.json: + {"ignore": ["J3"], # parts to leave out, as for placement_check + "groups": [{"parts": ["C20", "R12", ...], # parts that may trade places + "spares": [[131.7, 114.1, 270], ...], # empty slots they may move to (optional) + "flip": true}], # also try each part turned 180 deg + "turns": {"U4": [90, 180, 270]}} # extra in-place turns to try + +Cost = ratsnest crossings + 0.02 x ratsnest mm + 3 per decoupling cap over its limit + 1 per +uncovered IC power pin + 10 per courtyard conflict (see placement_check.py). Moves are +applied while they lower the cost; the result is printed as "REF": (x, y, rot) lines. +Look at the result before using it: the ratsnest cannot see routing channels. +""" +import argparse +import itertools +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import pcbnew # noqa: E402 +from placement_check import DEFAULT_FILL, Check # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("board") + ap.add_argument("slots") + ap.add_argument("--out", help="save a copy of the board with the result") + a = ap.parse_args() + cfg = json.load(open(a.slots)) + board = pcbnew.LoadBoard(a.board) + F = {f.GetReference(): f for f in board.GetFootprints()} + ignore = cfg.get("ignore", []) + groups, spare = [], {} + for g in cfg["groups"]: + members = list(g["parts"]) + for k, s in enumerate(g.get("spares", [])): + key = "_spare%d_%d" % (len(groups), k) + spare[key] = (pcbnew.FromMM(s[0]), pcbnew.FromMM(s[1]), s[2]) + members.append(key) + groups.append((members, g.get("flip", True))) + turns = {r: t for r, t in cfg.get("turns", {}).items()} + for members, flip in groups: + if flip: + for r in members: + if not r.startswith("_spare"): + turns.setdefault(r, [180]) + + def cost(): + c = Check(board, DEFAULT_FILL, ignore) + r = c.ratsnest() + caps, unc = c.decoupling() + return (len(c.crossings(r)) + 3 * sum(1 for k in caps if not k["ok"]) + len(unc) + + 0.02 * sum(e[3] for e in r) + 10 * len(c.courtyards())) + + def pose(ref): + if ref in spare: + return spare[ref] + p = F[ref].GetPosition() + return (p.x, p.y, F[ref].GetOrientationDegrees()) + + def put(ref, p): + if ref in spare: + spare[ref] = p + else: + F[ref].SetPosition(pcbnew.VECTOR2I(int(p[0]), int(p[1]))) + F[ref].SetOrientationDegrees(p[2]) + + def swap(x, y): + px, py = pose(x), pose(y) + put(x, (py[0], py[1], px[2])) + put(y, (px[0], px[1], py[2])) + + best = cost() + print("start cost %.2f" % best) + while True: + found = None + for members, _ in groups: + for x, y in itertools.combinations(members, 2): + if x in spare and y in spare: + continue + swap(x, y) + c = cost() + swap(x, y) + if c < best - 1e-6 and (found is None or c < found[0]): + found = (c, ("swap", x, y)) + for r, ts in turns.items(): + for t in ts: + p = pose(r) + put(r, (p[0], p[1], (p[2] + t) % 360)) + c = cost() + put(r, p) + if c < best - 1e-6 and (found is None or c < found[0]): + found = (c, ("turn", r, t)) + if not found: + break + best, m = found + if m[0] == "swap": + swap(m[1], m[2]) + else: + p = pose(m[1]) + put(m[1], (p[0], p[1], (p[2] + m[2]) % 360)) + print("%.2f %s" % (best, " ".join(map(str, m)))) + refs = [r for members, _ in groups for r in members if r not in spare] + [r for r in turns if r not in spare] + for r in dict.fromkeys(refs): + p = F[r].GetPosition() + print(' "%s": (%g, %g, %d),' % (r, round(p.x / 1e6, 3), round(p.y / 1e6, 3), round(F[r].GetOrientationDegrees()) % 360)) + if a.out: + pcbnew.SaveBoard(a.out, board) + + +if __name__ == "__main__": + main() diff --git a/tools/placer/Cargo.lock b/tools/placer/Cargo.lock new file mode 100644 index 0000000..606a2fd --- /dev/null +++ b/tools/placer/Cargo.lock @@ -0,0 +1,354 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "placer" +version = "0.1.0" +dependencies = [ + "anyhow", + "rand", + "rayon", + "router", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "router" +version = "0.1.0" +dependencies = [ + "anyhow", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tools/placer/Cargo.toml b/tools/placer/Cargo.toml new file mode 100644 index 0000000..64ddf81 --- /dev/null +++ b/tools/placer/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "placer" +version = "0.1.0" +edition = "2021" +description = "Simulated-annealing component placer for KiCad boards (see knowledge/tooling/placer.md)" + +[dependencies] +anyhow = "1" +rand = { version = "0.8", features = ["small_rng"] } +rayon = "1" +router = { path = "../router-rs" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "1" + +[profile.release] +debug = 1 diff --git a/tools/placer/apply.py b/tools/placer/apply.py new file mode 100644 index 0000000..db080dc --- /dev/null +++ b/tools/placer/apply.py @@ -0,0 +1,50 @@ +"""Write a placer result into a copy of a board: footprint positions and turns, no copper. + +Run with KiCad's bundled Python (pcbnew), with the source board closed or saved: + + $KPY tools/placer/apply.py board.kicad_pcb placement.json out.kicad_pcb + +placement.json maps ref -> [x, y, rotation in degrees], at the top level or under +"placement" (placer's rank_NN.json). Tracks and vias are deleted (the old routing belongs to +the old placement); zones are kept and refilled by the router's write step. The board's +.kicad_pro is copied next to the output, because pcbnew.SaveBoard would write default net +settings into it (knowledge/tooling/kicad.md, pcbnew quirks). +""" +import json +import os +import shutil +import sys + +import pcbnew + + +def main(src, placement, out): + d = json.load(open(placement)) + d = d.get("placement", d) + b = pcbnew.LoadBoard(src) + seen = set() + for f in b.GetFootprints(): + r = f.GetReference() + if r in d: + x, y, rot = d[r] + f.SetPosition(pcbnew.VECTOR2I(pcbnew.FromMM(x), pcbnew.FromMM(y))) + f.SetOrientationDegrees(rot) + seen.add(r) + missing = set(d) - seen + if missing: + sys.exit("not on the board: %s" % ", ".join(sorted(missing))) + for t in list(b.GetTracks()): + b.Delete(t) # not Remove: it breaks the board lists (knowledge/tooling/kicad.md) + pro_src = src[:-len(".kicad_pcb")] + ".kicad_pro" + pro_out = out[:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro_src).read() + pcbnew.SaveBoard(out, b) + open(pro_out, "w").write(keep) + dru = src[:-len(".kicad_pcb")] + ".kicad_dru" + if os.path.exists(dru): + shutil.copy(dru, out[:-len(".kicad_pcb")] + ".kicad_dru") + print("placed %d footprints -> %s" % (len(seen), out)) + + +if __name__ == "__main__": + main(*sys.argv[1:4]) diff --git a/tools/placer/export.py b/tools/placer/export.py new file mode 100644 index 0000000..9476c56 --- /dev/null +++ b/tools/placer/export.py @@ -0,0 +1,110 @@ +"""Export a board's placement problem for the Rust placer (tools/placer) as JSON. + +Run with KiCad's bundled Python (pcbnew); the board can be open in KiCad (it reads the saved file): + + kicad-cli sch export netlist -o board.net board.kicad_sch + $KPY tools/placer/export.py board.kicad_pcb problem.json [board.net] + +The netlist is optional and gives the pin types (power_in etc.), which a board made by script +does not carry. + +Geometry is in the footprint's own frame (orientation 0, origin at the anchor), so the placer +can turn parts by 90 degree steps. Output keys: + bounds [x0, y0, x1, y1] of the board outline (mm, without the Edge.Cuts line width) + parts ref, value, fpid, x, y, rot (deg), locked, board_only, fields (Place_* symbol + fields), court (F.CrtYd polygons, local), pads (num, net, pintype, x, y, w, h local, + tht) + netclass net -> class name; classes: class name -> track width and clearance (mm) + fill nets with a copper zone (they reach their pads through a pour and a via) + keepouts rule areas (board and footprint) that forbid footprints, pads or tracks: poly + in board coordinates, footprints / pads / tracks true where forbidden. Plus, + for an outline that is not its bbox (e.g. a connector tab), the bbox outside the + outline grown by the copper-to-edge clearance as a pad keep-out: the placer checks + pads against the bbox only, so a pad beside a tab could reach the real edge + (seen: a cap 0.4 mm from the edge next to a jack tab) +""" +import json +import re +import sys + +import pcbnew + +MM = 1e6 + + +def polys(ps): + out = [] + for k in range(ps.OutlineCount()): + ol = ps.Outline(k) + out.append([[round(ol.CPoint(i).x / MM, 4), round(ol.CPoint(i).y / MM, 4)] for i in range(ol.PointCount())]) + return out + + +def pintypes(netlist): + """(ref, pin) -> pintype from a KiCad netlist.""" + return {(r, p): t for r, p, t in re.findall( + r'\(node\s+\(ref "([^"]*)"\)\s+\(pin "([^"]*)"\)(?:\s+\(pinfunction "[^"]*"\))?\s+\(pintype "([^"]*)"\)', + open(netlist).read())} + + +def main(src, out, netlist=None): + types = pintypes(netlist) if netlist else {} + b = pcbnew.LoadBoard(src) + outline = pcbnew.SHAPE_POLY_SET() + b.GetBoardPolygonOutlines(outline, True) + bb = outline.BBox() + d = dict(bounds=[bb.GetLeft() / MM, bb.GetTop() / MM, bb.GetRight() / MM, bb.GetBottom() / MM], + parts=[], netclass={}, classes={}, fill=[], keepouts=[]) + # the bbox outside the outline, grown by the copper-to-edge clearance: pads stay out + outside = pcbnew.SHAPE_POLY_SET() + outside.NewOutline() + for x, y in ((bb.GetLeft(), bb.GetTop()), (bb.GetRight(), bb.GetTop()), (bb.GetRight(), bb.GetBottom()), + (bb.GetLeft(), bb.GetBottom())): + outside.Append(x, y) + outside.BooleanSubtract(outline) + if outside.OutlineCount(): + outside.Inflate(b.GetDesignSettings().m_CopperEdgeClearance, pcbnew.CORNER_STRATEGY_CHAMFER_ALL_CORNERS, + pcbnew.FromMM(0.005)) + for poly in polys(outside): + d["keepouts"].append(dict(poly=poly, footprints=False, pads=True, tracks=False)) + # rule areas before the footprints are moved to their local frame below + zones = list(b.Zones()) + [z for f in b.GetFootprints() for z in f.Zones()] + for z in zones: + if z.GetIsRuleArea() and (z.GetDoNotAllowFootprints() or z.GetDoNotAllowPads() or z.GetDoNotAllowTracks()): + for poly in polys(z.Outline()): + d["keepouts"].append(dict(poly=poly, footprints=z.GetDoNotAllowFootprints(), pads=z.GetDoNotAllowPads(), + tracks=z.GetDoNotAllowTracks())) + for f in sorted(b.GetFootprints(), key=lambda f: f.GetReference()): + part = dict(ref=f.GetReference(), value=f.GetValue(), fpid=f.GetFPIDAsString(), + x=f.GetPosition().x / MM, y=f.GetPosition().y / MM, rot=f.GetOrientationDegrees(), + locked=f.IsLocked(), board_only=bool(f.GetAttributes() & pcbnew.FP_BOARD_ONLY), + back=f.GetLayer() == pcbnew.B_Cu, + fields={fl.GetName(): fl.GetText() for fl in f.GetFields() if fl.GetName().startswith("Place_")}) + # local frame: the loaded board is never saved, so turn and move the footprint home + f.SetOrientationDegrees(0) + f.SetPosition(pcbnew.VECTOR2I(0, 0)) + f.BuildCourtyardCaches() + part["court"] = polys(f.GetCourtyard(pcbnew.F_CrtYd)) + part["pads"] = [] + for p in f.Pads(): + r = p.GetBoundingBox() + part["pads"].append(dict(num=p.GetNumber(), net=p.GetNetname(), pintype=types.get((part["ref"], p.GetNumber()), p.GetPinType()), + x=round(p.GetPosition().x / MM, 4), y=round(p.GetPosition().y / MM, 4), + w=round(r.GetWidth() / MM, 4), h=round(r.GetHeight() / MM, 4), + tht=p.GetAttribute() in (pcbnew.PAD_ATTRIB_PTH, pcbnew.PAD_ATTRIB_NPTH))) + part["pads"].sort(key=lambda p: (p["num"], p["x"], p["y"])) + d["parts"].append(part) + for name, ni in b.GetNetInfo().NetsByName().items(): + if str(name): + d["netclass"][str(name)] = ni.GetNetClassName() + pro = json.load(open(src[:-len(".kicad_pcb")] + ".kicad_pro")) + for c in pro["net_settings"]["classes"]: + d["classes"][c["name"]] = dict(track=c["track_width"], clearance=c["clearance"]) + d["fill"] = sorted({z.GetNetname() for z in b.Zones() if not z.GetIsRuleArea() and z.GetNetname()}) + json.dump(d, open(out, "w"), indent=1) + print("parts %d, pads %d, nets %d, fill %s, keepouts %d, bounds %s" % ( + len(d["parts"]), sum(len(p["pads"]) for p in d["parts"]), len(d["netclass"]), d["fill"], len(d["keepouts"]), d["bounds"])) + + +if __name__ == "__main__": + main(*sys.argv[1:4]) diff --git a/tools/placer/src/anneal.rs b/tools/placer/src/anneal.rs new file mode 100644 index 0000000..96b18b8 --- /dev/null +++ b/tools/placer/src/anneal.rs @@ -0,0 +1,461 @@ +//! Simulated annealing over part positions and 90 degree turns (VPR-style schedule: moves +//! per temperature grow with N^(4/3), the cooling rate and move range adapt to the +//! acceptance rate). A run stops when it has converged: the best cost improved by less than +//! 0.1 % over the last 15 temperatures and fewer than 5 % of the moves are accepted. +//! The legality terms (overlap, band, bounds) start at 1 % and reach full weight once the +//! temperature has dropped by 100x, so that big parts can pass each other early on. +//! A push move shifts a part together with the parts it would run into (transitively), so +//! a row of parts can slide as one where moving any single one would overlap its neighbour. + +use crate::cost::State; +use crate::geom::{dist, turn, Pt, Rect}; +use crate::model::Model; +use rand::rngs::SmallRng; +use rand::{Rng, SeedableRng}; + +/// largest number of parts (masters) one push may move +const PUSH_MAX: usize = 8; + +#[derive(Clone, Copy, PartialEq)] +pub enum Start { + /// from the board's placement + Keep, + /// random positions inside each part's group bbox (or the board), random turns + Scramble, +} + +#[derive(Clone)] +pub struct Opts { + pub start: Start, + pub inner: f64, + pub seed: u64, + /// initial temperature = t0 x the standard deviation of random move deltas + pub t0: f64, + pub grid: f64, +} + +pub struct Run { + pub seed: u64, + pub cost: f64, + pub at: Vec<Pt>, + pub rot: Vec<u8>, + pub moves: u64, + pub temps: u32, +} + +struct Ctx<'m> { + m: &'m Model, + swaps: Vec<Vec<usize>>, + groups: Vec<usize>, + /// movable ICs (>= 3 pads) with the movable 2-pad parts on their nets; a cluster move + /// takes those that are within 3 mm of the IC at the time + clusters: Vec<Vec<usize>>, + grid: f64, +} + +fn clusters(m: &Model) -> Vec<Vec<usize>> { + m.movable + .iter() + .filter(|&&i| m.parts[i].pads.len() >= 3) + .map(|&i| { + let mut c = vec![i]; + c.extend(m.movable.iter().copied().filter(|&j| { + m.parts[j].pads.len() == 2 && m.parts[j].nets.iter().any(|n| m.parts[i].nets.contains(n)) + })); + c + }) + .filter(|c| c.len() > 1) + .collect() +} + +impl<'m> Ctx<'m> { + fn snap(&self, v: f64) -> f64 { + (v / self.grid).round() * self.grid + } + + /// Keep a part's anchor such that its courtyard stays on the board. + fn clamp(&self, i: usize, at: Pt, r: u8) -> Pt { + let b = self.m.bounds; + let h = self.m.parts[i].hull.place((0.0, 0.0), r); + let fit = |v: f64, lo: f64, hi: f64| if lo <= hi { v.clamp(lo, hi) } else { (lo + hi) / 2.0 }; + (self.snap(fit(at.0, b.x0 - h.x0, b.x1 - h.x1)), self.snap(fit(at.1, b.y0 - h.y0, b.y1 - h.y1))) + } + + /// One random move as (part, anchor, rotation) triples. Single parts stay on the board; + /// a group move that would push a part off it is dropped. + fn pick(&self, s: &State, rng: &mut SmallRng, rlim: f64) -> Vec<(usize, Pt, u8)> { + let mut mv = self.pick_any(s, rng, rlim); + if mv.len() == 1 { + let (i, at, r) = mv[0]; + mv[0].1 = self.clamp(i, at, r); + } else if mv.iter().any(|&(i, at, r)| { + let h = self.m.parts[i].hull.place(at, r); + h.outside(&self.m.bounds) > 1e-9 + }) { + mv.clear(); + } + mv + } + + /// Shift part i by d with every movable part whose courtyard the moving ones would hit, + /// transitively. A follower that is hit brings its master (and so all its followers); + /// fixed parts are not pushed. Empty if more than PUSH_MAX parts would move. + fn push(&self, s: &State, i: usize, d: Pt) -> Vec<(usize, Pt, u8)> { + let m = self.m; + if d == (0.0, 0.0) { + return vec![]; + } + let mut c = vec![i]; + let mut moving: Vec<bool> = vec![false; m.parts.len()]; + let mut k = 0; + while k < c.len() { + let bodies: Vec<usize> = std::iter::once(c[k]).chain(m.parts[c[k]].followers.iter().copied()).collect(); + for &b in &bodies { + moving[b] = true; + } + for &b in &bodies { + let h = s.hull(b); + let moved = Rect::new(h.x0 + d.0, h.y0 + d.1, h.x1 + d.0, h.y1 + d.1); + for j in 0..m.parts.len() { + if moving[j] || m.parts[j].fixed || !s.hull(j).hits(&moved) { + continue; + } + let root = m.parts[j].follow.map_or(j, |(m0, _)| m0); + if !c.contains(&root) { + c.push(root); + if c.len() > PUSH_MAX { + return vec![]; + } + } + } + } + k += 1; + } + c.iter().map(|&j| (j, (s.at[j].0 + d.0, s.at[j].1 + d.1), s.rot[j])).collect() + } + + fn pick_any(&self, s: &State, rng: &mut SmallRng, rlim: f64) -> Vec<(usize, Pt, u8)> { + let m = self.m; + let mv = &m.movable; + let i = mv[rng.gen_range(0..mv.len())]; + let (at, r) = (s.at[i], s.rot[i]); + let jitter = |rng: &mut SmallRng| (rng.gen_range(-rlim..=rlim), rng.gen_range(-rlim..=rlim)); + let u: f64 = rng.gen(); + if u < 0.32 { + let (dx, dy) = jitter(rng); + vec![(i, (self.snap(at.0 + dx), self.snap(at.1 + dy)), r)] + } else if u < 0.40 { + // push: half of them along one axis only, which is how rows slide + let (mut dx, mut dy) = jitter(rng); + if rng.gen_bool(0.5) { + if rng.gen_bool(0.5) { + dx = 0.0 + } else { + dy = 0.0 + } + } + self.push(s, i, (self.snap(dx), self.snap(dy))) + } else if u < 0.55 { + vec![(i, at, (r + rng.gen_range(1..4)) & 3)] + } else if u < 0.62 { + let (dx, dy) = jitter(rng); + vec![(i, (self.snap(at.0 + dx), self.snap(at.1 + dy)), (r + rng.gen_range(1..4)) & 3)] + } else if u < 0.72 { + // swap with a part of the same footprint + let c = &self.swaps[i]; + if c.is_empty() { + return vec![]; + } + let j = c[rng.gen_range(0..c.len())]; + let k: u8 = if rng.gen_bool(0.5) { 0 } else { 2 }; + vec![(i, s.at[j], (s.rot[j] + k) & 3), (j, at, (r + k) & 3)] + } else if u < 0.80 { + // put one of its pads next to another pad of the same net (decaps: next to a pin) + let p = &m.parts[i]; + let own: Vec<usize> = p.pads.iter().copied().filter(|&k| m.pads[k].net.is_some()).collect(); + if own.is_empty() { + return vec![]; + } + let k = own[rng.gen_range(0..own.len())]; + let net = &m.nets[m.pads[k].net.unwrap()]; + let others: Vec<usize> = net.pads.iter().copied().filter(|&q| m.pads[q].part != i).collect(); + if others.is_empty() { + return vec![]; + } + let q = others[rng.gen_range(0..others.len())]; + let tq = s.pad_pos(q); + // land in front of the target pin when it has a direction + let qn = m.pads[q].normal.map(|n| turn(n, s.rot[m.pads[q].part])); + let d = rng.gen_range(1.2..3.0); + let (tx, ty) = match qn { + Some(n) => (tq.0 + n.0 * d + rng.gen_range(-0.6..0.6), tq.1 + n.1 * d + rng.gen_range(-0.6..0.6)), + None => { + let a = rng.gen_range(0.0..std::f64::consts::TAU); + (tq.0 + d * a.cos(), tq.1 + d * a.sin()) + } + }; + // turn so that our pad faces the target, else at random + let rot = match (m.pads[k].normal, qn) { + (Some(kn), Some(n)) => (0..4u8) + .max_by(|&a, &b| { + let fa = turn(kn, a); + let fb = turn(kn, b); + (-(fa.0 * n.0 + fa.1 * n.1)).partial_cmp(&-(fb.0 * n.0 + fb.1 * n.1)).unwrap() + }) + .unwrap(), + _ => rng.gen_range(0..4), + }; + let l = turn(m.pads[k].local, rot); + vec![(i, (self.snap(tx - l.0), self.snap(ty - l.1)), rot)] + } else if u < 0.88 { + // an IC with its satellites: shift, or turn about the IC + if self.clusters.is_empty() { + return vec![]; + } + let all = &self.clusters[rng.gen_range(0..self.clusters.len())]; + let near = s.hull(all[0]).grow(3.0); + let c: Vec<usize> = all.iter().copied().enumerate().filter(|&(k, j)| k == 0 || s.hull(j).hits(&near)).map(|(_, j)| j).collect(); + let o = s.at[c[0]]; + if rng.gen_bool(0.75) { + let (dx, dy) = jitter(rng); + let (dx, dy) = (self.snap(dx), self.snap(dy)); + c.iter().map(|&j| (j, (s.at[j].0 + dx, s.at[j].1 + dy), s.rot[j])).collect() + } else { + let k = rng.gen_range(1..4u8); + c.iter() + .map(|&j| { + let d = turn((s.at[j].0 - o.0, s.at[j].1 - o.1), k); + (j, (self.snap(o.0 + d.0), self.snap(o.1 + d.1)), (s.rot[j] + k) & 3) + }) + .collect() + } + } else { + // a whole group: shift, or turn about its centre + if self.groups.is_empty() { + return vec![]; + } + let g = &m.groups[self.groups[rng.gen_range(0..self.groups.len())]]; + if rng.gen_bool(0.75) { + let (dx, dy) = jitter(rng); + let (dx, dy) = (self.snap(dx), self.snap(dy)); + g.parts.iter().map(|&j| (j, (s.at[j].0 + dx, s.at[j].1 + dy), s.rot[j])).collect() + } else { + let k = rng.gen_range(1..4u8); + let n = g.parts.len() as f64; + let c = g.parts.iter().fold((0.0, 0.0), |a, &j| (a.0 + s.at[j].0 / n, a.1 + s.at[j].1 / n)); + g.parts + .iter() + .map(|&j| { + let d = turn((s.at[j].0 - c.0, s.at[j].1 - c.1), k); + (j, (self.snap(c.0 + d.0), self.snap(c.1 + d.1)), (s.rot[j] + k) & 3) + }) + .collect() + } + } + } +} + +fn scramble(m: &Model, rng: &mut SmallRng, grid: f64) -> (Vec<Pt>, Vec<u8>) { + let mut at: Vec<Pt> = m.parts.iter().map(|p| p.at0).collect(); + let mut rot: Vec<u8> = m.parts.iter().map(|p| p.rot0).collect(); + let fixed: Vec<_> = (0..m.parts.len()).filter(|&j| m.parts[j].fixed).map(|j| m.parts[j].hull.place(at[j], rot[j])).collect(); + for &i in &m.movable { + let p = &m.parts[i]; + let area = p.groups.iter().find_map(|&g| m.groups[g].bbox).unwrap_or(m.bounds); + // the spot of a few random tries that overlaps the fixed parts least + let mut best = (f64::MAX, (0.0, 0.0), 0u8); + for _ in 0..20 { + let r = rng.gen_range(0..4u8); + let h = p.hull.place((0.0, 0.0), r); + let (x0, x1) = (area.x0 - h.x0, area.x1 - h.x1); + let (y0, y1) = (area.y0 - h.y0, area.y1 - h.y1); + let x = if x1 > x0 { rng.gen_range(x0..x1) } else { (x0 + x1) / 2.0 }; + let y = if y1 > y0 { rng.gen_range(y0..y1) } else { (y0 + y1) / 2.0 }; + let at = ((x / grid).round() * grid, (y / grid).round() * grid); + let hw = p.hull.place(at, r); + let ov: f64 = fixed.iter().map(|f| f.inter(&hw)).sum(); + if ov < best.0 { + best = (ov, at, r); + } + if ov == 0.0 { + break; + } + } + at[i] = best.1; + rot[i] = best.2; + } + m.sync(&mut at, &mut rot); + (at, rot) +} + +pub fn anneal(m: &Model, o: &Opts) -> Run { + let mut rng = SmallRng::seed_from_u64(o.seed); + let (at, rot) = match o.start { + Start::Keep => { + let (mut at, mut rot): (Vec<Pt>, Vec<u8>) = (m.parts.iter().map(|p| p.at0).collect(), m.parts.iter().map(|p| p.rot0).collect()); + m.sync(&mut at, &mut rot); + (at, rot) + } + Start::Scramble => scramble(m, &mut rng, o.grid), + }; + let mut s = State::new(m, at, rot); + let swaps = m + .parts + .iter() + .enumerate() + .map(|(i, p)| { + if p.fixed { + return vec![]; + } + m.movable.iter().copied().filter(|&j| j != i && m.parts[j].fpid == p.fpid).collect() + }) + .collect(); + let groups = (0..m.groups.len()).filter(|&g| m.groups[g].parts.len() >= 2).collect(); + let ctx = Ctx { m, swaps, groups, clusters: clusters(m), grid: o.grid }; + let diag = dist((m.bounds.x0, m.bounds.y0), (m.bounds.x1, m.bounds.y1)); + let nmov = m.movable.len().max(1) as f64; + let per_t = (o.inner * nmov.powf(4.0 / 3.0)).ceil() as usize; + let nnets = m.nets.len().max(1) as f64; + + // initial temperature from the spread of random move deltas, measured with the legality + // terms at their starting weight (at full weight a scrambled start's overlaps dominate) + const PEN0: f64 = 0.01; + if o.start == Start::Scramble { + s.set_pen(PEN0); + } + let mut rlim = if o.start == Start::Keep { 2.0 } else { diag }; + let mut deltas = vec![]; + for _ in 0..(per_t.min(500)) { + let mv = ctx.pick(&s, &mut rng, rlim); + if mv.is_empty() { + continue; + } + let d = s.propose(&mv); + deltas.push(d); + s.reject(); + } + let mean = deltas.iter().sum::<f64>() / deltas.len().max(1) as f64; + let sd = (deltas.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / deltas.len().max(1) as f64).sqrt(); + let mut t = o.t0 * sd; + let t_full = t / 100.0; + let ramp = |t: f64| if o.start == Start::Keep { 1.0 } else { (t_full / t).clamp(PEN0, 1.0) }; + s.set_pen(ramp(t)); + let mut moves = 0u64; + // PLACER_TRACE=1: one line per temperature on stderr + let trace = std::env::var("PLACER_TRACE").is_ok(); + let mut temps = 0u32; + let mut best = (f64::MAX, s.at.clone(), s.rot.clone()); + let (mut mark, mut stall) = (f64::MAX, 0); + loop { + let mut acc = 0usize; + let mut tried = 0usize; + for _ in 0..per_t { + let mv = ctx.pick(&s, &mut rng, rlim); + if mv.is_empty() { + continue; + } + tried += 1; + let d = s.propose(&mv); + if d <= 0.0 || (t > 0.0 && rng.gen::<f64>() < (-d / t).exp()) { + s.accept(); + acc += 1; + if s.pen() == 1.0 && s.total < best.0 { + best = (s.total, s.at.clone(), s.rot.clone()); + } + } else { + s.reject(); + } + } + moves += tried as u64; + temps += 1; + let a = acc as f64 / tried.max(1) as f64; + if trace { + let big = *m.movable.iter().max_by_key(|&&i| m.parts[i].pads.len()).unwrap(); + eprintln!( + "t {temps:3} T {t:10.3} pen {:.3} acc {a:.3} rlim {rlim:6.2} cost {:10.1} {} at ({:.1}, {:.1})", + s.pen(), + s.total, + m.parts[big].reference, + s.at[big].0, + s.at[big].1 + ); + } + rlim = (rlim * (1.0 - 0.44 + a)).clamp(0.3, diag); + t *= if a > 0.96 { + 0.5 + } else if a > 0.8 { + 0.9 + } else if a > 0.15 { + 0.95 + } else { + 0.8 + }; + // converged: no real progress for 15 temperatures and hardly anything accepted + s.set_pen(ramp(t)); + if s.pen() < 1.0 { + continue; + } + if s.total < best.0 { + best = (s.total, s.at.clone(), s.rot.clone()); + } + if best.0 < mark * (1.0 - 1e-3) { + mark = best.0; + stall = 0; + } else { + stall += 1; + } + if (stall >= 15 && a < 0.05) || t < 1e-9 * nnets || temps >= 1000 { + break; + } + } + // quench: greedy small moves from the best state, with the legality terms at 10x so that + // leftover overlaps are pushed out + let mut s = State::new(m, best.1, best.2); + s.set_pen(10.0); + for _ in 0..per_t * 4 { + let mv = ctx.pick(&s, &mut rng, 0.5); + if mv.is_empty() { + continue; + } + if s.propose(&mv) < 0.0 { + s.accept(); + } else { + s.reject(); + } + moves += 1; + } + s.set_pen(1.0); + let cost = s.total; + Run { seed: o.seed, cost, at: s.at.clone(), rot: s.rot.clone(), moves, temps } +} + +/// Random moves with random acceptance; checks the incremental total against a full +/// recomputation. Returns the largest drift seen. +pub fn selftest(m: &Model, moves: usize, seed: u64) -> f64 { + let mut rng = SmallRng::seed_from_u64(seed); + let (at, rot) = scramble(m, &mut rng, 0.05); + let mut s = State::new(m, at, rot); + let swaps = (0..m.parts.len()).map(|_| vec![]).collect(); + let groups = (0..m.groups.len()).filter(|&g| m.groups[g].parts.len() >= 2).collect(); + let ctx = Ctx { m, swaps, groups, clusters: clusters(m), grid: 0.05 }; + let mut worst: f64 = 0.0; + for k in 0..moves { + let r = rng.gen_range(0.3..10.0); + let mv = ctx.pick(&s, &mut rng, r); + if mv.is_empty() { + continue; + } + s.propose(&mv); + if rng.gen_bool(0.5) { + s.accept(); + } else { + s.reject(); + } + if k % 500 == 499 { + let inc = s.total; + let full = s.recompute().total(); + worst = worst.max((inc - full).abs() / full.abs().max(1.0)); + } + } + worst +} diff --git a/tools/placer/src/congest.rs b/tools/placer/src/congest.rs new file mode 100644 index 0000000..db61efc --- /dev/null +++ b/tools/placer/src/congest.rs @@ -0,0 +1,321 @@ +//! Routing channels: how much track a placement asks for compared with the room between the +//! pads. Two measures on a grid of cells: +//! +//! rudy each ratsnest line spreads its track (Manhattan length x the class's track + +//! clearance) evenly over its bounding box; overflow = track area above the cells' +//! room, in mm of default track. Cheap; blind to detours. +//! groute coarse global routing with negotiated congestion (PathFinder): every net is +//! routed as a tree (Dijkstra to the nearest tree node) on two layers with vias; cells used beyond their room +//! get dearer each round (present and history cost) until nobody overuses them or +//! the rounds run out. Reports the remaining overflow, length and vias. +//! +//! Room of a cell per layer = its width, minus pads (grown by the clearance; SMD pads block +//! F.Cu, THT pads both layers), track keep-outs and the edge clearance. Cells holding a pin are +//! not counted as overflowing: a pad would otherwise block its own net. + +use crate::cost::State; +use crate::geom::{Pt, Rect}; +use crate::model::Model; +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +const CLR: f64 = 0.2; +/// default track + clearance (mm), the unit of the overflow figures +const UNIT: f64 = 0.4; + +pub struct Grid { + x0: f64, + y0: f64, + cell: f64, + nx: usize, + ny: usize, + /// room per node (layer * nx * ny + cell), mm of cross-section + cap: Vec<f64>, + /// node holds a pin of some net + pin: Vec<bool>, +} + +impl Grid { + fn idx(&self, p: Pt) -> (usize, usize) { + let i = (((p.0 - self.x0) / self.cell).floor().max(0.0) as usize).min(self.nx - 1); + let j = (((p.1 - self.y0) / self.cell).floor().max(0.0) as usize).min(self.ny - 1); + (i, j) + } + + fn cell_rect(&self, i: usize, j: usize) -> Rect { + let x = self.x0 + i as f64 * self.cell; + let y = self.y0 + j as f64 * self.cell; + Rect::new(x, y, x + self.cell, y + self.cell) + } + + /// Cells overlapped by r: (i, j, overlap area). + fn cover(&self, r: &Rect) -> Vec<(usize, usize, f64)> { + let (i0, j0) = self.idx((r.x0, r.y0)); + let (i1, j1) = self.idx((r.x1, r.y1)); + let mut v = vec![]; + for j in j0..=j1 { + for i in i0..=i1 { + let a = self.cell_rect(i, j).inter(r); + if a > 0.0 { + v.push((i, j, a)); + } + } + } + v + } + + pub fn new(m: &Model, s: &State, cell: f64) -> Grid { + let b = m.bounds; + let nx = ((b.x1 - b.x0) / cell).ceil() as usize; + let ny = ((b.y1 - b.y0) / cell).ceil() as usize; + let n = nx * ny; + let mut g = Grid { x0: b.x0, y0: b.y0, cell, nx, ny, cap: vec![cell; 2 * n], pin: vec![false; 2 * n] }; + let area = cell * cell; + let block = |g: &mut Grid, r: &Rect, layers: &[usize]| { + for (i, j, a) in g.cover(r) { + for &l in layers { + let k = l * n + j * nx + i; + g.cap[k] -= cell * a / area; + } + } + }; + for (k, pad) in m.pads.iter().enumerate() { + let r = s.pad_rect(k).grow(CLR); + let layers: &[usize] = if pad.tht { &[0, 1] } else { &[0] }; + block(&mut g, &r, layers); + let (i, j) = g.idx(s.pad_pos(k)); + for &l in layers { + g.pin[l * n + j * nx + i] = true; + } + } + for r in &m.track_keepouts { + block(&mut g, r, &[0, 1]); + } + // the edge clearance: everything outside the board shrunk by it + let inner = b.grow(-m.w.edge); + for j in 0..ny { + for i in 0..nx { + let c = g.cell_rect(i, j); + let out = c.area() - c.inter(&inner); + for l in 0..2 { + g.cap[l * n + j * nx + i] -= cell * out / area; + } + } + } + for c in g.cap.iter_mut() { + *c = c.max(0.0); + } + g + } +} + +/// RUDY overflow in mm of default track. +pub fn rudy(m: &Model, s: &State, g: &Grid) -> f64 { + let n = g.nx * g.ny; + let mut demand = vec![0.0; n]; + for (a, b, net) in s.lines() { + let l1 = (a.0 - b.0).abs() + (a.1 - b.1).abs(); + let mut r = Rect::new(a.0, a.1, b.0, b.1); + // at least one cell wide, so straight lines spread over their own cells + let gx = ((g.cell - (r.x1 - r.x0)) / 2.0).max(0.0); + let gy = ((g.cell - (r.y1 - r.y0)) / 2.0).max(0.0); + r = Rect::new(r.x0 - gx, r.y0 - gy, r.x1 + gx, r.y1 + gy); + let track = l1 * m.nets[net].pitch; + let ra = r.area(); + for (i, j, a) in g.cover(&r) { + demand[j * g.nx + i] += track * a / ra; + } + } + let mut over = 0.0; + for c in 0..n { + let room = (g.cap[c] + g.cap[n + c]) * g.cell; + over += (demand[c] - room).max(0.0); + } + over / UNIT +} + +#[derive(Debug, Default, Clone, Copy)] +pub struct GResult { + /// default tracks beyond the cells' room after the last round, summed over cells + pub overflow: f64, + /// cells (per layer) still overused + pub over_cells: usize, + pub length: f64, + pub vias: usize, + pub rounds: usize, +} + +#[derive(PartialEq)] +struct Q(f64, usize); +impl Eq for Q {} +impl PartialOrd for Q { + fn partial_cmp(&self, o: &Self) -> Option<Ordering> { + Some(self.cmp(o)) + } +} +impl Ord for Q { + fn cmp(&self, o: &Self) -> Ordering { + o.0.total_cmp(&self.0) // min-heap + } +} + +pub struct GOpts { + pub rounds: usize, + /// via cost in cells + pub via: f64, + /// B.Cu step cost factor (the detailed router prefers F.Cu) + pub bmult: f64, +} + +impl Default for GOpts { + fn default() -> Self { + GOpts { rounds: 30, via: 4.0, bmult: 1.5 } + } +} + +pub fn groute(m: &Model, s: &State, g: &Grid, o: &GOpts) -> GResult { + let n = g.nx * g.ny; + let nn = 2 * n; + // nets as pin lists (node sets per pin: F, or F and B for THT), in Prim order + struct GNet { + pins: Vec<Vec<usize>>, + d: f64, + } + let mut nets = vec![]; + for net in &m.nets { + let mut pins: Vec<(Pt, Vec<usize>)> = vec![]; + for &k in &net.pads { + let p = s.pad_pos(k); + let (i, j) = g.idx(p); + let c = j * g.nx + i; + let nodes = if m.pads[k].tht { vec![c, n + c] } else { vec![c] }; + if !pins.iter().any(|(_, v)| v[0] == c) { + pins.push((p, nodes)); + } + } + if pins.len() < 2 { + continue; + } + let pts: Vec<Pt> = pins.iter().map(|p| p.0).collect(); + let mut order = vec![0]; + for (_, b) in crate::geom::mst(&pts) { + order.push(b); + } + // a track wider than a cell takes the whole cell (and its neighbours' room is not tracked) + nets.push(GNet { pins: order.into_iter().map(|k| pins[k].1.clone()).collect(), d: net.pitch.min(g.cell) }); + } + + let mut usage = vec![0.0; nn]; + let mut hist = vec![0.0; nn]; + let mut paths: Vec<Vec<usize>> = vec![vec![]; nets.len()]; + let mut vias = vec![0usize; nets.len()]; + let mut gcost = vec![f64::INFINITY; nn]; + let mut par = vec![usize::MAX; nn]; + let mut stamp = vec![0u32; nn]; + let mut intree = vec![0u32; nn]; + let mut call = 0u32; + let mut tcall = 0u32; + let mut res = GResult::default(); + let mut pf = 0.5; + for round in 0..o.rounds { + res.rounds = round + 1; + for (ni, net) in nets.iter().enumerate() { + for &v in &paths[ni] { + usage[v] -= net.d; + } + paths[ni].clear(); + vias[ni] = 0; + tcall += 1; + let mut tree: Vec<usize> = net.pins[0].clone(); + for &v in &tree { + intree[v] = tcall; + } + for pin in &net.pins[1..] { + if pin.iter().any(|&v| intree[v] == tcall) { + continue; + } + // Dijkstra from the pin to the nearest node of the tree (several targets, so no + // simple heuristic); the grid is small enough + call += 1; + let mut heap = BinaryHeap::new(); + for &v in pin { + stamp[v] = call; + gcost[v] = 0.0; + par[v] = usize::MAX; + heap.push(Q(0.0, v)); + } + let mut found = usize::MAX; + while let Some(Q(_, v)) = heap.pop() { + if intree[v] == tcall { + found = v; + break; + } + let gv = gcost[v]; + let (l, c) = (v / n, v % n); + let (x, y) = ((c % g.nx) as i64, (c / g.nx) as i64); + let mut relax = |w: usize, step: f64, heap: &mut BinaryHeap<Q>| { + let lw = w / n; + let over = if g.pin[w] { 0.0 } else { (usage[w] + net.d - g.cap[w]).max(0.0) / UNIT }; + let base = step * if lw == 1 { o.bmult } else { 1.0 }; + let ng = gv + base * (1.0 + hist[w]) * (1.0 + pf * over); + if stamp[w] != call || ng < gcost[w] { + stamp[w] = call; + gcost[w] = ng; + par[w] = v; + heap.push(Q(ng, w)); + } + }; + for (dx, dy, st) in [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0), (1, 1, 1.414), (1, -1, 1.414), (-1, 1, 1.414), (-1, -1, 1.414)] { + let (qx, qy) = (x + dx, y + dy); + if qx < 0 || qy < 0 || qx >= g.nx as i64 || qy >= g.ny as i64 { + continue; + } + relax(l * n + qy as usize * g.nx + qx as usize, st, &mut heap); + } + relax((1 - l) * n + c, o.via, &mut heap); + } + if found == usize::MAX { + continue; + } + let mut v = found; + while v != usize::MAX { + if intree[v] != tcall { + intree[v] = tcall; + tree.push(v); + } + let p = par[v]; + if p != usize::MAX && p / n != v / n { + vias[ni] += 1; + } + v = p; + } + } + for &v in &tree { + usage[v] += net.d; + } + paths[ni] = tree; + } + let mut over = 0.0; + let mut cells = 0; + for v in 0..nn { + if g.pin[v] { + continue; + } + let ov = usage[v] - g.cap[v]; + if ov > 1e-9 { + over += ov; + cells += 1; + hist[v] += 0.3 * ov / UNIT; + } + } + res.overflow = over / UNIT; + res.over_cells = cells; + if cells == 0 { + break; + } + pf *= 1.6; + } + res.length = paths.iter().map(|p| p.len() as f64 * g.cell).sum(); + res.vias = vias.iter().sum(); + res +} diff --git a/tools/placer/src/cost.rs b/tools/placer/src/cost.rs new file mode 100644 index 0000000..a91e25d --- /dev/null +++ b/tools/placer/src/cost.rs @@ -0,0 +1,696 @@ +//! Placement cost with incremental updates: a move changes only the nets, part pairs and +//! part terms of the parts it moves, so only those are evaluated again. Crossings and blocks +//! are updated from the ratsnest lines that changed (most of a big net's MST stays as it was) +//! and from the moved pads. +//! +//! Terms (weights in model::Weights): +//! per net ratsnest length x net weight, escape (lines leaving a pin backwards), +//! decoupling (cap to its pin, ground pad to the IC's ground pin), coverage +//! (every decoupled IC pin has a cap within 3 mm) +//! global crossings of ratsnest lines of different nets (each one a via on 2 layers); +//! the line from each decap to its pin counts too, so caps keep pin order +//! per net/part block: ratsnest lines over another net's pads (a detour or a via) +//! per pair courtyard overlap, other parts' pads in a fine-pitch IC's fan-out band, +//! [[link]] pads farther apart than allowed +//! per part outside the board / pad edge clearance, in a keep-out, outside a group bbox; +//! [[pull]] pads' distance to their board side +//! +//! A move of a replicated channel's master moves its followers along (propose expands it). + +use crate::geom::{crosses, dist, mst, seg_hits, turn, Pt, Rect}; +use crate::model::Model; + +#[derive(Clone, Copy)] +pub struct Seg { + a: Pt, + b: Pt, + w: f64, + bb: Rect, + net: usize, + /// parts at the two ends + pa: usize, + pb: usize, +} + +/// The same line (pad positions are recomputed identically, so exact comparison works). +fn same(e: &Seg, f: &Seg) -> bool { + (e.a == f.a && e.b == f.b) || (e.a == f.b && e.b == f.a) +} + +fn cross_w(e: &Seg, f: &Seg) -> f64 { + if e.bb.hits(&f.bb) && crosses(e.a, e.b, f.a, f.b) { + (e.w + f.w) / 2.0 + } else { + 0.0 + } +} + +/// A net's lines after a proposed move. +struct Pending { + net: usize, + cost: f64, + segs: Vec<Seg>, + bb: Rect, + /// old lines that are gone + removed: Vec<bool>, + /// new lines that were not there before + added: Vec<usize>, +} + +/// Weighted cost terms (and the raw crossing count) of a whole placement. +#[derive(Default, Clone, Copy, Debug, serde::Serialize)] +pub struct Terms { + pub length: f64, + pub escape: f64, + pub decap: f64, + pub cover: f64, + pub crossing: f64, + pub overlap: f64, + pub band: f64, + pub bounds: f64, + pub block: f64, + pub link: f64, + pub pull: f64, + pub crossings: usize, + pub ratsnest_mm: f64, +} + +impl Terms { + pub fn total(&self) -> f64 { + self.length + self.escape + self.decap + self.cover + self.crossing + self.overlap + self.band + self.bounds + self.block + self.link + self.pull + } +} + +#[derive(Default, Clone, Copy)] +struct NetT { + length: f64, + escape: f64, + decap: f64, + cover: f64, + mm: f64, +} + +impl NetT { + fn sum(&self) -> f64 { + self.length + self.escape + self.decap + self.cover + } +} + +pub struct State<'m> { + pub m: &'m Model, + pub at: Vec<Pt>, + pub rot: Vec<u8>, + pp: Vec<Pt>, + /// courtyard hull of each part on the board + hull_w: Vec<Rect>, + net_cost: Vec<f64>, + segs: Vec<Vec<Seg>>, + /// bounding box of each net's lines + nbb: Vec<Rect>, + pair: Vec<f64>, + unary: Vec<f64>, + pub total: f64, + /// scale of the legality terms (overlap, band, bounds); the annealer ramps it up to 1 + pen: f64, + // pending move + cur: u32, + nstamp: Vec<u32>, + pstamp: Vec<u32>, + moved: Vec<usize>, + old: Vec<(Pt, u8)>, + new: Vec<(Pt, u8)>, + p_net: Vec<Pending>, + p_pair: Vec<(usize, f64)>, + p_un: Vec<(usize, f64)>, + p_delta: f64, +} + +/// A rectangle that hits nothing. +const NONE: Rect = Rect { x0: f64::INFINITY, y0: f64::INFINITY, x1: f64::NEG_INFINITY, y1: f64::NEG_INFINITY }; + +fn segs_bb(segs: &[Seg]) -> Rect { + segs.iter().fold(NONE, |a, e| a.union(&e.bb)) +} + +fn cross_between(a: &[Seg], b: &[Seg]) -> f64 { + let mut s = 0.0; + for e in a { + for f in b { + if e.bb.hits(&f.bb) && crosses(e.a, e.b, f.a, f.b) { + s += (e.w + f.w) / 2.0; + } + } + } + s +} + +impl<'m> State<'m> { + pub fn new(m: &'m Model, at: Vec<Pt>, rot: Vec<u8>) -> State<'m> { + let n = m.parts.len(); + let mut s = State { + m, + at, + rot, + pp: vec![(0.0, 0.0); m.pads.len()], + hull_w: vec![Rect::default(); n], + net_cost: vec![0.0; m.nets.len()], + segs: vec![vec![]; m.nets.len()], + nbb: vec![NONE; m.nets.len()], + pair: vec![0.0; n * n], + unary: vec![0.0; n], + total: 0.0, + pen: 1.0, + cur: 0, + nstamp: vec![0; m.nets.len()], + pstamp: vec![0; n], + moved: vec![], + old: vec![], + new: vec![], + p_net: vec![], + p_pair: vec![], + p_un: vec![], + p_delta: 0.0, + }; + s.recompute(); + s + } + + /// Scale the legality terms and re-evaluate. + pub fn set_pen(&mut self, pen: f64) { + if pen != self.pen { + self.pen = pen; + self.recompute(); + } + } + + pub fn pen(&self) -> f64 { + self.pen + } + + pub fn initial(m: &'m Model) -> State<'m> { + State::new(m, m.parts.iter().map(|p| p.at0).collect(), m.parts.iter().map(|p| p.rot0).collect()) + } + + /// Evaluate everything from scratch; returns the terms. + pub fn recompute(&mut self) -> Terms { + let m = self.m; + for i in 0..m.parts.len() { + self.place_pads(i); + } + let mut t = Terms::default(); + for n in 0..m.nets.len() { + let (nt, segs) = self.net_eval(n); + self.net_cost[n] = nt.sum(); + self.nbb[n] = segs_bb(&segs); + self.segs[n] = segs; + t.length += nt.length; + t.escape += nt.escape; + t.decap += nt.decap; + t.cover += nt.cover; + t.ratsnest_mm += nt.mm; + } + let mut x = 0.0; + for a in 0..m.nets.len() { + for b in a + 1..m.nets.len() { + let c = cross_between(&self.segs[a], &self.segs[b]); + x += c; + if c > 0.0 { + t.crossings += self.segs[a] + .iter() + .map(|e| self.segs[b].iter().filter(|f| e.bb.hits(&f.bb) && crosses(e.a, e.b, f.a, f.b)).count()) + .sum::<usize>(); + } + } + } + t.crossing = m.w.crossing * x; + let n = m.parts.len(); + for i in 0..n { + for j in i + 1..n { + let (ov, band, link) = self.pair_eval(i, j); + self.pair[i * n + j] = ov + band + link; + t.overlap += ov; + t.band += band; + t.link += link; + } + let (bounds, pull) = self.unary_eval(i); + self.unary[i] = bounds + pull; + t.bounds += bounds; + t.pull += pull; + } + let all: Vec<usize> = (0..n).collect(); + t.block = m.w.block * self.segs.iter().flatten().map(|e| self.block_parts(e, &all)).sum::<f64>(); + self.total = t.total(); + t + } + + fn set_pose(&mut self, i: usize, at: Pt, r: u8) { + self.at[i] = at; + self.rot[i] = r; + self.place_pads(i); + } + + fn place_pads(&mut self, i: usize) { + let p = &self.m.parts[i]; + self.hull_w[i] = p.hull.place(self.at[i], self.rot[i]); + for &k in &p.pads { + let l = turn(self.m.pads[k].local, self.rot[i]); + self.pp[k] = (self.at[i].0 + l.0, self.at[i].1 + l.1); + } + } + + pub fn pad_rect(&self, k: usize) -> Rect { + let pad = &self.m.pads[k]; + let h = if self.rot[pad.part] & 1 == 1 { (pad.half.1, pad.half.0) } else { pad.half }; + Rect::around(self.pp[k], h.0, h.1) + } + + fn net_eval(&self, n: usize) -> (NetT, Vec<Seg>) { + let m = self.m; + let w = &m.w; + let net = &m.nets[n]; + let mut t = NetT::default(); + let pts: Vec<Pt> = net.pads.iter().map(|&k| self.pp[k]).collect(); + let mut segs = Vec::with_capacity(pts.len()); + let mut esc = 0.0; + for (i, j) in mst(&pts) { + let (a, b) = (pts[i], pts[j]); + let l = dist(a, b); + t.mm += l; + let (ka, kb) = (net.pads[i], net.pads[j]); + let (pa, pb) = (m.pads[ka].part, m.pads[kb].part); + segs.push(Seg { a, b, w: net.weight, bb: Rect::new(a.0, a.1, b.0, b.1), net: n, pa, pb }); + if pa == pb || l < 1e-6 { + continue; // same part: fixed geometry + } + for (k, from, to) in [(ka, a, b), (kb, b, a)] { + if let Some(nl) = m.pads[k].normal { + let nw = turn(nl, self.rot[m.pads[k].part]); + let c = (nw.0 * (to.0 - from.0) + nw.1 * (to.1 - from.1)) / l; + esc += ((1.0 - c) / 2.0).powi(2) * l.min(m.parts[m.pads[k].part].detour); + } + } + } + t.length = net.weight * w.length * t.mm; + // not scaled by the net weight: a pin facing away costs a detour on any net + t.escape = w.escape * esc; + for &d in &net.decaps { + let dc = &m.decaps[d]; + let (s, g) = (self.pp[dc.sig], self.pp[dc.gnd]); + let mut best = (f64::MAX, 0.0, 0); + for (c, gp) in &dc.cands { + let ds = dist(s, self.pp[*c]); + let dg = gp.iter().map(|&q| dist(g, self.pp[q])).fold(f64::MAX, f64::min); + let v = ds + if dg < f64::MAX { 0.5 * dg } else { 0.0 }; + if v < best.0 { + best = (v, ds, *c); + } + } + // the cap is routed to this pin first: its line takes part in the crossings + let c = self.pp[best.2]; + let pb = m.pads[best.2].part; + segs.push(Seg { a: s, b: c, w: net.weight, bb: Rect::new(s.0, s.1, c.0, c.1), net: n, pa: dc.part, pb }); + let (lim, coef) = if dc.bulk { (8.0, 0.3) } else { (3.0, 1.0) }; + // quadratic for the first 2 mm past the limit, then linear (a far cap still pulls, + // but a scrambled start does not swamp everything else) + let x = (best.1 - lim).max(0.0); + let over = if x <= 2.0 { x * x } else { 4.0 * x - 4.0 }; + t.decap += w.decap * coef * best.0 + w.decap_limit * over; + } + for &q in &net.cover { + let near = net + .decaps + .iter() + .map(|&d| dist(self.pp[m.decaps[d].sig], self.pp[q])) + .fold(f64::MAX, f64::min); + t.cover += w.cover * (near - 3.0).max(0.0).min(20.0); + } + (t, segs) + } + + /// Cost of a [[link]] at the current poses (0 within its distance). + fn link_eval(&self, l: usize) -> f64 { + let k = &self.m.links[l]; + let x = (dist(self.pp[k.a], self.pp[k.b]) - k.max).max(0.0); + self.m.w.link * k.weight * if x <= 2.0 { x * x } else { 4.0 * x - 4.0 } + } + + /// (overlap, band, link) cost of a pair of parts. + fn pair_eval(&self, i: usize, j: usize) -> (f64, f64, f64) { + let m = self.m; + let (a, b) = (&m.parts[i], &m.parts[j]); + let mut link = 0.0; + for &l in &a.links { + let k = &m.links[l]; + let (pa, pb) = (m.pads[k.a].part, m.pads[k.b].part); + if (pa == i && pb == j) || (pa == j && pb == i) { + link += self.link_eval(l); + } + } + if a.fixed && b.fixed { + return (0.0, 0.0, link); + } + let g = m.w.fanout; + if !self.hull_w[i].grow(g).hits(&self.hull_w[j].grow(g)) { + return (0.0, 0.0, link); + } + let mut ov = 0.0; + for ra in &a.court { + let ra = ra.place(self.at[i], self.rot[i]); + for rb in &b.court { + ov += ra.inter(&rb.place(self.at[j], self.rot[j])); + } + } + let mut band = 0.0; + for (x, y) in [(i, j), (j, i)] { + if let Some(bl) = m.parts[x].band { + let br = bl.place(self.at[x], self.rot[x]); + for &k in &m.parts[y].pads { + band += br.inter(&self.pad_rect(k)); + } + } + } + (self.pen * m.w.overlap * ov, self.pen * m.w.band * band, link) + } + + /// Unweighted block cost of line `e` over the pads of `parts` (pads of other nets; parts + /// at the line's own ends are left out, the escape term covers those). + fn block_parts(&self, e: &Seg, parts: &[usize]) -> f64 { + let m = self.m; + let mut s = 0.0; + for &j in parts { + if j == e.pa || j == e.pb || !e.bb.hits(&self.hull_w[j]) { + continue; + } + for &k in &m.parts[j].pads { + if m.pads[k].net != Some(e.net) && seg_hits(e.a, e.b, &self.pad_rect(k)) { + s += e.w; + } + } + } + s + } + + /// Lines that changed with the pending move: the new ones (after) or the removed ones (before). + fn changed<'a>(&'a self, pn: &'a [Pending], after: bool) -> Vec<&'a Seg> { + let mut v = vec![]; + for p in pn { + if after { + v.extend(p.added.iter().map(|&j| &p.segs[j])); + } else { + v.extend(self.segs[p.net].iter().zip(&p.removed).filter(|(_, &r)| r).map(|(e, _)| e)); + } + } + v + } + + /// Unchanged lines of the nets the move touched. + fn kept<'a>(&'a self, p: &'a Pending) -> impl Iterator<Item = &'a Seg> { + self.segs[p.net].iter().zip(&p.removed).filter(|(_, &r)| !r).map(|(e, _)| e) + } + + /// Crossings of the changed lines with the unchanged ones and with each other. + fn cross_changed(&self, pn: &[Pending], after: bool) -> f64 { + let ch = self.changed(pn, after); + let mut x = 0.0; + for (a, e) in ch.iter().enumerate() { + for k in 0..self.m.nets.len() { + if self.nstamp[k] != self.cur && self.nbb[k].hits(&e.bb) { + x += self.segs[k].iter().map(|f| cross_w(e, f)).sum::<f64>(); + } + } + for p in pn.iter().filter(|p| p.net != e.net) { + x += self.kept(p).map(|f| cross_w(e, f)).sum::<f64>(); + } + x += ch[a + 1..].iter().filter(|f| f.net != e.net).map(|f| cross_w(e, f)).sum::<f64>(); + } + x + } + + /// Blocks of the changed lines over all parts, and of the unchanged lines over the moved + /// parts, at the current poses. + fn block_changed(&self, pn: &[Pending], after: bool, region: &Rect, all: &[usize]) -> f64 { + let mut b: f64 = self.changed(pn, after).iter().map(|e| self.block_parts(e, all)).sum(); + for k in 0..self.m.nets.len() { + if self.nstamp[k] != self.cur && self.nbb[k].hits(region) { + for e in self.segs[k].iter().filter(|e| e.bb.hits(region)) { + b += self.block_parts(e, &self.moved); + } + } + } + for p in pn { + for e in self.kept(p).filter(|e| e.bb.hits(region)) { + b += self.block_parts(e, &self.moved); + } + } + b + } + + /// (bounds, pull) cost of a part. + fn unary_eval(&self, i: usize) -> (f64, f64) { + let m = self.m; + let p = &m.parts[i]; + if p.fixed { + return (0.0, 0.0); + } + // the side of the part's group region, else of the board + let b = p.groups.iter().find_map(|&g| m.groups[g].bbox).unwrap_or(m.bounds); + let mut pull = 0.0; + for &(k, dir, wt) in &p.pulls { + let q = self.pp[k]; + // distance to the side the outward vector points at + let d = match dir { + (x, _) if x > 0.5 => b.x1 - q.0, + (x, _) if x < -0.5 => q.0 - b.x0, + (_, y) if y > 0.5 => b.y1 - q.1, + _ => q.1 - b.y0, + }; + pull += m.w.pull * wt * d.max(0.0); + } + let mut s = 0.0; + let inner = m.bounds.grow(-m.w.edge); + // area outside, plus the distance so that a part far outside is pulled back + let out = |r: &Rect, b: &Rect| { + r.outside(b) + (b.x0 - r.x0).max(r.x1 - b.x1).max(0.0) + (b.y0 - r.y0).max(r.y1 - b.y1).max(0.0) + }; + for r in &p.court { + let r = r.place(self.at[i], self.rot[i]); + s += out(&r, &m.bounds); + for k in &m.keepouts { + s += r.inter(k); + } + for &g in &p.groups { + if let Some(b) = m.groups[g].bbox { + s += out(&r, &b); + } + } + } + for &k in &p.pads { + let r = self.pad_rect(k); + s += r.outside(&inner); + for z in &m.pad_keepouts { + s += r.inter(z); + } + } + (self.pen * m.w.overlap * s, pull) + } + + /// Move parts to new anchors/rotations; returns the cost delta. Follow with accept() or reject(). + pub fn propose(&mut self, moves: &[(usize, Pt, u8)]) -> f64 { + let m = self.m; + self.cur += 1; + let cur = self.cur; + self.moved.clear(); + self.old.clear(); + self.new.clear(); + // followers go where their master goes + let mut mv: Vec<(usize, Pt, u8)> = moves.iter().copied().filter(|&(i, _, _)| m.parts[i].follow.is_none()).collect(); + for k in 0..mv.len() { + let (i, at, r) = mv[k]; + for &f in &m.parts[i].followers { + let off = m.parts[f].follow.unwrap().1; + mv.push((f, (at.0 + off.0, at.1 + off.1), r)); + } + } + for &(i, at, r) in &mv { + self.moved.push(i); + self.old.push((self.at[i], self.rot[i])); + self.new.push((at, r & 3)); + self.set_pose(i, at, r & 3); + self.pstamp[i] = cur; + } + let mut delta = 0.0; + // nets: new lines, and which lines changed + let mut pn = std::mem::take(&mut self.p_net); + pn.clear(); + for mi in 0..self.moved.len() { + for &n in &m.parts[self.moved[mi]].nets { + if self.nstamp[n] == cur { + continue; + } + self.nstamp[n] = cur; + let (t, segs) = self.net_eval(n); + delta += t.sum() - self.net_cost[n]; + let old = &self.segs[n]; + let mut removed = vec![false; old.len()]; + let mut matched = vec![false; segs.len()]; + for (i, e) in old.iter().enumerate() { + match (0..segs.len()).find(|&j| !matched[j] && same(e, &segs[j])) { + Some(j) => matched[j] = true, + None => removed[i] = true, + } + } + let added = (0..segs.len()).filter(|&j| !matched[j]).collect(); + pn.push(Pending { net: n, cost: t.sum(), bb: segs_bb(&segs), segs, removed, added }); + } + } + delta += m.w.crossing * (self.cross_changed(&pn, true) - self.cross_changed(&pn, false)); + // blocks: after the move, then at the old poses + let n = m.parts.len(); + let all: Vec<usize> = (0..n).collect(); + let mut region = NONE; + for (k, &i) in self.moved.iter().enumerate() { + region = region.union(&self.hull_w[i]).union(&m.parts[i].hull.place(self.old[k].0, self.old[k].1)); + } + let b_after = self.block_changed(&pn, true, ®ion, &all); + for k in 0..self.moved.len() { + let (a, r) = self.old[k]; + self.set_pose(self.moved[k], a, r); + } + let b_before = self.block_changed(&pn, false, ®ion, &all); + for k in 0..self.moved.len() { + let (a, r) = self.new[k]; + self.set_pose(self.moved[k], a, r); + } + delta += m.w.block * (b_after - b_before); + self.p_net = pn; + // pairs and part terms + self.p_pair.clear(); + self.p_un.clear(); + for mi in 0..self.moved.len() { + let s = self.moved[mi]; + for j in 0..n { + if j == s || (self.pstamp[j] == cur && j < s) { + continue; + } + let (lo, hi) = if s < j { (s, j) } else { (j, s) }; + let (ov, band, link) = self.pair_eval(lo, hi); + let v = ov + band + link; + let key = lo * n + hi; + if v != self.pair[key] { + delta += v - self.pair[key]; + self.p_pair.push((key, v)); + } + } + let (bounds, pull) = self.unary_eval(s); + let u = bounds + pull; + delta += u - self.unary[s]; + self.p_un.push((s, u)); + } + self.p_delta = delta; + delta + } + + pub fn accept(&mut self) { + for p in self.p_net.drain(..) { + self.net_cost[p.net] = p.cost; + self.segs[p.net] = p.segs; + self.nbb[p.net] = p.bb; + } + for &(k, v) in &self.p_pair { + self.pair[k] = v; + } + for &(i, v) in &self.p_un { + self.unary[i] = v; + } + self.total += self.p_delta; + } + + pub fn reject(&mut self) { + for k in (0..self.moved.len()).rev() { + let i = self.moved[k]; + (self.at[i], self.rot[i]) = self.old[k]; + self.place_pads(i); + } + } + + /// Ratsnest lines of all nets (MST plus each decap's line to its pin): (a, b, net). + pub fn lines(&self) -> Vec<(Pt, Pt, usize)> { + self.segs.iter().flatten().map(|e| (e.a, e.b, e.net)).collect() + } + + pub fn hull(&self, i: usize) -> Rect { + self.hull_w[i] + } + + pub fn pad_pos(&self, k: usize) -> Pt { + self.pp[k] + } + + /// Readable findings for calibration: (category, text, cost), worst first. + pub fn findings(&self) -> Vec<(String, String, f64)> { + let m = self.m; + let mut out = vec![]; + let name = |k: usize| format!("{}.{}", m.parts[m.pads[k].part].reference, m.pads[k].num); + let short = |n: &str| n.rsplit('/').next().unwrap_or(n).to_string(); + for (ni, net) in m.nets.iter().enumerate() { + let (t, _) = self.net_eval(ni); + if t.escape > 0.5 { + out.push(("escape".into(), short(&net.name), t.escape)); + } + for &d in &net.decaps { + let dc = &m.decaps[d]; + let s = self.pp[dc.sig]; + let (c, ds) = dc + .cands + .iter() + .map(|(c, _)| (*c, dist(s, self.pp[*c]))) + .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap()) + .unwrap(); + let lim = if dc.bulk { 8.0 } else { 3.0 }; + if ds > lim * 0.8 { + out.push(("decap".into(), format!("{} -> {} {:.2} mm", m.parts[dc.part].reference, name(c), ds), ds)); + } + } + for &q in &net.cover { + let near = net + .decaps + .iter() + .map(|&d| dist(self.pp[m.decaps[d].sig], self.pp[q])) + .fold(f64::MAX, f64::min); + if near > 3.0 { + out.push(("cover".into(), format!("{} nearest cap {:.2} mm", name(q), near), m.w.cover * (near - 3.0))); + } + } + } + let n = m.parts.len(); + for i in 0..n { + for j in i + 1..n { + let (ov, band, link) = self.pair_eval(i, j); + if link > 1e-9 { + out.push(("link".into(), format!("{} / {}", m.parts[i].reference, m.parts[j].reference), link)); + } + if ov > 1e-9 { + out.push(("overlap".into(), format!("{} / {}", m.parts[i].reference, m.parts[j].reference), ov)); + } + if band > 1e-9 { + out.push(("band".into(), format!("{} / {}", m.parts[i].reference, m.parts[j].reference), band)); + } + } + for k in 0..m.nets.len() { + let b = m.w.block * self.segs[k].iter().map(|e| self.block_parts(e, &[i])).sum::<f64>(); + if b > 1e-9 { + out.push(("block".into(), format!("{} over {}", short(&m.nets[k].name), m.parts[i].reference), b)); + } + } + let (u, pull) = self.unary_eval(i); + if u > 1e-9 { + out.push(("bounds".into(), m.parts[i].reference.clone(), u)); + } + if pull > 1e-9 { + out.push(("pull".into(), m.parts[i].reference.clone(), pull)); + } + } + out.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap()); + out + } +} diff --git a/tools/placer/src/geom.rs b/tools/placer/src/geom.rs new file mode 100644 index 0000000..3514340 --- /dev/null +++ b/tools/placer/src/geom.rs @@ -0,0 +1,174 @@ +//! Axis-aligned rectangles, 90 degree turns, segment crossings and the MST. + +pub type Pt = (f64, f64); + +#[derive(Clone, Copy, Debug, Default)] +pub struct Rect { + pub x0: f64, + pub y0: f64, + pub x1: f64, + pub y1: f64, +} + +impl Rect { + pub fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Rect { + Rect { x0: x0.min(x1), y0: y0.min(y1), x1: x0.max(x1), y1: y0.max(y1) } + } + pub fn around(c: Pt, hw: f64, hh: f64) -> Rect { + Rect::new(c.0 - hw, c.1 - hh, c.0 + hw, c.1 + hh) + } + pub fn area(&self) -> f64 { + (self.x1 - self.x0) * (self.y1 - self.y0) + } + /// Overlap area with `o`. + pub fn inter(&self, o: &Rect) -> f64 { + let w = self.x1.min(o.x1) - self.x0.max(o.x0); + let h = self.y1.min(o.y1) - self.y0.max(o.y0); + if w > 0.0 && h > 0.0 { + w * h + } else { + 0.0 + } + } + pub fn hits(&self, o: &Rect) -> bool { + self.x0 < o.x1 && o.x0 < self.x1 && self.y0 < o.y1 && o.y0 < self.y1 + } + /// Area of `self` that lies outside `b`. + pub fn outside(&self, b: &Rect) -> f64 { + self.area() - self.inter(b) + } + pub fn grow(&self, d: f64) -> Rect { + Rect { x0: self.x0 - d, y0: self.y0 - d, x1: self.x1 + d, y1: self.y1 + d } + } + pub fn union(&self, o: &Rect) -> Rect { + Rect { x0: self.x0.min(o.x0), y0: self.y0.min(o.y0), x1: self.x1.max(o.x1), y1: self.y1.max(o.y1) } + } + /// The rectangle of a footprint-local rectangle on a part at `at`, turned by `k` x 90 degrees. + pub fn place(&self, at: Pt, k: u8) -> Rect { + let a = turn((self.x0, self.y0), k); + let b = turn((self.x1, self.y1), k); + Rect::new(a.0 + at.0, a.1 + at.1, b.0 + at.0, b.1 + at.1) + } +} + +/// Turn a footprint-local vector by k x 90 degrees as KiCad does: positive angles turn +/// counter-clockwise on screen, where y points down. +pub fn turn(p: Pt, k: u8) -> Pt { + match k & 3 { + 0 => p, + 1 => (p.1, -p.0), + 2 => (-p.0, -p.1), + _ => (-p.1, p.0), + } +} + +pub fn dist(a: Pt, b: Pt) -> f64 { + ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() +} + +/// Proper crossing of segments ab and cd; touching or shared ends do not count. +pub fn crosses(a: Pt, b: Pt, c: Pt, d: Pt) -> bool { + fn orient(p: Pt, q: Pt, r: Pt) -> f64 { + (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0) + } + let (o1, o2) = (orient(a, b, c), orient(a, b, d)); + if o1 * o2 >= 0.0 { + return false; + } + let (o3, o4) = (orient(c, d, a), orient(c, d, b)); + o3 * o4 < 0.0 +} + +/// Segment ab passes through rectangle r (Liang-Barsky clipping). +pub fn seg_hits(a: Pt, b: Pt, r: &Rect) -> bool { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + for (p, q) in [(-dx, a.0 - r.x0), (dx, r.x1 - a.0), (-dy, a.1 - r.y0), (dy, r.y1 - a.1)] { + if p.abs() < 1e-12 { + if q < 0.0 { + return false; + } + } else { + let t = q / p; + if p < 0.0 { + t0 = t0.max(t); + } else { + t1 = t1.min(t); + } + if t0 > t1 { + return false; + } + } + } + true +} + +/// Prim's MST over the points: (i, j) pairs. +pub fn mst(pts: &[Pt]) -> Vec<(usize, usize)> { + let n = pts.len(); + let mut out = Vec::with_capacity(n.saturating_sub(1)); + if n < 2 { + return out; + } + let mut inside = vec![false; n]; + let mut best = vec![f64::INFINITY; n]; + let mut link = vec![usize::MAX; n]; + best[0] = 0.0; + for _ in 0..n { + let mut i = usize::MAX; + for k in 0..n { + if !inside[k] && (i == usize::MAX || best[k] < best[i]) { + i = k; + } + } + inside[i] = true; + if link[i] != usize::MAX { + out.push((link[i], i)); + } + for k in 0..n { + if !inside[k] { + let d = dist(pts[i], pts[k]); + if d < best[k] { + best[k] = d; + link[k] = i; + } + } + } + } + out +} + +/// Cover a polygon with rectangles: one horizontal slab per pair of vertex heights, each +/// cut into the x intervals that lie inside. Exact for rectilinear outlines, a slight +/// overestimate for slanted edges and arcs (each slab takes the wider of its two ends). +pub fn poly_rects(poly: &[[f64; 2]]) -> Vec<Rect> { + let mut ys: Vec<f64> = poly.iter().map(|p| p[1]).collect(); + ys.sort_by(|a, b| a.partial_cmp(b).unwrap()); + ys.dedup_by(|a, b| (*a - *b).abs() < 1e-4); + let xs_at = |y: f64| { + let mut xs = Vec::new(); + for i in 0..poly.len() { + let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); + if (a[1] <= y && b[1] > y) || (b[1] <= y && a[1] > y) { + xs.push(a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0])); + } + } + xs.sort_by(|a, b| a.partial_cmp(b).unwrap()); + xs + }; + let mut out = Vec::new(); + for w in ys.windows(2) { + let (y0, y1) = (w[0], w[1]); + let eps = (y1 - y0) * 1e-3; + let (lo, hi) = (xs_at(y0 + eps), xs_at(y1 - eps)); + if lo.len() != hi.len() { + continue; + } + for k in (0..lo.len()).step_by(2) { + if k + 1 < lo.len() { + out.push(Rect::new(lo[k].min(hi[k]), y0, lo[k + 1].max(hi[k + 1]), y1)); + } + } + } + out +} diff --git a/tools/placer/src/main.rs b/tools/placer/src/main.rs new file mode 100644 index 0000000..c94f865 --- /dev/null +++ b/tools/placer/src/main.rs @@ -0,0 +1,279 @@ +//! placer: simulated-annealing component placement for KiCad boards. +//! +//! placer score PROBLEM CONFIG [PLACEMENT.json] cost terms and findings of a placement +//! placer selftest PROBLEM CONFIG incremental cost == full evaluation +//! placer congest PROBLEM CONFIG [--cell MM] PLACEMENT... routing-channel measures (RUDY, +//! global route) per placement, one line each +//! placer run PROBLEM CONFIG OUT_DIR [--runs N] [--start scramble|keep] [--seed S] +//! [--inner X] [--t0 X] [--top K] [--route BOARD.json ROUTE.toml [--route-top K]] +//! placer route PROBLEM CONFIG BOARD.json ROUTE.toml OUT_DIR PLACEMENT... +//! route placements, rank them by the result +//! +//! PROBLEM comes from export.py, CONFIG is the board's placement.toml. `run` anneals N +//! independent runs in parallel and writes the best K as OUT_DIR/rank_NN.json plus +//! OUT_DIR/runs.tsv. A placement file maps ref -> [x, y, rotation in degrees], either at the +//! top level or under "placement". +//! +//! `--route` routes the best K placements in-process with tools/router-rs (BOARD.json is any +//! dump of the board from tools/router/dump_board.py; parts are moved to each placement) and +//! ranks them by the router's result (split nets, failed connections, pour islands, then the +//! route.toml's [rank] score of length, vias, necked and B.Cu length): OUT_DIR/routed.tsv, +//! routes_NN.json for tools/router/write_board.py, routed_best.json (the placement). + +mod anneal; +mod congest; +mod cost; +mod geom; +mod model; + +use anneal::{anneal, selftest, Opts, Start}; +use anyhow::{bail, Context, Result}; +use cost::State; +use model::Model; +use rayon::prelude::*; +use std::collections::BTreeMap; +use std::time::Instant; + +fn placement_json(m: &Model, s: &State) -> BTreeMap<String, [f64; 3]> { + m.parts + .iter() + .enumerate() + .map(|(i, p)| { + let r = s.rot[i] as f64 * 90.0; + (p.reference.clone(), [(s.at[i].0 * 1e4).round() / 1e4, (s.at[i].1 * 1e4).round() / 1e4, r]) + }) + .collect() +} + +fn load_placement<'m>(m: &'m Model, path: &str) -> Result<State<'m>> { + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| path.to_string())?)?; + let map = v.get("placement").unwrap_or(&v).as_object().context("placement must be an object")?; + let mut at: Vec<_> = m.parts.iter().map(|p| p.at0).collect(); + let mut rot: Vec<_> = m.parts.iter().map(|p| p.rot0).collect(); + for (r, xyr) in map { + let Some(i) = m.part(r) else { bail!("{path}: no part {r}") }; + let a: Vec<f64> = serde_json::from_value(xyr.clone())?; + at[i] = (a[0], a[1]); + rot[i] = (((a[2] / 90.0).round() as i64).rem_euclid(4)) as u8; + } + Ok(State::new(m, at, rot)) +} + +/// No courtyard overlap, nothing off the board, in a keep-out or outside its group bbox. +fn legal(s: &mut State) -> bool { + let t = s.recompute(); + t.overlap < 1e-6 && t.bounds < 1e-6 +} + +/// Route placements (name, placement, legal) on a board in parallel; write routes_NAME.json, +/// routed.tsv (legal placements first, then best routed first) and routed_best.json into `out`. +fn route_all(board: &str, toml: &str, out: &str, cands: Vec<(String, BTreeMap<String, [f64; 3]>, bool)>) -> Result<()> { + let cfg = router::config::Config::load(toml)?; + let base = std::path::Path::new(toml).parent().unwrap_or(std::path::Path::new(".")); + let t0 = Instant::now(); + let mut rows: Vec<(String, router::run::Summary, bool)> = cands + .par_iter() + .map(|(name, p, ok)| -> Result<(String, router::run::Summary, bool)> { + let mut b = router::io::BoardJson::load(board)?; + router::placement::apply(&mut b, p)?; + let (run, sum) = router::run::route(&b, &cfg, base, &Default::default())?; + std::fs::write(format!("{out}/routes_{name}.json"), serde_json::to_string(&run.r.result())?)?; + Ok((name.clone(), sum, *ok)) + }) + .collect::<Result<_>>()?; + rows.sort_by_key(|r| (!r.2, r.1.key())); + let secs = t0.elapsed().as_secs_f64(); + let mut tsv = String::from("placement\tlegal\tsplit\tfailed\tislands\tvias\tlength_mm\tneck_mm\tbcu_mm\tscore\tsecs\n"); + for (n, s, ok) in &rows { + tsv += &format!("{n}\t{}\t{}\t{}\t{}\t{}\t{:.1}\t{:.1}\t{:.1}\t{:.1}\t{:.1}\n", *ok as u8, s.split, s.failed, s.islands, s.vias, s.length, s.neck, s.bcu, s.score, s.secs); + } + std::fs::write(format!("{out}/routed.tsv"), &tsv)?; + let complete = rows.iter().filter(|r| r.2 && r.1.split == 0 && r.1.failed == 0 && r.1.islands == 0).count(); + println!("routed {} placements in {secs:.1} s: {complete} legal and complete; best first:", rows.len()); + for (n, s, _) in rows.iter().take(5) { + println!( + " {n}: split {} failed {} islands {} vias {} length {:.0} mm neck {:.1} mm score {:.0} ({:.1} s)", + s.split, s.failed, s.islands, s.vias, s.length, s.neck, s.score, s.secs + ); + } + if let Some((best, _, _)) = rows.first() { + let p = &cands.iter().find(|c| &c.0 == best).unwrap().1; + std::fs::write(format!("{out}/routed_best.json"), serde_json::to_string_pretty(&serde_json::json!({"from": best, "placement": p}))?)?; + } + Ok(()) +} + +fn print_terms(t: &cost::Terms) { + println!( + "total {:.1} = length {:.1} + escape {:.1} + decap {:.1} + cover {:.1} + crossing {:.1} + overlap {:.1} + band {:.1} + bounds {:.1} + block {:.1} + link {:.1} + pull {:.1}", + t.total(), + t.length, + t.escape, + t.decap, + t.cover, + t.crossing, + t.overlap, + t.band, + t.bounds, + t.block, + t.link, + t.pull + ); + println!("crossings {}, ratsnest {:.1} mm", t.crossings, t.ratsnest_mm); +} + +fn main() -> Result<()> { + let args: Vec<String> = std::env::args().collect(); + let usage = "usage: placer score PROBLEM CONFIG [PLACEMENT]\n placer run PROBLEM CONFIG OUT_DIR [--runs N] [--start scramble|keep] [--seed S] [--inner X] [--t0 X] [--top K] [--route BOARD.json ROUTE.toml [--route-top K]]\n placer route PROBLEM CONFIG BOARD.json ROUTE.toml OUT_DIR PLACEMENT..."; + if args.len() < 4 { + bail!("{usage}"); + } + let m = Model::load(&args[2], &args[3])?; + match args[1].as_str() { + "score" => { + let mut s = match args.get(4) { + Some(p) => load_placement(&m, p)?, + None => State::initial(&m), + }; + let t = s.recompute(); + println!( + "{} parts ({} movable), {} nets, {} decaps, {} groups", + m.parts.len(), + m.movable.len(), + m.nets.len(), + m.decaps.len(), + m.groups.len() + ); + let gs: Vec<String> = m.groups.iter().map(|g| format!("{} ({})", g.name, g.parts.len())).collect(); + println!("groups: {}", gs.join(", ")); + print_terms(&t); + for (cat, what, c) in s.findings().iter().take(40) { + println!(" {cat:8} {what:40} {c:8.2}"); + } + } + "run" => { + let out = args.get(4).context(usage)?; + let mut o = Opts { start: Start::Scramble, inner: 10.0, seed: 1, t0: 20.0, grid: 0.05 }; + let (mut runs, mut top) = (8usize, 10usize); + let (mut route, mut route_top) = (None, None); + let mut k = 5; + while k < args.len() { + let v = args.get(k + 1).context(usage)?; + match args[k].as_str() { + "--route" => { + route = Some((v.clone(), args.get(k + 2).context(usage)?.clone())); + k += 1; + } + "--route-top" => route_top = Some(v.parse::<usize>()?), + "--runs" => runs = v.parse()?, + "--start" => o.start = if v == "keep" { Start::Keep } else { Start::Scramble }, + "--seed" => o.seed = v.parse()?, + "--inner" => o.inner = v.parse()?, + "--t0" => o.t0 = v.parse()?, + "--top" => top = v.parse()?, + a => bail!("unknown option {a}\n{usage}"), + } + k += 2; + } + std::fs::create_dir_all(out)?; + let t0 = Instant::now(); + let res: Vec<_> = (0..runs) + .into_par_iter() + .map(|r| anneal(&m, &Opts { seed: o.seed + r as u64, ..o.clone() })) + .collect(); + let secs = t0.elapsed().as_secs_f64(); + // legal placements first (no courtyard overlap, nothing off the board or in a keep-out) + let legal: Vec<bool> = res.iter().map(|r| legal(&mut State::new(&m, r.at.clone(), r.rot.clone()))).collect(); + let mut idx: Vec<usize> = (0..res.len()).collect(); + idx.sort_by(|&a, &b| legal[b].cmp(&legal[a]).then(res[a].cost.partial_cmp(&res[b].cost).unwrap())); + let legal: Vec<bool> = idx.iter().map(|&i| legal[i]).collect(); + let res: Vec<_> = idx.into_iter().map(|i| &res[i]).collect(); + let moves: u64 = res.iter().map(|r| r.moves).sum(); + println!( + "{runs} runs in {secs:.1} s ({:.0} k moves/s total, {:.2} s per run per core)", + moves as f64 / secs / 1e3, + secs * rayon::current_num_threads() as f64 / runs as f64 + ); + let mut cands = Vec::new(); + let mut tsv = String::from("rank\tseed\tcost\tcrossings\tratsnest_mm\toverlap\tband\tbounds\ttemps\tmoves\n"); + for (rank, r) in res.iter().enumerate() { + let mut s = State::new(&m, r.at.clone(), r.rot.clone()); + let t = s.recompute(); + tsv += &format!( + "{rank}\t{}\t{:.2}\t{}\t{:.1}\t{:.2}\t{:.2}\t{:.2}\t{}\t{}\n", + r.seed, r.cost, t.crossings, t.ratsnest_mm, t.overlap, t.band, t.bounds, r.temps, r.moves + ); + if rank < route_top.unwrap_or(top) { + cands.push((format!("{rank:02}"), placement_json(&m, &s), legal[rank])); + } + if rank < top { + let j = serde_json::json!({"seed": r.seed, "cost": r.cost, "terms": t, "placement": placement_json(&m, &s)}); + std::fs::write(format!("{out}/rank_{rank:02}.json"), serde_json::to_string_pretty(&j)?)?; + } + if rank < 5 { + print!("#{rank} seed {} ", r.seed); + print_terms(&t); + } + } + std::fs::write(format!("{out}/runs.tsv"), tsv)?; + if let Some((board, toml)) = route { + route_all(&board, &toml, out, cands)?; + } + } + "route" => { + let (board, toml, out) = (args.get(4).context(usage)?, args.get(5).context(usage)?, args.get(6).context(usage)?); + std::fs::create_dir_all(out)?; + let mut cands = Vec::new(); + for f in &args[7..] { + let mut s = load_placement(&m, f)?; + let name = std::path::Path::new(f).file_stem().unwrap().to_string_lossy().into_owned(); + let ok = legal(&mut s); + cands.push((name, placement_json(&m, &s), ok)); + } + route_all(board, toml, out, cands)?; + } + "congest" => { + let mut cell = 0.5; + let mut files = vec![]; + let mut k = 4; + while k < args.len() { + if args[k] == "--cell" { + cell = args.get(k + 1).context(usage)?.parse()?; + k += 2; + } else { + files.push(args[k].clone()); + k += 1; + } + } + println!("file\tcost\tcrossings\trudy\tgr_overflow\tgr_cells\tgr_length\tgr_vias\tgr_rounds\tms"); + let rows: Vec<String> = files + .par_iter() + .map(|f| { + let t0 = Instant::now(); + let mut s = load_placement(&m, f).unwrap(); + let t = s.recompute(); + let g = congest::Grid::new(&m, &s, cell); + let r = congest::rudy(&m, &s, &g); + let gr = congest::groute(&m, &s, &g, &congest::GOpts::default()); + format!( + "{}\t{:.1}\t{}\t{:.1}\t{:.1}\t{}\t{:.0}\t{}\t{}\t{:.0}", + f, t.total(), t.crossings, r, gr.overflow, gr.over_cells, gr.length, gr.vias, gr.rounds, + t0.elapsed().as_secs_f64() * 1e3 + ) + }) + .collect(); + for r in rows { + println!("{r}"); + } + } + "selftest" => { + let drift = selftest(&m, 20000, 7); + println!("largest relative drift of the incremental total: {drift:.2e}"); + if drift > 1e-6 { + bail!("incremental cost drifts from the full evaluation"); + } + } + _ => bail!("{usage}"), + } + Ok(()) +} diff --git a/tools/placer/src/model.rs b/tools/placer/src/model.rs new file mode 100644 index 0000000..c8e978b --- /dev/null +++ b/tools/placer/src/model.rs @@ -0,0 +1,700 @@ +//! The placement problem: parts, pads, nets from export.py's JSON, plus the sidecar config +//! (placement.toml) and what can be inferred from the netlist (decoupling caps, pin normals, +//! fine-pitch fan-out bands, fixed parts). +//! +//! Labels beyond the netlist: `[[link]]` keeps two pads within a distance (a net tie on a +//! Kelvin pad), `[[pull]]` draws the pads of interface nets towards a board side (where the +//! host connects), `[[replicate]]` makes repeated channels copies of the first one at a fixed +//! pitch (followers move with their master and are never moved on their own). + +use crate::geom::{poly_rects, Pt, Rect}; +use anyhow::{bail, Context, Result}; +use serde::Deserialize; +use std::collections::HashMap; + +// ---------- export.py JSON ---------- + +#[derive(Deserialize)] +struct JPad { + num: String, + net: String, + x: f64, + y: f64, + w: f64, + h: f64, + tht: bool, +} + +#[derive(Deserialize)] +struct JPart { + #[serde(rename = "ref")] + reference: String, + value: String, + fpid: String, + x: f64, + y: f64, + rot: f64, + locked: bool, + board_only: bool, + fields: HashMap<String, String>, + court: Vec<Vec<[f64; 2]>>, + pads: Vec<JPad>, +} + +#[derive(Deserialize)] +struct JKeepout { + poly: Vec<[f64; 2]>, + footprints: bool, + pads: bool, + #[serde(default)] + tracks: bool, +} + +#[derive(Deserialize)] +struct JClass { + track: f64, + clearance: f64, +} + +#[derive(Deserialize)] +struct JProblem { + bounds: [f64; 4], + parts: Vec<JPart>, + netclass: HashMap<String, String>, + #[serde(default)] + classes: HashMap<String, JClass>, + fill: Vec<String>, + keepouts: Vec<JKeepout>, +} + +// ---------- placement.toml ---------- + +/// Cost weights. Lengths are in mm, areas in mm^2. +#[derive(Deserialize, Clone, Debug)] +#[serde(default, deny_unknown_fields)] +pub struct Weights { + /// per mm of ratsnest (MST) length, times the net weight + pub length: f64, + /// per crossing of two ratsnest lines, times the mean weight of both nets + pub crossing: f64, + /// per line that leaves a pin backwards, times the detour (part size); not scaled by net weight + pub escape: f64, + /// per ratsnest line over another net's pad, times the net weight + pub block: f64, + /// per mm from a decoupling cap to its pin (ground pad counts half) + pub decap: f64, + /// beyond the decap limit (3 mm, 8 mm for bulk caps): per mm^2 for the first 2 mm, then 4 per mm + pub decap_limit: f64, + /// per mm that a decoupled IC pin is farther than 3 mm from its nearest cap + pub cover: f64, + /// per mm^2 of courtyard overlap, outside the board, in a keep-out or outside a group bbox + pub overlap: f64, + /// per mm^2 of another part's pad in a fine-pitch IC's fan-out band + pub band: f64, + /// fan-out band width in front of fine-pitch pin rows (mm) + pub fanout: f64, + /// copper-to-edge clearance for pads (mm) + pub edge: f64, + /// [[link]] past its distance: per mm^2 for the first 2 mm, then 4 per mm (times its weight) + pub link: f64, + /// [[pull]]: per mm from a pad to its side of the part's group bbox, else of the board + /// (times its weight) + pub pull: f64, +} + +impl Default for Weights { + fn default() -> Self { + Weights { + length: 1.0, + crossing: 4.0, + escape: 3.0, + block: 3.0, + decap: 3.0, + decap_limit: 20.0, + cover: 4.0, + overlap: 100.0, + band: 40.0, + fanout: 1.0, + edge: 0.5, + link: 20.0, + pull: 1.0, + } + } +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +struct CNet { + #[serde(rename = "match")] + pattern: String, + weight: f64, +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +struct CGroup { + name: String, + #[serde(default)] + parts: Vec<String>, + bbox: Option<[f64; 4]>, +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +struct CAttach { + part: String, + /// "U2.21" + pin: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CLink { + /// "NT1.2" + a: String, + b: String, + /// pad centre distance (mm) allowed without cost + max: f64, + #[serde(default = "one")] + weight: f64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CPull { + /// net name globs + nets: Vec<String>, + /// "N", "S", "E" or "W" + side: String, + #[serde(default = "one")] + weight: f64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CReplicate { + /// channels, each a list of parts; channel k's part i follows channel 0's part i + parts: Vec<Vec<String>>, + /// offset (mm) from one channel to the next, in board axes + pitch: [f64; 2], +} + +fn one() -> f64 { + 1.0 +} + +#[derive(Deserialize, Default)] +#[serde(default, deny_unknown_fields)] +struct Config { + fixed: Vec<String>, + /// net-class name -> weight; classes not listed weigh 1 + class: HashMap<String, f64>, + net: Vec<CNet>, + group: Vec<CGroup>, + attach: Vec<CAttach>, + link: Vec<CLink>, + pull: Vec<CPull>, + replicate: Vec<CReplicate>, + weights: Weights, +} + +// ---------- model ---------- + +pub struct Pad { + pub part: usize, + pub num: String, + /// None for unconnected pads and fill nets + pub net: Option<usize>, + pub fill: bool, + pub local: Pt, + pub half: Pt, + /// outward direction a track leaves the pin in, footprint-local + pub normal: Option<Pt>, + /// through-hole (blocks both layers) + pub tht: bool, +} + +pub struct Part { + pub reference: String, + pub fpid: String, + pub fixed: bool, + pub at0: Pt, + pub rot0: u8, + pub pads: Vec<usize>, + pub court: Vec<Rect>, + /// bounding box of the courtyard (local) + pub hull: Rect, + /// fine-pitch ICs: pad envelope grown by the fan-out width (local) + pub band: Option<Rect>, + /// detour length when a line leaves a pin backwards + pub detour: f64, + /// non-fill nets on this part + pub nets: Vec<usize>, + /// all groups this part belongs to, innermost first + pub groups: Vec<usize>, + /// links this part has a pad in + pub links: Vec<usize>, + /// [[pull]] pads: (pad, outward unit vector of the side, weight) + pub pulls: Vec<(usize, Pt, f64)>, + /// replicated channel: (master part, offset from it); moves only with the master + pub follow: Option<(usize, Pt)>, + /// parts that follow this one + pub followers: Vec<usize>, +} + +pub struct Link { + pub a: usize, + pub b: usize, + pub max: f64, + pub weight: f64, +} + +pub struct Decap { + pub part: usize, + pub sig: usize, + pub gnd: usize, + pub bulk: bool, + /// candidate pins (pad) with the ground pins of the same part + pub cands: Vec<(usize, Vec<usize>)>, +} + +pub struct Net { + pub name: String, + pub pads: Vec<usize>, + pub weight: f64, + /// track width + clearance of the net's class (mm): the room one track takes + pub pitch: f64, + pub decaps: Vec<usize>, + /// IC pins that need a cap within 3 mm + pub cover: Vec<usize>, +} + +pub struct Group { + pub name: String, + pub bbox: Option<Rect>, + /// movable members, including those of subgroups + pub parts: Vec<usize>, +} + +pub struct Model { + pub parts: Vec<Part>, + pub pads: Vec<Pad>, + pub nets: Vec<Net>, + pub decaps: Vec<Decap>, + pub groups: Vec<Group>, + pub links: Vec<Link>, + pub bounds: Rect, + /// rule areas no courtyard may enter + pub keepouts: Vec<Rect>, + /// rule areas no pad may enter + pub pad_keepouts: Vec<Rect>, + /// rule areas no track may enter + pub track_keepouts: Vec<Rect>, + pub w: Weights, + pub movable: Vec<usize>, +} + +const COURT_MARGIN: f64 = 0.03; + +fn glob(pat: &str, s: &str) -> bool { + // '*' only + let parts: Vec<&str> = pat.split('*').collect(); + if parts.len() == 1 { + return pat == s; + } + let mut rest = s; + for (i, p) in parts.iter().enumerate() { + if i == 0 { + if !rest.starts_with(p) { + return false; + } + rest = &rest[p.len()..]; + } else if i == parts.len() - 1 { + return rest.ends_with(p); + } else if let Some(k) = rest.find(p) { + rest = &rest[k + p.len()..]; + } else { + return false; + } + } + true +} + +fn cap_uf(v: &str) -> f64 { + let v = v.trim(); + let k = v.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(v.len()); + let n: f64 = v[..k].parse().unwrap_or(0.0); + let f = match v[k..].chars().next() { + Some('p') => 1e-6, + Some('n') => 1e-3, + Some('u') | Some('µ') => 1.0, + Some('m') => 1e3, + _ => 1.0, + }; + n * f +} + +fn is_ic(reference: &str, npads: usize) -> bool { + npads >= 4 && !reference.starts_with(['J', 'P']) && !reference.starts_with("TP") +} + +/// Outward direction of each pad: 2-pad parts along their axis, ICs and connectors from the +/// side of the pad envelope the pad sits on (pads elongated along it decide first); centre +/// pads (exposed pads, module ground pads) and THT pads have none. +fn normals(pads: &[JPad]) -> Vec<Option<Pt>> { + let smd: Vec<&JPad> = pads.iter().filter(|p| !p.tht).collect(); + if smd.len() == 2 && pads.len() == 2 { + let c = ((smd[0].x + smd[1].x) / 2.0, (smd[0].y + smd[1].y) / 2.0); + return pads + .iter() + .map(|p| { + let (dx, dy) = (p.x - c.0, p.y - c.1); + let l = (dx * dx + dy * dy).sqrt(); + (l > 1e-6).then(|| (dx / l, dy / l)) + }) + .collect(); + } + if smd.len() < 3 { + return pads.iter().map(|_| None).collect(); + } + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for p in &smd { + x0 = x0.min(p.x); + y0 = y0.min(p.y); + x1 = x1.max(p.x); + y1 = y1.max(p.y); + } + let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + pads.iter() + .map(|p| { + if p.tht { + return None; + } + let d = [p.x - x0, x1 - p.x, p.y - y0, y1 - p.y]; + let m = d.iter().cloned().fold(f64::MAX, f64::min); + if m > 0.3 { + return None; // not on the perimeter + } + if p.w > 1.3 * p.h { + return Some((if p.x < cx { -1.0 } else { 1.0 }, 0.0)); + } + if p.h > 1.3 * p.w { + return Some((0.0, if p.y < cy { -1.0 } else { 1.0 })); + } + let dirs = [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0)]; + let (mut nx, mut ny) = (0.0, 0.0); + for (k, dir) in dirs.iter().enumerate() { + if d[k] < m + 0.2 { + nx += dir.0; + ny += dir.1; + } + } + let l = ((nx * nx + ny * ny) as f64).sqrt(); + (l > 1e-6).then(|| (nx / l, ny / l)) + }) + .collect() +} + +fn rot_steps(deg: f64) -> u8 { + (((deg / 90.0).round() as i64).rem_euclid(4)) as u8 +} + +impl Model { + pub fn load(problem: &str, config: &str) -> Result<Model> { + let jp: JProblem = serde_json::from_str(&std::fs::read_to_string(problem).with_context(|| problem.to_string())?)?; + let cfg: Config = toml::from_str(&std::fs::read_to_string(config).with_context(|| config.to_string())?) + .with_context(|| format!("parsing {config}"))?; + let w = cfg.weights.clone(); + let fillset: std::collections::HashSet<&str> = jp.fill.iter().map(|s| s.as_str()).collect(); + let is_fill = |n: &str| { + fillset.contains(n) || { + let base = n.rsplit('/').next().unwrap_or(n); + matches!(base, "GND" | "GNDA" | "GNDD" | "AGND" | "DGND" | "VSS" | "PGND") + } + }; + + // nets + let mut netid: HashMap<String, usize> = HashMap::new(); + let mut nets: Vec<Net> = Vec::new(); + let mut names: Vec<&String> = jp.netclass.keys().collect(); + names.sort(); + for n in names { + if is_fill(n) { + continue; + } + let cls = &jp.netclass[n]; + let mut weight = *cfg.class.get(cls).unwrap_or(&1.0); + for o in &cfg.net { + if glob(&o.pattern, n) { + weight = o.weight; + } + } + let pitch = jp.classes.get(cls).map(|c| c.track + c.clearance).unwrap_or(0.4); + netid.insert(n.clone(), nets.len()); + nets.push(Net { name: n.clone(), pads: vec![], weight, pitch, decaps: vec![], cover: vec![] }); + } + + // parts and pads + let mut parts = Vec::new(); + let mut pads = Vec::new(); + let fixed_cfg: std::collections::HashSet<&str> = cfg.fixed.iter().map(|s| s.as_str()).collect(); + for (pi, p) in jp.parts.iter().enumerate() { + // grown by a bit more than half the courtyard line: KiCad's DRC flags courtyards + // that touch, so parts must keep at least one grid step apart + let mut court: Vec<Rect> = p.court.iter().flat_map(|poly| poly_rects(poly)).map(|r| r.grow(COURT_MARGIN)).collect(); + if court.is_empty() { + for q in &p.pads { + court.push(Rect::around((q.x, q.y), q.w / 2.0 + 0.25, q.h / 2.0 + 0.25)); + } + } + let hull = court.iter().skip(1).fold(court[0], |a, r| a.union(r)); + let field_fixed = p.fields.get("Place_Fixed").map(|v| !v.is_empty() && v != "0" && v != "no").unwrap_or(false); + let hole = p.fpid.contains("MountingHole") || p.fpid.contains("DIN_Post") || p.fpid.contains("DIN_Housing"); + let fixed = p.locked || p.board_only || hole || field_fixed || fixed_cfg.contains(p.reference.as_str()); + let ns = normals(&p.pads); + let mut ids = vec![]; + for (q, n) in p.pads.iter().zip(ns) { + let net = netid.get(&q.net).copied(); + if let Some(k) = net { + nets[k].pads.push(pads.len()); + } + ids.push(pads.len()); + pads.push(Pad { + part: pi, + num: q.num.clone(), + net, + fill: is_fill(&q.net), + local: (q.x, q.y), + half: (q.w / 2.0, q.h / 2.0), + normal: n, + tht: q.tht, + }); + } + // fine-pitch: >= 8 SMD pads with neighbours closer than 0.7 mm + let smd: Vec<&JPad> = p.pads.iter().filter(|q| !q.tht).collect(); + let pitch = smd + .iter() + .enumerate() + .flat_map(|(i, a)| smd[i + 1..].iter().map(move |b| ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt())) + .fold(f64::MAX, f64::min); + let band = (smd.len() >= 8 && pitch < 0.7).then(|| { + smd.iter() + .map(|q| Rect::around((q.x, q.y), q.w / 2.0, q.h / 2.0)) + .reduce(|a, b| a.union(&b)) + .unwrap() + .grow(w.fanout) + }); + let mut pn: Vec<usize> = ids.iter().filter_map(|&k| pads[k].net).collect(); + pn.sort(); + pn.dedup(); + parts.push(Part { + reference: p.reference.clone(), + fpid: p.fpid.clone(), + fixed, + at0: (p.x, p.y), + rot0: rot_steps(p.rot), + pads: ids, + court, + hull, + band, + detour: ((hull.x1 - hull.x0) + (hull.y1 - hull.y0)) / 2.0, + nets: pn, + groups: vec![], + links: vec![], + pulls: vec![], + follow: None, + followers: vec![], + }); + } + let pref: HashMap<String, usize> = parts.iter().enumerate().map(|(i, p)| (p.reference.clone(), i)).collect(); + + // decoupling caps: C with one pad on a fill net, the other on a net with IC pins + let mut decaps = Vec::new(); + let xtal_nets: std::collections::HashSet<usize> = parts + .iter() + .filter(|p| p.reference.starts_with('Y')) + .flat_map(|p| p.nets.clone()) + .collect(); + let attach: HashMap<&str, &str> = cfg.attach.iter().map(|a| (a.part.as_str(), a.pin.as_str())).collect(); + for (pi, (p, jpart)) in parts.iter().zip(&jp.parts).enumerate() { + if !p.reference.starts_with('C') || p.pads.len() != 2 { + continue; + } + let (a, b) = (p.pads[0], p.pads[1]); + let (sig, gnd) = match (pads[a].fill, pads[b].fill) { + (false, true) => (a, b), + (true, false) => (b, a), + _ => continue, + }; + let Some(net) = pads[sig].net else { continue }; + let bulk = cap_uf(&jpart.value) >= 4.7; + let mut cands = vec![]; + if let Some(pin) = attach.get(p.reference.as_str()) { + let (r, num) = pin.split_once('.').context("attach pin must be REF.PIN")?; + let Some(&ic) = pref.get(r) else { bail!("attach {}: no part {r}", p.reference) }; + let Some(&k) = parts[ic].pads.iter().find(|&&k| pads[k].num == num) else { + bail!("attach {}: no pin {pin}", p.reference) + }; + cands.push(k); + } else { + for &k in &nets[net].pads { + let q = &parts[pads[k].part]; + let ok = is_ic(&q.reference, q.pads.len()) || (bulk && q.reference.starts_with(['L', 'F'])); + if pads[k].part != pi && ok { + cands.push(k); + } + } + } + if cands.is_empty() { + continue; + } + let cands = cands + .into_iter() + .map(|k| { + let g = parts[pads[k].part].pads.iter().copied().filter(|&j| pads[j].fill).collect(); + (k, g) + }) + .collect(); + nets[net].decaps.push(decaps.len()); + decaps.push(Decap { part: pi, sig, gnd, bulk, cands }); + } + // IC pins on nets with a small cap need a cap within 3 mm (crystal nets excluded) + for (ni, net) in nets.iter_mut().enumerate() { + if xtal_nets.contains(&ni) || !net.decaps.iter().any(|&d| !decaps[d].bulk) { + continue; + } + net.cover = net + .pads + .iter() + .copied() + .filter(|&k| { + let q = &parts[pads[k].part]; + is_ic(&q.reference, q.pads.len()) && !q.reference.starts_with(['Y', 'L', 'F']) + }) + .collect(); + } + + // links, pulls and replicated channels + let pad_of = |parts: &[Part], s: &str, what: &str| -> Result<usize> { + let (r, num) = s.split_once('.').with_context(|| format!("{what} {s}: write REF.PIN"))?; + let Some(&pi) = pref.get(r) else { bail!("{what} {s}: no part {r}") }; + parts[pi].pads.iter().copied().find(|&k| pads[k].num == num).with_context(|| format!("{what} {s}: no pin {num}")) + }; + let mut links = Vec::new(); + for l in &cfg.link { + let (a, b) = (pad_of(&parts, &l.a, "link")?, pad_of(&parts, &l.b, "link")?); + for k in [a, b] { + let pi = pads[k].part; + if !parts[pi].links.contains(&links.len()) { + parts[pi].links.push(links.len()); + } + } + links.push(Link { a, b, max: l.max, weight: l.weight }); + } + for pl in &cfg.pull { + let dir = match pl.side.as_str() { + "N" => (0.0, -1.0), + "S" => (0.0, 1.0), + "W" => (-1.0, 0.0), + "E" => (1.0, 0.0), + o => bail!("pull: side {o:?} is not N, S, E or W"), + }; + for (pi, jpart) in jp.parts.iter().enumerate() { + for (q, &k) in jpart.pads.iter().zip(&parts[pi].pads.clone()) { + if pl.nets.iter().any(|g| glob(g, &q.net)) { + parts[pi].pulls.push((k, dir, pl.weight)); + } + } + } + } + for rp in &cfg.replicate { + let Some(first) = rp.parts.first() else { continue }; + for (c, chan) in rp.parts.iter().enumerate().skip(1) { + if chan.len() != first.len() { + bail!("replicate: channel {c} has {} parts, channel 0 has {}", chan.len(), first.len()); + } + for (r0, r) in first.iter().zip(chan) { + let (Some(&m0), Some(&f)) = (pref.get(r0.as_str()), pref.get(r.as_str())) else { bail!("replicate: no part {r0} or {r}") }; + if parts[m0].fpid != parts[f].fpid { + bail!("replicate: {r} ({}) is not the footprint of {r0} ({})", parts[f].fpid, parts[m0].fpid); + } + if parts[m0].fixed || parts[f].fixed { + bail!("replicate: {r0} and {r} must both be movable"); + } + parts[f].follow = Some((m0, (rp.pitch[0] * c as f64, rp.pitch[1] * c as f64))); + parts[m0].followers.push(f); + } + } + } + + // groups: from the config and from Place_Group fields ("eth/xtal" is a subgroup of "eth") + let mut groups: Vec<Group> = Vec::new(); + let mut gid: HashMap<String, usize> = HashMap::new(); + let mut member: Vec<(usize, String)> = vec![]; + for (pi, p) in jp.parts.iter().enumerate() { + if let Some(g) = p.fields.get("Place_Group").filter(|g| !g.is_empty()) { + member.push((pi, g.clone())); + } + } + for g in &cfg.group { + gid.insert(g.name.clone(), groups.len()); + groups.push(Group { name: g.name.clone(), bbox: g.bbox.map(|b| Rect::new(b[0], b[1], b[2], b[3])), parts: vec![] }); + for r in &g.parts { + let Some(&pi) = pref.get(r.as_str()) else { bail!("group {}: no part {r}", g.name) }; + member.retain(|(q, _)| *q != pi); // the config overrides the field + member.push((pi, g.name.clone())); + } + } + for (pi, g) in member { + // the group and every parent group + let segs: Vec<&str> = g.split('/').collect(); + for k in (1..=segs.len()).rev() { + let name = segs[..k].join("/"); + let id = *gid.entry(name.clone()).or_insert_with(|| { + groups.push(Group { name: name.clone(), bbox: None, parts: vec![] }); + groups.len() - 1 + }); + if !parts[pi].fixed && parts[pi].follow.is_none() && !groups[id].parts.contains(&pi) { + groups[id].parts.push(pi); + } + if !parts[pi].groups.contains(&id) { + parts[pi].groups.push(id); + } + } + } + + let keepouts = jp.keepouts.iter().filter(|k| k.footprints).flat_map(|k| poly_rects(&k.poly)).collect(); + let pad_keepouts = jp.keepouts.iter().filter(|k| k.pads).flat_map(|k| poly_rects(&k.poly)).collect(); + let track_keepouts = jp.keepouts.iter().filter(|k| k.tracks).flat_map(|k| poly_rects(&k.poly)).collect(); + let movable = (0..parts.len()).filter(|&i| !parts[i].fixed && parts[i].follow.is_none()).collect(); + let b = jp.bounds; + Ok(Model { + parts, + pads, + nets, + decaps, + groups, + links, + bounds: Rect::new(b[0], b[1], b[2], b[3]), + keepouts, + pad_keepouts, + track_keepouts, + w, + movable, + }) + } + + /// Put every follower at its master's pose plus its offset. + pub fn sync(&self, at: &mut [Pt], rot: &mut [u8]) { + for (i, p) in self.parts.iter().enumerate() { + if let Some((m0, off)) = p.follow { + at[i] = (at[m0].0 + off.0, at[m0].1 + off.1); + rot[i] = rot[m0]; + } + } + } + + pub fn part(&self, r: &str) -> Option<usize> { + self.parts.iter().position(|p| p.reference == r) + } +} diff --git a/tools/pnr.sh b/tools/pnr.sh new file mode 100644 index 0000000..b21bde5 --- /dev/null +++ b/tools/pnr.sh @@ -0,0 +1,60 @@ +#!/bin/sh +# Place and route a board with tools/placer + tools/router-rs, check the best candidates with +# KiCad's DRC, and install one. See knowledge/tooling/pnr.md. +# +# sh tools/pnr.sh run BOARD_DIR [TOP] # 32 placements, all routed; DRC of the TOP (6) best +# sh tools/pnr.sh install BOARD_DIR RANK # e.g. rank_00: checkpoint, references, pours, DRC, ERC +# +# BOARD_DIR holds <name>.kicad_pcb/.kicad_sch/.kicad_pro (name = the directory name) with +# placement.toml and route.toml next to them. Output goes to BOARD_DIR/out/pnr/. +# Close the board in KiCad first: an open editor rewrites .kicad_pro and would overwrite the +# installed board on its next save. RUNS (32), JOBS (6), KICAD_PYTHON and KICAD_CLI are read +# from the environment. +set -e +T=$(dirname "$0") +. "$T/kicad_env.sh" +CMD=$1; M=${2%/}; N=$(basename "$M"); O=$M/out/pnr +[ -n "$CMD" ] && [ -d "$M" ] || { sed -n 5,6p "$0"; exit 1; } +if ls "$M"/~"$N".kicad_p*.lck >/dev/null 2>&1; then echo "$N is open in KiCad; close it first" >&2; exit 1; fi + +case $CMD in +run) + mkdir -p "$O" + cargo build --release -q --manifest-path "$T/placer/Cargo.toml" + $KC sch export netlist -o "$O/$N.net" "$M/$N.kicad_sch" >/dev/null + $KPY "$T/placer/export.py" "$M/$N.kicad_pcb" "$O/problem.json" "$O/$N.net" 2>/dev/null | tail -n 1 + $KPY "$T/router/dump_board.py" "$M/$N.kicad_pcb" "$O/board.json" 2>/dev/null | tail -n 1 + R=${RUNS:-32} + "$T/placer/target/release/placer" run "$O/problem.json" "$M/placement.toml" "$O/run" --runs "$R" --inner 10 \ + --top "$R" --route "$O/board.json" "$M/route.toml" --route-top "$R" > "$O/placer.log" 2>&1 + grep -A 5 'legal and complete' "$O/placer.log" + TOP=$(awk -v d="$O" -v n="${3:-6}" 'NR > 1 && NR <= n + 1 {print d "/run/rank_" $1 ".json"}' "$O/run/routed.tsv") + rm -rf "$O/eval" + # shellcheck disable=SC2086 + E=$M BOARD=$N TOML=$M/route.toml JOBS=${JOBS:-6} sh "$T/pnr_eval.sh" "$O/eval" $TOP + ;; +install) + R=$3; [ -f "$O/eval/$R/routed.kicad_pcb" ] || { echo "no $O/eval/$R/routed.kicad_pcb" >&2; exit 1; } + C=$M/out/before-pnr-$(date +%Y-%m-%d-%H%M); mkdir -p "$C" + cp "$M/$N.kicad_pcb" "$M/$N.kicad_pro" "$C/" + $KPY "$T/silk_refs.py" "$O/eval/$R/routed.kicad_pcb" "$O/silk.kicad_pcb" 2>/dev/null | tail -n 1 + $KPY - "$O/silk.kicad_pcb" "$M/$N.kicad_pcb" <<'EOF' 2>/dev/null +import sys, pcbnew +b = pcbnew.LoadBoard(sys.argv[1]) +pcbnew.ZONE_FILLER(b).Fill(b.Zones()) +pcbnew.SaveBoard(sys.argv[2], b) +EOF + cp "$C/$N.kicad_pro" "$M/$N.kicad_pro" # SaveBoard rewrites the project's net settings + $KC pcb drc --refill-zones --schematic-parity --format json -o "$O/drc.json" "$M/$N.kicad_pcb" >/dev/null + $KC sch erc --format json -o "$O/erc.json" "$M/$N.kicad_sch" >/dev/null + python3 - "$O/drc.json" "$O/erc.json" <<'EOF' +import collections, json, sys +d = json.load(open(sys.argv[1])); e = json.load(open(sys.argv[2])) +c = collections.Counter((v['type'], v['severity']) for v in d['violations']) +print('DRC %s unconnected=%d parity=%d | ERC %d' % (dict(c), len(d['unconnected_items']), + len(d.get('schematic_parity', [])), sum(len(s['violations']) for s in e['sheets']))) +EOF + echo "checkpoint: $C" + ;; +*) sed -n 5,6p "$0"; exit 1 ;; +esac diff --git a/tools/pnr_eval.sh b/tools/pnr_eval.sh new file mode 100644 index 0000000..ed73828 --- /dev/null +++ b/tools/pnr_eval.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# Apply, route and DRC-check placer candidates, several in parallel. Called by tools/pnr.sh run. +# +# E=BOARD_DIR BOARD=NAME sh tools/pnr_eval.sh OUT_DIR placement.json... +# TOML=route.toml ROUTER=path/to/router JOBS=4 (optional; TOML defaults to $E/route.toml) +# +# Per placement: placer/apply.py -> router/dump_board.py -> router route -> router/write_board.py +# -> kicad-cli DRC, in OUT_DIR/<placement>/ (routed.kicad_pcb, drc.json, route.log). One line +# per board is printed, sorted by name, then +# SUMMARY complete=<boards with 0 unconnected after DRC>/<total> unconnected=<sum> vias=<mean> length=<mean> +T=$(cd "$(dirname "$0")" && pwd) +. "$T/kicad_env.sh" +: "${E:?set E to the board directory}" "${BOARD:?set BOARD to the board name}" +ROUTER=${ROUTER:-$T/router-rs/target/release/router} +TOML=${TOML:-$E/route.toml} +PLANE=${PLANE:-GND} # the plane net whose dangling vias write_board.py prunes +export E BOARD ROUTER TOML PLANE + +if [ "$1" = "--one" ]; then + OUT=$2; P=$3 + N=$(basename "$P" .json) + D="$OUT/$N" + mkdir -p "$D" + $KPY "$T/placer/apply.py" "$E/$BOARD.kicad_pcb" "$P" "$D/$BOARD.kicad_pcb" >/dev/null 2>&1 + $KPY "$T/router/dump_board.py" "$D/$BOARD.kicad_pcb" "$D/board.json" >/dev/null 2>&1 + "$ROUTER" route "$D/board.json" "$TOML" "$D/routes.json" > "$D/route.log" 2>&1 || true + $KPY "$T/router/write_board.py" "$D/$BOARD.kicad_pcb" "$D/routes.json" "$D/routed.kicad_pcb" \ + --replace --prune-vias "$PLANE" >/dev/null 2>&1 + cp "$D/$BOARD.kicad_pro" "$D/routed.kicad_pro" + [ -f "$D/$BOARD.kicad_dru" ] && cp "$D/$BOARD.kicad_dru" "$D/routed.kicad_dru" + $KC pcb drc --refill-zones --format json -o "$D/drc.json" "$D/routed.kicad_pcb" >/dev/null 2>&1 + DRC=$(python3 -c " +import collections, json, sys +d = json.load(open(sys.argv[1])) +c = collections.Counter(v['type'] for v in d['violations'] if not v['type'].startswith('silk')) +print('unconnected=%d drc=%s' % (len(d['unconnected_items']), dict(c)))" "$D/drc.json" 2>/dev/null || echo "unconnected=? drc=error") + R=$(grep RESULT "$D/route.log" | sed 's/RESULT //') + printf "%-12s %s %s\n" "$N" "${R:-CRASH $(tail -n 1 "$D/route.log")}" "$DRC" > "$D/line.txt" + exit 0 +fi + +OUT=$1; shift +mkdir -p "$OUT" +printf '%s\n' "$@" | xargs -P "${JOBS:-4}" -I{} sh "$0" --one "$OUT" {} +for P in "$@"; do cat "$OUT/$(basename "$P" .json)/line.txt"; done | sort | tee "$OUT/lines.txt" +python3 - "$OUT/lines.txt" <<'PY' +import re, sys +rows = [l for l in open(sys.argv[1]) if l.strip()] +unc = [int(m.group(1)) if (m := re.search(r"unconnected=(\d+)", l)) else 0 for l in rows] +def f(k): return [float(m.group(1)) for l in rows if (m := re.search(k + r"=([\d.]+)", l))] +v, ln = f("vias"), f("length") +print("SUMMARY complete=%d/%d unconnected=%d vias=%.1f length=%.1f" % ( + sum(1 for u in unc if u == 0), len(rows), sum(unc), sum(v) / max(len(v), 1), sum(ln) / max(len(ln), 1))) +PY diff --git a/tools/prune_copper.py b/tools/prune_copper.py new file mode 100644 index 0000000..acac211 --- /dev/null +++ b/tools/prune_copper.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Remove footprints, optionally cut the board outline down, and delete the copper left dangling. + +Run with KiCad's bundled Python: + + $KPY tools/prune_copper.py board.kicad_pcb [out.kicad_pcb] [--remove J3,J4] [--clip X0,Y0,X1,Y1] + [--netlist board.net] + + --remove footprints to delete + --clip new rectangular board outline in mm: Edge.Cuts is replaced, zone outlines are + intersected with it, and tracks/vias reaching outside it are deleted + --netlist rename nets to the names in a kicad-cli netlist, matched by pad (e.g. after root-sheet + labels were removed and the nets take their hierarchical names) + +Then dangling copper is pruned until nothing changes, like KiCad's "Cleanup Tracks & Vias": +zones are refilled, connectivity rebuilt, and every track or via that DRC would call dangling +(KiCad's TestTrackEndpointDangling) is deleted. Plane drops and stitching vias in fills stay. + +pcbnew.SaveBoard rewrites the .kicad_pro; it is copied before and restored after. Close the +board in KiCad before writing to its own path. +""" +import argparse +import os +import re + +import pcbnew + + +def rename(b, netlist): + """Give every net the name the schematic now has, matched by the pads on it.""" + want = {} + text = open(netlist).read() + for chunk in re.split(r'\(net\s', text[text.index("(nets"):])[1:]: + name = re.search(r'\(name "((?:[^"\\]|\\.)*)"\)', chunk).group(1) + for ref, pin in re.findall(r'\(node\s+\(ref "([^"]+)"\)\s+\(pin "([^"]+)"\)', chunk): + want[(ref, pin)] = name + old2new = {} + for f in b.GetFootprints(): + for p in f.Pads(): + new = want.get((f.GetReference(), p.GetNumber())) + if new and p.GetNetname() and new != p.GetNetname(): + old2new[p.GetNetname()] = new + nets = b.GetNetsByName() + made = {} + for old, new in old2new.items(): + if new not in nets and new not in made: + made[new] = pcbnew.NETINFO_ITEM(b, new) + b.Add(made[new]) + def net(name): + return made.get(name) or b.GetNetsByName()[name] + for f in b.GetFootprints(): + for p in f.Pads(): + if p.GetNetname() in old2new: + p.SetNet(net(old2new[p.GetNetname()])) + for t in list(b.GetTracks()) + list(b.Zones()): + if t.GetNetname() in old2new: + t.SetNet(net(old2new[t.GetNetname()])) + print("renamed %d nets" % len(old2new)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("board") + ap.add_argument("out", nargs="?") + ap.add_argument("--remove", default="") + ap.add_argument("--clip") + ap.add_argument("--netlist", help="kicad-cli netlist: rename nets to the schematic's names (pads, tracks, vias, zones)") + a = ap.parse_args() + out = a.out or a.board + b = pcbnew.LoadBoard(a.board) + edges = [d for d in b.GetDrawings() if d.GetLayer() == pcbnew.Edge_Cuts] + + for ref in filter(None, a.remove.split(",")): + b.Delete(b.FindFootprintByReference(ref)) # Delete, not Remove: Remove() on a footprint breaks Tracks()/Zones() afterwards + + if a.netlist: + rename(b, a.netlist) + + if a.clip: + x0, y0, x1, y1 = (float(v) for v in a.clip.split(",")) + for d in edges: + b.Delete(d) + r = pcbnew.PCB_SHAPE(b) + r.SetShape(pcbnew.SHAPE_T_RECT) + r.SetStart(pcbnew.VECTOR2I_MM(x0, y0)) + r.SetEnd(pcbnew.VECTOR2I_MM(x1, y1)) + r.SetLayer(pcbnew.Edge_Cuts) + r.SetWidth(pcbnew.FromMM(0.1)) + b.Add(r) + rect = pcbnew.SHAPE_POLY_SET() + rect.NewOutline() + for x, y in ((x0, y0), (x1, y0), (x1, y1), (x0, y1)): + rect.Append(pcbnew.FromMM(x), pcbnew.FromMM(y)) + for z in b.Zones(): + o = z.Outline() + o.BooleanIntersection(rect) + box = pcbnew.BOX2I(pcbnew.VECTOR2I_MM(x0, y0), pcbnew.VECTOR2I_MM(x1 - x0, y1 - y0)) + for t in list(b.GetTracks()): + if not box.Contains(t.GetBoundingBox()): + b.Delete(t) + + filler = pcbnew.ZONE_FILLER(b) + removed = [0, 0] + while True: + filler.Fill(b.Zones()) + b.BuildConnectivity() + conn = b.GetConnectivity() + kill = [t for t in b.GetTracks() if conn.TestTrackEndpointDangling(t, False)] + if not kill: + break + for t in kill: + removed[t.GetClass() == "PCB_VIA"] += 1 + b.Delete(t) + + filler.Fill(b.Zones()) + pro = out[:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro).read() if os.path.exists(pro) else None + pcbnew.SaveBoard(out, b) + if keep is not None: + open(pro, "w").write(keep) + print("removed %d tracks, %d vias; %d tracks, %d vias left" % (removed[0], removed[1], + sum(1 for t in b.GetTracks() if t.GetClass() == "PCB_TRACK"), + sum(1 for t in b.GetTracks() if t.GetClass() == "PCB_VIA"))) + + +if __name__ == "__main__": + main() diff --git a/tools/router-rs/Cargo.lock b/tools/router-rs/Cargo.lock new file mode 100644 index 0000000..04eead0 --- /dev/null +++ b/tools/router-rs/Cargo.lock @@ -0,0 +1,191 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "router" +version = "0.1.0" +dependencies = [ + "anyhow", + "serde", + "serde_json", + "toml", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tools/router-rs/Cargo.toml b/tools/router-rs/Cargo.toml new file mode 100644 index 0000000..c7ff51a --- /dev/null +++ b/tools/router-rs/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "router" +version = "0.1.0" +edition = "2021" +description = "Grid maze router for 2-layer KiCad boards (see knowledge/tooling/rust-router.md)" + +[lib] +name = "router" +path = "src/lib.rs" + +[[bin]] +name = "router" +path = "src/main.rs" + +[dependencies] +anyhow = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +toml = "1" + +[profile.release] +debug = 1 diff --git a/tools/router-rs/README.md b/tools/router-rs/README.md new file mode 100644 index 0000000..969c415 --- /dev/null +++ b/tools/router-rs/README.md @@ -0,0 +1,13 @@ +# Router (Rust) + +Grid router for 2-layer KiCad boards with negotiated congestion (all nets at once, ground drops +optionally included), cleanup passes, a pour-connectivity check and a sequential mode that runs +the old route scripts' order from a `route.toml`. Footprint copper such as net-tie bridges is +respected; `area = "pours"` in route.toml keeps all copper inside the plane pours (a design block's area). +Reads board.json from `tools/router/dump_board.py`, writes routes.json for +`tools/router/write_board.py`; the placer links it to route its candidates. +Documentation and lessons: [knowledge/tooling/rust-router.md](../../knowledge/tooling/rust-router.md); end to end on your board: [knowledge/tooling/pnr.md](../../knowledge/tooling/pnr.md). + + cargo build --release + target/release/router route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL] + target/release/router place board.json placement.json moved.json diff --git a/tools/router-rs/src/astar.rs b/tools/router-rs/src/astar.rs new file mode 100644 index 0000000..2be7595 --- /dev/null +++ b/tools/router-rs/src/astar.rs @@ -0,0 +1,320 @@ +//! Grid A* core, 2 layers (port of tools/router/astar.c with the same arithmetic in f32; +//! a radix heap replaces the binary heap, so ties break differently). +//! +//! States are cell * 2 + layer, so both layers of a cell share a cache line. Foreign distance for net X: n1 == X ? d2 : d1. + +use crate::board::Field; + +/// A step "runs alongside" copper within this distance (mm) beyond its clearance. +const HUG_BAND: f32 = 0.15; + +/// A via's conflicts and history weigh like this many track steps. +const VIA_SOFT: f32 = 8.0; + +const DX: [i32; 8] = [1, 1, 0, -1, -1, -1, 0, 1]; +const DY: [i32; 8] = [0, 1, 1, 1, 0, -1, -1, -1]; + +pub struct SearchArgs<'a> { + pub nx: usize, + pub n: usize, + pub f: &'a [Field], + pub padd: &'a [f32], + /// per cell distance to the nearest drill edge; a via needs r_hole + pub hole: &'a [f32], + pub r_hole: f32, + /// steps a path needs between two of its own vias + pub via_gap: u16, + pub cost: &'a [f32], + /// negotiation: a step onto other nets' soft copper costs (base + hist) * (1 + pres) + /// (INFINITY: not allowed); elsewhere base + hist + pub soft: Option<&'a [Field]>, + pub hist: &'a [f32], + pub pres: f32, + pub net: i32, + pub src: &'a [i32], + pub tgt: &'a [u8], + pub goal_layer1: bool, + pub hx: i32, + pub hy: i32, + pub r_nom: f32, + pub r_neck: f32, + pub r_via: f32, + pub r_vpad: f32, + pub r_diag: f32, + pub neckbox: &'a [[i32; 4]], + pub via_cost: f32, + pub via_cmult: f32, + pub bmult: f32, + pub turn_cost: f32, + pub allow_via: bool, + pub max_expand: i64, + pub layer_mask: u8, + /// heuristic weight: 1 is exact A*, more trades path cost for fewer expansions + pub hweight: f32, + /// extra cost per step farther than HUG_BAND from other copper + pub hug: f32, + /// per state distance to the copper of the net's bundle partners (pair, bus), and the + /// extra cost per step farther than HUG_BAND from it + pub attract: Option<&'a [f32]>, + pub attract_cost: f32, + /// a necked step costs 0.3 plus this much per mm of width given up + pub neck: f32, + /// cell window [x0, y0, x1, y1] (inclusive) the search stays in + pub window: [i32; 4], +} + +/// Per-state search data, packed so that one state is one cache access. +#[derive(Clone, Copy, Default)] +struct Node { + g: f32, + par: i32, + stamp: u32, + dir: u8, + closed: bool, + /// steps since the path's last via (its own vias are not in the hole field yet) + since: u16, +} + +/// Radix heap on the f32 bit patterns of non-negative keys. A* pops keys in non-decreasing +/// order (the octile heuristic is consistent: every step costs at least its length), which +/// is all a radix heap needs; push and pop are O(1) amortised instead of a binary heap's +/// cache-missing O(log n). +struct RadixHeap { + last: u32, + len: usize, + buckets: Vec<Vec<(u32, i32)>>, +} + +impl RadixHeap { + fn new() -> RadixHeap { + RadixHeap { last: 0, len: 0, buckets: (0..33).map(|_| Vec::new()).collect() } + } + + fn clear(&mut self) { + self.buckets.iter_mut().for_each(Vec::clear); + self.last = 0; + self.len = 0; + } + + fn bucket(&self, k: u32) -> usize { + (32 - (k ^ self.last).leading_zeros()) as usize + } + + fn push(&mut self, f: f32, i: i32) { + let k = f.max(0.0).to_bits().max(self.last); // a key below the last pop would break the order + let b = self.bucket(k); + self.buckets[b].push((k, i)); + self.len += 1; + } + + fn pop(&mut self) -> i32 { + if self.buckets[0].is_empty() { + let b = (1..33).find(|&b| !self.buckets[b].is_empty()).unwrap(); + let items = std::mem::take(&mut self.buckets[b]); + self.last = items.iter().map(|e| e.0).min().unwrap(); + for &(k, i) in &items { + let nb = self.bucket(k); + self.buckets[nb].push((k, i)); + } + let mut v = items; + v.clear(); + self.buckets[b] = v; + } + self.len -= 1; + self.buckets[0].pop().unwrap().1 + } + + fn is_empty(&self) -> bool { + self.len == 0 + } +} + +pub struct Search { + node: Vec<Node>, + call: u32, + heap: RadixHeap, +} + +#[inline] +fn heur(x: i32, y: i32, hx: i32, hy: i32) -> f32 { + let (ax, ay) = ((x - hx).abs(), (y - hy).abs()); + ax.max(ay) as f32 + 0.414_213_56f32 * ax.min(ay) as f32 +} + +impl Search { + pub fn new(states: usize) -> Search { + Search { node: vec![Node::default(); states], call: 0, heap: RadixHeap::new() } + } + + fn push(&mut self, f: f32, i: i32) { + self.heap.push(f, i); + } + + fn pop(&mut self) -> i32 { + self.heap.pop() + } + + /// Path (target back to source) with neck flags, or None. + pub fn route(&mut self, a: &SearchArgs) -> Option<(Vec<i32>, Vec<u8>)> { + let nx = a.nx as i32; + let fdist = |s: usize| a.f[s].fdist(a.net); + self.call = self.call.wrapping_add(1); + if self.call == 0 { + self.node.iter_mut().for_each(|v| v.stamp = 0); + self.call = 1; + } + let call = self.call; + self.heap.clear(); + let neck_cost = 0.3 + a.neck * 2.0 * (a.r_nom - a.r_neck).max(0.0); + for &s in a.src { + let s = s as usize; + let l = s & 1; + if (a.layer_mask >> l) & 1 == 0 { + continue; + } + if fdist(s) < if a.r_neck > 0.0 { a.r_neck } else { a.r_nom } { + continue; // a track must fit at its start cell + } + self.node[s] = Node { g: 0.0, par: -1, stamp: call, dir: 255, closed: false, since: u16::MAX }; + let c = (s >> 1) as i32; + self.push(if a.goal_layer1 { 0.0 } else { a.hweight * heur(c % nx, c / nx, a.hx, a.hy) }, s as i32); + } + let mut expanded: i64 = 0; + let mut found: i64 = -1; + while !self.heap.is_empty() { + let s = self.pop() as usize; + if self.node[s].closed { + continue; + } + self.node[s].closed = true; + let l = s & 1; + let c = s >> 1; + let (x, y) = ((c % a.nx) as i32, (c / a.nx) as i32); + if a.tgt[s] != 0 || (a.goal_layer1 && l == 1) { + found = s as i64; + break; + } + expanded += 1; + if expanded > a.max_expand { + break; + } + let gcur = self.node[s].g; + let pd = self.node[s].dir; + let since = self.node[s].since; + for d in 0..8usize { + // cheap rejections first: reversals and sharp turns, closed states + let mut turn = 0.0f32; + if pd != 255 && pd as usize != d { + let mut t = (pd as i32 - d as i32).abs(); + if t > 4 { + t = 8 - t; + } + if t >= 3 { + continue; + } + turn = a.turn_cost * t as f32; + } + let (qx, qy) = (x + DX[d], y + DY[d]); + if qx < a.window[0] || qy < a.window[1] || qx > a.window[2] || qy > a.window[3] { + continue; + } + let nc = (qy * nx + qx) as usize; + let ns = nc * 2 + l; + let q = self.node[ns]; + if q.stamp == call && q.closed { + continue; + } + let fd = fdist(ns); + let odd = d & 1 == 1; + let need = a.r_nom + if odd { a.r_diag } else { 0.0 }; + let mut neck = false; + let mut r = need; + if fd < need { + if a.r_neck <= 0.0 { + continue; + } + let needn = a.r_neck + if odd { a.r_diag } else { 0.0 }; + if fd < needn { + continue; + } + if !a.neckbox.iter().any(|b| qx >= b[0] && qx <= b[2] && qy >= b[1] && qy <= b[3]) { + continue; + } + neck = true; + r = needn; + } + let step = if odd { 1.414_213_56f32 } else { 1.0f32 }; + let mut cst = step * if l == 1 { a.bmult } else { 1.0 } + a.cost[ns] * step; + if neck { + cst += neck_cost * step; + } + if a.hug > 0.0 && fd > r + HUG_BAND { + cst += a.hug * step; + } + if let Some(at) = a.attract { + if at[ns] > r + HUG_BAND { + cst += a.attract_cost * step; + } + } + if let Some(sf) = a.soft { + // PathFinder: (base + history) * (1 + present factor on conflict) + cst += a.hist[ns] * step; + if sf[ns].fdist(a.net) < r { + if a.pres == f32::INFINITY { + continue; + } + cst *= 1.0 + a.pres; + } + } + cst += turn; + let ng = gcur + cst; + if q.stamp == call && q.g <= ng { + continue; + } + self.node[ns] = Node { g: ng, par: s as i32, stamp: call, dir: d as u8, closed: false, since: since.saturating_add(1) }; + self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(qx, qy, a.hx, a.hy) }, ns as i32); + } + if a.allow_via && a.layer_mask & 3 == 3 { + let (s0, s1) = (c * 2, c * 2 + 1); + let mut soft_ok = true; + let mut vc = a.via_cost + a.via_cmult * (a.cost[s0] + a.cost[s1]); + if let Some(sf) = a.soft { + let n = (sf[s0].fdist(a.net) < a.r_via) as u32 + (sf[s1].fdist(a.net) < a.r_via) as u32; + soft_ok = n == 0 || a.pres != f32::INFINITY; + vc += VIA_SOFT * (a.hist[s0] + a.hist[s1]); + if n > 0 { + vc *= 1.0 + a.pres * n as f32; + } + } + if soft_ok && since >= a.via_gap && a.hole[c] >= a.r_hole && fdist(s0) >= a.r_via && fdist(s1) >= a.r_via && a.padd[s0] >= a.r_vpad && a.padd[s1] >= a.r_vpad { + let ns = c * 2 + 1 - l; + let ng = gcur + vc; + let q = &mut self.node[ns]; + if !(q.stamp == call && (q.closed || q.g <= ng)) { + *q = Node { g: ng, par: s as i32, stamp: call, dir: 255, closed: false, since: 0 }; + self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(x, y, a.hx, a.hy) }, ns as i32); + } + } + } + } + if std::env::var("ROUTER_TRACE").is_ok() { + eprintln!("EXP {} {}", expanded, found >= 0); + } + if found < 0 { + return None; + } + let (mut out, mut neck) = (Vec::new(), Vec::new()); + let mut s = found as i32; + while s >= 0 && out.len() < 400_000 { + let su = s as usize; + // the same test the search used to enter the cell: a full-width track that + // barely fits must not be drawn necked all along its run + let dd = self.node[su].dir; + let odd = dd != 255 && dd & 1 == 1; + neck.push((fdist(su) < a.r_nom + if odd { a.r_diag } else { 0.0 }) as u8); + out.push(s); + s = self.node[su].par; + } + Some((out, neck)) + } +} diff --git a/tools/router-rs/src/board.rs b/tools/router-rs/src/board.rs new file mode 100644 index 0000000..137b4fa --- /dev/null +++ b/tools/router-rs/src/board.rs @@ -0,0 +1,847 @@ +//! Board model and clearance fields (port of tools/router/pcbroute.py). +//! +//! The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu), with its origin on a +//! multiple of 0.05 mm, so that parts placed on the placer's 0.05 mm grid have their pads on +//! cell centres (an outline at 99.975 put 0.5 mm-pitch pins between two cell rows, where no +//! 0.25 mm neck fits). For every cell, d1/n1 +//! hold the distance to and the net of the nearest copper, d2 the distance to the nearest +//! copper of another net. A track of width w fits where the foreign distance is +//! >= w/2 + CLR. Board edge, NPTH holes and keep-outs are net -1 copper in the static +//! `base` field. Items are kept in insertion order; removal re-inserts the neighbours of the +//! cleared region, as the Python router does, so ties resolve the same way. +//! +//! Footprint copper that is not a pad (`fpcopper`, e.g. a net tie's bridge) is static copper: +//! of its net when it touches pads of one net, else of no net (foreign to every net) with the +//! pads it joins cut out, so that the tie's nets still reach their pads from outside. +//! +//! Negotiated routing (router::negotiate) commits `soft` items: they go into a second field +//! (`soft`), which the search may violate at a cost (`pres` per conflicting step plus the +//! `hist` cost of the cell); everything else is hard. + +use crate::astar::{Search, SearchArgs}; +use crate::geom::{poly_poly, Poly, Pt}; +use crate::io::{BoardJson, FpCopperJson}; +use std::collections::HashMap; + +pub const RES: f64 = 0.05; +pub const CAP: f32 = 1.5; +pub const CLR: f64 = 0.2; +pub const M: f64 = 0.015; // numeric margin on clearance checks +pub const RDIAG: f64 = 0.02; // extra margin on diagonal steps +pub const EDGE_CLR: f64 = 0.5; +pub const HOLE_CLR: f64 = 0.3; +pub const HOLE_HOLE: f64 = 0.25; // drill edge to drill edge, any nets +/// A track may neck down within this distance (mm) of the pad bboxes it joins (default of the +/// `neck_zone` option). +pub const NECK_ZONE: f64 = 1.0; +/// Sample spacing (mm) of footprint copper. +pub const CU_STEP: f64 = 0.025; + +/// Drill of a via of diameter d (as written to the board). +pub fn via_drill(d: f64) -> f64 { + if d >= 0.8 { + 0.4 + } else { + 0.3 + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Shape { + Pad(usize), + Seg(Pt, Pt), + Via(Pt), + /// footprint copper (index into Board::cu) + Cu(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Owner { + Pad, + Existing, + Routed, + /// routed by negotiation (or its cleanup): the cleanup may reroute it + Negotiated, + Waypoint, +} + +#[derive(Clone, Debug)] +pub struct Item { + pub shape: Shape, + pub net: i32, + pub layers: u8, // bit 0 F.Cu, bit 1 B.Cu + pub w: f64, + pub bbox: [f64; 4], + pub owner: Owner, + pub soft: bool, +} + +impl Item { + pub fn on(&self, layer: usize) -> bool { + self.layers >> layer & 1 == 1 + } +} + +pub struct Pad { + pub refdes: String, + pub num: String, + pub net: i32, + pub layers: u8, + pub poly: Poly, + pub x: f64, + pub y: f64, + pub tht: bool, + pub drill: f64, + pub item: usize, +} + +/// Search settings of one connection (pcbroute.Board.route keyword arguments). +#[derive(Clone, Copy, Debug)] +pub struct SearchOpts { + pub via_cost: f64, + pub via_cmult: f64, + pub bmult: f64, + pub turn: f64, + pub allow_via: bool, + pub layer_mask: u8, + pub max_expand: i64, + pub hweight: f64, + /// search only within this margin (mm) around the connection's copper; 0: whole board + pub margin: f64, + /// extra cost per step that does not run alongside other copper (bundles parallel lines) + pub hug: f64, + /// a necked step costs 0.3 plus this much per mm of width given up (the cleanup uses 4: + /// 1.0 -> 0.2 mm costs 3.5 per step, so a net necks only where its width does not fit) + pub neck: f64, + /// a track may neck down within this distance (mm) of the pad bboxes it joins + pub neck_zone: f64, +} + +impl Default for SearchOpts { + fn default() -> Self { + SearchOpts { via_cost: 40.0, via_cmult: 0.0, bmult: 3.0, turn: 4.0, allow_via: true, layer_mask: 3, max_expand: 4_000_000, hweight: 1.0, margin: 0.0, hug: 0.0, neck: 0.0, neck_zone: NECK_ZONE } + } +} + +pub type Seg = (usize, Pt, Pt, f64); // layer, a, b, width + +/// Clearance field of one state: distance to and net of the nearest copper (d1, n1) and +/// distance to the nearest copper of another net (d2). +#[derive(Clone, Copy, Debug)] +pub struct Field { + pub d1: f32, + pub n1: i32, + pub d2: f32, +} + +impl Field { + pub const EMPTY: Field = Field { d1: CAP, n1: 0, d2: CAP }; + + /// Distance to copper of a net other than `net`. + #[inline] + pub fn fdist(&self, net: i32) -> f32 { + if self.n1 == net { + self.d2 + } else { + self.d1 + } + } + + #[inline] + fn add(&mut self, dd: f32, net: i32) { + if self.n1 == net { + self.d1 = self.d1.min(dd); + } else if dd < self.d1 { + self.d2 = self.d1; + self.d1 = dd; + self.n1 = net; + } else { + self.d2 = self.d2.min(dd); + } + } +} + +pub struct Board { + /// grid extent (origin snapped to the grid) + pub x0: f64, + pub y0: f64, + pub x1: f64, + pub y1: f64, + /// the board outline's bounds, for the edge clearance + edge: [f64; 4], + pub nx: usize, + pub ny: usize, + pub n: usize, + pub f: Vec<Field>, + pub padd: Vec<f32>, + pub soft: Vec<Field>, + pub hist: Vec<f32>, + /// commit soft items and price soft conflicts (`pres` = INFINITY: soft copper is hard) + pub soft_mode: bool, + pub pres: f32, + pub costs: HashMap<String, Vec<f32>>, + pub cost: String, + /// owner of committed routes + pub commit_owner: Owner, + base: Vec<f32>, // one layer; both layers share it + pub pads: Vec<Pad>, + pub items: Vec<Item>, + pub alive: Vec<bool>, + pub netid: HashMap<String, i32>, + pub netnames: Vec<String>, // by net id; id 0 is unused, -1 is "" + npth: Vec<(f64, f64, f64)>, + /// per cell: distance to the nearest drill edge (pads, NPTH, vias of any net) + pub hole: Vec<f32>, + hole_base: Vec<f32>, + keepouts: Vec<Poly>, + /// bundle attraction (cleanup): per state distance to the partners' copper, and its cost + attract: Vec<f32>, + attract_cost: f32, + /// routing area (route.toml `area`): copper stays `area_margin` inside the union + area: Vec<Poly>, + area_margin: f64, + /// footprint copper as sample points (spacing CU_STEP) inside its outline + pub cu: Vec<Vec<Pt>>, + tgt: Vec<u8>, + search: Search, +} + +impl Board { + pub fn new(d: &BoardJson, plane_nets: &[String], area: Vec<Poly>, area_margin: f64) -> Board { + let [bx0, by0, x1, y1] = d.bounds; + // the grid's origin on a multiple of RES (exact multiples stay) + let snap = |v: f64| if ((v / RES).round() * RES - v).abs() < 1e-9 { v } else { (v / RES).floor() * RES }; + let (x0, y0) = (snap(bx0), snap(by0)); + let nx = ((x1 - x0) / RES - 1e-6).ceil() as usize + 1; + let ny = ((y1 - y0) / RES - 1e-6).ceil() as usize + 1; + let n = nx * ny; + let mut b = Board { + x0, + y0, + x1, + y1, + edge: d.bounds, + nx, + ny, + n, + f: vec![Field::EMPTY; 2 * n], + padd: vec![CAP; 2 * n], + soft: vec![Field::EMPTY; 2 * n], + hist: vec![0.0; 2 * n], + soft_mode: false, + pres: 0.0, + costs: HashMap::from([("none".to_string(), vec![0.0; 2 * n])]), + cost: "none".into(), + commit_owner: Owner::Routed, + base: vec![CAP; n], + pads: Vec::new(), + items: Vec::new(), + alive: Vec::new(), + netid: HashMap::new(), + netnames: vec![String::new()], + npth: Vec::new(), + keepouts: d.keepouts.iter().map(|k| Poly::new(k.iter().map(|p| (p[0], p[1])).collect())).collect(), + area, + area_margin, + attract: Vec::new(), + attract_cost: 0.0, + cu: Vec::new(), + tgt: vec![0; 2 * n], + hole: vec![CAP; n], + hole_base: vec![CAP; n], + search: Search::new(2 * n), + }; + for p in &d.pads { + let layers = (p.f.is_some() as u8) | (p.b.is_some() as u8) << 1; + if layers == 0 { + continue; + } + let net = if p.net.is_empty() || p.net.starts_with("unconnected") { + -1 + } else { + match b.netid.get(&p.net) { + Some(&k) => k, + None => { + let k = b.netnames.len() as i32; + b.netid.insert(p.net.clone(), k); + b.netnames.push(p.net.clone()); + k + } + } + }; + let pts = p.f.as_ref().or(p.b.as_ref()).unwrap(); + b.pads.push(Pad { + refdes: p.refdes.clone(), + num: p.num.clone(), + net, + layers, + poly: Poly::new(pts.iter().map(|q| (q[0], q[1])).collect()), + x: p.x, + y: p.y, + tht: layers == 3, + drill: p.drill, + item: usize::MAX, + }); + } + b.npth = d.pads.iter().filter(|p| p.npth).map(|p| (p.x, p.y, p.drill)).collect(); + b.build_static(plane_nets); + for c in &d.fpcopper { + b.add_fpcopper(c); + } + let holes: Vec<(f64, f64, f64)> = b.pads.iter().filter(|p| p.tht && p.drill > 0.0).map(|p| (p.x, p.y, p.drill / 2.0)).chain(b.npth.iter().map(|h| (h.0, h.1, h.2 / 2.0))).collect(); + for (x, y, r) in holes { + b.hole_min(x, y, r, true); + } + b.hole.clone_from(&b.hole_base); + b + } + + /// Footprint copper as a static item: the net of the pads it touches if they share one, + /// else no net with those pads cut out (a net tie's bridge). + fn add_fpcopper(&mut self, c: &FpCopperJson) { + let l = if c.layer == "B" { 1 } else { 0 }; + let poly = Poly::new(c.poly.iter().map(|p| (p[0], p[1])).collect()); + let touch: Vec<usize> = (0..self.pads.len()) + .filter(|&k| self.pads[k].refdes == c.refdes && self.pads[k].layers >> l & 1 == 1 && poly_poly(&self.pads[k].poly, &poly) <= 1e-6) + .collect(); + let mut nets: Vec<i32> = touch.iter().map(|&k| self.pads[k].net).collect(); + nets.sort(); + nets.dedup(); + let (net, cut) = if nets.len() == 1 { (nets[0], vec![]) } else { (-1, touch) }; + let bb = poly.bbox; + let mut pts = Vec::new(); + let mut y = bb[1] + CU_STEP / 2.0; + while y < bb[3] { + let mut x = bb[0] + CU_STEP / 2.0; + while x < bb[2] { + if poly.contains((x, y)) && cut.iter().all(|&k| self.pads[k].poly.dist((x, y)) > CU_STEP / 2.0) { + pts.push((x, y)); + } + x += CU_STEP; + } + y += CU_STEP; + } + if pts.is_empty() { + return; + } + let h = CU_STEP / 2.0; + let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for &(x, y) in &pts { + b = [b[0].min(x - h), b[1].min(y - h), b[2].max(x + h), b[3].max(y + h)]; + } + self.cu.push(pts); + let k = self.cu.len() - 1; + self.add(Item { shape: Shape::Cu(k), net, layers: 1 << l, w: 0.0, bbox: b, owner: Owner::Pad, soft: false }); + } + + pub fn netname(&self, net: i32) -> &str { + if net < 0 { + "" + } else { + &self.netnames[net as usize] + } + } + + pub fn cell_xy(&self, i: usize, j: usize) -> Pt { + (self.x0 + i as f64 * RES, self.y0 + j as f64 * RES) + } + + pub fn xy_cell(&self, x: f64, y: f64) -> (i64, i64) { + (((x - self.x0) / RES).round_ties_even() as i64, ((y - self.y0) / RES).round_ties_even() as i64) + } + + fn gx(&self, i: usize) -> f64 { + self.x0 + i as f64 * RES + } + + fn gy(&self, j: usize) -> f64 { + self.y0 + j as f64 * RES + } + + /// Cell window (inclusive) covering bbox b grown by `pad`, clipped to the grid. + pub fn window(&self, b: &[f64; 4], pad: f64) -> (usize, usize, usize, usize) { + let i0 = ((b[0] - pad - self.x0) / RES).floor().max(0.0) as usize; + let j0 = ((b[1] - pad - self.y0) / RES).floor().max(0.0) as usize; + let i1 = (((b[2] + pad - self.x0) / RES).ceil() as i64).min(self.nx as i64 - 1); + let j1 = (((b[3] + pad - self.y0) / RES).ceil() as i64).min(self.ny as i64 - 1); + (i0, j0, i1.max(-1) as usize, j1.max(-1) as usize) + } + + fn build_static(&mut self, plane_nets: &[String]) { + let (nx, ny) = (self.nx, self.ny); + let mut base = vec![0.0f64; self.n]; + for j in 0..ny { + for i in 0..nx { + let (x, y) = (self.gx(i), self.gy(j)); + let e = self.edge; + base[j * nx + i] = (x - e[0]).min(e[2] - x).min(y - e[1]).min(e[3] - y) - (EDGE_CLR - CLR); + } + } + // routing area: outside it is no-net copper, like the board edge (signed distance to + // the union, approximated by the deepest containing polygon) + if !self.area.is_empty() { + for j in 0..ny { + for i in 0..nx { + let p = (self.gx(i), self.gy(j)); + let inside = self.area.iter().filter(|a| a.contains(p)).map(|a| a.boundary_dist(p)).fold(f64::NEG_INFINITY, f64::max); + let d = if inside.is_finite() { inside } else { -self.area.iter().map(|a| a.dist(p)).fold(f64::INFINITY, f64::min) }; + let c = &mut base[j * nx + i]; + *c = c.min(d - (self.area_margin - CLR)); + } + } + } + // values >= CAP do not matter (the fields are capped), so holes and keep-outs only + // need a window around them + for &(x, y, dr) in &self.npth.clone() { + let r = dr / 2.0 + HOLE_CLR; + let (i0, j0, i1, j1) = self.window(&[x, y, x, y], r + 2.0); + for j in j0..=j1 { + for i in i0..=i1 { + let v = (self.gx(i) - x).hypot(self.gy(j) - y) - r + CLR; + let c = &mut base[j * nx + i]; + *c = c.min(v); + } + } + } + for k in 0..self.keepouts.len() { + let bb = self.keepouts[k].bbox; + let (i0, j0, i1, j1) = self.window(&bb, 2.0); + for j in j0..=j1 { + for i in i0..=i1 { + let v = self.keepouts[k].dist((self.gx(i), self.gy(j))) + CLR; + let c = &mut base[j * nx + i]; + *c = c.min(v); + } + } + } + for (k, v) in base.iter().enumerate() { + self.base[k] = *v as f32; + } + self.reset_region(None); + // pad distance field for via-in-pad avoidance (SMD pads, not exposed plane pads) + for k in 0..self.pads.len() { + let p = &self.pads[k]; + if p.tht { + continue; + } + let b = p.poly.bbox; + if b[2] - b[0] > 2.5 && b[3] - b[1] > 2.5 && p.net >= 0 && plane_nets.iter().any(|n| n == self.netname(p.net)) { + continue; + } + let (i0, j0, i1, j1) = self.window(&b, 1.0); + for j in j0..=j1 { + for i in i0..=i1 { + let dd = p.poly.dist((self.gx(i), self.gy(j))) as f32; + for l in 0..2 { + if p.layers >> l & 1 == 1 { + let c = &mut self.padd[(j * nx + i) * 2 + l]; + *c = c.min(dd); + } + } + } + } + } + for k in 0..self.pads.len() { + let p = &self.pads[k]; + let it = Item { shape: Shape::Pad(k), net: p.net, layers: p.layers, w: 0.0, bbox: p.poly.bbox, owner: Owner::Pad, soft: false }; + let id = self.add(it); + self.pads[k].item = id; + } + } + + /// Append an item and insert it into the fields; returns its id. + pub fn add(&mut self, it: Item) -> usize { + self.items.push(it); + self.alive.push(true); + let id = self.items.len() - 1; + self.insert(id, None); + if let Shape::Via(p) = self.items[id].shape { + self.hole_min(p.0, p.1, via_drill(self.items[id].w) / 2.0, false); + } + id + } + + /// Lower the hole field (or its static base) around a drill of radius r at (x, y). + fn hole_min(&mut self, x: f64, y: f64, r: f64, base: bool) { + let (i0, j0, i1, j1) = self.window(&[x, y, x, y], r + 1.0); + for j in j0..=j1 { + for i in i0..=i1 { + let d = ((self.gx(i) - x).hypot(self.gy(j) - y) - r) as f32; + let c = if base { &mut self.hole_base[j * self.nx + i] } else { &mut self.hole[j * self.nx + i] }; + *c = c.min(d); + } + } + } + + /// Rebuild the hole field around (x, y) after a via there was removed. + fn hole_reset(&mut self, x: f64, y: f64) { + let (i0, j0, i1, j1) = self.window(&[x, y, x, y], 2.5); + for j in j0..=j1 { + for i in i0..=i1 { + self.hole[j * self.nx + i] = self.hole_base[j * self.nx + i]; + } + } + for o in 0..self.items.len() { + if let (true, Shape::Via(p)) = (self.alive[o], self.items[o].shape) { + if (p.0 - x).abs() < 4.0 && (p.1 - y).abs() < 4.0 { + let r = via_drill(self.items[o].w) / 2.0; + let (k0, l0, k1, l1) = self.window(&[p.0, p.1, p.0, p.1], r + 1.0); + for j in l0.max(j0)..=l1.min(j1) { + for i in k0.max(i0)..=k1.min(i1) { + let d = ((self.gx(i) - p.0).hypot(self.gy(j) - p.1) - r) as f32; + let c = &mut self.hole[j * self.nx + i]; + *c = c.min(d); + } + } + } + } + } + } + + /// Attract the following searches to the copper of `items` (a net's bundle partners): + /// a step farther than the hug band from it costs `cost` more. Distances are exact within + /// ATTRACT_R of the items, CAP beyond. `cost` 0 switches it off. + pub fn set_attract(&mut self, items: &[usize], cost: f64) { + const ATTRACT_R: f64 = 1.5; + self.attract_cost = cost as f32; + if cost <= 0.0 { + return; + } + self.attract.clear(); + self.attract.resize(2 * self.n, CAP); + for &id in items { + let it = &self.items[id]; + let (i0, j0, i1, j1) = self.window(&it.bbox, ATTRACT_R); + for j in j0..=j1 { + for i in i0..=i1 { + let d = self.item_dist(it, self.gx(i), self.gy(j)); + for l in 0..2 { + if it.on(l) { + let a = &mut self.attract[(j * self.nx + i) * 2 + l]; + *a = a.min(d); + } + } + } + } + } + } + + pub fn reset_region(&mut self, b: Option<&[f64; 4]>) { + self.reset(b, false) + } + + fn reset(&mut self, b: Option<&[f64; 4]>, soft: bool) { + let (i0, j0, i1, j1) = match b { + None => (0, 0, self.nx - 1, self.ny - 1), + Some(b) => self.window(b, 0.0), + }; + for l in 0..2 { + for j in j0..=j1 { + for i in i0..=i1 { + let c = j * self.nx + i; + if soft { + self.soft[c * 2 + l] = Field::EMPTY; + } else { + let bd = self.base[c]; + self.f[c * 2 + l] = Field { d1: bd.min(CAP), n1: if bd < CAP { -1 } else { 0 }, d2: CAP }; + } + } + } + } + } + + /// Move all soft items into the hard field (after negotiation). + pub fn harden(&mut self) { + let ids: Vec<usize> = (0..self.items.len()).filter(|&i| self.alive[i] && self.items[i].soft).collect(); + for &id in &ids { + self.items[id].soft = false; + self.insert(id, None); + } + self.reset(None, true); + } + + /// Distance from (x, y) to an item's copper (f64 as in numpy, then f32). + pub fn item_dist(&self, it: &Item, x: f64, y: f64) -> f32 { + match it.shape { + Shape::Pad(k) => self.pads[k].poly.dist((x, y)) as f32, + Shape::Seg((x1, y1), (x2, y2)) => { + let (dx, dy) = (x2 - x1, y2 - y1); + let l2 = dx * dx + dy * dy; + let t = if l2 == 0.0 { 0.0 } else { (((x - x1) * dx + (y - y1) * dy) / l2).clamp(0.0, 1.0) }; + ((x - (x1 + t * dx)).hypot(y - (y1 + t * dy)) - it.w / 2.0) as f32 + } + Shape::Via((vx, vy)) => ((x - vx).hypot(y - vy) - it.w / 2.0) as f32, + Shape::Cu(k) => (self.cu[k].iter().map(|p| (x - p.0).hypot(y - p.1)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0) as f32, + } + } + + fn insert(&mut self, id: usize, clip: Option<&[f64; 4]>) { + let it = self.items[id].clone(); + let b = it.bbox; + let (i0, j0, i1, j1) = match clip { + Some(c) => { + let b2 = [(b[0] - CAP as f64).max(c[0]), (b[1] - CAP as f64).max(c[1]), (b[2] + CAP as f64).min(c[2]), (b[3] + CAP as f64).min(c[3])]; + if b2[0] > b2[2] || b2[1] > b2[3] { + return; + } + self.window(&b2, 0.0) + } + None => self.window(&b, CAP as f64), + }; + let net = it.net; + let field = if it.soft { &mut self.soft } else { &mut self.f }; + for j in j0..=j1 { + for i in i0..=i1 { + let (x, y) = (self.x0 + i as f64 * RES, self.y0 + j as f64 * RES); + let dd = match it.shape { + Shape::Pad(k) => self.pads[k].poly.dist((x, y)) as f32, + Shape::Seg((x1, y1), (x2, y2)) => { + let (dx, dy) = (x2 - x1, y2 - y1); + let l2 = dx * dx + dy * dy; + let t = if l2 == 0.0 { 0.0 } else { (((x - x1) * dx + (y - y1) * dy) / l2).clamp(0.0, 1.0) }; + ((x - (x1 + t * dx)).hypot(y - (y1 + t * dy)) - it.w / 2.0) as f32 + } + Shape::Via((vx, vy)) => ((x - vx).hypot(y - vy) - it.w / 2.0) as f32, + Shape::Cu(k) => (self.cu[k].iter().map(|p| (x - p.0).hypot(y - p.1)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0) as f32, + }; + for l in 0..2 { + if !it.on(l) { + continue; + } + field[(j * self.nx + i) * 2 + l].add(dd, net); + } + } + } + } + + pub fn remove_items(&mut self, ids: &[usize]) { + for &id in ids { + self.alive[id] = false; + } + let c = CAP as f64; + for &id in ids { + let ib = self.items[id].bbox; + let soft = self.items[id].soft; + let b = [ib[0] - c, ib[1] - c, ib[2] + c, ib[3] + c]; + self.reset(Some(&b), soft); + for o in 0..self.items.len() { + if !self.alive[o] || self.items[o].soft != soft { + continue; + } + let ob = self.items[o].bbox; + if ob[0] - c > b[2] || ob[2] + c < b[0] || ob[1] - c > b[3] || ob[3] + c < b[1] { + continue; + } + self.insert(o, Some(&b)); + } + if let Shape::Via(p) = self.items[id].shape { + self.hole_reset(p.0, p.1); + } + } + } + + /// Distance to foreign copper for `net` at state index s. + pub fn fdist(&self, s: usize, net: i32) -> f32 { + self.f[s].fdist(net) + } + + /// Grid states (cell * 2 + layer, sorted) covered by the copper of `ids` on `layers`. + pub fn cells_of(&self, ids: &[usize], layers: u8) -> Vec<i32> { + let mut out = Vec::new(); + for &id in ids { + let it = &self.items[id]; + let (i0, j0, i1, j1) = self.window(&it.bbox, 0.05); + for j in j0..=j1 { + for i in i0..=i1 { + if self.item_dist(it, self.gx(i), self.gy(j)) <= 0.0 { + for l in 0..2 { + if it.on(l) && layers >> l & 1 == 1 { + out.push(((j * self.nx + i) * 2 + l) as i32); + } + } + } + } + } + } + out.sort_unstable(); + out.dedup(); + out + } + + /// A* from the copper of `src` to the copper of `tgt` (and `extra_tgt` cells, or any + /// B.Cu cell with `goal_layer1`). Returns the cell path (source first) and neck flags. + #[allow(clippy::too_many_arguments)] + pub fn route( + &mut self, + net: i32, + src: &[usize], + tgt: &[usize], + goal_layer1: bool, + w: f64, + wneck: f64, + via_d: f64, + neck_items: &[usize], + hxy: Option<Pt>, + extra_tgt: Option<&[i32]>, + o: &SearchOpts, + ) -> Option<(Vec<i32>, Vec<u8>)> { + let src_cells = self.cells_of(src, 3); + if src_cells.is_empty() { + return None; + } + let mut tc = if tgt.is_empty() { Vec::new() } else { self.cells_of(tgt, 3) }; + if let Some(e) = extra_tgt { + tc.extend_from_slice(e); + } + for &c in &tc { + self.tgt[c as usize] = 1; + } + let hxy = hxy.unwrap_or_else(|| match tgt.first() { + Some(&g) => match self.items[g].shape { + Shape::Pad(k) => self.pads[k].poly.centroid(), + Shape::Via(p) => p, + Shape::Seg(a, _) => a, + Shape::Cu(k) => self.cu[k][0], + }, + None => (self.x0, self.y0), + }); + let (hx, hy) = self.xy_cell(hxy.0, hxy.1); + let mut boxes = Vec::new(); + for &id in neck_items { + let b = self.items[id].bbox; + let (i0, j0) = self.xy_cell(b[0] - o.neck_zone, b[1] - o.neck_zone); + let (i1, j1) = self.xy_cell(b[2] + o.neck_zone, b[3] + o.neck_zone); + boxes.push([i0 as i32, j0 as i32, i1 as i32, j1 as i32]); + } + let mut window = [0, 0, self.nx as i32 - 1, self.ny as i32 - 1]; + if o.margin > 0.0 && !tgt.is_empty() { + let mut bb = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for &id in src.iter().chain(tgt) { + let b = self.items[id].bbox; + bb = [bb[0].min(b[0]), bb[1].min(b[1]), bb[2].max(b[2]), bb[3].max(b[3])]; + } + let (i0, j0, i1, j1) = self.window(&bb, o.margin); + window = [i0 as i32, j0 as i32, i1 as i32, j1 as i32]; + } + let args = SearchArgs { + window, + nx: self.nx, + n: self.n, + f: &self.f, + padd: &self.padd, + hole: &self.hole, + r_hole: (via_drill(via_d) / 2.0 + HOLE_HOLE + M) as f32, + via_gap: ((via_drill(via_d) + HOLE_HOLE) / RES).ceil() as u16 + 1, + cost: &self.costs[&self.cost], + soft: if self.soft_mode { Some(&self.soft) } else { None }, + hist: &self.hist, + pres: self.pres, + net, + src: &src_cells, + tgt: &self.tgt, + goal_layer1, + hx: hx as i32, + hy: hy as i32, + r_nom: (w / 2.0 + CLR + M) as f32, + r_neck: if wneck != 0.0 { (wneck / 2.0 + CLR + M) as f32 } else { 0.0 }, + r_via: (via_d / 2.0 + CLR + M) as f32, + r_vpad: (via_d / 2.0 + 0.05) as f32, + r_diag: RDIAG as f32, + neckbox: &boxes, + via_cost: o.via_cost as f32, + via_cmult: o.via_cmult as f32, + bmult: o.bmult as f32, + turn_cost: o.turn as f32, + allow_via: o.allow_via, + max_expand: o.max_expand, + layer_mask: o.layer_mask, + hweight: o.hweight as f32, + hug: o.hug as f32, + attract: if self.attract_cost > 0.0 { Some(&self.attract) } else { None }, + attract_cost: self.attract_cost, + neck: o.neck as f32, + }; + let t = std::time::Instant::now(); + let r = self.search.route(&args); + if std::env::var("ROUTER_TRACE").is_ok() { + eprintln!("ASTAR {:.6}", t.elapsed().as_secs_f64()); + } + if std::env::var("ROUTER_TRACE").is_ok() { + eprintln!("TRACE net={} src={} tgt={} first={:?} last={:?} hx={} hy={} len={:?}", net, src_cells.len(), tc.len(), src_cells.first(), src_cells.last(), hx, hy, r.as_ref().map(|(p, _)| (p.len(), p[p.len() - 1], p[0]))); + } + for &c in &tc { + self.tgt[c as usize] = 0; + } + r.map(|(mut p, mut nk)| { + p.reverse(); + nk.reverse(); + (p, nk) + }) + } + + /// Cell path to segments (collinear steps of equal width merged) and vias. + pub fn path_to_geom(&self, path: &[i32], neck: &[u8], w: f64, wneck: f64) -> (Vec<Seg>, Vec<Pt>) { + let pts: Vec<(usize, usize, usize, bool)> = path + .iter() + .zip(neck) + .map(|(&s, &nk)| { + let (l, c) = (s as usize & 1, s as usize >> 1); + (l, c % self.nx, c / self.nx, nk != 0) + }) + .collect(); + let width = |a: &(usize, usize, usize, bool), b: &(usize, usize, usize, bool)| if wneck != 0.0 && (a.3 || b.3) { wneck } else { w }; + let mut segs = Vec::new(); + let mut vias = Vec::new(); + let flush = |run: &[(usize, usize, usize, bool)], segs: &mut Vec<Seg>| { + if run.len() < 2 { + return; + } + let mut k = 0; + while k < run.len() - 1 { + let (l, i, j, _) = run[k]; + let wd = width(&run[k], &run[k + 1]); + let d = (run[k + 1].1 as i64 - i as i64, run[k + 1].2 as i64 - j as i64); + let mut m = k + 1; + while m < run.len() - 1 { + let w2 = width(&run[m], &run[m + 1]); + if (run[m + 1].1 as i64 - run[m].1 as i64, run[m + 1].2 as i64 - run[m].2 as i64) != d || w2 != wd { + break; + } + m += 1; + } + segs.push((l, self.cell_xy(i, j), self.cell_xy(run[m].1, run[m].2), wd)); + k = m; + } + }; + let mut run = vec![pts[0]]; + for &p in &pts[1..] { + if p.0 != run[run.len() - 1].0 { + flush(&run, &mut segs); + vias.push(self.cell_xy(p.1, p.2)); + run = vec![p]; + } else { + run.push(p); + } + } + flush(&run, &mut segs); + (segs, vias) + } + + pub fn seg_item(net: i32, l: usize, a: Pt, b: Pt, w: f64, owner: Owner) -> Item { + let bbox = [a.0.min(b.0) - w / 2.0, a.1.min(b.1) - w / 2.0, a.0.max(b.0) + w / 2.0, a.1.max(b.1) + w / 2.0]; + Item { shape: Shape::Seg(a, b), net, layers: 1 << l, w, bbox, owner, soft: false } + } + + pub fn via_item(net: i32, p: Pt, d: f64, layers: u8, owner: Owner) -> Item { + let r = d / 2.0; + Item { shape: Shape::Via(p), net, layers, w: d, bbox: [p.0 - r, p.1 - r, p.0 + r, p.1 + r], owner, soft: false } + } + + pub fn commit(&mut self, net: i32, segs: &[Seg], vias: &[Pt], via_d: f64) -> Vec<usize> { + let o = self.commit_owner; + let mut items: Vec<Item> = segs.iter().map(|&(l, a, b, w)| Board::seg_item(net, l, a, b, w, o)).collect(); + items.extend(vias.iter().map(|&v| Board::via_item(net, v, via_d, 3, o))); + let soft = self.soft_mode; + items.into_iter().map(|it| self.add(Item { soft, ..it })).collect() + } +} diff --git a/tools/router-rs/src/cleanup.rs b/tools/router-rs/src/cleanup.rs new file mode 100644 index 0000000..d3ed3bc --- /dev/null +++ b/tools/router-rs/src/cleanup.rs @@ -0,0 +1,408 @@ +//! Cleanup after negotiation: reroute each net with the rest fixed (hugging other copper, +//! kept only if it is no worse), drop vias that connect nothing, pull chains of track tight. +//! Only negotiated copper (Owner::Negotiated) is touched. + +use crate::board::{Item, Owner, Shape, CLR, M, RES}; +use crate::geom::{point_seg, Pt}; +use crate::router::Router; +use serde_json::json; +use std::collections::HashMap; + +/// Vias count like this much track length (mm) when comparing two routes of a net. +const VIA_MM: f64 = 2.0; +/// Necked track (narrower than the net's width) counts this much extra per mm. +const NECK_MM: f64 = 2.0; + +impl Router { + fn negotiated(&self, net: i32) -> Vec<usize> { + self.net_items[net as usize].iter().copied().filter(|&id| self.b.alive[id] && self.b.items[id].owner == Owner::Negotiated).collect() + } + + /// (pieces, vias, track length + NECK_MM x necked length) of a net's copper. + fn net_score(&self, net: i32) -> (usize, usize, f64) { + let pieces = self.components(&self.net_items_all(net)).len(); + let (mut vias, mut len) = (0, 0.0); + for &id in &self.net_items[net as usize] { + match self.b.items[id].shape { + Shape::Via(_) => vias += 1, + Shape::Seg(a, b) => len += (a.0 - b.0).hypot(a.1 - b.1), + Shape::Pad(_) | Shape::Cu(_) => {} + } + } + (pieces, vias, len + NECK_MM * self.net_necked_mm(net)) + } + + fn take(&mut self, net: i32, ids: &[usize]) -> Vec<Item> { + let items: Vec<Item> = ids.iter().map(|&id| self.b.items[id].clone()).collect(); + self.net_items[net as usize].retain(|id| !ids.contains(id)); + self.b.remove_items(ids); + items + } + + fn put(&mut self, net: i32, items: Vec<Item>) -> Vec<usize> { + let ids: Vec<usize> = items.into_iter().map(|it| self.b.add(it)).collect(); + self.net_items[net as usize].extend_from_slice(&ids); + ids + } + + /// Reroute every negotiated net once with all other copper fixed (hugging other copper, + /// necks priced by the width they give up). + fn reroute_pass(&mut self, hug: f64, neck: f64, attract: f64) -> (usize, usize) { + let jobs = self.jobs.clone(); + let (mut tried, mut kept) = (0, 0); + for j in jobs.iter().filter(|j| !j.plane) { + let net = self.nid(&j.name); + let old_ids = self.negotiated(net); + if old_ids.is_empty() { + continue; + } + tried += 1; + let before = self.net_score(net); + let failed = self.failed.clone(); + let old = self.take(net, &old_ids); + let mut j2 = j.clone(); + j2.opts.hug = Some(hug); + j2.opts.neck = Some(neck); + for jn in &mut j2.joins { + jn.3.hug = Some(hug); + jn.3.neck = Some(neck); + } + // bundled nets run alongside their partners' copper where they can + self.attract_partners(net, attract); + self.route_job(&j2, Some(&[])); + self.b.set_attract(&[], 0.0); + let after = self.net_score(net); + let score = |s: (usize, usize, f64)| s.2 + VIA_MM * s.1 as f64; + if after.0 > before.0 || score(after) > score(before) * 1.02 { + let new_ids = self.negotiated(net); + self.take(net, &new_ids); + self.put(net, old); + self.failed = failed; + } else { + kept += 1; + } + } + (tried, kept) + } + + /// Remove negotiated vias whose removal leaves the net in as many pieces. + fn drop_vias(&mut self) -> usize { + let mut n = 0; + for net in 1..self.b.netnames.len() as i32 { + if self.plane_nets.iter().any(|p| p == self.b.netname(net)) { + continue; + } + for id in self.negotiated(net) { + if !matches!(self.b.items[id].shape, Shape::Via(_)) { + continue; + } + let before = self.components(&self.net_items_all(net)).len(); + let it = self.take(net, &[id]); + if self.components(&self.net_items_all(net)).len() > before { + self.put(net, it); + } else { + n += 1; + } + } + } + n + } + + /// Does a track of width w from a to b on layer l keep its clearance to other nets? + /// The field is sampled every RES/2; each sample allows for its distance to the cell + /// centre and for the gap to the next sample, so the test is conservative. + fn track_clear(&self, net: i32, l: usize, a: Pt, b: Pt, w: f64) -> bool { + let len = (b.0 - a.0).hypot(b.1 - a.1); + let n = (len / (RES / 2.0)).ceil().max(1.0) as usize; + for k in 0..=n { + let t = k as f64 / n as f64; + let p = (a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1)); + let (i, j) = self.b.xy_cell(p.0, p.1); + if i < 0 || j < 0 || i >= self.b.nx as i64 || j >= self.b.ny as i64 { + return false; + } + let c = self.b.cell_xy(i as usize, j as usize); + let off = (c.0 - p.0).hypot(c.1 - p.1) + RES / 4.0; + let fd = self.b.f[(j as usize * self.b.nx + i as usize) * 2 + l].fdist(net) as f64; + if fd < w / 2.0 + CLR + M + off { + return false; + } + } + true + } + + /// Octilinear link from a to b (straight, 45 degrees, or a straight and a diagonal leg) + /// that keeps clearance, as its points. + fn link(&self, net: i32, l: usize, a: Pt, b: Pt, w: f64) -> Option<Vec<Pt>> { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + if dx.abs() < 1e-9 || dy.abs() < 1e-9 || (dx.abs() - dy.abs()).abs() < 1e-9 { + return self.track_clear(net, l, a, b, w).then(|| vec![a, b]); + } + let d = dx.abs().min(dy.abs()); + let (sx, sy) = (dx.signum() * d, dy.signum() * d); + for c in [(a.0 + sx, a.1 + sy), (b.0 - sx, b.1 - sy)] { + if self.track_clear(net, l, a, c, w) && self.track_clear(net, l, c, b, w) { + return Some(vec![a, c, b]); + } + } + None + } + + /// Split negotiated tracks where other copper of the net ends on them, so every joint is + /// a track end. + fn split_at_joints(&mut self, net: i32) { + let mut pts: Vec<Pt> = Vec::new(); + for &id in &self.net_items[net as usize] { + match self.b.items[id].shape { + Shape::Seg(a, b) => pts.extend([a, b]), + Shape::Via(p) => pts.push(p), + Shape::Pad(_) | Shape::Cu(_) => {} + } + } + for id in self.negotiated(net) { + let it = self.b.items[id].clone(); + let Shape::Seg(a, b) = it.shape else { continue }; + let near = |p: &Pt, q: Pt| (p.0 - q.0).hypot(p.1 - q.1) < 1e-6; + let mut cut: Vec<(f64, Pt)> = pts + .iter() + .filter(|p| !near(p, a) && !near(p, b) && point_seg(**p, a, b) < 1e-6) + .map(|&p| ((p.0 - a.0).hypot(p.1 - a.1), p)) + .collect(); + if cut.is_empty() { + continue; + } + cut.sort_by(|x, y| x.0.total_cmp(&y.0)); + cut.dedup_by(|x, y| (x.0 - y.0).abs() < 1e-6); + let mut chain = vec![a]; + chain.extend(cut.into_iter().map(|c| c.1)); + chain.push(b); + self.take(net, &[id]); + let l = if it.on(0) { 0 } else { 1 }; + let pieces = chain.windows(2).map(|s| crate::board::Board::seg_item(net, l, s[0], s[1], it.w, Owner::Negotiated)).collect(); + self.put(net, pieces); + } + } + + /// Chains of negotiated tracks between fixed points (vias, pads, junctions, changes of + /// layer or width), as item ids and points. + fn chains(&self, net: i32) -> Vec<(Vec<usize>, Vec<Pt>)> { + let key = |p: Pt| ((p.0 * 1e5).round() as i64, (p.1 * 1e5).round() as i64); + let segs = self.negotiated(net).into_iter().filter(|&id| matches!(self.b.items[id].shape, Shape::Seg(..))).collect::<Vec<_>>(); + let mut at: HashMap<(i64, i64), Vec<usize>> = HashMap::new(); + for &id in &segs { + if let Shape::Seg(a, b) = self.b.items[id].shape { + at.entry(key(a)).or_default().push(id); + at.entry(key(b)).or_default().push(id); + } + } + // degree counts every track end of the net, not only negotiated ones + let mut deg: HashMap<(i64, i64), usize> = HashMap::new(); + let mut vias = Vec::new(); + for &id in &self.net_items[net as usize] { + match self.b.items[id].shape { + Shape::Seg(a, b) => { + *deg.entry(key(a)).or_default() += 1; + *deg.entry(key(b)).or_default() += 1; + } + Shape::Via(p) => vias.push(p), + Shape::Pad(_) | Shape::Cu(_) => {} + } + } + let pads: Vec<usize> = self.pads_by_net[net as usize].clone(); + let fixed = |p: Pt| { + let k = key(p); + let ids = &at[&k]; + if deg[&k] != 2 || ids.len() != 2 { + return true; + } + let (s, t) = (&self.b.items[ids[0]], &self.b.items[ids[1]]); + s.layers != t.layers + || (s.w - t.w).abs() > 1e-9 + || vias.iter().any(|v| (v.0 - p.0).hypot(v.1 - p.1) < 1e-6) + || pads.iter().any(|&k| self.b.pads[k].poly.dist(p) < 1e-6) + }; + let mut used: Vec<usize> = Vec::new(); + let mut out = Vec::new(); + for &start in &segs { + if used.contains(&start) { + continue; + } + let Shape::Seg(a, b) = self.b.items[start].shape else { continue }; + // walk back to a fixed end, then forward collecting the chain + let (mut cur, mut end) = (start, a); + let mut guard = 0; + while !fixed(end) && guard < 100_000 { + guard += 1; + let nxt = *at[&key(end)].iter().find(|&&o| o != cur).unwrap(); + let Shape::Seg(p, q) = self.b.items[nxt].shape else { unreachable!() }; + end = if key(p) == key(end) { q } else { p }; + cur = nxt; + } + if guard >= 100_000 { + used.push(start); + continue; // a loop without fixed points + } + let _ = b; + let mut ids = vec![cur]; + let Shape::Seg(p, q) = self.b.items[cur].shape else { unreachable!() }; + let mut pts = vec![end]; + let mut tip = if key(p) == key(end) { q } else { p }; + pts.push(tip); + while !fixed(tip) { + let nxt = *at[&key(tip)].iter().find(|&&o| o != *ids.last().unwrap()).unwrap(); + let Shape::Seg(p, q) = self.b.items[nxt].shape else { unreachable!() }; + tip = if key(p) == key(tip) { q } else { p }; + ids.push(nxt); + pts.push(tip); + } + used.extend_from_slice(&ids); + out.push((ids, pts)); + } + out + } + + /// Replace runs of each chain by octilinear shortcuts where they keep clearance. + fn pull_tight(&mut self) -> (usize, f64) { + let (mut n, mut saved) = (0, 0.0); + for net in 1..self.b.netnames.len() as i32 { + if self.negotiated(net).is_empty() { + continue; + } + self.split_at_joints(net); + for (ids, pts) in self.chains(net) { + if pts.len() < 3 { + continue; + } + let it = self.b.items[ids[0]].clone(); + let (l, w) = (if it.on(0) { 0 } else { 1 }, it.w); + let mut out = vec![pts[0]]; + let mut i = 0; + while i < pts.len() - 1 { + let mut step = None; + for j in (i + 2..pts.len()).rev() { + if let Some(lk) = self.link(net, l, pts[i], pts[j], w) { + step = Some((j, lk)); + break; + } + } + match step { + Some((j, lk)) => { + out.extend_from_slice(&lk[1..]); + i = j; + } + None => { + out.push(pts[i + 1]); + i += 1; + } + } + } + let length = |v: &[Pt]| v.windows(2).map(|s| (s[1].0 - s[0].0).hypot(s[1].1 - s[0].1)).sum::<f64>(); + let gain = length(&pts) - length(&out); + if gain < 1e-6 { + continue; + } + let before = self.components(&self.net_items_all(net)).len(); + let old = self.take(net, &ids); + let new = out + .windows(2) + .filter(|s| (s[1].0 - s[0].0).hypot(s[1].1 - s[0].1) > 1e-9) + .map(|s| crate::board::Board::seg_item(net, l, s[0], s[1], w, Owner::Negotiated)) + .collect(); + let new_ids = self.put(net, new); + if self.components(&self.net_items_all(net)).len() > before { + self.take(net, &new_ids); + self.put(net, old); + } else { + n += 1; + saved += gain; + } + } + } + (n, saved) + } + + /// Widen necked negotiated tracks (at most the neck width, narrower than the net's width) + /// to the widest width, in 0.05 mm steps, that keeps clearance. Stubs inside a pad stay. + fn widen(&mut self) -> usize { + let mut n = 0; + for j in self.jobs.clone() { + let net = self.nid(&j.name); + let (w, wneck) = self.job_widths(&j); + for id in self.negotiated(net) { + let it = self.b.items[id].clone(); + let Shape::Seg(a, b) = it.shape else { continue }; + if it.w >= w - 1e-9 || it.w > wneck + 1e-9 { + continue; + } + let mid = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0); + if self.pads_by_net[net as usize].iter().any(|&k| self.b.pads[k].poly.contains(mid)) { + continue; + } + let l = if it.on(0) { 0 } else { 1 }; + let mut cand = w; + while cand > it.w + 1e-9 { + if self.track_clear(net, l, a, b, cand) { + self.take(net, &[id]); + self.put(net, vec![crate::board::Board::seg_item(net, l, a, b, cand, Owner::Negotiated)]); + n += 1; + break; + } + cand = ((cand - 0.05) * 1e6).round() / 1e6; + } + } + } + n + } + + /// Remove routed copper that ends nowhere (what KiCad's DRC calls dangling): tracks with + /// an end that touches no other copper of the net, and on signal nets vias that touch at + /// most one item. Ripped branches leave such remnants. Fixed copper stays. + pub fn prune_dangling(&mut self) -> usize { + let mut total = 0; + loop { + let mut gone = Vec::new(); + for net in 1..self.b.netnames.len() as i32 { + let plane = self.plane_nets.iter().any(|p| p == self.b.netname(net)); + let all = self.net_items_all(net); + for &id in &self.net_items[net as usize] { + let it = &self.b.items[id]; + if it.owner == Owner::Existing || !self.b.alive[id] { + continue; + } + let dangling = match it.shape { + Shape::Seg(a, b) => { + let l = if it.on(0) { 0 } else { 1 }; + let touches = |p: Pt| all.iter().any(|&o| o != id && self.b.items[o].on(l) && self.b.item_dist(&self.b.items[o], p.0, p.1) <= 1e-4); + !touches(a) || !touches(b) + } + Shape::Via(_) if !plane => all.iter().filter(|&&o| o != id && self.item_item(id, o) <= 1e-4).count() <= 1, + _ => false, + }; + if dangling { + gone.push((net, id)); + } + } + } + if gone.is_empty() { + return total; + } + total += gone.len(); + for (net, id) in gone { + self.take(net, &[id]); + } + } + } + + /// The cleanup passes (after a negotiate step). + pub fn cleanup(&mut self, hug: f64, neck: f64, attract: f64) { + let t = std::time::Instant::now(); + self.b.commit_owner = Owner::Negotiated; + let (tried, kept) = self.reroute_pass(hug, neck, attract); + let vias = self.drop_vias(); + let (chains, saved) = self.pull_tight(); + let widened = self.widen(); + let pruned = self.prune_dangling(); + self.b.commit_owner = Owner::Routed; + self.log.push(json!(["cleanup", "rerouted", kept, "of", tried, "vias dropped", vias, "chains tightened", chains, "widened", widened, "dangling pruned", pruned, "mm saved", (saved * 10.0).round() / 10.0, "s", (t.elapsed().as_secs_f64() * 1000.0).round() / 1000.0])); + } +} diff --git a/tools/router-rs/src/config.rs b/tools/router-rs/src/config.rs new file mode 100644 index 0000000..090d999 --- /dev/null +++ b/tools/router-rs/src/config.rs @@ -0,0 +1,389 @@ +//! route.toml: the board's routing rules (replaces the Python route scripts). +//! +//! ```toml +//! prefix = "/My Sheet/" # net names may leave it out +//! plane_nets = ["GND"] +//! +//! [[fixed]] # fixed copper, loaded before the steps +//! name = "bus" # path from --fixed bus=FILE, or `path` (relative to the toml) +//! done = true # its nets are complete: `rest` leaves them alone +//! [[fixed]] +//! name = "keep" +//! unmoved = true # a board dump: keep copper of nets whose parts did not move +//! exclude = ["GND"] +//! optional = true +//! +//! [costs.sig] # cost maps: rectangles relative to a footprint's origin +//! zones = [{ layer = "F", fp = "U1", rect = [-8.1, -9.2, 8.1, 10.66], cost = 200 }] +//! [costs.rudy] +//! rudy = { scale = 4.0, max = 20.0 } # RUDY congestion of the pads' MSTs on F.Cu +//! +//! [[step]] +//! do = "connect" # via, plane, connect, pair, decaps, rest, repair, tie, stitch +//! nets = ["XI", "XO"] +//! cost = "sig" # "none" clears; left out, the previous map stays +//! ``` +//! +//! Steps run in order. Pads are written "REF:NUM". +//! +//! `do = "pour"` checks the plane nets' pours (board.json `zones`) for islands that leave +//! pads apart and, with `fix` (default), joins them with vias of diameter `d` (0.6). +//! `planes = true` on a negotiate step routes the plane nets' drops in the negotiation +//! (instead of a `plane` step before it), so they can give way to signals. +//! `[rank]` sets how routed boards compare (see Rank). +//! +//! `area = "pours"` keeps all copper inside the plane nets' pours (board.json `zones`), e.g. a +//! design block's area; `area = [[x, y], ...]` gives a polygon. `area_margin` (mm, default 0) +//! keeps copper that far inside. +//! +//! `[[bundle]] nets = [...]` (pairs, buses): a step of one of these nets that does not run +//! alongside its bundle partners' copper costs `attract` more (hug is 0.3): on the negotiate +//! step (default 0, off; 0.5 works well) and on the cleanup step (default 0.5). Soft: +//! nothing is forced, and the cleanup still keeps a reroute only if it is at most 2 % worse. +//! Negotiation is where it counts: in the cleanup the space beside a partner is mostly taken. +//! +//! `do = "negotiate"` routes every net still in pieces at once (negotiated congestion), with +//! `cost`, `rounds`, `pres`, `pres_mult`, `hist` and search settings as defaults; a +//! `[nets.NAME]` table overrides them per net (w, wneck, neck_zone, via_d, root, decaps, +//! priority, cost, ...) and `[[nets.NAME.join]]` adds pad pairs routed first (a, b, cost, w, wneck, +//! allow_via). Higher `priority` routes first in each round. +//! +//! `[[escape]] nets = [...], from = [x, y], to = [x, y]` reserves escape lines for nets that +//! leave the block (a module's interface nets, one pad each): a virtual pad per net, spread +//! evenly from `from` to `to` in the order given (`size` mm square, default 0.25, on F.Cu), +//! routed with everything else (`w` mm wide, default the nets' own width), so a board only +//! counts as complete when every such net can still reach the block edge past the block's own +//! copper. Their copper is left out of the +//! output (`keep = true` keeps it); the base board routes the real lines. +//! +//! `neck_zone` (mm, default 1): a track may neck to `wneck` only within this distance of the +//! pads it joins. A fine-pitch part whose pins are nearly all used needs more (0.4 mm-pitch +//! QFN: 2), so neighbouring lines can spread apart before they must be full width. + +use crate::router::{NetOpts, PadRef}; +use anyhow::{anyhow, bail, Result}; +use serde::Deserialize; +use std::collections::BTreeMap; + +fn default_planes() -> Vec<String> { + vec!["GND".into()] +} + +fn yes() -> bool { + true +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + #[serde(default)] + pub prefix: String, + #[serde(default = "default_planes")] + pub plane_nets: Vec<String>, + #[serde(default)] + pub fixed: Vec<Fixed>, + #[serde(default)] + pub costs: BTreeMap<String, CostDef>, + #[serde(default)] + pub nets: BTreeMap<String, NetCfg>, + #[serde(default)] + pub step: Vec<Step>, + #[serde(default)] + pub rank: Rank, + /// Routing area: all copper stays inside it (`area_margin` mm in, default 0). + #[serde(default)] + pub area: Option<Area>, + #[serde(default)] + pub area_margin: f64, + /// Nets the cleanup draws together: `[[bundle]] nets = ["USB_DP", "USB_DN"]`. + #[serde(default)] + pub bundle: Vec<Bundle>, + /// Escape lines for nets that leave the block, to virtual pads along an edge. + #[serde(default)] + pub escape: Vec<Escape>, +} + +fn escape_size() -> f64 { + 0.25 +} + +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct Escape { + /// in their order along the edge, from `from` to `to` + pub nets: Vec<String>, + pub from: [f64; 2], + pub to: [f64; 2], + #[serde(default = "escape_size")] + pub size: f64, + /// track width of the escape lines (default: the nets' own); the lines only reserve room, + /// so they may be as thin as the base board will route them (e.g. 0.15 at a 0.4 mm pitch) + pub w: Option<f64>, + /// write the escape copper to the output too + #[serde(default)] + pub keep: bool, +} + +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct Bundle { + pub nets: Vec<String>, +} + +/// `area = "pours"` (the union of the plane nets' zones in board.json) or a polygon. +#[derive(Deserialize, Clone)] +#[serde(untagged)] +pub enum Area { + Pours(String), + Poly(Vec<[f64; 2]>), +} + +/// How routed boards of the same board compare (placer --route): fewer split nets, failed +/// connections and pour islands first, then the lowest score = net length x weight + +/// via_mm x vias + neck_mm x necked length + bcu_mm x B.Cu length. +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields, default)] +pub struct Rank { + pub via_mm: f64, + pub neck_mm: f64, + pub bcu_mm: f64, + /// net length weights by glob (`*` only), e.g. { match = "*/SENSE*", weight = 2.0 } + pub nets: Vec<RankNet>, +} + +impl Default for Rank { + fn default() -> Self { + Rank { via_mm: 2.0, neck_mm: 2.0, bcu_mm: 0.0, nets: vec![] } + } +} + +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields)] +pub struct RankNet { + #[serde(rename = "match")] + pub pattern: String, + pub weight: f64, +} + +/// Glob with `*` only. +pub fn glob(pat: &str, s: &str) -> bool { + let parts: Vec<&str> = pat.split('*').collect(); + if parts.len() == 1 { + return pat == s; + } + let mut rest = s; + for (i, p) in parts.iter().enumerate() { + if i == 0 { + if !rest.starts_with(p) { + return false; + } + rest = &rest[p.len()..]; + } else if i == parts.len() - 1 { + return rest.ends_with(p); + } else if let Some(k) = rest.find(p) { + rest = &rest[k + p.len()..]; + } else { + return false; + } + } + true +} + +#[derive(Deserialize, Default, Clone)] +#[serde(deny_unknown_fields)] +pub struct NetCfg { + #[serde(default)] + pub join: Vec<JoinCfg>, + pub cost: Option<String>, + pub root: Option<String>, + pub decaps: Option<bool>, + pub priority: Option<i32>, + pub w: Option<f64>, + pub wneck: Option<f64>, + pub via_d: Option<f64>, + pub via_cost: Option<f64>, + pub via_cmult: Option<f64>, + pub bmult: Option<f64>, + pub turn: Option<f64>, + pub allow_via: Option<bool>, + pub max_expand: Option<i64>, + pub neck: Option<f64>, + pub neck_zone: Option<f64>, +} + +/// A pad pair of the net routed first, with its own settings (e.g. AVDD pins joined inside +/// a QFP's pad ring without vias). +#[derive(Deserialize, Default, Clone)] +#[serde(deny_unknown_fields)] +pub struct JoinCfg { + pub a: String, + pub b: String, + pub cost: Option<String>, + pub w: Option<f64>, + pub wneck: Option<f64>, + pub allow_via: Option<bool>, +} + +impl NetCfg { + /// Search settings: these where set, else the step's. + pub fn opts(&self, step: &NetOpts) -> NetOpts { + NetOpts { + w: self.w.or(step.w), + wneck: self.wneck.or(step.wneck), + via_d: self.via_d.or(step.via_d), + via_cost: self.via_cost.or(step.via_cost), + via_cmult: self.via_cmult.or(step.via_cmult), + bmult: self.bmult.or(step.bmult), + turn: self.turn.or(step.turn), + allow_via: self.allow_via.or(step.allow_via), + max_expand: self.max_expand.or(step.max_expand), + hweight: step.hweight, + margin: step.margin, + hug: step.hug, + neck: self.neck.or(step.neck), + neck_zone: self.neck_zone.or(step.neck_zone), + } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Fixed { + pub name: String, + pub path: Option<String>, + #[serde(default)] + pub unmoved: bool, + #[serde(default)] + pub exclude: Vec<String>, + #[serde(default = "yes")] + pub protect: bool, + #[serde(default)] + pub done: bool, + #[serde(default)] + pub optional: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CostDef { + #[serde(default)] + pub zones: Vec<Zone>, + pub rudy: Option<Rudy>, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Zone { + pub layer: String, + pub fp: Option<String>, + pub rect: [f64; 4], + pub cost: f64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Rudy { + #[serde(default = "f_layer")] + pub layer: String, + pub scale: f64, + pub max: f64, +} + +fn f_layer() -> String { + "F".into() +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +pub struct Step { + #[serde(rename = "do")] + pub kind: String, + pub label: Option<String>, + pub cost: Option<String>, + pub net: Option<String>, + pub nets: Option<Vec<String>>, + pub fp: Option<String>, + pub at: Option<Vec<[f64; 2]>>, + pub d: Option<f64>, + pub only: Option<Vec<String>>, + pub skip: Option<Vec<String>>, + pub exclude: Option<Vec<String>>, + pub root: Option<String>, + pub pads: Option<Vec<String>>, + pub a: Option<String>, + pub b: Option<String>, + pub pad: Option<String>, + pub rounds: Option<usize>, + pub radius: Option<f64>, + pub pitch: Option<f64>, + pub area: Option<[f64; 4]>, + pub w: Option<f64>, + pub wneck: Option<f64>, + pub via_d: Option<f64>, + pub via_cost: Option<f64>, + pub via_cmult: Option<f64>, + pub bmult: Option<f64>, + pub turn: Option<f64>, + pub allow_via: Option<bool>, + pub max_expand: Option<i64>, + pub hweight: Option<f64>, + pub margin: Option<f64>, + pub hug: Option<f64>, + /// negotiate (default 0) and cleanup (default 0.5): extra cost per step away from the + /// net's [[bundle]] partners + pub attract: Option<f64>, + /// necked step cost per mm of width given up (cleanup default 4, elsewhere 0) + pub neck: Option<f64>, + /// a track may neck to `wneck` within this distance (mm) of the pads it joins (default 1) + pub neck_zone: Option<f64>, + pub pres: Option<f64>, + pub pres_mult: Option<f64>, + pub hist: Option<f64>, + pub decaps: Option<bool>, + /// negotiate: route the plane nets' drops in the negotiation too + pub planes: Option<bool>, + /// pour: stitch islands to the rest of the pour with vias + pub fix: Option<bool>, +} + +impl Step { + pub fn opts(&self) -> NetOpts { + NetOpts { + w: self.w, + wneck: self.wneck, + via_d: self.via_d, + via_cost: self.via_cost, + via_cmult: self.via_cmult, + bmult: self.bmult, + turn: self.turn, + allow_via: self.allow_via, + max_expand: self.max_expand, + hweight: self.hweight, + margin: self.margin, + hug: self.hug, + neck: self.neck, + neck_zone: self.neck_zone, + } + } + + pub fn net(&self) -> Result<&str> { + self.net.as_deref().ok_or_else(|| anyhow!("step {}: `net` missing", self.kind)) + } +} + +pub fn pad_ref(s: &str) -> Result<PadRef> { + let Some((r, n)) = s.split_once(':') else { bail!("pad {s:?}: write REF:NUM") }; + Ok((r.to_string(), n.to_string())) +} + +pub fn pad_refs(v: &[String]) -> Result<Vec<PadRef>> { + v.iter().map(|s| pad_ref(s)).collect() +} + +impl Config { + pub fn load(path: &str) -> Result<Config> { + use anyhow::Context; + let s = std::fs::read_to_string(path).with_context(|| path.to_string())?; + toml::from_str(&s).with_context(|| path.to_string()) + } +} diff --git a/tools/router-rs/src/geom.rs b/tools/router-rs/src/geom.rs new file mode 100644 index 0000000..f176e39 --- /dev/null +++ b/tools/router-rs/src/geom.rs @@ -0,0 +1,281 @@ +//! 2-D geometry in mm: pad polygons, segments, exact distances. +//! +//! Point-to-segment distance follows GEOS (shapely), so the distance fields match the +//! Python router's to the last bit wherever possible. + +pub type Pt = (f64, f64); + +#[derive(Clone, Debug)] +pub struct Poly { + pub pts: Vec<Pt>, + pub bbox: [f64; 4], +} + +impl Poly { + pub fn new(mut pts: Vec<Pt>) -> Poly { + if pts.len() > 1 && pts[0] == pts[pts.len() - 1] { + pts.pop(); + } + let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for &(x, y) in &pts { + b[0] = b[0].min(x); + b[1] = b[1].min(y); + b[2] = b[2].max(x); + b[3] = b[3].max(y); + } + Poly { pts, bbox: b } + } + + pub fn edges(&self) -> impl Iterator<Item = (Pt, Pt)> + '_ { + let n = self.pts.len(); + (0..n).map(move |i| (self.pts[i], self.pts[(i + 1) % n])) + } + + /// Interior or boundary (GEOS RayCrossingCounter with a robust orientation test). + pub fn contains(&self, p: Pt) -> bool { + if p.0 < self.bbox[0] || p.0 > self.bbox[2] || p.1 < self.bbox[1] || p.1 > self.bbox[3] { + return false; + } + let mut crossings = 0; + for (a, b) in self.edges() { + if a.0 < p.0 && b.0 < p.0 { + continue; + } + if p == b { + return true; + } + if a.1 == p.1 && b.1 == p.1 { + if p.0 >= a.0.min(b.0) && p.0 <= a.0.max(b.0) { + return true; + } + continue; + } + if (a.1 > p.1 && b.1 <= p.1) || (b.1 > p.1 && a.1 <= p.1) { + let mut o = orientation(a, b, p); + if o == 0 { + return true; + } + if b.1 < a.1 { + o = -o; + } + if o > 0 { + crossings += 1; + } + } + } + crossings % 2 == 1 + } + + /// Distance from a point to the outline, from either side. + pub fn boundary_dist(&self, p: Pt) -> f64 { + self.edges().map(|(a, b)| point_seg(p, a, b)).fold(f64::INFINITY, f64::min) + } + + /// Distance from a point, 0 inside (shapely's `distance`). + pub fn dist(&self, p: Pt) -> f64 { + if self.contains(p) { + return 0.0; + } + self.edges().map(|(a, b)| point_seg(p, a, b)).fold(f64::INFINITY, f64::min) + } + + fn ring(&self) -> Vec<Pt> { + let mut r = self.pts.clone(); + r.push(self.pts[0]); + r + } + + /// Area as GEOS computes it (shapely's `area`), so equal pads sort alike. + pub fn area(&self) -> f64 { + let r = self.ring(); + if r.len() < 3 { + return 0.0; + } + let x0 = r[0].0; + let mut sum = 0.0; + for i in 1..r.len() - 1 { + sum += (r[i].0 - x0) * (r[i - 1].1 - r[i + 1].1); + } + (sum / 2.0).abs() + } + + /// Area centroid as GEOS computes it (shapely's `centroid`). + pub fn centroid(&self) -> Pt { + let r = self.ring(); + let base = r[0]; + let mut signed = 0.0; + for i in 0..r.len() - 1 { + signed += r[i].0 * r[i + 1].1 - r[i + 1].0 * r[i].1; + } + let sign = if signed > 0.0 { -1.0 } else { 1.0 }; // positive area for clockwise shells + let (mut cx, mut cy, mut a2) = (0.0, 0.0, 0.0); + for i in 0..r.len() - 1 { + let (p1, p2) = (r[i], r[i + 1]); + let area2 = (p1.0 - base.0) * (p2.1 - base.1) - (p2.0 - base.0) * (p1.1 - base.1); + cx += sign * area2 * (base.0 + p1.0 + p2.0); + cy += sign * area2 * (base.1 + p1.1 + p2.1); + a2 += sign * area2; + } + if a2 == 0.0 { + return base; + } + (cx / 3.0 / a2, cy / 3.0 / a2) + } + + /// Shorter side of the minimum-area rotated rectangle (the pad's narrow width). + pub fn minor(&self) -> f64 { + let h = hull(&self.pts); + let n = h.len(); + let mut best = (f64::INFINITY, 0.0); + for i in 0..n { + let (a, b) = (h[i], h[(i + 1) % n]); + let l = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt(); + if l == 0.0 { + continue; + } + let (ux, uy) = ((b.0 - a.0) / l, (b.1 - a.1) / l); + let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); + for &p in &h { + let u = (p.0 - a.0) * ux + (p.1 - a.1) * uy; + let v = -(p.0 - a.0) * uy + (p.1 - a.1) * ux; + u0 = u0.min(u); + u1 = u1.max(u); + v0 = v0.min(v); + v1 = v1.max(v); + } + let area = (u1 - u0) * (v1 - v0); + if area < best.0 { + best = (area, (u1 - u0).min(v1 - v0)); + } + } + best.1 + } +} + +fn hull(pts: &[Pt]) -> Vec<Pt> { + let mut p = pts.to_vec(); + p.sort_by(|a, b| a.partial_cmp(b).unwrap()); + p.dedup(); + if p.len() < 3 { + return p; + } + let cross = |o: Pt, a: Pt, b: Pt| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0); + let mut h: Vec<Pt> = Vec::new(); + for &q in p.iter().chain(p.iter().rev().skip(1)) { + while h.len() >= 2 && cross(h[h.len() - 2], h[h.len() - 1], q) <= 0.0 { + h.pop(); + } + h.push(q); + } + h.pop(); + h +} + +// double-double arithmetic for the orientation sign (GEOS CGAlgorithmsDD) +fn two_sum(a: f64, b: f64) -> (f64, f64) { + let s = a + b; + let bb = s - a; + (s, (a - (s - bb)) + (b - bb)) +} + +fn dd_sub(a: (f64, f64), b: (f64, f64)) -> (f64, f64) { + let (s, e) = two_sum(a.0, -b.0); + two_sum(s, e + a.1 - b.1) +} + +fn dd_mul(a: (f64, f64), b: (f64, f64)) -> (f64, f64) { + let p = a.0 * b.0; + let e = a.0.mul_add(b.0, -p) + (a.0 * b.1 + a.1 * b.0); + two_sum(p, e) +} + +/// Sign of the turn a -> b -> c: 1 left, -1 right, 0 collinear (robust). +pub fn orientation(a: Pt, b: Pt, c: Pt) -> i32 { + let sign = |d: f64| (d > 0.0) as i32 - (d < 0.0) as i32; + let det_l = (a.0 - c.0) * (b.1 - c.1); + let det_r = (a.1 - c.1) * (b.0 - c.0); + let det = det_l - det_r; + let sum = if det_l > 0.0 && det_r > 0.0 { + det_l + det_r + } else if det_l < 0.0 && det_r < 0.0 { + -det_l - det_r + } else { + return sign(det); + }; + if det.abs() >= 1e-15 * sum { + return sign(det); + } + let dx1 = two_sum(b.0, -a.0); + let dy1 = two_sum(b.1, -a.1); + let dx2 = two_sum(c.0, -b.0); + let dy2 = two_sum(c.1, -b.1); + let d = dd_sub(dd_mul(dx1, dy2), dd_mul(dy1, dx2)); + sign(if d.0 != 0.0 { d.0 } else { d.1 }) +} + +/// GEOS `Distance::pointToSegment`. +pub fn point_seg(p: Pt, a: Pt, b: Pt) -> f64 { + if a == b { + return ((p.0 - a.0).powi(2) + (p.1 - a.1).powi(2)).sqrt(); + } + let len2 = (b.0 - a.0) * (b.0 - a.0) + (b.1 - a.1) * (b.1 - a.1); + let r = ((p.0 - a.0) * (b.0 - a.0) + (p.1 - a.1) * (b.1 - a.1)) / len2; + if r <= 0.0 { + return ((p.0 - a.0).powi(2) + (p.1 - a.1).powi(2)).sqrt(); + } + if r >= 1.0 { + return ((p.0 - b.0).powi(2) + (p.1 - b.1).powi(2)).sqrt(); + } + let s = ((a.1 - p.1) * (b.0 - a.0) - (a.0 - p.0) * (b.1 - a.1)) / len2; + s.abs() * len2.sqrt() +} + +fn orient(a: Pt, b: Pt, c: Pt) -> f64 { + (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0) +} + +fn on_seg(a: Pt, b: Pt, p: Pt) -> bool { + p.0 >= a.0.min(b.0) && p.0 <= a.0.max(b.0) && p.1 >= a.1.min(b.1) && p.1 <= a.1.max(b.1) +} + +pub fn seg_intersect(a: Pt, b: Pt, c: Pt, d: Pt) -> bool { + let (o1, o2, o3, o4) = (orient(a, b, c), orient(a, b, d), orient(c, d, a), orient(c, d, b)); + if ((o1 > 0.0 && o2 < 0.0) || (o1 < 0.0 && o2 > 0.0)) && ((o3 > 0.0 && o4 < 0.0) || (o3 < 0.0 && o4 > 0.0)) { + return true; + } + (o1 == 0.0 && on_seg(a, b, c)) || (o2 == 0.0 && on_seg(a, b, d)) || (o3 == 0.0 && on_seg(c, d, a)) || (o4 == 0.0 && on_seg(c, d, b)) +} + +pub fn seg_seg(a: Pt, b: Pt, c: Pt, d: Pt) -> f64 { + if seg_intersect(a, b, c, d) { + return 0.0; + } + point_seg(a, c, d).min(point_seg(b, c, d)).min(point_seg(c, a, b)).min(point_seg(d, a, b)) +} + +pub fn seg_poly(a: Pt, b: Pt, p: &Poly) -> f64 { + if p.contains(a) || p.contains(b) { + return 0.0; + } + p.edges().map(|(c, d)| seg_seg(a, b, c, d)).fold(f64::INFINITY, f64::min) +} + +pub fn poly_poly(p: &Poly, q: &Poly) -> f64 { + if p.contains(q.pts[0]) || q.contains(p.pts[0]) { + return 0.0; + } + let mut m = f64::INFINITY; + for (a, b) in p.edges() { + for (c, d) in q.edges() { + m = m.min(seg_seg(a, b, c, d)); + if m == 0.0 { + return 0.0; + } + } + } + m +} + +pub fn bbox_gap(a: &[f64; 4], b: &[f64; 4], m: f64) -> bool { + a[0] - m > b[2] || a[2] + m < b[0] || a[1] - m > b[3] || a[3] + m < b[1] +} diff --git a/tools/router-rs/src/io.rs b/tools/router-rs/src/io.rs new file mode 100644 index 0000000..be51147 --- /dev/null +++ b/tools/router-rs/src/io.rs @@ -0,0 +1,145 @@ +//! JSON formats shared with the Python tools: board.json from tools/router/dump_board.py +//! in, routes.json for tools/router/write_board.py and plot_routes.py out. + +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap}; + +#[derive(Deserialize, Serialize, Clone)] +pub struct PadJson { + #[serde(rename = "ref")] + pub refdes: String, + pub num: String, + pub net: String, + pub x: f64, + pub y: f64, + pub drill: f64, + #[serde(default)] + pub npth: bool, + #[serde(rename = "F")] + pub f: Option<Vec<[f64; 2]>>, + #[serde(rename = "B")] + pub b: Option<Vec<[f64; 2]>>, +} + +#[derive(Deserialize, Serialize, Clone)] +pub struct FpJson { + pub x: f64, + pub y: f64, + pub rot: f64, + #[serde(default)] + pub value: String, +} + +#[derive(Deserialize, Serialize, Clone)] +pub struct ClassJson { + pub track: f64, + pub via: f64, +} + +/// Footprint copper that is not a pad, on "F" or "B". +#[derive(Deserialize, Serialize, Clone)] +pub struct FpCopperJson { + #[serde(rename = "ref")] + pub refdes: String, + pub layer: String, + pub poly: Vec<[f64; 2]>, +} + +/// A copper pour: net, layer ("F.Cu" / "B.Cu") and outline. +#[derive(Deserialize, Serialize, Clone)] +pub struct ZoneJson { + pub net: String, + pub layer: String, + pub pts: Vec<[f64; 2]>, +} + +#[derive(Deserialize, Serialize, Clone)] +pub struct TrackJson { + pub net: String, + pub layer: String, + pub x1: f64, + pub y1: f64, + pub x2: f64, + pub y2: f64, + pub w: f64, +} + +#[derive(Deserialize, Serialize, Clone)] +pub struct ViaJson { + pub net: String, + pub x: f64, + pub y: f64, + pub d: f64, + #[serde(default)] + pub drill: f64, +} + +#[derive(Deserialize, Serialize, Clone)] +pub struct BoardJson { + pub bounds: [f64; 4], + pub pads: Vec<PadJson>, + #[serde(default)] + pub fps: BTreeMap<String, FpJson>, + #[serde(default)] + pub netclass: HashMap<String, String>, + #[serde(default)] + pub classes: HashMap<String, ClassJson>, + #[serde(default)] + pub fpcopper: Vec<FpCopperJson>, + /// copper pours (not rule areas): net, layer, outline + #[serde(default)] + pub zones: Vec<ZoneJson>, + #[serde(default)] + pub keepouts: Vec<Vec<[f64; 2]>>, + /// Owning footprint of each keepout ("" for board rule areas); absent in old dumps. + #[serde(default)] + pub keepout_refs: Vec<String>, + #[serde(default)] + pub tracks: Vec<TrackJson>, + #[serde(default)] + pub vias: Vec<ViaJson>, +} + +impl BoardJson { + pub fn load(path: &str) -> anyhow::Result<BoardJson> { + use anyhow::Context; + let s = std::fs::read_to_string(path).with_context(|| path.to_string())?; + serde_json::from_str(&s).with_context(|| path.to_string()) + } +} + +#[derive(Serialize)] +pub struct RoutesJson { + pub segs: Vec<TrackJson>, + pub vias: Vec<ViaJson>, + pub failed: Vec<Vec<String>>, + pub log: Vec<serde_json::Value>, +} + +#[derive(Deserialize)] +pub struct PadNet { + #[serde(rename = "ref")] + pub refdes: String, + pub net: String, +} + +/// Fixed copper: a board dump (tracks, vias, fps, pads) or just tracks and vias. +#[derive(Deserialize)] +pub struct CopperJson { + #[serde(default)] + pub tracks: Vec<TrackJson>, + #[serde(default)] + pub vias: Vec<ViaJson>, + #[serde(default)] + pub fps: BTreeMap<String, FpJson>, + #[serde(default)] + pub pads: Vec<PadNet>, +} + +impl CopperJson { + pub fn load(path: &str) -> anyhow::Result<CopperJson> { + use anyhow::Context; + let s = std::fs::read_to_string(path).with_context(|| path.to_string())?; + serde_json::from_str(&s).with_context(|| path.to_string()) + } +} diff --git a/tools/router-rs/src/lib.rs b/tools/router-rs/src/lib.rs new file mode 100644 index 0000000..925b1af --- /dev/null +++ b/tools/router-rs/src/lib.rs @@ -0,0 +1,15 @@ +//! Grid maze router for 2-layer KiCad boards (see knowledge/tooling/rust-router.md). +//! +//! Reads board.json from tools/router/dump_board.py and the board's route.toml, writes +//! routes.json for tools/router/write_board.py. + +pub mod astar; +pub mod board; +pub mod cleanup; +pub mod config; +pub mod geom; +pub mod io; +pub mod placement; +pub mod pour; +pub mod router; +pub mod run; diff --git a/tools/router-rs/src/main.rs b/tools/router-rs/src/main.rs new file mode 100644 index 0000000..85802ce --- /dev/null +++ b/tools/router-rs/src/main.rs @@ -0,0 +1,107 @@ +//! router: grid maze router for 2-layer KiCad boards. +//! +//! router route BOARD.json ROUTE.toml OUT.json [--fixed NAME=FILE]... [--stop LABEL] +//! router place BOARD.json PLACEMENT.json OUT.json +//! +//! `place` writes BOARD.json with the footprints moved to a placer result (ref -> [x, y, rot]), +//! so a placement can be routed without KiCad; existing tracks and vias are left as they are. +//! BOARD.json comes from tools/router/dump_board.py, OUT.json goes to +//! tools/router/write_board.py. `--stop` ends after the step with that label (to look at +//! partial results). Prints one summary line: +//! "RESULT split=<nets in pieces> failed=<connections; a poured plane net's failed drops count +//! only through islands> islands=<plane pad groups apart> +//! vias=<n> length=<mm> bcu=<mm> neck=<mm narrower than the net width> score=<[rank]> time=<s>". + +use anyhow::{bail, Context, Result}; +use router::config::Config; +use router::io::BoardJson; +use router::placement; +use router::run::Run; +use std::collections::HashMap; +use std::path::Path; +use std::time::Instant; + +fn main() -> Result<()> { + let args: Vec<String> = std::env::args().skip(1).collect(); + if args.len() == 4 && args[0] == "place" { + let mut d = BoardJson::load(&args[1])?; + placement::apply(&mut d, &placement::load(&args[2])?)?; + std::fs::write(&args[3], serde_json::to_string(&d)?).with_context(|| args[3].to_string())?; + return Ok(()); + } + if args.len() < 4 || args[0] != "route" { + bail!("usage: router route BOARD.json ROUTE.toml OUT.json [--fixed NAME=FILE]... [--stop LABEL]\n router place BOARD.json PLACEMENT.json OUT.json"); + } + let t0 = Instant::now(); + let (board, toml, out) = (&args[1], &args[2], &args[3]); + let mut fixed = HashMap::new(); + let mut stop = None; + let mut k = 4; + while k < args.len() { + match args[k].as_str() { + "--fixed" => { + let (n, f) = args.get(k + 1).and_then(|a| a.split_once('=')).context("--fixed NAME=FILE")?; + fixed.insert(n.to_string(), f.to_string()); + k += 2; + } + "--stop" => { + stop = Some(args.get(k + 1).context("--stop LABEL")?.clone()); + k += 2; + } + a => bail!("unknown argument {a}"), + } + } + let d = BoardJson::load(board)?; + let cfg = Config::load(toml)?; + let base = Path::new(toml).parent().unwrap_or(Path::new(".")); + let mut run = Run::new(&d, &cfg, base, &fixed, true)?; + let t_setup = t0.elapsed().as_secs_f64(); + for s in &cfg.step { + let t = Instant::now(); + run.step(&cfg, s)?; + if std::env::var("ROUTER_TIMES").is_ok() { + eprintln!("{:>7.3} s {} {}", t.elapsed().as_secs_f64(), s.kind, s.nets.as_ref().map(|n| n.join(",")).or(s.net.clone()).unwrap_or_default()); + } + if stop.is_some() && s.label == stop { + println!("stopped after {}", s.label.as_deref().unwrap_or("")); + break; + } + } + let sum = run.summary(&cfg, t0.elapsed().as_secs_f64()); + let r = &run.r; + let incomplete: Vec<_> = r + .log + .iter() + .filter(|l| { + let a = l.as_array().unwrap(); + (a.len() > 4 && a[1] == "pads" && a[4].as_i64() > Some(0)) || (a.len() > 2 && a[1] == "components" && a[2].as_i64() > Some(1)) + }) + .collect(); + println!("incomplete: {incomplete:?}"); + println!("failed: {:?}", r.failed); + let res = r.result(); + std::fs::write(out, serde_json::to_string(&res)?).with_context(|| out.to_string())?; + let len = |l: Option<&str>| -> f64 { res.segs.iter().filter(|s| l.is_none_or(|l| s.layer == l)).map(|s| (s.x2 - s.x1).hypot(s.y2 - s.y1)).sum() }; + let split = r.split_nets(&r.plane_nets); + println!( + "segs {} vias {} B.Cu {:.1} mm, setup {:.2} s, total {:.2} s", + res.segs.len(), + res.vias.len(), + len(Some("B.Cu")), + t_setup, + t0.elapsed().as_secs_f64() + ); + println!( + "RESULT split={} failed={} islands={} vias={} length={:.1} bcu={:.1} neck={:.1} score={:.1} time={:.1}", + split.len(), + sum.failed, + sum.islands, + res.vias.len(), + len(None), + len(Some("B.Cu")), + sum.neck, + sum.score, + t0.elapsed().as_secs_f64() + ); + Ok(()) +} diff --git a/tools/router-rs/src/placement.rs b/tools/router-rs/src/placement.rs new file mode 100644 index 0000000..9409742 --- /dev/null +++ b/tools/router-rs/src/placement.rs @@ -0,0 +1,99 @@ +//! Move footprints of a board.json to a placer result without KiCad. +//! +//! Placement files are ref -> [x, y, rotation in degrees], at the top level or under +//! "placement" (tools/placer). KiCad's y axis points down and its angles turn counter-clockwise +//! on screen, so a footprint-local point (u, v) lies at +//! (x + u cos a + v sin a, y - u sin a + v cos a) for orientation a; moving from pose +//! (x0, y0, a0) to (x1, y1, a1) is that rotation by a1 - a0 about the old origin, then the shift. +//! +//! Pads, the footprint's own copper and its rule areas (via `keepout_refs`) move with it. +//! `tracks` and `vias` stay where they are: the old copper belongs to the old placement. +//! Footprints on the bottom side are not handled. + +use crate::io::BoardJson; +use anyhow::{bail, Context, Result}; +use std::collections::BTreeMap; + +/// Reads a placement file. +pub fn load(path: &str) -> Result<BTreeMap<String, [f64; 3]>> { + let s = std::fs::read_to_string(path).with_context(|| path.to_string())?; + let v: serde_json::Value = serde_json::from_str(&s).with_context(|| path.to_string())?; + let v = v.get("placement").cloned().unwrap_or(v); + serde_json::from_value(v).with_context(|| format!("{path}: expected ref -> [x, y, rot]")) +} + +/// Rigid transform: rotate by an angle (KiCad sense) about (ox, oy), then shift to (nx, ny). +struct Pose { + ox: f64, + oy: f64, + nx: f64, + ny: f64, + c: f64, + s: f64, +} + +impl Pose { + fn new(from: (f64, f64, f64), to: [f64; 3]) -> Pose { + let a = (to[2] - from.2).rem_euclid(360.0); + // exact values at right angles, so the common rotations add no noise + let (s, c) = match a { + 0.0 => (0.0, 1.0), + 90.0 => (1.0, 0.0), + 180.0 => (0.0, -1.0), + 270.0 => (-1.0, 0.0), + _ => a.to_radians().sin_cos(), + }; + Pose { ox: from.0, oy: from.1, nx: to[0], ny: to[1], c, s } + } + + fn pt(&self, x: f64, y: f64) -> (f64, f64) { + let (u, v) = (x - self.ox, y - self.oy); + (self.nx + u * self.c + v * self.s, self.ny - u * self.s + v * self.c) + } + + fn poly(&self, p: &mut [[f64; 2]]) { + for q in p { + let (x, y) = self.pt(q[0], q[1]); + *q = [x, y]; + } + } +} + +/// Moves each listed footprint; errors on unknown references and on bottom-side parts. +pub fn apply(d: &mut BoardJson, placement: &BTreeMap<String, [f64; 3]>) -> Result<()> { + let mut poses = BTreeMap::new(); + for (r, to) in placement { + let f = d.fps.get_mut(r.as_str()).with_context(|| format!("{r} is not on the board"))?; + poses.insert(r.as_str(), Pose::new((f.x, f.y, f.rot), *to)); + (f.x, f.y, f.rot) = (to[0], to[1], to[2]); + } + for p in &mut d.pads { + let Some(pose) = poses.get(p.refdes.as_str()) else { continue }; + if !p.npth && p.f.is_none() && p.b.is_some() { + bail!("{} has a bottom-side pad; flipped footprints are not supported", p.refdes); + } + (p.x, p.y) = pose.pt(p.x, p.y); + for poly in [&mut p.f, &mut p.b].into_iter().flatten() { + pose.poly(poly); + } + } + for c in &mut d.fpcopper { + if let Some(pose) = poses.get(c.refdes.as_str()) { + pose.poly(&mut c.poly); + } + } + if d.keepout_refs.is_empty() { + if !d.keepouts.is_empty() { + eprintln!("warning: board.json has no keepout_refs (old dump): footprint keep-outs are not moved"); + } + } else if d.keepout_refs.len() != d.keepouts.len() { + bail!("keepout_refs and keepouts differ in length"); + } else { + for (k, r) in d.keepouts.iter_mut().zip(&d.keepout_refs) { + if let Some(pose) = poses.get(r.as_str()) { + pose.poly(k); + } + } + } + Ok(()) +} diff --git a/tools/router-rs/src/pour.rs b/tools/router-rs/src/pour.rs new file mode 100644 index 0000000..b7aaab4 --- /dev/null +++ b/tools/router-rs/src/pour.rs @@ -0,0 +1,224 @@ +//! Pour connectivity of the plane nets: where each copper pour of the board.json (`zones`) +//! will fill, which pieces of the net's copper the fill joins, and stitching vias for islands. +//! +//! A cell fills when it lies in the pour outline and the nearest copper of another net (or the +//! board edge, keep-out, hole) is at least FILL_R away: the zone clearance plus half KiCad's +//! minimum fill width, so a neck too thin to fill does not count as a connection. Fill cells +//! form islands (4-connected, per layer). The net's copper joins an island where its tracks +//! and vias touch it and where a pad is within THERMAL_R (thermal gap plus spoke). Pieces of +//! copper with pads that end up apart are what KiCad's DRC reports as unconnected. + +use crate::board::{via_drill, SearchOpts, CLR, HOLE_HOLE, M}; +use crate::router::Router; +use serde_json::json; + +/// Fill needs this much room to other nets' copper (mm): clearance 0.2 + half of 0.25. +const FILL_R: f32 = 0.325; +/// A pad joins fill within this distance (mm): thermal gap 0.5 plus a little spoke. +const THERMAL_R: f64 = 0.6; + +struct Map { + /// island of each state (cell * 2 + layer), -1 where nothing fills + lab: Vec<i32>, + nisl: usize, + /// the net's copper pieces (item ids) + pieces: Vec<Vec<usize>>, + /// union-find over islands (0..nisl) and pieces (nisl..) + par: Vec<usize>, +} + +impl Map { + fn find(&mut self, mut a: usize) -> usize { + while self.par[a] != a { + self.par[a] = self.par[self.par[a]]; + a = self.par[a]; + } + a + } + + fn union(&mut self, a: usize, b: usize) { + let (a, b) = (self.find(a), self.find(b)); + if a != b { + self.par[a] = b; + } + } +} + +impl Router { + fn pour_map(&self, net: i32) -> Option<Map> { + let b = &self.b; + let zones: Vec<_> = self.zones.iter().filter(|z| z.0 == net).collect(); + if zones.is_empty() { + return None; + } + let mut fill = vec![false; 2 * b.n]; + for (_, l, poly) in &zones { + let (i0, j0, i1, j1) = b.window(&poly.bbox, 0.0); + for j in j0..=j1 { + for i in i0..=i1 { + let s = (j * b.nx + i) * 2 + l; + if !fill[s] && b.f[s].fdist(net) >= FILL_R && poly.contains(b.cell_xy(i, j)) { + fill[s] = true; + } + } + } + } + let mut lab = vec![-1i32; 2 * b.n]; + let mut nisl = 0; + let mut stack = Vec::new(); + for s0 in 0..2 * b.n { + if !fill[s0] || lab[s0] >= 0 { + continue; + } + lab[s0] = nisl as i32; + stack.push(s0); + while let Some(s) = stack.pop() { + let (c, l) = (s >> 1, s & 1); + let (i, j) = (c % b.nx, c / b.nx); + let mut nb = [usize::MAX; 4]; + if i > 0 { + nb[0] = c - 1; + } + if i + 1 < b.nx { + nb[1] = c + 1; + } + if j > 0 { + nb[2] = c - b.nx; + } + if j + 1 < b.ny { + nb[3] = c + b.nx; + } + for q in nb.into_iter().filter(|&q| q != usize::MAX) { + let t = q * 2 + l; + if fill[t] && lab[t] < 0 { + lab[t] = nisl as i32; + stack.push(t); + } + } + } + nisl += 1; + } + let pieces = self.components(&self.net_items_all(net)); + let mut m = Map { lab, nisl, par: (0..nisl + pieces.len()).collect(), pieces }; + for p in 0..m.pieces.len() { + for id in m.pieces[p].clone() { + let it = &b.items[id]; + let r = if matches!(it.shape, crate::board::Shape::Pad(_)) { THERMAL_R } else { crate::board::RES }; + let (i0, j0, i1, j1) = b.window(&it.bbox, r); + for j in j0..=j1 { + for i in i0..=i1 { + let (x, y) = b.cell_xy(i, j); + for l in 0..2 { + let s = (j * b.nx + i) * 2 + l; + if it.on(l) && m.lab[s] >= 0 && (b.item_dist(it, x, y) as f64) <= r { + let isl = m.lab[s] as usize; + m.union(isl, nisl + p); + } + } + } + } + } + } + Some(m) + } + + /// Roots of the pieces that hold pads, with their pad counts (most pads first). + fn pad_groups(&self, m: &mut Map) -> Vec<(usize, usize)> { + let mut cnt: std::collections::BTreeMap<usize, usize> = std::collections::BTreeMap::new(); + for p in 0..m.pieces.len() { + let pads = m.pieces[p].iter().filter(|&&id| matches!(self.b.items[id].shape, crate::board::Shape::Pad(_))).count(); + if pads > 0 { + let r = m.find(m.nisl + p); + *cnt.entry(r).or_default() += pads; + } + } + let mut v: Vec<(usize, usize)> = cnt.into_iter().collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + v + } + + /// Groups of a plane net's pads that its pours and copper leave apart, beyond the first + /// (0: connected; also 0 when the net has no pour in the board.json). + pub fn pour_splits(&self, name: &str) -> usize { + let Some(&net) = self.b.netid.get(name) else { return 0 }; + match self.pour_map(net) { + Some(mut m) => self.pad_groups(&mut m).len().saturating_sub(1), + None => 0, + } + } + + /// Join pour islands that hold pads to the main group: a via of diameter d where one layer + /// belongs to the island and the other to the main group, else a track (and vias) from the + /// group's copper to the main group's fill. Returns (groups left apart, joints added). + pub fn pour_fix(&mut self, name: &str, d: f64) -> (usize, usize) { + let Some(&net) = self.b.netid.get(name) else { return (0, 0) }; + let mut added = 0; + loop { + let Some(mut m) = self.pour_map(net) else { return (0, 0) }; + let groups = self.pad_groups(&mut m); + if groups.len() <= 1 { + self.log.push(json!([name, "pour groups apart", 0, "joints added", added])); + return (0, added); + } + let main = groups[0].0; + let b = &self.b; + let (r_via, r_vpad) = ((d / 2.0 + CLR + M) as f32, (d / 2.0 + 0.05) as f32); + let r_hole = (via_drill(d) / 2.0 + HOLE_HOLE + M) as f32; + let mut spot = None; + 'groups: for &(g, _) in &groups[1..] { + for c in 0..b.n { + let (s0, s1) = (c * 2, c * 2 + 1); + if m.lab[s0] < 0 || m.lab[s1] < 0 { + continue; + } + let (r0, r1) = (m.find(m.lab[s0] as usize), m.find(m.lab[s1] as usize)); + if !((r0 == g && r1 == main) || (r0 == main && r1 == g)) { + continue; + } + if b.f[s0].fdist(net) >= r_via && b.f[s1].fdist(net) >= r_via && b.padd[s0] >= r_vpad && b.padd[s1] >= r_vpad && b.hole[c] >= r_hole { + spot = Some(b.cell_xy(c % b.nx, c / b.nx)); + break 'groups; + } + } + } + if let Some(p) = spot { + let items = self.b.commit(net, &[], &[p], d); + self.net_items[net as usize].extend_from_slice(&items); + added += 1; + continue; + } + // no via joins an island to the main group: route a group's copper to the main + // group's fill (a drop that ended in a pocket no pour reaches) + let roots: Vec<usize> = (0..m.nisl).map(|i| m.find(i)).collect(); + let tgt: Vec<i32> = (0..2 * b.n).filter(|&s| m.lab[s] >= 0 && roots[m.lab[s] as usize] == main).map(|s| s as i32).collect(); + let mut joined = false; + for &(g, _) in &groups[1..] { + let mine: Vec<usize> = (0..m.pieces.len()).filter(|&p| m.find(m.nisl + p) == g).collect(); + let src: Vec<usize> = mine.iter().flat_map(|&p| m.pieces[p].clone()).collect(); + let so = SearchOpts { hweight: 0.0, ..Default::default() }; + if self.join_to(net, &src, &tgt, d, &so) { + joined = true; + added += 1; + break; + } + } + if !joined { + // name the pads of the groups left apart + let mut apart = Vec::new(); + for p in 0..m.pieces.len() { + let r = m.find(m.nisl + p); + if r == main { + continue; + } + for &id in &m.pieces[p] { + if let crate::board::Shape::Pad(k) = self.b.items[id].shape { + apart.push(format!("{}:{}", self.b.pads[k].refdes, self.b.pads[k].num)); + } + } + } + self.log.push(json!([name, "pour groups apart", groups.len() - 1, "joints added", added, "pads apart", apart])); + return (groups.len() - 1, added); + } + } + } +} diff --git a/tools/router-rs/src/router.rs b/tools/router-rs/src/router.rs new file mode 100644 index 0000000..b22b78a --- /dev/null +++ b/tools/router-rs/src/router.rs @@ -0,0 +1,1268 @@ +//! Routing strategies on top of the board fields (port of tools/router/pipeline.py): +//! plane drops, component joining, pad pairs, decoupling caps, rip-up and reroute. + +use crate::board::{Board, Item, Owner, SearchOpts, Seg, Shape, CLR, CU_STEP, M, RDIAG, RES}; +use crate::geom::{bbox_gap, point_seg, poly_poly, seg_poly, seg_seg, Poly, Pt}; +use crate::io::{BoardJson, FpJson, RoutesJson, TrackJson, ViaJson}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +/// Per-connection settings; unset fields take the net class or the search defaults. +#[derive(Clone, Debug, Default)] +pub struct NetOpts { + pub w: Option<f64>, + pub wneck: Option<f64>, + pub via_d: Option<f64>, + pub via_cost: Option<f64>, + pub via_cmult: Option<f64>, + pub bmult: Option<f64>, + pub turn: Option<f64>, + pub allow_via: Option<bool>, + pub max_expand: Option<i64>, + pub hweight: Option<f64>, + pub margin: Option<f64>, + pub hug: Option<f64>, + pub neck: Option<f64>, + pub neck_zone: Option<f64>, +} + +impl NetOpts { + pub fn search(&self) -> SearchOpts { + let d = SearchOpts::default(); + SearchOpts { + via_cost: self.via_cost.unwrap_or(d.via_cost), + via_cmult: self.via_cmult.unwrap_or(d.via_cmult), + bmult: self.bmult.unwrap_or(d.bmult), + turn: self.turn.unwrap_or(d.turn), + allow_via: self.allow_via.unwrap_or(d.allow_via), + layer_mask: d.layer_mask, + max_expand: self.max_expand.unwrap_or(d.max_expand), + hweight: self.hweight.unwrap_or(d.hweight), + margin: self.margin.unwrap_or(d.margin), + hug: self.hug.unwrap_or(d.hug), + neck: self.neck.unwrap_or(d.neck), + neck_zone: self.neck_zone.unwrap_or(d.neck_zone), + } + } +} + +pub type PadRef = (String, String); + +/// Search margin (mm) for a net rerouted whole after being stuck in conflict. +const WIDE_MARGIN: f64 = 5.0; + +struct Redo { + cost: Option<String>, + pads: Option<Vec<PadRef>>, + root: Option<PadRef>, + opts: NetOpts, +} + +pub struct Router { + pub b: Board, + netclass: HashMap<String, String>, + width: HashMap<String, f64>, + via: HashMap<String, f64>, + pub plane_nets: Vec<String>, + pub fps: BTreeMap<String, FpJson>, + pub log: Vec<Value>, + pub net_items: Vec<Vec<usize>>, + pub failed: Vec<Vec<String>>, + pub pads_by_net: Vec<Vec<usize>>, + registry: HashMap<String, Vec<Redo>>, + /// negotiation: each net's search paths (states, neck flags, radii) for conflict checks + paths: Vec<Vec<PathRec>>, + /// the nets of the last negotiation, for the cleanup + pub(crate) jobs: Vec<Job>, + /// print progress notes (off when many boards are routed in parallel) + pub verbose: bool, + /// copper pours: net, layer, outline + pub zones: Vec<(i32, usize, crate::geom::Poly)>, + /// route.toml [[bundle]]s: nets the cleanup draws together (pairs, buses) + pub bundles: Vec<Vec<i32>>, + /// nets whose copper the output leaves out (route.toml [[escape]] lines) + pub hidden: BTreeSet<i32>, + /// track width of [[escape]] nets where the escape sets one (instead of their class's) + pub escape_w: HashMap<String, f64>, +} + +struct PathRec { + items: Vec<usize>, + states: Vec<i32>, + neck: Vec<u8>, + r_nom: f32, + r_neck: f32, + r_via: f32, +} + +/// One net of a negotiated routing. +#[derive(Clone, Debug)] +pub struct Job { + pub name: String, + pub cost: String, + pub root: Option<PadRef>, + pub decaps: bool, + pub priority: i32, + pub opts: NetOpts, + /// a plane net: each SMD pad drops to a via (opts: w 0.4, wneck 0.25, via_cost 12, + /// via_cmult 2 unless set) + pub plane: bool, + /// pad pairs routed first: (a, b, cost map, settings) + pub joins: Vec<(PadRef, PadRef, String, NetOpts)>, +} + +#[derive(Clone, Copy, Debug)] +pub struct Negotiation { + pub rounds: usize, + pub pres: f32, + pub pres_mult: f32, + pub hist: f32, + /// extra cost per step away from the net's [[bundle]] partners (0: off) + pub attract: f64, +} + +pub fn mst(pts: &[Pt]) -> Vec<(Pt, Pt)> { + let n = pts.len(); + if n < 2 { + return Vec::new(); + } + let mut in_t = vec![false; n]; + in_t[0] = true; + let mut dist: Vec<f64> = pts.iter().map(|p| (p.0 - pts[0].0).hypot(p.1 - pts[0].1)).collect(); + let mut par = vec![0; n]; + let mut edges = Vec::new(); + for _ in 0..n - 1 { + let mut k = usize::MAX; + for i in 0..n { + if !in_t[i] && (k == usize::MAX || dist[i] < dist[k]) { + k = i; + } + } + in_t[k] = true; + edges.push((pts[par[k]], pts[k])); + for i in 0..n { + if !in_t[i] { + let d = (pts[i].0 - pts[k].0).hypot(pts[i].1 - pts[k].1); + if d < dist[i] { + dist[i] = d; + par[i] = k; + } + } + } + } + edges +} + +/// Capacitance in uF from a value such as "100n" or "4.7uF" (0 if unreadable). +fn cap_value_uf(v: &str) -> f64 { + let s = v.trim_start(); + let end = s.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(s.len()); + let Ok(x) = s[..end].parse::<f64>() else { return 0.0 }; + let m = match s[end..].trim_start().chars().next() { + Some('p') => 1e-6, + Some('n') => 1e-3, + Some('u') | Some('µ') => 1.0, + Some('m') => 1e3, + _ => 1.0, + }; + x * m +} + +impl Router { + pub fn new(d: &BoardJson, plane_nets: &[String], area: Vec<Poly>, area_margin: f64) -> Router { + let b = Board::new(d, plane_nets, area, area_margin); + let mut width: HashMap<String, f64> = HashMap::from([("Default".to_string(), 0.2)]); + let mut via = HashMap::new(); + for (k, c) in &d.classes { + width.insert(k.clone(), c.track); + if c.via != 0.6 { + via.insert(k.clone(), c.via); + } + } + let nn = b.netnames.len(); + let mut pads_by_net = vec![Vec::new(); nn]; + for (k, p) in b.pads.iter().enumerate() { + if p.net >= 0 { + pads_by_net[p.net as usize].push(k); + } + } + let zones = d + .zones + .iter() + .filter_map(|z| { + let net = *b.netid.get(&z.net)?; + let l = if z.layer == "B.Cu" { 1 } else { 0 }; + Some((net, l, crate::geom::Poly::new(z.pts.iter().map(|p| (p[0], p[1])).collect()))) + }) + .collect(); + Router { + zones, + b, + netclass: d.netclass.clone(), + width, + via, + plane_nets: plane_nets.to_vec(), + fps: d.fps.clone(), + log: Vec::new(), + net_items: vec![Vec::new(); nn], + failed: Vec::new(), + pads_by_net, + registry: HashMap::new(), + paths: (0..nn).map(|_| Vec::new()).collect(), + jobs: Vec::new(), + verbose: true, + bundles: Vec::new(), + hidden: BTreeSet::new(), + escape_w: HashMap::new(), + } + } + + pub fn nid(&self, name: &str) -> i32 { + *self.b.netid.get(name).unwrap_or_else(|| panic!("no net {name}")) + } + + fn nets(&self) -> impl Iterator<Item = i32> { + 1..self.b.netnames.len() as i32 + } + + /// A net's track width unless a step or [nets.NAME] sets one: its [[escape]] width, else its + /// class's. + fn default_w(&self, name: &str, class: &str) -> f64 { + self.escape_w.get(name).copied().unwrap_or_else(|| *self.width.get(class).unwrap_or(&0.2)) + } + + /// Track width, neck width and via size for a net (class defaults, as pipeline.connect). + pub(crate) fn widths(&self, name: &str, o: &NetOpts) -> (f64, f64, f64) { + let c = self.netclass.get(name).map(String::as_str).unwrap_or("Default"); + let w = o.w.unwrap_or_else(|| self.default_w(name, c)); + let wneck = o.wneck.unwrap_or(if w > 0.2 { 0.2 } else { 0.0 }); + let via_d = o.via_d.unwrap_or_else(|| *self.via.get(c).unwrap_or(&0.6)); + (w, wneck, via_d) + } + + /// Failed connections that leave the board incomplete: those of nets still in pieces, and + /// drops of plane nets without a pour. A net that ended whole by another path is complete + /// (a failed join), and a poured plane net is judged by the pour check (`islands`). + pub fn failed_count(&self) -> usize { + let split = self.split_nets(&self.plane_nets); + let poured = |n: &str| self.zones.iter().any(|z| self.b.netname(z.0) == n); + self.failed + .iter() + .filter(|f| if self.plane_nets.contains(&f[0]) { !poured(&f[0]) } else { split.contains(&f[0]) }) + .count() + } + + /// Track and neck width of a job's net (plane drops: 0.4 / 0.25 unless set). + pub(crate) fn job_widths(&self, j: &Job) -> (f64, f64) { + if j.plane { + (j.opts.w.unwrap_or(0.4), j.opts.wneck.unwrap_or(0.25)) + } else { + let (w, wn, _) = self.widths(&j.name, &j.opts); + (w, wn) + } + } + + /// Track length (mm) narrower than its net's width, outside the net's pads (stubs into a + /// small pad are not counted). Plane nets are left out. + pub fn necked_mm(&self) -> f64 { + self.nets().filter(|&n| !self.plane_nets.iter().any(|p| p == self.b.netname(n))).map(|n| self.net_necked_mm(n)).sum() + } + + /// necked_mm of one net. + pub(crate) fn net_necked_mm(&self, net: i32) -> f64 { + let name = self.b.netname(net); + let w = match self.jobs.iter().find(|j| j.name == name) { + Some(j) => self.job_widths(j).0, + None => self.widths(name, &NetOpts::default()).0, + }; + let mut total = 0.0; + for &id in &self.net_items[net as usize] { + let it = &self.b.items[id]; + let Shape::Seg(a, c) = it.shape else { continue }; + if it.w >= w - 1e-9 || !self.b.alive[id] { + continue; + } + let mid = ((a.0 + c.0) / 2.0, (a.1 + c.1) / 2.0); + if self.pads_by_net[net as usize].iter().any(|&k| self.b.pads[k].poly.contains(mid)) { + continue; + } + total += (a.0 - c.0).hypot(a.1 - c.1); + } + total + } + + pub fn set_cost(&mut self, name: &str) { + assert!(self.b.costs.contains_key(name), "no cost map {name}"); + self.b.cost = name.to_string(); + } + + pub fn pad_item(&self, net: i32, r: &PadRef) -> usize { + self.pads_by_net[net as usize] + .iter() + .map(|&k| &self.b.pads[k]) + .find(|p| p.refdes == r.0 && p.num == r.1) + .unwrap_or_else(|| panic!("no pad {}:{} on {}", r.0, r.1, self.b.netname(net))) + .item + } + + // ----- congestion estimate (RUDY over MST edges of signal nets) ----- + pub fn build_rudy(&self) -> Vec<f32> { + let b = &self.b; + let mut r = vec![0f32; b.n]; + for net in self.nets() { + let name = b.netname(net); + if self.plane_nets.iter().any(|p| p == name) { + continue; + } + let pts: Vec<Pt> = self.pads_by_net[net as usize].iter().map(|&k| (b.pads[k].x, b.pads[k].y)).collect(); + for (a, c) in mst(&pts) { + let (x0, x1) = (a.0.min(c.0) - 0.4, a.0.max(c.0) + 0.4); + let (y0, y1) = (a.1.min(c.1) - 0.4, a.1.max(c.1) + 0.4); + let dens = (((x1 - x0) + (y1 - y0)) / ((x1 - x0) * (y1 - y0)) * 0.25) as f32; + let (i0, j0) = b.xy_cell(x0, y0); + let (i1, j1) = b.xy_cell(x1, y1); + for j in j0.max(0)..=j1.min(b.ny as i64 - 1) { + for i in i0.max(0)..=i1.min(b.nx as i64 - 1) { + r[j as usize * b.nx + i as usize] += dens; + } + } + } + } + r + } + + // ----- geometry helpers ----- + fn item_xy_dist(&self, id: usize, xy: Pt) -> f32 { + self.b.item_dist(&self.b.items[id], xy.0, xy.1) + } + + /// Distance between two items' copper (negative where they overlap). + pub(crate) fn item_item(&self, a: usize, c: usize) -> f64 { + let (ia, ic) = (&self.b.items[a], &self.b.items[c]); + let pads = &self.b.pads; + match (ia.shape, ic.shape) { + (Shape::Pad(p), Shape::Pad(q)) => poly_poly(&pads[p].poly, &pads[q].poly), + (Shape::Pad(p), Shape::Seg(s, e)) | (Shape::Seg(s, e), Shape::Pad(p)) => { + let w = if let Shape::Seg(..) = ia.shape { ia.w } else { ic.w }; + seg_poly(s, e, &pads[p].poly) - w / 2.0 + } + (Shape::Pad(p), Shape::Via(v)) | (Shape::Via(v), Shape::Pad(p)) => { + let w = if let Shape::Via(..) = ia.shape { ia.w } else { ic.w }; + pads[p].poly.dist(v) - w / 2.0 + } + (Shape::Seg(s, e), Shape::Seg(t, f)) => seg_seg(s, e, t, f) - ia.w / 2.0 - ic.w / 2.0, + (Shape::Seg(s, e), Shape::Via(v)) | (Shape::Via(v), Shape::Seg(s, e)) => point_seg(v, s, e) - ia.w / 2.0 - ic.w / 2.0, + (Shape::Via(v), Shape::Via(u)) => (v.0 - u.0).hypot(v.1 - u.1) - ia.w / 2.0 - ic.w / 2.0, + // footprint copper: its sample points against the other item + (Shape::Cu(k), _) => self.b.cu[k].iter().map(|p| self.b.item_dist(ic, p.0, p.1) as f64).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0, + (_, Shape::Cu(k)) => self.b.cu[k].iter().map(|p| self.b.item_dist(ia, p.0, p.1) as f64).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0, + } + } + + /// Connected pieces of copper, in order of their first item. + pub fn components(&self, ids: &[usize]) -> Vec<Vec<usize>> { + let n = ids.len(); + let mut par: Vec<usize> = (0..n).collect(); + fn f(par: &mut [usize], mut a: usize) -> usize { + while par[a] != a { + par[a] = par[par[a]]; + a = par[a]; + } + a + } + for i in 0..n { + let ii = &self.b.items[ids[i]]; + for j in i + 1..n { + let ij = &self.b.items[ids[j]]; + if ii.layers & ij.layers == 0 || bbox_gap(&ii.bbox, &ij.bbox, 1e-4) { + continue; + } + if self.item_item(ids[i], ids[j]) <= 1e-4 { + let (a, c) = (f(&mut par, i), f(&mut par, j)); + if a != c { + par[a] = c; + } + } + } + } + let mut order: Vec<usize> = Vec::new(); + let mut groups: HashMap<usize, Vec<usize>> = HashMap::new(); + for i in 0..n { + let r = f(&mut par, i); + groups.entry(r).or_insert_with(|| { + order.push(r); + Vec::new() + }); + groups.get_mut(&r).unwrap().push(ids[i]); + } + order.into_iter().map(|r| groups.remove(&r).unwrap()).collect() + } + + /// Draw the next searches towards the copper of the net's [[bundle]] partners (see + /// Board::set_attract); returns whether the net has any. Reset with set_attract(&[], 0.0). + pub(crate) fn attract_partners(&mut self, net: i32, cost: f64) -> bool { + let partners: Vec<i32> = self.bundles.iter().filter(|b| b.contains(&net)).flatten().copied().filter(|&p| p != net).collect(); + if cost > 0.0 && !partners.is_empty() { + let items: Vec<usize> = partners.iter().flat_map(|&p| self.net_items_all(p)).collect(); + self.b.set_attract(&items, cost); + } + !partners.is_empty() + } + + pub fn net_items_all(&self, net: i32) -> Vec<usize> { + let mut v: Vec<usize> = self.pads_by_net[net as usize].iter().map(|&k| self.b.pads[k].item).collect(); + v.extend_from_slice(&self.net_items[net as usize]); + v + } + + fn comp_pts(&self, comp: &[usize]) -> Vec<Pt> { + let mut pts = Vec::new(); + for &id in comp { + match self.b.items[id].shape { + Shape::Seg(a, c) => { + pts.push(a); + pts.push(c); + } + Shape::Via(p) => pts.push(p), + Shape::Pad(k) => pts.push(self.b.pads[k].poly.centroid()), + Shape::Cu(k) => pts.push(self.b.cu[k][0]), + } + } + pts + } + + fn item_containing(&self, ids: &[usize], xy: Pt, l: usize) -> Option<usize> { + let mut best = None; + for &id in ids { + let it = &self.b.items[id]; + if !it.on(l) { + continue; + } + match it.shape { + Shape::Pad(k) => { + if self.b.pads[k].poly.dist(xy) < 1e-6 { + return Some(id); + } + } + _ => { + if self.item_xy_dist(id, xy) <= 1e-6 { + best = Some(id); + } + } + } + } + best + } + + /// Straight stub from a path end to the centre of the pad, via or track it ends in. + fn end_stub(&self, id: usize, xy: Pt, l: usize, w: f64) -> Option<Seg> { + let it = &self.b.items[id]; + let near = |p: Pt| (p.0 - xy.0).hypot(p.1 - xy.1) < 1e-6; + match it.shape { + Shape::Pad(k) => { + let c = self.b.pads[k].poly.centroid(); + if near(c) { + return None; + } + Some((l, xy, c, w.min(self.b.pads[k].poly.minor()))) + } + Shape::Via(p) => { + if it.owner == Owner::Waypoint || near(p) { + return None; + } + Some((l, xy, p, w.min(it.w))) + } + Shape::Seg(a, c) => { + let (dx, dy) = (c.0 - a.0, c.1 - a.1); + let l2 = dx * dx + dy * dy; + let t = if l2 == 0.0 { 0.0 } else { (((xy.0 - a.0) * dx + (xy.1 - a.1) * dy) / l2).clamp(0.0, 1.0) }; + let q = (a.0 + t * dx, a.1 + t * dy); + if near(q) { + return None; + } + Some((l, xy, q, w.min(it.w))) + } + Shape::Cu(_) => None, + } + } + + /// Keep a stub only where its copper clears every foreign item exactly; narrow it if needed. + fn safe_stub(&self, net: i32, st: Seg) -> Option<Seg> { + let (l, a, c, w) = st; + let (x0, y0, x1, y1) = (a.0.min(c.0), a.1.min(c.1), a.0.max(c.0), a.1.max(c.1)); + let mut dists = Vec::new(); + for (id, it) in self.b.items.iter().enumerate() { + if !self.b.alive[id] || it.net == net || !it.on(l) { + continue; + } + if !(it.bbox[0] < x1 + 1.0 && it.bbox[2] > x0 - 1.0 && it.bbox[1] < y1 + 1.0 && it.bbox[3] > y0 - 1.0) { + continue; + } + dists.push(match it.shape { + Shape::Pad(k) => seg_poly(a, c, &self.b.pads[k].poly), + Shape::Seg(s, e) => (seg_seg(a, c, s, e) - it.w / 2.0).max(0.0), + Shape::Via(p) => (point_seg(p, a, c) - it.w / 2.0).max(0.0), + Shape::Cu(k) => (self.b.cu[k].iter().map(|&p| point_seg(p, a, c)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0).max(0.0), + }); + } + for wd in [w, 0.25, 0.2] { + if wd > w { + continue; + } + if dists.iter().all(|&d| d >= wd / 2.0 + CLR + 0.005) { + return Some((l, a, c, wd)); + } + } + None + } + + #[allow(clippy::too_many_arguments)] + fn do_route( + &mut self, + net: i32, + src: &[usize], + tgt: &[usize], + w: f64, + wneck: f64, + via_d: f64, + goal_layer1: bool, + extra_tgt: Option<&[i32]>, + hxy: Option<Pt>, + so: &SearchOpts, + ) -> Option<Vec<usize>> { + let neck_items: Vec<usize> = tgt.iter().chain(src).copied().filter(|&id| matches!(self.b.items[id].shape, Shape::Pad(_))).take(60).collect(); + let mut r = self.b.route(net, src, tgt, goal_layer1, w, wneck, via_d, &neck_items, hxy, extra_tgt, so); + if r.is_none() && so.margin > 0.0 { + // nothing inside the window: the whole board + r = self.b.route(net, src, tgt, goal_layer1, w, wneck, via_d, &neck_items, hxy, extra_tgt, &SearchOpts { margin: 0.0, ..*so }); + } + let (path, neck) = r?; + let (mut segs, vias) = self.b.path_to_geom(&path, &neck, w, wneck); + let nx = self.b.nx; + let end = |s: i32| { + let (l, c) = (s as usize & 1, s as usize >> 1); + (l, self.b.cell_xy(c % nx, c / nx)) + }; + let (l0, xy0) = end(path[0]); + let (l1, xy1) = end(path[path.len() - 1]); + let w0 = if wneck != 0.0 && neck[0] != 0 { wneck } else { w }; + let w1 = if wneck != 0.0 && neck[neck.len() - 1] != 0 { wneck } else { w }; + let a = self.item_containing(src, xy0, l0).and_then(|id| self.end_stub(id, xy0, l0, w0)).and_then(|s| self.safe_stub(net, s)); + let tl: Vec<usize> = tgt.iter().chain(&self.net_items[net as usize]).copied().collect(); + let c = self.item_containing(&tl, xy1, l1).and_then(|id| self.end_stub(id, xy1, l1, w1)).and_then(|s| self.safe_stub(net, s)); + segs.extend(a); + segs.extend(c); + let items = self.b.commit(net, &segs, &vias, via_d); + if self.b.soft_mode { + self.paths[net as usize].push(PathRec { + items: items.clone(), + states: path, + neck, + r_nom: (w / 2.0 + CLR + M) as f32, + r_neck: if wneck != 0.0 { (wneck / 2.0 + CLR + M) as f32 } else { 0.0 }, + r_via: (via_d / 2.0 + CLR + M) as f32, + }); + } + self.net_items[net as usize].extend_from_slice(&items); + Some(items) + } + + /// Route from the copper `src` of a net to any of the states `tgt` (0.4 mm track, 0.25 mm + /// necks, vias of diameter d). + pub(crate) fn join_to(&mut self, net: i32, src: &[usize], tgt: &[i32], d: f64, so: &SearchOpts) -> bool { + self.do_route(net, src, &[], 0.4, 0.25, d, false, Some(tgt), None, so).is_some() + } + + fn pad_label(&self, id: usize) -> Vec<String> { + match self.b.items[id].shape { + Shape::Pad(k) => vec![self.b.pads[k].refdes.clone(), self.b.pads[k].num.clone()], + _ => vec!["copper".into()], + } + } + + // ----- plane nets: drop each SMD pad to the bottom plane ----- + #[allow(clippy::too_many_arguments)] + /// `skip_dropped`: leave out pads whose copper already reaches a via or THT pad (a + /// negotiation round redoes only the drops it ripped). + pub fn route_plane_net(&mut self, name: &str, w: f64, wneck: f64, via_cost: f64, via_cmult: f64, only: Option<&[PadRef]>, skip: &[PadRef], skip_dropped: bool) { + let net = self.nid(name); + let idx = self.pads_by_net[net as usize].clone(); + let has = |set: &[PadRef], k: usize| set.iter().any(|r| r.0 == self.b.pads[k].refdes && r.1 == self.b.pads[k].num); + let mut dropped = BTreeSet::new(); + if skip_dropped { + for cp in self.components(&self.net_items_all(net)) { + let down = cp.iter().any(|&id| match self.b.items[id].shape { + Shape::Via(_) => true, + Shape::Pad(k) => self.b.pads[k].tht, + _ => false, + }); + if down { + dropped.extend(cp); + } + } + } + let mut smd: Vec<usize> = idx + .iter() + .copied() + .filter(|&k| !self.b.pads[k].tht && only.is_none_or(|o| has(o, k)) && !has(skip, k) && !dropped.contains(&self.b.pads[k].item)) + .collect(); + // big pads (exposed pads) first + smd.sort_by(|&a, &c| (-self.b.pads[a].poly.area()).total_cmp(&-self.b.pads[c].poly.area())); + let mut planed: Vec<usize> = idx.iter().filter(|&&k| self.b.pads[k].tht).map(|&k| self.b.pads[k].item).collect(); + planed.extend(self.net_items[net as usize].iter().copied().filter(|&id| matches!(self.b.items[id].shape, Shape::Via(_)))); + let so = SearchOpts { via_cost, via_cmult, bmult: 50.0, turn: 2.0, ..Default::default() }; + let mut nf = 0; + for &k in &smd { + let pi = self.b.pads[k].item; + let touches = planed.iter().any(|&o| matches!(self.b.items[o].shape, Shape::Pad(_)) && poly_poly(&self.b.pads[k].poly, self.pad_poly(o)) < 1e-6); + if touches { + continue; + } + let bb = self.b.pads[k].poly.bbox; + if bb[2] - bb[0] > 2.5 && bb[3] - bb[1] > 2.5 { + let c = self.b.pads[k].poly.centroid(); + let (x0, y0) = (self.b.x0, self.b.y0); + let v = (((c.0 - x0) / RES).round_ties_even() * RES + x0, ((c.1 - y0) / RES).round_ties_even() * RES + y0); + let items = self.b.commit(net, &[], &[v], 0.6); + self.net_items[net as usize].extend_from_slice(&items); + planed.extend(items); + planed.push(pi); + continue; + } + let tgt_cells = if planed.is_empty() { None } else { Some(self.b.cells_of(&planed, 1)) }; + match self.do_route(net, &[pi], &[], w, wneck, 0.6, true, tgt_cells.as_deref(), None, &so) { + None => { + let mut f = vec![name.to_string()]; + f.extend(self.pad_label(pi)); + self.failed.push(f); + nf += 1; + } + Some(items) => { + planed.extend(items); + planed.push(pi); + } + } + } + self.log.push(json!([name, "plane pads", smd.len(), "failed", nf])); + } + + fn pad_poly(&self, id: usize) -> &crate::geom::Poly { + match self.b.items[id].shape { + Shape::Pad(k) => &self.b.pads[k].poly, + _ => unreachable!(), + } + } + + /// Join all copper of a net (or only the pieces containing `pads`) into one. + pub fn connect(&mut self, name: &str, root: Option<&PadRef>, pads: Option<&[PadRef]>, o: &NetOpts) -> usize { + let net = self.nid(name); + let (w, wneck, via_d) = self.widths(name, o); + let so = o.search(); + let max_tries = 2; + let mut tries: HashMap<usize, usize> = HashMap::new(); + let want: Option<Vec<usize>> = pads.map(|ps| ps.iter().map(|p| self.pad_item(net, p)).collect()); + let ri = root.map(|r| self.pad_item(net, r)); + loop { + let mut comps = self.components(&self.net_items_all(net)); + if let Some(want) = &want { + comps.retain(|cp| want.iter().any(|w| cp.contains(w))); + } + if comps.len() <= 1 { + break; + } + let main = match ri { + Some(ri) => comps.iter().position(|cp| cp.contains(&ri)).expect("root pad not in the net's copper"), + None => { + let mut m = 0; + for (k, cp) in comps.iter().enumerate() { + if cp.len() > comps[m].len() { + m = k; + } + } + m + } + }; + let p = self.comp_pts(&comps[main]); + let mut best: Option<(f64, usize)> = None; + for (k, cp) in comps.iter().enumerate() { + if k == main || *tries.get(&cp[0]).unwrap_or(&0) >= max_tries { + continue; + } + let q = self.comp_pts(cp); + let d = q.iter().flat_map(|a| p.iter().map(move |b| (a.0 - b.0).hypot(a.1 - b.1))).fold(f64::INFINITY, f64::min); + if best.is_none_or(|(bd, _)| d < bd) { + best = Some((d, k)); + } + } + let Some((_, t)) = best else { break }; + *tries.entry(comps[t][0]).or_insert(0) += 1; + // heuristic point: nearest point of the target to the main piece + let q = self.comp_pts(&comps[t]); + let mut qb = (f64::INFINITY, q[0]); + for &a in &q { + let d = p.iter().map(|b| (a.0 - b.0).hypot(a.1 - b.1)).fold(f64::INFINITY, f64::min); + if d < qb.0 { + qb = (d, a); + } + } + let (mc, tc) = (comps[main].clone(), comps[t].clone()); + if self.do_route(net, &mc, &tc, w, wneck, via_d, false, None, Some(qb.1), &so).is_none() { + let mut f = vec![name.to_string()]; + match tc.iter().find(|&&id| matches!(self.b.items[id].shape, Shape::Pad(_))) { + Some(&id) => f.extend(self.pad_label(id)), + None => f.push("copper".into()), + } + self.failed.push(f); + } + } + let n = self.components(&self.net_items_all(net)).len(); + self.log.push(json!([name, "components", n])); + n + } + + /// Route pad a to pad b directly (connect would join to the nearest copper of the net). + pub fn route_pair(&mut self, name: &str, a: &PadRef, b: &PadRef, o: &NetOpts) -> bool { + let net = self.nid(name); + let c = self.netclass.get(name).map(String::as_str).unwrap_or("Default"); + let w = o.w.unwrap_or_else(|| self.default_w(name, c)); + let wneck = o.wneck.unwrap_or(if w > 0.2 { 0.2 } else { 0.0 }); + let via_d = o.via_d.unwrap_or_else(|| *self.via.get(c).unwrap_or(&0.6)); + let (pa, pb) = (self.pad_item(net, a), self.pad_item(net, b)); + if self.components(&self.net_items_all(net)).iter().any(|cp| cp.contains(&pa) && cp.contains(&pb)) { + return true; + } + if self.do_route(net, &[pa], &[pb], w, wneck, via_d, false, None, None, &o.search()).is_none() { + self.failed.push(vec![name.to_string(), b.0.clone(), b.1.clone()]); + return false; + } + true + } + + /// Join each decoupling cap on the net to its nearest IC pin before the rest of the net. + /// A cap is a 2-pad C* part with its other pad on a plane net; candidates are pins of + /// parts with >= 4 pads, and for bulk caps (>= 4.7 uF) also inductors and ferrites. + pub fn connect_decaps(&mut self, name: &str, o: &NetOpts) { + let net = self.nid(name); + let mut nfp: HashMap<&str, usize> = HashMap::new(); + for q in &self.b.pads { + *nfp.entry(q.refdes.as_str()).or_insert(0) += 1; + } + let idx = &self.pads_by_net[net as usize]; + let mut pairs = Vec::new(); + for &k in idx { + let p = &self.b.pads[k]; + if !p.refdes.starts_with('C') { + continue; + } + let other: Vec<_> = self.b.pads.iter().enumerate().filter(|(j, q)| q.refdes == p.refdes && *j != k).map(|(_, q)| q).collect(); + if other.len() != 1 || other[0].net < 0 || !self.plane_nets.iter().any(|n| n == self.b.netname(other[0].net)) { + continue; + } + let bulk = cap_value_uf(self.fps.get(&p.refdes).map(|f| f.value.as_str()).unwrap_or("")) >= 4.7; + let mut best: Option<(f64, usize)> = None; + for &j in idx { + let q = &self.b.pads[j]; + let r = q.refdes.as_str(); + let ok = r != p.refdes && ((nfp[r] >= 4 && !r.starts_with('J') && !r.starts_with("TP")) || (bulk && (r.starts_with('L') || r.starts_with("FB")))); + if !ok { + continue; + } + let d = (q.x - p.x).hypot(q.y - p.y); + if best.is_none_or(|(bd, _)| d < bd) { + best = Some((d, j)); + } + } + if let Some((_, j)) = best { + let q = &self.b.pads[j]; + pairs.push(((p.refdes.clone(), p.num.clone()), (q.refdes.clone(), q.num.clone()))); + } + } + for (a, b) in pairs { + self.route_pair(name, &a, &b, o); + } + } + + pub fn place_via(&mut self, name: &str, x: f64, y: f64, d: f64) -> Option<usize> { + let net = self.nid(name); + let (i, j) = self.b.xy_cell(x, y); + let (x, y) = self.b.cell_xy(i as usize, j as usize); + if (self.b.hole[j as usize * self.b.nx + i as usize] as f64) < crate::board::via_drill(d) / 2.0 + crate::board::HOLE_HOLE + M { + if self.verbose { + eprintln!("via blocked by a hole {name} {x:.3} {y:.3}"); + } + return None; + } + for l in 0..2 { + let s = (j as usize * self.b.nx + i as usize) * 2 + l; + let fd = self.b.fdist(s, net); + if fd < (d / 2.0 + CLR + M) as f32 { + if self.verbose { + eprintln!("via blocked {name} {x:.3} {y:.3} {fd}"); + } + return None; + } + } + let items = self.b.commit(net, &[], &[(x, y)], d); + self.net_items[net as usize].extend_from_slice(&items); + Some(items[0]) + } + + /// Tie a pad to a new via at xy (a THT ground pad that tracks would close in). + pub fn tie(&mut self, name: &str, pad: &PadRef, xy: Pt, w: Option<f64>, d: f64, o: &NetOpts) -> bool { + let net = self.nid(name); + let label = vec![name.to_string(), pad.0.clone(), pad.1.clone()]; + let Some(v) = self.place_via(name, xy.0, xy.1, d) else { + self.failed.push(label); + return false; + }; + let p = self.pad_item(net, pad); + let c = self.netclass.get(name).map(String::as_str).unwrap_or("Default"); + let w = w.unwrap_or_else(|| self.default_w(name, c)); + if self.do_route(net, &[p], &[v], w, 0.0, d, false, None, None, &o.search()).is_none() { + self.failed.push(label); + return false; + } + true + } + + /// Stitching vias on a grid wherever a via clears all foreign copper, keep-outs and the + /// edge on both layers and does not land in a pad. Only for a finished board. + pub fn stitch(&mut self, name: &str, pitch: f64, d: f64, area: Option<[f64; 4]>) -> usize { + let net = self.nid(name); + let [x0, y0, x1, y1] = area.unwrap_or([self.b.x0, self.b.y0, self.b.x1, self.b.y1]); + let r = (d / 2.0 + CLR + M) as f32; + let mut placed = Vec::new(); + let mut y = y0 + pitch / 2.0; + while y < y1 { + let mut x = x0 + pitch / 2.0; + while x < x1 { + let (i, j) = self.b.xy_cell(x, y); + let ok = (0..2).all(|l| { + let s = (j as usize * self.b.nx + i as usize) * 2 + l; + !(self.b.fdist(s, net) < r + || self.b.padd[s] < (d / 2.0 + 0.05) as f32 + || self.b.f[s].n1 == net && self.b.f[s].d1 < (d / 2.0 + 0.3) as f32) + }); + if ok { + let p = self.b.cell_xy(i as usize, j as usize); + placed.extend(self.b.commit(net, &[], &[p], d)); + } + x += pitch; + } + y += pitch; + } + self.net_items[net as usize].extend_from_slice(&placed); + self.log.push(json!([name, "stitching vias", placed.len()])); + placed.len() + } + + // ----- rip-up and reroute ----- + + /// connect() that remembers its cost map and settings, so repair() can redo it. + pub fn route_net(&mut self, name: &str, cost: Option<&str>, root: Option<&PadRef>, pads: Option<&[PadRef]>, o: &NetOpts) -> usize { + self.registry.entry(name.to_string()).or_default().push(Redo { + cost: cost.map(String::from), + pads: pads.map(|p| p.to_vec()), + root: root.cloned(), + opts: o.clone(), + }); + if let Some(c) = cost { + self.set_cost(c); + } + self.connect(name, root, pads, o) + } + + fn redo(&mut self, name: &str) { + let recs = match self.registry.get(name) { + Some(r) => r.iter().map(|r| (r.cost.clone(), r.pads.clone(), r.root.clone(), r.opts.clone())).collect(), + None => vec![(None, None, None, NetOpts::default())], + }; + for (cost, pads, root, opts) in recs { + if let Some(c) = cost { + self.set_cost(&c); + } + self.connect(name, root.as_ref(), pads.as_deref(), &opts); + } + } + + /// Remove the router's copper of a net (kept existing copper stays). + pub fn rip_net(&mut self, name: &str) { + let net = self.nid(name) as usize; + let items = std::mem::take(&mut self.net_items[net]); + let (keep, rip): (Vec<usize>, Vec<usize>) = items.into_iter().partition(|&id| self.b.items[id].owner == Owner::Existing); + self.b.remove_items(&rip); + self.net_items[net] = keep; + self.failed.retain(|f| f[0] != name); + } + + /// Nets whose copper is still in more than one piece. + pub fn split_nets(&self, skip: &[String]) -> Vec<String> { + let mut out = Vec::new(); + for net in self.nets() { + let name = self.b.netname(net); + if skip.iter().any(|s| s == name) || self.pads_by_net[net as usize].len() < 2 { + continue; + } + if self.components(&self.net_items_all(net)).len() > 1 { + out.push(name.to_string()); + } + } + out + } + + /// Rip-up and reroute: for each split net, remove the nets with copper within `radius` + /// of its unconnected pads, route it first, then route the removed nets again. Only nets + /// routed through route_net() are ripped; `protect` nets never are. + pub fn repair(&mut self, rounds: usize, radius: f64, protect: &BTreeSet<String>, skip: &[String]) -> Vec<String> { + for rnd in 0..rounds { + let bad = self.split_nets(skip); + self.log.push(json!(["repair", rnd, "split", bad])); + if bad.is_empty() { + return bad; + } + for name in &bad { + let net = self.nid(name); + let comps = self.components(&self.net_items_all(net)); + if comps.len() <= 1 { + continue; + } + let mut main = 0; + for (k, cp) in comps.iter().enumerate() { + if cp.len() > comps[main].len() { + main = k; + } + } + let pads: Vec<usize> = comps + .iter() + .enumerate() + .filter(|&(k, _)| k != main) + .flat_map(|(_, cp)| cp.iter().copied()) + .filter(|&id| matches!(self.b.items[id].shape, Shape::Pad(_))) + .collect(); + if pads.is_empty() { + continue; + } + let mut victims = BTreeSet::new(); + for id in 0..self.b.items.len() { + let it = &self.b.items[id]; + if !self.b.alive[id] || it.net < 0 || it.net == net || matches!(it.shape, Shape::Pad(_)) { + continue; + } + let vn = self.b.netname(it.net); + if protect.contains(vn) || skip.iter().any(|s| s == vn) || !self.registry.contains_key(vn) || victims.contains(vn) { + continue; + } + if pads.iter().any(|&p| !bbox_gap(&it.bbox, &self.b.items[p].bbox, radius) && self.item_item(id, p) <= radius) { + victims.insert(vn.to_string()); + } + } + self.rip_net(name); + for vn in &victims { + self.rip_net(vn); + } + self.redo(name); + for vn in &victims { + self.redo(vn); + } + } + } + self.split_nets(skip) + } + + // ----- negotiated congestion (PathFinder) ----- + + /// Remove a net's soft copper (negotiated routes), keeping anything routed before. + fn rip_soft(&mut self, net: i32) { + let items = std::mem::take(&mut self.net_items[net as usize]); + let (rip, keep): (Vec<usize>, Vec<usize>) = items.into_iter().partition(|&id| self.b.items[id].soft); + self.b.remove_items(&rip); + self.net_items[net as usize] = keep; + self.paths[net as usize].clear(); + let name = self.b.netname(net).to_string(); + self.failed.retain(|f| f[0] != name); + } + + /// Route the nets still in conflict with everyone else's copper hard, trying their orders + /// (all of them up to 4 nets, else forward and reverse) and keeping the one that leaves + /// the fewest nets in pieces. + fn legalize(&mut self, jobs: &[Job], left: &[usize]) { + fn perms(v: &[usize]) -> Vec<Vec<usize>> { + if v.len() <= 1 { + return vec![v.to_vec()]; + } + let mut out = Vec::new(); + for i in 0..v.len() { + let mut rest = v.to_vec(); + let x = rest.remove(i); + for mut p in perms(&rest) { + p.insert(0, x); + out.push(p); + } + } + out + } + let orders = if left.len() <= 4 { perms(left) } else { vec![left.to_vec(), left.iter().rev().copied().collect()] }; + let nets: Vec<i32> = left.iter().map(|&k| self.nid(&jobs[k].name)).collect(); + let mut best: Option<(usize, usize)> = None; // (split nets, order index) + for (oi, order) in orders.iter().enumerate() { + for &net in &nets { + self.rip_soft(net); + } + for &k in order { + self.route_job(&jobs[k], None); + } + let split = left.iter().filter(|&&k| !self.job_done(&jobs[k])).count(); + if best.is_none_or(|(b, _)| split < b) { + best = Some((split, oi)); + } + if split == 0 { + break; + } + } + let (split, oi) = best.unwrap(); + self.log.push(json!(["legalize", left.len(), "orders tried", orders.len().min(oi + 1), "split", split])); + // without a clean order the board holds the last one tried: route the best again + if split != 0 && oi + 1 != orders.len() { + for &net in &nets { + self.rip_soft(net); + } + for &k in &orders[oi] { + self.route_job(&jobs[k], None); + } + } + } + + /// A job's net is complete: in one piece, or for a plane net every drop routed. + fn job_done(&self, j: &Job) -> bool { + if j.plane { + !self.failed.iter().any(|f| f[0] == j.name) + } else { + self.components(&self.net_items_all(self.nid(&j.name))).len() <= 1 + } + } + + /// Remove only the connections (paths) of a net that are in conflict. + fn rip_paths(&mut self, net: i32, bad: &[usize]) { + let ni = net as usize; + let mut rip = Vec::new(); + for (k, p) in std::mem::take(&mut self.paths[ni]).into_iter().enumerate() { + if bad.contains(&k) { + rip.extend(p.items); + } else { + self.paths[ni].push(p); + } + } + self.net_items[ni].retain(|id| !rip.contains(id)); + self.b.remove_items(&rip); + let name = self.b.netname(net).to_string(); + self.failed.retain(|f| f[0] != name); + } + + /// Route a job's net; `bad` = its paths in conflict (None: rip the whole net first and + /// search a wider window, WIDE_MARGIN, around each connection). + pub(crate) fn route_job(&mut self, j: &Job, bad: Option<&[usize]>) { + let net = self.nid(&j.name); + if j.plane { + match bad { + Some(b) => self.rip_paths(net, b), + None => self.rip_soft(net), + } + self.set_cost(&j.cost); + let (w, wneck) = self.job_widths(j); + self.route_plane_net(&j.name, w, wneck, j.opts.via_cost.unwrap_or(12.0), j.opts.via_cmult.unwrap_or(2.0), None, &[], true); + return; + } + let wide; + let j = match bad { + Some(b) => { + self.rip_paths(net, b); + j + } + None => { + self.rip_soft(net); + let mut w = j.clone(); + let m = w.opts.margin.map(|m| if m > 0.0 { m.max(WIDE_MARGIN) } else { m }); + w.opts.margin = m; + for jn in &mut w.joins { + jn.3.margin = m; + } + wide = w; + &wide + } + }; + for (a, b, cost, o) in &j.joins { + self.set_cost(cost); + self.route_pair(&j.name, a, b, o); + } + self.set_cost(&j.cost); + if j.decaps { + self.connect_decaps(&j.name, &j.opts); + } + self.connect(&j.name, j.root.as_ref(), None, &j.opts); + } + + /// States of a net's paths whose copper violates clearance to other nets' soft copper, + /// and the nets it conflicts with. + fn conflicts(&self, net: i32) -> (Vec<usize>, BTreeSet<i32>, Vec<usize>) { + let (mut cells, mut nets, mut bad) = (Vec::new(), BTreeSet::new(), Vec::new()); + let sf = &self.b.soft; + let nx = self.b.nx as i32; + let mut hit = |s: usize, r: f32, cells: &mut Vec<usize>| { + let f = sf[s]; + if f.fdist(net) < r { + cells.push(s); + nets.insert(if f.n1 == net { -2 } else { f.n1 }); + } + }; + for (pi, p) in self.paths[net as usize].iter().enumerate() { + let n0 = cells.len(); + for k in 0..p.states.len() { + let s = p.states[k] as usize; + if k > 0 && (p.states[k - 1] as usize & 1) != (s & 1) { + hit(s & !1, p.r_via, &mut cells); + hit(s | 1, p.r_via, &mut cells); + continue; + } + let diag = k > 0 && { + let (a, b) = ((p.states[k - 1] >> 1), (p.states[k] >> 1)); + a % nx != b % nx && a / nx != b / nx + }; + let r = if p.neck[k] != 0 && p.r_neck > 0.0 { p.r_neck } else { p.r_nom } + if diag { RDIAG as f32 } else { 0.0 }; + hit(s, r, &mut cells); + } + if cells.len() > n0 { + bad.push(pi); + } + } + nets.remove(&-2); + (cells, nets, bad) + } + + /// Route all jobs at once: each round routes the nets in conflict against everyone + /// else's copper, with conflicts priced by a present factor that grows every round and a + /// history cost on cells that stayed in conflict. Nets still in conflict after the last + /// round are routed again with other nets' copper hard; what fails then is reported. + pub fn negotiate(&mut self, jobs: &[Job], o: &Negotiation) { + self.b.soft_mode = true; + self.b.commit_owner = Owner::Negotiated; + self.b.pres = o.pres; + let mut todo: Vec<(usize, Option<Vec<usize>>)> = (0..jobs.len()).map(|k| (k, Some(Vec::new()))).collect(); + let mut left: Vec<usize> = Vec::new(); + let mut stuck = vec![0usize; jobs.len()]; // rounds in conflict in a row + for round in 0..o.rounds { + let t = std::time::Instant::now(); + for (k, bad) in &todo { + let net = self.nid(&jobs[*k].name); + self.attract_partners(net, o.attract); + self.route_job(&jobs[*k], bad.as_deref()); + self.b.set_attract(&[], 0.0); + } + let dt = t.elapsed().as_secs_f64(); + left.clear(); + let mut next = Vec::new(); + let mut ncells = 0; + for (k, j) in jobs.iter().enumerate() { + let net = self.nid(&j.name); + let (cells, others, bad) = self.conflicts(net); + if !cells.is_empty() && std::env::var("ROUTER_TRACE").is_ok() && round + 1 == o.rounds { + let xy: Vec<_> = cells.iter().map(|&s| { let c = s >> 1; let p = self.b.cell_xy(c % self.b.nx, c / self.b.nx); (s & 1, (p.0 * 100.0).round() / 100.0, (p.1 * 100.0).round() / 100.0) }).collect(); + eprintln!("CONFLICT {} with {:?}: {:?}", j.name, others.iter().map(|&n| self.b.netname(n)).collect::<Vec<_>>(), xy); + } + if !cells.is_empty() { + ncells += cells.len(); + for s in cells { + self.b.hist[s] += o.hist; + } + left.push(k); + stuck[k] += 1; + // reroute the conflicting connections; the whole net if that keeps failing + next.push((k, if stuck[k] % 3 == 0 { None } else { Some(bad) })); + } else { + stuck[k] = 0; + } + } + self.log.push(json!(["negotiate", round, "pres", self.b.pres, "conflicting nets", left.len(), "cells", ncells, "routed", todo.len(), "s", (dt * 1000.0).round() / 1000.0])); + if left.is_empty() { + break; + } + todo = next; + self.b.pres *= o.pres_mult; + } + if !left.is_empty() { + let names: Vec<&str> = left.iter().map(|&k| jobs[k].name.rsplit('/').next().unwrap()).collect(); + if self.verbose { + println!("still in conflict after {} rounds: {:?}", o.rounds, names); + } + self.b.pres = f32::INFINITY; + self.legalize(jobs, &left); + } + self.b.soft_mode = false; + self.b.pres = 0.0; + self.b.harden(); + self.paths.iter_mut().for_each(Vec::clear); + self.b.commit_owner = Owner::Routed; + self.jobs = jobs.to_vec(); + let pruned = self.prune_dangling(); + self.log.push(json!(["negotiate", "dangling pruned", pruned])); + } + + /// Add tracks and vias as fixed copper (saved with the result, never ripped). + pub fn load_existing(&mut self, tracks: &[TrackJson], vias: &[ViaJson], keep: impl Fn(&str) -> bool) { + for t in tracks { + let Some(&net) = self.b.netid.get(&t.net) else { continue }; + if !keep(&t.net) { + continue; + } + let l = if t.layer == "F.Cu" { 0 } else { 1 }; + let id = self.b.add(Board::seg_item(net, l, (t.x1, t.y1), (t.x2, t.y2), t.w, Owner::Existing)); + self.net_items[net as usize].push(id); + } + for v in vias { + let Some(&net) = self.b.netid.get(&v.net) else { continue }; + if !keep(&v.net) { + continue; + } + let id = self.b.add(Board::via_item(net, (v.x, v.y), v.d, 3, Owner::Existing)); + self.net_items[net as usize].push(id); + } + } + + pub fn add_item(&mut self, it: Item) -> usize { + let net = it.net; + let id = self.b.add(it); + if net >= 0 { + self.net_items[net as usize].push(id); + } + id + } + + pub fn geometry(&self) -> (Vec<TrackJson>, Vec<ViaJson>) { + let (mut segs, mut vias) = (Vec::new(), Vec::new()); + for net in self.nets().filter(|n| !self.hidden.contains(n)) { + let name = self.b.netname(net).to_string(); + for &id in &self.net_items[net as usize] { + let it = &self.b.items[id]; + match it.shape { + Shape::Seg(a, c) if (a.0 - c.0).hypot(a.1 - c.1) < 1e-6 => {} + Shape::Seg(a, c) => segs.push(TrackJson { + net: name.clone(), + layer: if it.on(0) { "F.Cu" } else { "B.Cu" }.into(), + x1: a.0, + y1: a.1, + x2: c.0, + y2: c.1, + w: it.w, + }), + Shape::Via(p) => vias.push(ViaJson { net: name.clone(), x: p.0, y: p.1, d: it.w, drill: if it.w >= 0.8 { 0.4 } else { 0.3 } }), + Shape::Pad(_) | Shape::Cu(_) => {} + } + } + } + (segs, vias) + } + + pub fn result(&self) -> RoutesJson { + let (segs, vias) = self.geometry(); + RoutesJson { segs, vias, failed: self.failed.clone(), log: self.log.clone() } + } +} diff --git a/tools/router-rs/src/run.rs b/tools/router-rs/src/run.rs new file mode 100644 index 0000000..8de3e65 --- /dev/null +++ b/tools/router-rs/src/run.rs @@ -0,0 +1,451 @@ +//! Run a route.toml on a board: fixed copper, cost maps, then the steps in order. + +use crate::config::{pad_ref, pad_refs, Area, Config, Step}; +use crate::geom::Poly; +use crate::io::{BoardJson, CopperJson}; +use crate::router::{mst, Job, Negotiation, Router}; +use anyhow::{bail, Context, Result}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::Path; + +pub struct Run { + pub r: Router, + pub protect: BTreeSet<String>, + pub done: BTreeSet<String>, + pub left: Vec<String>, +} + +fn resolve(r: &Router, prefix: &str, name: &str) -> Result<String> { + if r.b.netid.contains_key(name) { + return Ok(name.to_string()); + } + let p = format!("{prefix}{name}"); + if r.b.netid.contains_key(&p) { + return Ok(p); + } + bail!("no net {name:?} (prefix {prefix:?})") +} + +fn build_costs(r: &mut Router, cfg: &Config, d: &BoardJson) -> Result<()> { + let (n, nx, ny) = (r.b.n, r.b.nx as i64, r.b.ny as i64); + for (name, def) in &cfg.costs { + let mut c = vec![0f32; 2 * n]; + let layer = |s: &str| -> Result<usize> { + match s { + "F" | "F.Cu" => Ok(0), + "B" | "B.Cu" => Ok(1), + _ => bail!("cost {name}: layer {s:?} is not F or B"), + } + }; + if let Some(ru) = &def.rudy { + let l = layer(&ru.layer)?; + for (k, v) in r.build_rudy().into_iter().enumerate() { + c[k * 2 + l] += (v * ru.scale as f32).min(ru.max as f32); + } + } + for z in &def.zones { + let l = layer(&z.layer)?; + let (ox, oy) = match &z.fp { + Some(f) => { + let fp = d.fps.get(f).with_context(|| format!("cost {name}: no footprint {f}"))?; + (fp.x, fp.y) + } + None => (0.0, 0.0), + }; + let (i0, j0) = r.b.xy_cell(ox + z.rect[0], oy + z.rect[1]); + let (i1, j1) = r.b.xy_cell(ox + z.rect[2], oy + z.rect[3]); + for j in j0.max(0)..=j1.min(ny - 1) { + for i in i0.max(0)..=i1.min(nx - 1) { + c[(j * nx + i) as usize * 2 + l] += z.cost as f32; + } + } + } + r.b.costs.insert(name.clone(), c); + } + Ok(()) +} + +impl Run { + /// Load fixed copper and cost maps. `fixed` maps a [[fixed]] name to a file (overrides + /// its `path`); `base` is the directory of the route.toml. + pub fn new(d: &BoardJson, cfg: &Config, base: &Path, fixed: &HashMap<String, String>, verbose: bool) -> Result<Run> { + let area: Vec<Poly> = match &cfg.area { + None => Vec::new(), + Some(Area::Pours(s)) if s == "pours" => { + let a: Vec<Poly> = + d.zones.iter().filter(|z| cfg.plane_nets.contains(&z.net)).map(|z| Poly::new(z.pts.iter().map(|p| (p[0], p[1])).collect())).collect(); + if a.is_empty() { + bail!("area = \"pours\": board.json has no zones of {:?}", cfg.plane_nets); + } + a + } + Some(Area::Pours(s)) => bail!("area = {s:?}: give \"pours\" or a polygon [[x, y], ...]"), + Some(Area::Poly(p)) => vec![Poly::new(p.iter().map(|q| (q[0], q[1])).collect())], + }; + // [[escape]]: a virtual pad per net along the edge (ref "~ESC") + let mut de; + let (mut hidden, mut escape_w) = (Vec::new(), Vec::new()); + let d = if cfg.escape.is_empty() { + d + } else { + de = d.clone(); + let names: BTreeSet<&str> = d.pads.iter().map(|p| p.net.as_str()).collect(); + let mut k = 0; + for e in &cfg.escape { + let n = e.nets.len().max(2) - 1; + for (i, name) in e.nets.iter().enumerate() { + let p = format!("{}{name}", cfg.prefix); + let net = if names.contains(name.as_str()) { name.clone() } else if names.contains(p.as_str()) { p } else { bail!("escape: no net {name:?}") }; + let t = i as f64 / n as f64; + // on the routing grid: a pad between two cells may leave no cell to reach it from + let snap = |v: f64| (v / crate::board::RES).round() * crate::board::RES; + let (x, y, h) = (snap(e.from[0] + t * (e.to[0] - e.from[0])), snap(e.from[1] + t * (e.to[1] - e.from[1])), e.size / 2.0); + k += 1; + de.pads.push(crate::io::PadJson { + refdes: "~ESC".into(), + num: k.to_string(), + net: net.clone(), + x, + y, + drill: 0.0, + npth: false, + f: Some(vec![[x - h, y - h], [x + h, y - h], [x + h, y + h], [x - h, y + h]]), + b: None, + }); + if let Some(w) = e.w { + escape_w.push((net.clone(), w)); + } + if !e.keep { + hidden.push(net); + } + } + } + &de + }; + let mut r = Router::new(d, &cfg.plane_nets, area, cfg.area_margin); + r.hidden = hidden.iter().map(|n| r.b.netid[n]).collect(); + r.escape_w = escape_w.into_iter().collect(); + for b in &cfg.bundle { + let ids = b.nets.iter().map(|n| resolve(&r, &cfg.prefix, n).map(|n| r.b.netid[&n])).collect::<Result<Vec<i32>>>()?; + r.bundles.push(ids); + } + r.verbose = verbose; + let (mut protect, mut done) = (BTreeSet::new(), BTreeSet::new()); + for f in &cfg.fixed { + let path = match (fixed.get(&f.name), &f.path) { + (Some(p), _) => p.clone(), + (None, Some(p)) => base.join(p).to_string_lossy().into_owned(), + (None, None) if f.optional => { + if r.verbose { + println!("fixed {}: no file, skipped", f.name); + } + continue; + } + (None, None) => bail!("fixed {}: give --fixed {}=FILE", f.name, f.name), + }; + let old = CopperJson::load(&path)?; + let exclude: Vec<String> = f.exclude.iter().map(|n| resolve(&r, &cfg.prefix, n)).collect::<Result<_>>()?; + let keep: BTreeSet<String> = if f.unmoved { + // nets whose parts did not move and that lost no part keep their copper + let moved: BTreeSet<&str> = d + .fps + .iter() + .filter(|(k, p)| { + old.fps.get(*k).is_some_and(|o| (p.x - o.x).abs() > 1e-3 || (p.y - o.y).abs() > 1e-3 || (p.rot - o.rot).rem_euclid(360.0).abs() > 1e-3) + }) + .map(|(k, _)| k.as_str()) + .collect(); + let mut refs: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); + for p in d.pads.iter().filter(|p| !p.net.is_empty()) { + refs.entry(&p.net).or_default().insert(&p.refdes); + } + let mut old_refs: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); + for p in old.pads.iter().filter(|p| !p.net.is_empty()) { + old_refs.entry(&p.net).or_default().insert(&p.refdes); + } + refs.iter() + .filter(|(n, rs)| rs.is_disjoint(&moved) && !exclude.iter().any(|e| e == *n) && old_refs.get(*n).is_none_or(|o| o.is_subset(rs))) + .map(|(n, _)| n.to_string()) + .collect() + } else { + old.tracks.iter().map(|t| t.net.clone()).filter(|n| !exclude.contains(n)).collect() + }; + r.load_existing(&old.tracks, &old.vias, |n| keep.contains(n)); + let with_copper: BTreeSet<&str> = old.tracks.iter().filter(|t| keep.contains(&t.net)).map(|t| t.net.as_str()).collect(); + if r.verbose { + println!("fixed {}: {} nets with copper {:?}", f.name, with_copper.len(), with_copper.iter().map(|n| n.rsplit('/').next().unwrap()).collect::<Vec<_>>()); + } + if f.protect { + protect.extend(keep.iter().cloned()); + } + if f.done { + done.extend(keep.iter().cloned()); + } + } + build_costs(&mut r, cfg, d)?; + Ok(Run { r, protect, done, left: Vec::new() }) + } + + pub fn step(&mut self, cfg: &Config, s: &Step) -> Result<()> { + let r = &mut self.r; + let p = cfg.prefix.as_str(); + let o = s.opts(); + let names = |r: &Router| -> Result<Vec<String>> { + match (&s.nets, &s.net) { + (Some(v), _) => v.iter().map(|n| resolve(r, p, n)).collect(), + (None, Some(n)) => Ok(vec![resolve(r, p, n)?]), + _ => bail!("step {}: `net` or `nets` missing", s.kind), + } + }; + match s.kind.as_str() { + "via" => { + let net = resolve(r, p, s.net()?)?; + let (ox, oy) = match &s.fp { + Some(f) => { + let fp = r.fps.get(f).with_context(|| format!("via: no footprint {f}"))?; + (fp.x, fp.y) + } + None => (0.0, 0.0), + }; + for a in s.at.as_deref().unwrap_or(&[]) { + r.place_via(&net, ox + a[0], oy + a[1], s.d.unwrap_or(0.6)); + } + } + "plane" => { + let net = resolve(r, p, s.net()?)?; + if let Some(c) = &s.cost { + r.set_cost(c); + } + let only = s.only.as_deref().map(pad_refs).transpose()?; + let skip = pad_refs(s.skip.as_deref().unwrap_or(&[]))?; + r.route_plane_net(&net, s.w.unwrap_or(0.4), s.wneck.unwrap_or(0.25), s.via_cost.unwrap_or(12.0), s.via_cmult.unwrap_or(2.0), only.as_deref(), &skip, false); + } + "connect" => { + let root = s.root.as_deref().map(pad_ref).transpose()?; + let pads = s.pads.as_deref().map(pad_refs).transpose()?; + for net in names(r)? { + r.route_net(&net, s.cost.as_deref(), root.as_ref(), pads.as_deref(), &o); + } + } + "pair" => { + let net = resolve(r, p, s.net()?)?; + if let Some(c) = &s.cost { + r.set_cost(c); + } + let (a, b) = match (&s.a, &s.b) { + (Some(a), Some(b)) => (pad_ref(a)?, pad_ref(b)?), + _ => bail!("pair: `a` and `b` needed"), + }; + r.route_pair(&net, &a, &b, &o); + } + "decaps" => { + if let Some(c) = &s.cost { + r.set_cost(c); + } + for net in names(r)? { + r.connect_decaps(&net, &o); + } + } + "rest" => { + // every other net still in pieces, shortest MST first + let mut skip: BTreeSet<String> = self.done.clone(); + skip.extend(r.plane_nets.iter().cloned()); + for n in s.exclude.as_deref().unwrap_or(&[]) { + skip.insert(resolve(r, p, n)?); + } + let mut nets = Vec::new(); + for net in 1..r.b.netnames.len() as i32 { + let name = r.b.netname(net).to_string(); + let idx = &r.pads_by_net[net as usize]; + if skip.contains(&name) || idx.len() < 2 || r.components(&r.net_items_all(net)).len() <= 1 { + continue; + } + let pts: Vec<_> = idx.iter().map(|&k| (r.b.pads[k].x, r.b.pads[k].y)).collect(); + let len: f64 = mst(&pts).iter().map(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1)).sum(); + nets.push((len, name)); + } + nets.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1))); + for (_, name) in nets { + r.route_net(&name, s.cost.as_deref(), None, None, &o); + } + } + "negotiate" => { + let mut skip: BTreeSet<String> = self.done.clone(); + skip.extend(r.plane_nets.iter().cloned()); + for n in s.exclude.as_deref().unwrap_or(&[]) { + skip.insert(resolve(r, p, n)?); + } + let mut ncfg: BTreeMap<String, crate::config::NetCfg> = BTreeMap::new(); + for (n, c) in &cfg.nets { + ncfg.insert(resolve(r, p, n)?, c.clone()); + } + // each search stays within 1.5 mm of its connection unless the step says otherwise + let o = crate::router::NetOpts { margin: s.margin.or(Some(1.5)), ..o }; + let mut jobs = Vec::new(); + for net in 1..r.b.netnames.len() as i32 { + let name = r.b.netname(net).to_string(); + let idx = &r.pads_by_net[net as usize]; + if skip.contains(&name) || idx.len() < 2 || r.components(&r.net_items_all(net)).len() <= 1 { + continue; + } + let pts: Vec<_> = idx.iter().map(|&k| (r.b.pads[k].x, r.b.pads[k].y)).collect(); + let len: f64 = mst(&pts).iter().map(|(a, b)| (a.0 - b.0).hypot(a.1 - b.1)).sum(); + let c = ncfg.get(&name).cloned().unwrap_or_default(); + let cost = c.cost.clone().or(s.cost.clone()).unwrap_or_else(|| "none".into()); + let mut joins = Vec::new(); + for jn in &c.join { + let jo = crate::router::NetOpts { w: jn.w, wneck: jn.wneck, allow_via: jn.allow_via, ..c.opts(&o) }; + joins.push((pad_ref(&jn.a)?, pad_ref(&jn.b)?, jn.cost.clone().unwrap_or_else(|| cost.clone()), jo)); + } + let job = Job { + joins, + name, + cost, + root: c.root.as_deref().map(pad_ref).transpose()?, + decaps: c.decaps.or(s.decaps).unwrap_or(false), + priority: c.priority.unwrap_or(0), + opts: c.opts(&o), + plane: false, + }; + jobs.push((-job.priority, len, job)); + } + // planes = true: the plane nets' ground drops take part (first in each round) + if s.planes.unwrap_or(false) { + for name in r.plane_nets.clone() { + if !r.b.netid.contains_key(&name) { + continue; + } + let c = ncfg.get(&name).cloned().unwrap_or_default(); + let cost = c.cost.clone().or(s.cost.clone()).unwrap_or_else(|| "none".into()); + let job = Job { joins: vec![], name, cost, root: None, decaps: false, priority: c.priority.unwrap_or(10), opts: c.opts(&o), plane: true }; + jobs.push((-job.priority, 0.0, job)); + } + } + jobs.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then_with(|| a.2.name.cmp(&b.2.name))); + let jobs: Vec<Job> = jobs.into_iter().map(|j| j.2).collect(); + let neg = Negotiation { + rounds: s.rounds.unwrap_or(30), + pres: s.pres.unwrap_or(4.0) as f32, + pres_mult: s.pres_mult.unwrap_or(1.5) as f32, + hist: s.hist.unwrap_or(1.0) as f32, + attract: s.attract.unwrap_or(0.0), + }; + r.negotiate(&jobs, &neg); + } + "cleanup" => { + if r.jobs.is_empty() { + bail!("cleanup needs a negotiate step before it"); + } + r.cleanup(s.hug.unwrap_or(0.3), s.neck.unwrap_or(4.0), s.attract.unwrap_or(0.5)); + } + "repair" => { + let skip: Vec<String> = match &s.skip { + Some(v) => v.iter().map(|n| resolve(r, p, n)).collect::<Result<_>>()?, + None => r.plane_nets.clone(), + }; + let left = r.repair(s.rounds.unwrap_or(4), s.radius.unwrap_or(1.2), &self.protect, &skip); + if r.verbose { + println!("split after repair: {left:?}"); + } + // failures of nets that ended in one piece are history; plane drops are not + // part of the split check and keep theirs + let planes = r.plane_nets.clone(); + r.failed.retain(|f| left.contains(&f[0]) || planes.contains(&f[0])); + self.left = left; + } + "tie" => { + let net = resolve(r, p, s.net()?)?; + if let Some(c) = &s.cost { + r.set_cost(c); + } + let pad = pad_ref(s.pad.as_deref().context("tie: `pad` missing")?)?; + let at = s.at.as_deref().and_then(|a| a.first()).context("tie: `at` missing")?; + r.tie(&net, &pad, (at[0], at[1]), s.w, s.d.unwrap_or(0.6), &o); + } + "pour" => { + let nets = if s.net.is_some() || s.nets.is_some() { names(r)? } else { r.plane_nets.clone() }; + for net in nets { + let (left, added) = if s.fix.unwrap_or(true) { r.pour_fix(&net, s.d.unwrap_or(0.6)) } else { (r.pour_splits(&net), 0) }; + if r.verbose { + println!("pour {net}: {added} joints added, {left} groups apart"); + } + } + } + "stitch" => { + let net = resolve(r, p, s.net()?)?; + r.stitch(&net, s.pitch.unwrap_or(5.0), s.d.unwrap_or(0.6), s.area); + } + k => bail!("unknown step {k:?}"), + } + Ok(()) + } +} + +/// What a routed board came to. +#[derive(Clone, Debug, Default)] +pub struct Summary { + /// nets (not plane nets) still in more than one piece + pub split: usize, + /// failed connections, without those of plane nets that have a pour (see islands) + pub failed: usize, + /// groups of plane-net pads that the pours leave apart (beyond one per net) + pub islands: usize, + pub vias: usize, + pub length: f64, + /// track narrower than its net's width, outside pads + pub neck: f64, + pub bcu: f64, + /// [rank] score: weighted length + vias + neck + B.Cu (lower is better) + pub score: f64, + pub secs: f64, +} + +impl Summary { + /// Order for ranking routed boards: fewer split nets, failed connections, pour islands, + /// then the [rank] score. + pub fn key(&self) -> (usize, usize, usize, i64) { + (self.split, self.failed, self.islands, (self.score * 1000.0) as i64) + } +} + +impl Run { + pub fn summary(&self, cfg: &Config, secs: f64) -> Summary { + let r = &self.r; + let res = r.result(); + let len = |s: &crate::io::TrackJson| (s.x2 - s.x1).hypot(s.y2 - s.y1); + let rk = &cfg.rank; + let weight = |net: &str| { + let mut w = 1.0; + for n in &rk.nets { + if crate::config::glob(&n.pattern, net) || crate::config::glob(&format!("{}{}", cfg.prefix, n.pattern), net) { + w = n.weight; + } + } + w + }; + let (neck, bcu) = (r.necked_mm(), res.segs.iter().filter(|s| s.layer == "B.Cu").map(len).sum::<f64>()); + let wlen: f64 = res.segs.iter().map(|s| len(s) * weight(&s.net)).sum(); + Summary { + split: r.split_nets(&r.plane_nets).len(), + failed: r.failed_count(), + islands: r.plane_nets.iter().map(|n| r.pour_splits(n)).sum(), + vias: res.vias.len(), + length: res.segs.iter().map(len).sum(), + neck, + bcu, + score: wlen + rk.via_mm * res.vias.len() as f64 + rk.neck_mm * neck + rk.bcu_mm * bcu, + secs, + } + } +} + +/// Route a board with all steps of a route.toml (quietly, for many boards in parallel). +pub fn route(d: &BoardJson, cfg: &Config, base: &Path, fixed: &HashMap<String, String>) -> Result<(Run, Summary)> { + let t0 = std::time::Instant::now(); + let mut run = Run::new(d, cfg, base, fixed, false)?; + for s in &cfg.step { + run.step(cfg, s)?; + } + let sum = run.summary(cfg, t0.elapsed().as_secs_f64()); + Ok((run, sum)) +} diff --git a/tools/router/README.md b/tools/router/README.md new file mode 100644 index 0000000..a3f594e --- /dev/null +++ b/tools/router/README.md @@ -0,0 +1,12 @@ +# Router + +Scripted 2-layer grid maze router (A* in `astar.c`, strategies in `pipeline.py`), the +predecessor of the Rust router in `../router-rs`. Documentation, workflow and lessons: +[knowledge/tooling/router.md](../../knowledge/tooling/router.md). + +Setup once: + + python3 -m venv tools/router/.venv + tools/router/.venv/bin/pip install -r tools/router/requirements.txt + +The C core compiles itself (`cc`) on first import. diff --git a/tools/router/astar.c b/tools/router/astar.c new file mode 100644 index 0000000..3b3ccb5 --- /dev/null +++ b/tools/router/astar.c @@ -0,0 +1,136 @@ +// Grid A* maze router core, 2 layers (0 = F.Cu, 1 = B.Cu). +// Clearance uses exact distance fields: d1/n1 = distance to and net of nearest copper, +// d2 = distance to nearest copper of a net other than n1. Foreign distance for net X: +// n1 == X ? d2 : d1. +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <math.h> + +static int NX, NY, N; +static float *G = 0; static int32_t *PAR = 0; static uint32_t *STAMP = 0; static uint8_t *DIR = 0; static uint8_t *CLOSED = 0; +static uint32_t CALL = 0; +static int32_t *HEAPI = 0; static float *HEAPF = 0; static int HN = 0, HCAP = 0; + +int init(int nx, int ny) { + NX = nx; NY = ny; N = nx * ny; + free(G); free(PAR); free(STAMP); free(DIR); free(CLOSED); free(HEAPI); free(HEAPF); + G = malloc(sizeof(float) * 2 * N); PAR = malloc(sizeof(int32_t) * 2 * N); + STAMP = calloc(2 * N, sizeof(uint32_t)); DIR = malloc(2 * N); CLOSED = malloc(2 * N); + HCAP = 1 << 22; HEAPI = malloc(sizeof(int32_t) * HCAP); HEAPF = malloc(sizeof(float) * HCAP); + CALL = 0; + return (G && PAR && STAMP && DIR && CLOSED && HEAPI && HEAPF) ? 0 : -1; +} + +static void hpush(float f, int32_t i) { + if (HN >= HCAP) { HCAP *= 2; HEAPI = realloc(HEAPI, sizeof(int32_t) * HCAP); HEAPF = realloc(HEAPF, sizeof(float) * HCAP); } + int k = HN++; + while (k > 0) { int p = (k - 1) >> 1; if (HEAPF[p] <= f) break; HEAPF[k] = HEAPF[p]; HEAPI[k] = HEAPI[p]; k = p; } + HEAPF[k] = f; HEAPI[k] = i; +} +static int32_t hpop(void) { + int32_t top = HEAPI[0]; float lf = HEAPF[--HN]; int32_t li = HEAPI[HN]; + int k = 0; + while (1) { int c = 2 * k + 1; if (c >= HN) break; if (c + 1 < HN && HEAPF[c + 1] < HEAPF[c]) c++; if (HEAPF[c] >= lf) break; HEAPF[k] = HEAPF[c]; HEAPI[k] = HEAPI[c]; k = c; } + HEAPF[k] = lf; HEAPI[k] = li; + return top; +} + +static const int DX[8] = {1, 1, 0, -1, -1, -1, 0, 1}; +static const int DY[8] = {0, 1, 1, 1, 0, -1, -1, -1}; + +static inline float fdist(const float *d1, const int32_t *n1, const float *d2, int32_t s, int net) { + return n1[s] == net ? d2[s] : d1[s]; +} +static inline float heur(int x, int y, int hx, int hy) { + int ax = abs(x - hx), ay = abs(y - hy); + return (ax > ay ? ax : ay) + 0.41421356f * (ax < ay ? ax : ay); +} + +// Returns path length (cells, target back to source) or -1. +// neck flag per output cell: 1 if only the neck radius passed. +int route(const float *d1, const int32_t *n1, const float *d2, const float *padd, const float *costmap, + int net, const int32_t *src, int nsrc, const uint8_t *tgt, int goal_layer1, + int hx, int hy, + float r_nom, float r_neck, float r_via, float r_vpad, float r_diag, + const int32_t *neckbox, int nbox, + float via_cost, float via_cmult, float bmult, float turn_cost, int allow_via, int max_expand, + int32_t *out, uint8_t *outneck, int maxout, int layer_mask) +{ + CALL++; + if (CALL == 0) { memset(STAMP, 0, sizeof(uint32_t) * 2 * N); CALL = 1; } + HN = 0; + for (int i = 0; i < nsrc; i++) { + int32_t s = src[i]; + int L = s / N; if (!((layer_mask >> L) & 1)) continue; + float sfd = fdist(d1, n1, d2, s, net); + if (sfd < (r_neck > 0 ? r_neck : r_nom)) continue; // a track must fit at its start cell + STAMP[s] = CALL; G[s] = 0; PAR[s] = -1; DIR[s] = 255; CLOSED[s] = 0; + int c = s % N; + hpush(goal_layer1 ? 0 : heur(c % NX, c / NX, hx, hy), s); + } + int expanded = 0, found = -1; + while (HN > 0) { + int32_t s = hpop(); + if (CLOSED[s]) continue; + CLOSED[s] = 1; + int L = s / N; int c = s % N; int x = c % NX, y = c / NX; + if ((tgt && tgt[s]) || (goal_layer1 && L == 1)) { found = s; break; } + if (++expanded > max_expand) break; + float gcur = G[s]; + int pd = DIR[s]; + for (int d = 0; d < 8; d++) { + int qx = x + DX[d], qy = y + DY[d]; + if (qx < 0 || qy < 0 || qx >= NX || qy >= NY) continue; + int nc = qy * NX + qx; int32_t ns = (int32_t)(L * N + nc); + float fd = fdist(d1, n1, d2, ns, net); + float need = r_nom + ((d & 1) ? r_diag : 0); + int neck = 0; + if (fd < need) { + if (r_neck <= 0) continue; + float needn = r_neck + ((d & 1) ? r_diag : 0); + if (fd < needn) continue; + int nb = 0; + for (int b = 0; b < nbox; b++) { if (qx >= neckbox[4*b] && qx <= neckbox[4*b+2] && qy >= neckbox[4*b+1] && qy <= neckbox[4*b+3]) { nb = 1; break; } } + if (!nb) continue; + neck = 1; + } + float step = (d & 1) ? 1.41421356f : 1.0f; + float cst = step * (L ? bmult : 1.0f) + (costmap ? costmap[(size_t)L * N + nc] * step : 0); + if (neck) cst += 0.3f * step; + if (pd != 255 && pd != d) { + int t = abs(pd - d); if (t > 4) t = 8 - t; + if (t >= 3) continue; + cst += turn_cost * t; + } + float ng = gcur + cst; + if (STAMP[ns] == CALL && (CLOSED[ns] || G[ns] <= ng)) continue; + STAMP[ns] = CALL; G[ns] = ng; PAR[ns] = s; DIR[ns] = (uint8_t)d; CLOSED[ns] = 0; + hpush(ng + (goal_layer1 ? 0 : heur(qx, qy, hx, hy)), ns); + } + if (allow_via && ((layer_mask & 3) == 3)) { + int32_t s0 = c, s1 = N + c; + if (fdist(d1, n1, d2, s0, net) >= r_via && fdist(d1, n1, d2, s1, net) >= r_via && + padd[s0] >= r_vpad && padd[s1] >= r_vpad) { + int32_t ns = (int32_t)((1 - L) * N + c); + float ng = gcur + via_cost + (costmap ? via_cmult * (costmap[c] + costmap[N + c]) : 0); + if (!(STAMP[ns] == CALL && (CLOSED[ns] || G[ns] <= ng))) { + STAMP[ns] = CALL; G[ns] = ng; PAR[ns] = s; DIR[ns] = 255; CLOSED[ns] = 0; + hpush(ng + (goal_layer1 ? 0 : heur(x, y, hx, hy)), ns); + } + } + } + } + if (found < 0) return -1; + int n = 0; int32_t s = found; + while (s >= 0 && n < maxout) { + int32_t p = PAR[s]; + float fd = fdist(d1, n1, d2, s, net); + // the same test the search used to enter the cell: a full-width track that barely + // fits (e.g. 0.5 mm beside a bus line) must not be drawn necked all along its run + int dd = DIR[s]; + outneck[n] = fd < r_nom + ((dd != 255 && (dd & 1)) ? r_diag : 0) ? 1 : 0; + out[n++] = s; s = p; + } + return n; +} diff --git a/tools/router/dump_board.py b/tools/router/dump_board.py new file mode 100644 index 0000000..33b4528 --- /dev/null +++ b/tools/router/dump_board.py @@ -0,0 +1,105 @@ +"""Export what the router needs from a saved .kicad_pcb into JSON. + +Run with KiCad's bundled Python (pcbnew); the board's .kicad_pro is read for net classes: + + $KPY tools/router/dump_board.py board.kicad_pcb board.json + +Output keys: + bounds [x0, y0, x1, y1] of Edge.Cuts (mm) + pads ref, num, net, x, y, drill, F / B (copper outline on that layer or null), npth + fps ref -> x, y, rot, value + netclass net -> class name; classes: name -> track width, via diameter, clearance + fpcopper footprint copper that is not a pad (ref, layer, poly) + keepouts polygons of rule areas that forbid tracks (board and footprint rule areas) + keepout_refs footprint reference owning each keepout ("" for board rule areas), parallel to keepouts + zones copper pours (not rule areas): net, layer, pts (outline), one entry per copper layer + tracks / vias existing copper, so a run can keep it (Router.load_existing) +""" +import json +import sys + +import pcbnew + +MM = 1e6 + + +def outline(ps): + if ps.OutlineCount() == 0: + return None + best = max(range(ps.OutlineCount()), key=lambda k: ps.Outline(k).Area()) + ol = ps.Outline(best) + return [[ol.CPoint(i).x / MM, ol.CPoint(i).y / MM] for i in range(ol.PointCount())] + + +def shape_poly(item, layer): + ps = pcbnew.SHAPE_POLY_SET() + item.TransformShapeToPolygon(ps, layer, 0, pcbnew.FromMM(0.005), pcbnew.ERROR_INSIDE) + return outline(ps) + + +def main(src, out): + b = pcbnew.LoadBoard(src) + bb = b.GetBoardEdgesBoundingBox() + d = dict(bounds=[bb.GetLeft() / MM, bb.GetTop() / MM, bb.GetRight() / MM, bb.GetBottom() / MM], + pads=[], fps={}, netclass={}, classes={}, fpcopper=[], keepouts=[], keepout_refs=[], zones=[], tracks=[], vias=[]) + for f in b.GetFootprints(): + ref = f.GetReference() + d["fps"][ref] = dict(x=f.GetPosition().x / MM, y=f.GetPosition().y / MM, rot=f.GetOrientationDegrees(), value=f.GetValue()) + for p in f.Pads(): + npth = p.GetAttribute() == pcbnew.PAD_ATTRIB_NPTH + drill = p.GetDrillSize().x / MM if p.HasHole() else 0.0 + cu = {} + for key, layer in (("F", pcbnew.F_Cu), ("B", pcbnew.B_Cu)): + cu[key] = None if npth or not p.IsOnLayer(layer) else shape_poly(p, layer) + d["pads"].append(dict(ref=ref, num=p.GetNumber(), net=p.GetNetname(), x=p.GetPosition().x / MM, + y=p.GetPosition().y / MM, drill=drill, npth=npth, **cu)) + for g in f.GraphicalItems(): + for key, layer in (("F", pcbnew.F_Cu), ("B", pcbnew.B_Cu)): + if g.GetLayer() == layer: + poly = shape_poly(g, layer) + if poly: + d["fpcopper"].append(dict(ref=ref, layer=key, poly=poly)) + for z in f.Zones(): + if z.GetIsRuleArea() and z.GetDoNotAllowTracks(): + d["keepouts"].append(outline(z.Outline())) + d["keepout_refs"].append(ref) + for z in b.Zones(): + if z.GetIsRuleArea() and z.GetDoNotAllowTracks(): + d["keepouts"].append(outline(z.Outline())) + d["keepout_refs"].append("") + for z in b.Zones(): + if z.GetIsRuleArea(): + continue + for key, layer in (("F.Cu", pcbnew.F_Cu), ("B.Cu", pcbnew.B_Cu)): + if z.IsOnLayer(layer): + d["zones"].append(dict(net=z.GetNetname(), layer=key, pts=outline(z.Outline()))) + for name, ni in b.GetNetInfo().NetsByName().items(): + name = str(name) + if name: + d["netclass"][name] = ni.GetNetClassName() + pro = json.load(open(src[:-len(".kicad_pcb")] + ".kicad_pro")) + for c in pro["net_settings"]["classes"]: + d["classes"][c["name"]] = dict(track=c["track_width"], via=c["via_diameter"], drill=c["via_drill"], clearance=c["clearance"]) + for t in b.GetTracks(): + if t.GetClass() == "PCB_VIA": + d["vias"].append(dict(net=t.GetNetname(), x=t.GetPosition().x / MM, y=t.GetPosition().y / MM, + d=t.GetWidth(pcbnew.F_Cu) / MM, drill=t.GetDrillValue() / MM)) + elif t.GetClass() == "PCB_TRACK": + d["tracks"].append(dict(net=t.GetNetname(), layer=b.GetLayerName(t.GetLayer()), x1=t.GetStart().x / MM, + y1=t.GetStart().y / MM, x2=t.GetEnd().x / MM, y2=t.GetEnd().y / MM, w=t.GetWidth() / MM)) + # KiCad orders footprints by UUID, which a regenerated board draws anew: sort, so the same + # placement always gives the same dump and the router (order-sensitive) the same result + d["pads"].sort(key=lambda p: (p["ref"], p["num"], p["x"], p["y"])) + d["fps"] = dict(sorted(d["fps"].items())) + for k in ("fpcopper", "zones", "tracks", "vias"): + d[k].sort(key=json.dumps) + pairs = sorted(zip(d["keepouts"], d["keepout_refs"]), key=lambda kr: json.dumps(kr[0])) + d["keepouts"] = [k for k, _ in pairs] + d["keepout_refs"] = [r for _, r in pairs] + json.dump(d, open(out, "w")) + print("pads %d, footprints %d, keepouts %d, fp copper %d, zones %d, tracks %d, vias %d, bounds %s" + % (len(d["pads"]), len(d["fps"]), len(d["keepouts"]), len(d["fpcopper"]), len(d["zones"]), len(d["tracks"]), len(d["vias"]), d["bounds"])) + + +if __name__ == "__main__": + main(*sys.argv[1:3]) diff --git a/tools/router/pcbroute.py b/tools/router/pcbroute.py new file mode 100644 index 0000000..24f932e --- /dev/null +++ b/tools/router/pcbroute.py @@ -0,0 +1,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 diff --git a/tools/router/pipeline.py b/tools/router/pipeline.py new file mode 100644 index 0000000..f7783d3 --- /dev/null +++ b/tools/router/pipeline.py @@ -0,0 +1,638 @@ +"""Routing strategies on top of pcbroute: plane drops, tree routing, component joining. + +Typical use (see knowledge/tooling/router.md): + + R = Router("board.json") # from dump_board.py + R.route_plane_net("GND") # every SMD ground pad gets its own via to the plane + R.connect("/Comms ETH/XI") # join all copper of a net + R.save("routes.json") # for write_board.py +""" +import sys, time, math, json +import numpy as np +from shapely.geometry import Point, LineString +import pcbroute as P +from pcbroute import Item, Board, cell_xy, xy_cell, RES, CLR, M + +# Filled in by Router() from the board dump: net -> class, class -> width / via size. +NETCLASS, WIDTH, VIA, DOMAINS = {}, {"Default": 0.2}, {}, {} +PLANE_NETS = ["GND"] + +def pad_minor(poly): + r = poly.minimum_rotated_rectangle + xs, ys = r.exterior.coords.xy + e = [math.hypot(xs[i+1]-xs[i], ys[i+1]-ys[i]) for i in range(2)] + return min(e) + +class Router: + def __init__(self, board_json, seeds=(), plane_nets=("GND",), domains=None): + d = json.load(open(board_json)) if isinstance(board_json, str) else board_json + P.setup(*d["bounds"]) + NETCLASS.clear(); NETCLASS.update(d.get("netclass", {})) + WIDTH.update({k: v["track"] for k, v in d.get("classes", {}).items()}) + VIA.update({k: v["via"] for k, v in d.get("classes", {}).items() if v["via"] != 0.6}) + PLANE_NETS[:] = list(plane_nets) + DOMAINS.clear(); DOMAINS.update(domains or {}) + self.B = Board(d, NETCLASS, DOMAINS, plane_nets=plane_nets) + self.B.build_static(domain_seeds=seeds) + self.log = [] + self.net_items = {} # net -> list of committed items + self.connected = {} # net -> set of pad indexes connected to the main tree + self.failed = [] + self.pads_by_net = {} + for k, p in enumerate(self.B.pads): + if p["net"] >= 0: self.pads_by_net.setdefault(p["net"], []).append(k) + + def nid(self, name): return self.B.netid[name] + def cls(self, name): return NETCLASS.get(name, "Default") + + # ----- congestion estimate (RUDY over MST edges of signal nets) ----- + def build_rudy(self, weight=8.0, exclude=()): + B = self.B + R = np.zeros((P.NY, P.NX), np.float32) + for net, idx in self.pads_by_net.items(): + name = B.netname[net] + if name in PLANE_NETS or name in exclude: continue + pts = [(B.pads[k]["x"], B.pads[k]["y"]) for k in idx] + for (a, b) in mst(pts): + x0, x1 = sorted((a[0], b[0])); y0, y1 = sorted((a[1], b[1])) + x0 -= 0.4; x1 += 0.4; y0 -= 0.4; y1 += 0.4 + dens = ((x1 - x0) + (y1 - y0)) / ((x1 - x0) * (y1 - y0)) * 0.25 + i0, j0 = xy_cell(x0, y0); i1, j1 = xy_cell(x1, y1) + R[max(j0,0):j1+1, max(i0,0):i1+1] += dens + self.rudy = R + return R + + def set_cost(self, F=None, Bc=None): + self.B.cost[0] = 0 if F is None else F + self.B.cost[1] = 0 if Bc is None else Bc + + # ----- helpers ----- + def item_containing(self, items, xy, L): + best = None + for it in items: + if L not in it.layers: continue + if it.kind == "pad": + if it.geom.contains(Point(xy)) or it.geom.distance(Point(xy)) < 1e-6: return it + else: + d = it.dist(np.array([xy[0]]), np.array([xy[1]]))[0] + if d <= 1e-6: best = it + return best + + def end_stub(self, it, xy, L, w): + if it is None: return None + if it.kind == "pad": + c = it.geom.centroid + if math.hypot(c.x - xy[0], c.y - xy[1]) < 1e-6: return None + wd = min(w, pad_minor(it.geom)) + return (L, xy, (c.x, c.y), wd) + if it.kind == "via": + if it.owner and it.owner[0] == "wp": return None + x, y = it.geom + if math.hypot(x - xy[0], y - xy[1]) < 1e-6: return None + return (L, xy, (x, y), min(w, it.w)) + if it.kind == "seg": + (x1, y1), (x2, y2) = it.geom + ls = LineString([(x1, y1), (x2, y2)]) + q = ls.interpolate(ls.project(Point(xy))) + if math.hypot(q.x - xy[0], q.y - xy[1]) < 1e-6: return None + return (L, xy, (q.x, q.y), min(w, it.w)) + + def do_route(self, net, src_items, tgt_items, w, wneck, via_d, goal_layer1=False, extra_tgt=None, tag=None, **kw): + B = self.B + neck_items = [it for it in list(tgt_items or []) + list(src_items) if it.kind == "pad"][:60] + r = B.route(net, src_items, tgt_items, goal_layer1=goal_layer1, w=w, wneck=wneck, via_d=via_d, + neck_items=neck_items, extra_tgt_cells=extra_tgt, **kw) + if r is None: return None + path, neck = r + segs, vias = B.path_to_geom(net, path, neck, w, wneck, via_d) + # stubs at both ends + s0 = int(path[0]); s1 = int(path[-1]) + L0, c0 = s0 // P.N, s0 % P.N; L1, c1 = s1 // P.N, s1 % P.N + xy0 = cell_xy(c0 % P.NX, c0 // P.NX); xy1 = cell_xy(c1 % P.NX, c1 // P.NX) + w0 = wneck if (wneck and neck[0]) else w + w1 = wneck if (wneck and neck[-1]) else w + st = [] + a = self.end_stub(self.item_containing(src_items, xy0, L0), xy0, L0, w0) + a = self.safe_stub(net, a) + if a: st.append(a) + tl = list(tgt_items or []) + [it for it in self.net_items.get(net, [])] + b = self.end_stub(self.item_containing(tl, xy1, L1), xy1, L1, w1) + b = self.safe_stub(net, b) + if b: st.append(b) + items = B.commit(net, segs + st, vias, via_d, tag) + self.net_items.setdefault(net, []).extend(items) + return items + + # ----- plane nets: drop each top SMD pad to the bottom plane ----- + def route_plane_net(self, name, w=0.4, wneck=0.25, via_cost=12.0, via_cmult=2.0, order=None, only=None, skip=(), extra_planed=()): + B = self.B; net = self.nid(name) + idx = self.pads_by_net[net] + smd = [k for k in idx if not B.pads[k]["tht"] and (only is None or (B.pads[k]["ref"], B.pads[k]["num"]) in only) + and (B.pads[k]["ref"], B.pads[k]["num"]) not in skip] + # big pads (exposed pads) first + smd.sort(key=lambda k: -B.pads[k]["poly"].area) + planed = [B.pads[k]["item"] for k in idx if B.pads[k]["tht"]] + [it for it in self.net_items.get(net, []) if it.kind == "via"] + list(extra_planed) + nf = 0 + for k in smd: + p = B.pads[k] + if self.touches(p["item"], planed): + continue + bb = p["poly"].bounds + if bb[2] - bb[0] > 2.5 and bb[3] - bb[1] > 2.5: + c = p["poly"].centroid + items = B.commit(net, [], [(round((c.x - P.X0) / RES) * RES + P.X0, round((c.y - P.Y0) / RES) * RES + P.Y0)], 0.6, ("plane", name)) + self.net_items.setdefault(net, []).extend(items) + planed += items + [p["item"]] + continue + tgt_cells = B.cells_of(planed, layers=(0,)) if planed else None + items = self.do_route(net, [p["item"]], [], w, wneck, 0.6, goal_layer1=True, extra_tgt=tgt_cells, + via_cost=via_cost, via_cmult=via_cmult, bmult=50.0, turn=2.0, tag=("plane", name)) + if items is None: + self.failed.append((name, p["ref"], p["num"])); nf += 1; continue + planed += items + [p["item"]] + self.log.append((name, "plane pads", len(smd), "failed", nf)) + + def safe_stub(self, net, st): + """Keep a stub only where its copper clears every foreign item exactly; narrow it if needed.""" + if st is None: return None + L, a, b, w = st + line = LineString([a, b]) + x0, y0, x1, y1 = line.bounds + foreign = [it for it in self.B.items if it.net != net and L in it.layers and + it.bbox[0] < x1 + 1 and it.bbox[2] > x0 - 1 and it.bbox[1] < y1 + 1 and it.bbox[3] > y0 - 1] + shapes = [item_shape(it) for it in foreign] + for wd in (w, 0.25, 0.2): + if wd > w: continue + if all(line.distance(sh) >= wd / 2 + CLR + 0.005 for sh in shapes): + return (L, a, b, wd) + return None + + def touches(self, it, items): + for o in items: + if o.kind == "pad" and it.kind == "pad": + if it.geom.distance(o.geom) < 1e-6: return True + return False + + # ----- tree routing for an ordinary net ----- + def route_tree(self, name, root=None, w=None, wneck=None, via_d=None, **kw): + B = self.B; net = self.nid(name) + c = self.cls(name) + w = w or WIDTH[c] + if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 + via_d = via_d or VIA.get(c, 0.6) + idx = list(self.pads_by_net[net]) + if root is None: + root = idx[0] + else: + root = [k for k in idx if (B.pads[k]["ref"], B.pads[k]["num"]) == root][0] + tree_pads = {root} + tree_items = [B.pads[root]["item"]] + # pads that physically overlap tree copper are already connected + def absorb(): + changed = True + while changed: + changed = False + for k in idx: + if k in tree_pads: continue + pi = B.pads[k]["item"] + for it in tree_items: + if set(it.layers) & set(pi.layers) and (pi.geom.distance(Point(it.geom) if it.kind == "via" else (LineString(it.geom) if it.kind == "seg" else it.geom)) <= (it.w / 2 if it.kind != "pad" else 0) + 1e-6): + tree_pads.add(k); tree_items.append(pi); changed = True; break + absorb() + tries = {} + nfail = 0 + while len(tree_pads) < len(idx): + # nearest unconnected pad to the tree + best = None + for k in idx: + if k in tree_pads or tries.get(k, 0) >= 1: continue + p = B.pads[k] + dmin = min(math.hypot(p["x"] - B.pads[t]["x"], p["y"] - B.pads[t]["y"]) for t in tree_pads) + if best is None or dmin < best[0]: best = (dmin, k) + if best is None: break + k = best[1]; tries[k] = tries.get(k, 0) + 1 + items = self.do_route(net, tree_items, [B.pads[k]["item"]], w, wneck, via_d, tag=("tree", name), **kw) + if items is None: + nfail += 1; self.failed.append((name, B.pads[k]["ref"], B.pads[k]["num"])) + continue + tree_items.extend(items) + tree_pads.add(k); tree_items.append(B.pads[k]["item"]) + absorb() + self.log.append((name, "pads", len(idx), "unrouted", len(idx) - len(tree_pads))) + return len(idx) - len(tree_pads) + + def rip_net(self, name): + """Remove the router's copper of a net (kept existing copper stays).""" + net = self.nid(name) + items = self.net_items.pop(net, []) + keep = [it for it in items if it.owner and it.owner[0] == "existing"] + self.B.remove_items([it for it in items if not (it.owner and it.owner[0] == "existing")]) + if keep: + self.net_items[net] = keep + self.failed = [f for f in self.failed if f[0] != name] + + # ----- export ----- + def geometry(self): + segs, vias = [], [] + for net, items in self.net_items.items(): + name = self.B.netname[net] + for it in items: + if it.kind == "seg": + (a, b) = it.geom + segs.append(dict(net=name, layer="F.Cu" if it.layers[0] == 0 else "B.Cu", x1=a[0], y1=a[1], x2=b[0], y2=b[1], w=it.w)) + elif it.kind == "via": + vias.append(dict(net=name, x=it.geom[0], y=it.geom[1], d=it.w, drill=0.4 if it.w >= 0.8 else 0.3)) + return segs, vias + + def save(self, path): + segs, vias = self.geometry() + json.dump(dict(segs=segs, vias=vias, failed=self.failed, log=self.log), open(path, "w"), indent=0) + + def load(self, path): + d = json.load(open(path)) + B = self.B + for s in d["segs"]: + net = self.nid(s["net"]) + it = Item("seg", net, (0 if s["layer"] == "F.Cu" else 1,), ((s["x1"], s["y1"]), (s["x2"], s["y2"])), w=s["w"], owner=("load",)) + B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) + for v in d["vias"]: + net = self.nid(v["net"]) + it = Item("via", net, (0, 1), (v["x"], v["y"]), w=v["d"], owner=("load",)) + B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) + self.failed = [tuple(f) for f in d["failed"]] + + +def load_existing(self, d, keep=lambda t: True): + """Add tracks/vias from a board dump as fixed copper (they are saved with the result).""" + B = self.B + for s in d.get("tracks", []): + if s["net"] not in B.netid or not keep(s): continue + net = self.nid(s["net"]) + it = Item("seg", net, (0 if s["layer"] == "F.Cu" else 1,), ((s["x1"], s["y1"]), (s["x2"], s["y2"])), w=s["w"], owner=("existing",)) + B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) + for v in d.get("vias", []): + if v["net"] not in B.netid or not keep(v): continue + net = self.nid(v["net"]) + it = Item("via", net, (0, 1), (v["x"], v["y"]), w=v["d"], owner=("existing",)) + B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it) + +Router.load_existing = load_existing + + +def mst(pts): + n = len(pts) + if n < 2: return [] + inT = [False] * n; inT[0] = True + dist = [math.hypot(pts[i][0] - pts[0][0], pts[i][1] - pts[0][1]) for i in range(n)] + par = [0] * n; edges = [] + for _ in range(n - 1): + k = min((i for i in range(n) if not inT[i]), key=lambda i: dist[i]) + inT[k] = True; edges.append((pts[par[k]], pts[k])) + for i in range(n): + if not inT[i]: + d = math.hypot(pts[i][0] - pts[k][0], pts[i][1] - pts[k][1]) + if d < dist[i]: dist[i] = d; par[i] = k + return edges + +def _wp(net, x, y, L): + return Item("via", net, (L,), (x, y), w=0.12, owner=("wp",)) + +def route_waypoints(self, name, root, wps, w, wneck, via_d, **kw): + """Route a trunk from the root pad through waypoints [(x, y, layer)]; returns tree items.""" + B = self.B; net = self.nid(name) + idx = self.pads_by_net[net] + rk = [k for k in idx if (B.pads[k]["ref"], B.pads[k]["num"]) == root][0] + tree = [B.pads[rk]["item"]] + list(self.net_items.get(net, [])) + for (x, y, L) in wps: + wp = _wp(net, x, y, L) + items = self.do_route(net, tree, [wp], w, wneck, via_d, tag=("trunk", name), **kw) + if items is None: + print("waypoint failed", name, x, y); return None + tree += items + return tree + +Router.route_waypoints = route_waypoints + +def route_tree_from(self, name, tree_items, w=None, wneck=None, via_d=None, skip=(), **kw): + """Prim-style completion of a net from existing tree items.""" + B = self.B; net = self.nid(name) + c = self.cls(name) + w = w or WIDTH[c] + if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 + via_d = via_d or VIA.get(c, 0.6) + idx = [k for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) not in skip] + tree_items = list(tree_items) + tree_pads = set() + def absorb(): + changed = True + while changed: + changed = False + for k in idx: + if k in tree_pads: continue + pi = B.pads[k]["item"] + for it in tree_items: + if it is pi: tree_pads.add(k); changed = True; break + if not (set(it.layers) & set(pi.layers)): continue + g = Point(it.geom) if it.kind == "via" else (LineString(it.geom) if it.kind == "seg" else it.geom) + if pi.geom.distance(g) <= (it.w / 2 if it.kind != "pad" else 0) + 1e-6: + tree_pads.add(k); tree_items.append(pi); changed = True; break + absorb() + pts = [] + for it in tree_items: + if it.kind == "seg": pts += list(it.geom) + elif it.kind == "via": pts.append(it.geom) + else: c0 = it.geom.centroid; pts.append((c0.x, c0.y)) + tries = set() + while True: + cand = [k for k in idx if k not in tree_pads and k not in tries] + if not cand: break + P = np.array(pts) + best = min(cand, key=lambda k: np.min(np.hypot(P[:, 0] - B.pads[k]["x"], P[:, 1] - B.pads[k]["y"]))) + tries.add(best) + items = self.do_route(net, tree_items, [B.pads[best]["item"]], w, wneck, via_d, tag=("tree", name), **kw) + if items is None: + self.failed.append((name, B.pads[best]["ref"], B.pads[best]["num"])); continue + tree_items.extend(items); tree_items.append(B.pads[best]["item"]); tree_pads.add(best) + for it in items: + if it.kind == "seg": pts += list(it.geom) + elif it.kind == "via": pts.append(it.geom) + c0 = B.pads[best]["item"].geom.centroid; pts.append((c0.x, c0.y)) + absorb() + un = len(idx) - len(tree_pads) + self.log.append((name, "pads", len(idx), "unrouted", un)) + return tree_items + +Router.route_tree_from = route_tree_from + +# ---------------- component-based net completion ---------------- +from shapely.strtree import STRtree + +def item_shape(it): + if it.kind == "pad": return it.geom + if it.kind == "seg": return LineString(it.geom).buffer(it.w / 2, quad_segs=4) + return Point(it.geom).buffer(it.w / 2, quad_segs=4) + +def components(items): + shapes = [item_shape(i) for i in items] + tree = STRtree(shapes) + par = list(range(len(items))) + def f(a): + while par[a] != a: par[a] = par[par[a]]; a = par[a] + return a + for i, s in enumerate(shapes): + for j in tree.query(s.buffer(1e-4)): + j = int(j) + if j <= i: continue + if not (set(items[i].layers) & set(items[j].layers)): continue + if s.distance(shapes[j]) <= 1e-4: + a, b = f(i), f(j) + if a != b: par[a] = b + groups = {} + for i in range(len(items)): groups.setdefault(f(i), []).append(items[i]) + return list(groups.values()) + +def net_items_all(self, net, pads_only_subset=None): + B = self.B + pads = [B.pads[k]["item"] for k in self.pads_by_net[net]] + return pads + list(self.net_items.get(net, [])) + +def comp_pts(comp): + pts = [] + for it in comp: + if it.kind == "seg": pts += list(it.geom) + elif it.kind == "via": pts.append(it.geom) + else: + c = it.geom.centroid; pts.append((c.x, c.y)) + return np.array(pts) + +def connect(self, name, root=None, pads=None, w=None, wneck=None, via_d=None, max_tries=2, **kw): + """Join all copper of a net (or only the components containing `pads`) into one.""" + B = self.B; net = self.nid(name) + c = self.cls(name) + w = w or WIDTH[c] + if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 + via_d = via_d or VIA.get(c, 0.6) + def padit(rn): + return [B.pads[k]["item"] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(rn)][0] + tries = {} + while True: + comps = components(net_items_all(self, net)) + if pads is not None: + want = [padit(p) for p in pads] + comps = [cp for cp in comps if any(any(x is it for x in cp) for it in want)] + if len(comps) <= 1: break + if root is not None: + ri = padit(root) + main = [cp for cp in comps if any(x is ri for x in cp)][0] + else: + main = max(comps, key=len) + others = [cp for cp in comps if cp is not main and tries.get(id(cp[0]), 0) < max_tries] + if not others: break + P = comp_pts(main) + def dist(cp): + Q = comp_pts(cp) + return np.min(np.hypot(P[:, None, 0] - Q[None, :, 0], P[:, None, 1] - Q[None, :, 1])) + tgt = min(others, key=dist) + tries[id(tgt[0])] = tries.get(id(tgt[0]), 0) + 1 + # heuristic point: nearest point of target to main + Q = comp_pts(tgt) + dd = np.min(np.hypot(Q[:, None, 0] - P[None, :, 0], Q[:, None, 1] - P[None, :, 1]), axis=1) + q = Q[int(np.argmin(dd))] + items = self.do_route(net, main, tgt, w, wneck, via_d, tag=("conn", name), hxy=(q[0], q[1]), **kw) + if items is None: + tp = [it for it in tgt if it.kind == "pad"] + lab = tp[0].owner[1:] if tp else ("copper",) + self.failed.append((name,) + tuple(lab)) + comps = components(net_items_all(self, net)) + self.log.append((name, "components", len(comps))) + return len(comps) + +Router.connect = connect + +def place_via(self, name, x, y, d=0.6): + B = self.B; net = self.nid(name) + i, j = xy_cell(x, y); x, y = cell_xy(i, j) + for L in (0, 1): + s = L * P.N + j * P.NX + i + fd = B.d2.ravel()[s] if B.n1.ravel()[s] == net else B.d1.ravel()[s] + if fd < d / 2 + CLR + M: + print("via blocked", name, x, y, fd); return None + items = B.commit(net, [], [(x, y)], d, ("via", name)) + self.net_items.setdefault(net, []).extend(items) + return items[0] +Router.place_via = place_via + + +def cap_value_uf(v): + import re + m = re.match(r"\s*([\d.]+)\s*([pnuµm]?)F?", v or "") + if not m: + return 0.0 + return float(m.group(1)) * {"p": 1e-6, "n": 1e-3, "u": 1, "µ": 1, "m": 1e3, "": 1}[m.group(2)] + + +def connect_decaps(self, name, **kw): + """Join each decoupling cap on net `name` to its nearest IC pin before the rest of the net. + + A cap is a 2-pad C* part with its other pad on a plane net. Candidates are pins of parts + with >= 4 pads; bulk caps (>= 4.7 uF) may also go to an inductor or ferrite (L*, FB*). + """ + B = self.B; net = self.nid(name) + pads = [B.pads[k] for k in self.pads_by_net[net]] + for p in pads: + f = B.fps[p["ref"]] + if not p["ref"].startswith("C"): + continue + other = [q for q in B.pads if q["ref"] == p["ref"] and q is not p] + if len(other) != 1 or other[0]["net"] < 0 or B.netname[other[0]["net"]] not in PLANE_NETS: + continue + nfp = {} + for q in B.pads: + nfp[q["ref"]] = nfp.get(q["ref"], 0) + 1 + bulk = cap_value_uf(f["value"]) >= 4.7 + cand = [q for q in pads if q["ref"] != p["ref"] and (nfp[q["ref"]] >= 4 and not q["ref"].startswith(("J", "TP")) + or (bulk and q["ref"].startswith(("L", "FB"))))] + if not cand: + continue + q = min(cand, key=lambda q: math.hypot(q["x"] - p["x"], q["y"] - p["y"])) + self.route_pair(name, (p["ref"], p["num"]), (q["ref"], q["num"]), **kw) + +Router.connect_decaps = connect_decaps + + +def route_pair(self, name, a, b, w=None, wneck=None, via_d=None, **kw): + """Route pad a to pad b directly (connect() would join to the nearest copper of the net).""" + B = self.B; net = self.nid(name) + c = self.cls(name) + w = w or WIDTH.get(c, 0.2) + if wneck is None: wneck = 0.2 if w > 0.2 else 0.0 + via_d = via_d or VIA.get(c, 0.6) + pa = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(a)][0] + pb = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(b)][0] + if any(x is pb["item"] for cp in components(net_items_all(self, net)) if any(y is pa["item"] for y in cp) for x in cp): + return True + items = self.do_route(net, [pa["item"]], [pb["item"]], w, wneck, via_d, tag=("pair", name), **kw) + if items is None: + self.failed.append((name,) + tuple(b)) + return False + return True + +Router.route_pair = route_pair + + +def stitch(self, name, pitch=5.0, d=0.6, box=None): + """Stitching vias on a grid wherever a via of net `name` clears all foreign copper, + keep-outs and the board edge on both layers, and does not land in a pad.""" + B = self.B; net = self.nid(name) + x0, y0, x1, y1 = box or (P.X0, P.Y0, P.X1, P.Y1) + placed = [] + r = d / 2 + CLR + M + y = y0 + pitch / 2 + while y < y1: + x = x0 + pitch / 2 + while x < x1: + i, j = xy_cell(x, y) + ok = True + for L in (0, 1): + s = L * P.N + j * P.NX + i + fd = B.d2.ravel()[s] if B.n1.ravel()[s] == net else B.d1.ravel()[s] + if fd < r or B.padd.ravel()[s] < d / 2 + 0.05 or B.n1.ravel()[s] == net and B.d1.ravel()[s] < d / 2 + 0.3: + ok = False + if ok: + placed += B.commit(net, [], [cell_xy(i, j)], d, ("stitch", name)) + x += pitch + y += pitch + self.net_items.setdefault(net, []).extend(placed) + self.log.append((name, "stitching vias", len(placed))) + return placed + +Router.stitch = stitch + + +def tie(self, name, pad, xy, w=None, d=0.6, **kw): + """Tie a pad to a new via at xy (e.g. a THT ground pad that pours may not reach once + tracks close in around it). Run it before the tracks that would close it in.""" + B = self.B; net = self.nid(name) + v = self.place_via(name, xy[0], xy[1], d) + if v is None: + self.failed.append((name,) + tuple(pad)); return False + p = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(pad)][0] + items = self.do_route(net, [p["item"]], [v], w or WIDTH.get(self.cls(name), 0.2), 0.0, d, tag=("tie", name), **kw) + if items is None: + self.failed.append((name,) + tuple(pad)); return False + return True + +Router.tie = tie + + +# ---------------- rip-up and reroute ---------------- + +def route_net(self, name, cost=None, pads=None, **kw): + """connect() that remembers its cost maps and arguments, so repair() can redo it.""" + self.registry = getattr(self, "registry", {}) + self.registry.setdefault(name, []).append((cost, pads, kw)) + if cost is not None: + self.set_cost(**cost) + return self.connect(name, pads=pads, **kw) + +Router.route_net = route_net + + +def _redo(self, name): + for cost, pads, kw in self.registry.get(name, [(None, None, {})]): + if cost is not None: + self.set_cost(**cost) + self.connect(name, pads=pads, **kw) + + +def split_nets(self, skip=()): + """Nets (by name) whose copper is still in more than one piece.""" + out = [] + for net, idx in self.pads_by_net.items(): + name = self.B.netname[net] + if name in skip or len(idx) < 2: + continue + if len(components(net_items_all(self, net))) > 1: + out.append(name) + return out + +Router.split_nets = split_nets + + +def repair(self, rounds=4, radius=1.2, protect=(), skip=("GND",)): + """Rip-up and reroute: for each split net, remove the nets with copper within `radius` + of its unconnected pieces, route it first, then route the removed nets again. + Only nets routed through route_net() are ripped; `protect` nets are never ripped.""" + B = self.B + for rnd in range(rounds): + bad = self.split_nets(skip) + self.log.append(("repair", rnd, "split", bad)) + if not bad: + return [] + for name in bad: + net = self.nid(name) + comps = components(net_items_all(self, net)) + if len(comps) <= 1: + continue + main = max(comps, key=len) + shapes = [item_shape(it).buffer(radius) for cp in comps if cp is not main for it in cp if it.kind == "pad"] + if not shapes: + continue + victims = set() + for it in B.items: + if it.net < 0 or it.net == net or it.kind == "pad": + continue + vn = B.netname[it.net] + if vn in protect or vn in skip or vn not in self.registry: + continue + g = item_shape(it) + if any(g.intersects(s) for s in shapes): + victims.add(vn) + for vn in [name] + sorted(victims): + self.rip_net(vn) + _redo(self, name) + for vn in sorted(victims): + _redo(self, vn) + return self.split_nets(skip) + +Router.repair = repair diff --git a/tools/router/plot_routes.py b/tools/router/plot_routes.py new file mode 100644 index 0000000..f7b3976 --- /dev/null +++ b/tools/router/plot_routes.py @@ -0,0 +1,63 @@ +"""Plot router output over the board's pads, one colour per net, failed pins marked. + + tools/router/.venv/bin/python tools/router/plot_routes.py board.json routes.json out.png [x0 y0 x1 y1] + +Pads are grey (F.Cu darker, B.Cu-only lighter); F.Cu tracks solid, B.Cu tracks dashed; +vias are circles; every net is labelled at its longest segment; pins listed in +routes.json "failed" get a red cross. Use a window (mm) to zoom into a dense part. +""" +import json +import sys +import zlib + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.patches import Circle, Polygon # noqa: E402 + +board, routes, out = sys.argv[1:4] +win = [float(v) for v in sys.argv[4:8]] if len(sys.argv) >= 8 else None +d = json.load(open(board)) +r = json.load(open(routes)) +x0, y0, x1, y1 = win or d["bounds"] +scale = 12 if win else 4 +fig = plt.figure(figsize=((x1 - x0) / 25.4 * scale, (y1 - y0) / 25.4 * scale), dpi=100) +ax = fig.add_axes([0, 0, 1, 1]) +ax.set_xlim(x0, x1) +ax.set_ylim(y1, y0) +ax.set_aspect("equal") +ax.axis("off") +cmap = plt.get_cmap("tab20") + + +def col(net): + return cmap(zlib.crc32(net.encode()) % 20) + + +for p in d["pads"]: + poly = p["F"] or p["B"] + if poly: + ax.add_patch(Polygon(poly, closed=True, fc="#9e9e9e" if p["F"] else "#d0d0d0", ec="none", zorder=1)) + if win and x0 <= p["x"] <= x1 and y0 <= p["y"] <= y1: + ax.text(p["x"], p["y"], "%s.%s" % (p["ref"], p["num"]), fontsize=4, ha="center", va="center", zorder=5) +longest = {} +for s in r["segs"]: + lw = s["w"] * 72 / 25.4 * scale * 1.0 + ax.plot([s["x1"], s["x2"]], [s["y1"], s["y2"]], color=col(s["net"]), lw=lw, solid_capstyle="round", + ls="-" if s["layer"] == "F.Cu" else (0, (2, 1)), alpha=0.85 if s["layer"] == "F.Cu" else 0.6, zorder=3) + L = abs(s["x2"] - s["x1"]) + abs(s["y2"] - s["y1"]) + if L > longest.get(s["net"], (0,))[0]: + longest[s["net"]] = (L, (s["x1"] + s["x2"]) / 2, (s["y1"] + s["y2"]) / 2) +for v in r["vias"]: + ax.add_patch(Circle((v["x"], v["y"]), v["d"] / 2, fc="white", ec=col(v["net"]), lw=1.5, zorder=4)) +for net, (L, x, y) in longest.items(): + if x0 <= x <= x1 and y0 <= y <= y1: + ax.text(x, y, net.split("/")[-1], fontsize=6 if win else 4, color="black", zorder=6, + bbox=dict(fc=col(net), ec="none", alpha=0.7, pad=0.5)) +pads = {(p["ref"], p["num"]): p for p in d["pads"]} +for f in r.get("failed", []): + p = pads.get((f[1], f[2])) if len(f) >= 3 else None + if p: + ax.plot([p["x"]], [p["y"]], marker="x", color="red", ms=14, mew=3, zorder=7) +fig.savefig(out) +print("wrote", out) diff --git a/tools/router/requirements.txt b/tools/router/requirements.txt new file mode 100644 index 0000000..3f89b23 --- /dev/null +++ b/tools/router/requirements.txt @@ -0,0 +1,4 @@ +numpy +shapely +scipy +matplotlib diff --git a/tools/router/write_board.py b/tools/router/write_board.py new file mode 100644 index 0000000..a4eaa6d --- /dev/null +++ b/tools/router/write_board.py @@ -0,0 +1,131 @@ +"""Write router output (tracks, vias) and copper pours into a board. + +Run with KiCad's bundled Python (pcbnew): + + $KPY tools/router/write_board.py src.kicad_pcb routes.json out.kicad_pcb [--zones zones.json] [--replace] + + --replace delete all existing tracks and vias first (routes.json then holds everything) + --diff routes.json holds everything (a route with the board's copper as [[fixed]]): only + tracks/vias that differ are touched; untouched copper keeps its exact drill and width + --zones zones.json: {"zones": [{net, layer, pts, priority, clearance?}]}; zones are filled + +pcbnew.SaveBoard rewrites the project file next to `out` with default net settings +(knowledge/tooling/kicad.md, pcbnew quirks), so an existing .kicad_pro is copied +before the save and written back afterwards. Close the board in KiCad before writing to +its own path; an open editor overwrites the file on its next save. +""" +import argparse +import json +import os + +import pcbnew + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("src") + ap.add_argument("routes") + ap.add_argument("out") + ap.add_argument("--zones") + ap.add_argument("--replace", action="store_true") + ap.add_argument("--diff", action="store_true") + ap.add_argument("--prune-vias", metavar="NET", help="after filling, drop vias of NET that touch no track and do not sit in a fill on both layers (stitching vias that ended up isolated)") + a = ap.parse_args() + + mm = pcbnew.FromMM + b = pcbnew.LoadBoard(a.src) + nets = b.GetNetsByName() + if a.replace: + for t in list(b.GetTracks()): + b.Remove(t) + r = json.load(open(a.routes)) + if a.diff: + def skey(net, layer, x1, y1, x2, y2): + e = sorted([(round(x1, 3), round(y1, 3)), (round(x2, 3), round(y2, 3))]) + return (net, layer, e[0], e[1]) + want_s = {skey(t["net"], t["layer"], t["x1"], t["y1"], t["x2"], t["y2"]) for t in r["segs"]} + want_v = {(v["net"], round(v["x"], 3), round(v["y"], 3)) for v in r["vias"]} + have_s, have_v, gone = set(), set(), [] + for t in list(b.GetTracks()): + if t.GetClass() == "PCB_VIA": + k = (t.GetNetname(), round(t.GetPosition().x / 1e6, 3), round(t.GetPosition().y / 1e6, 3)) + if k in want_v: + have_v.add(k) + else: + gone.append(t) + elif t.GetClass() == "PCB_TRACK": + k = skey(t.GetNetname(), b.GetLayerName(t.GetLayer()), t.GetStart().x / 1e6, t.GetStart().y / 1e6, + t.GetEnd().x / 1e6, t.GetEnd().y / 1e6) + if k in want_s: + have_s.add(k) + else: + gone.append(t) + for t in gone: + b.Delete(t) + r["segs"] = [t for t in r["segs"] if skey(t["net"], t["layer"], t["x1"], t["y1"], t["x2"], t["y2"]) not in have_s] + r["vias"] = [v for v in r["vias"] if (v["net"], round(v["x"], 3), round(v["y"], 3)) not in have_v] + print("diff: %d tracks/vias removed" % len(gone)) + for s in r["segs"]: + t = pcbnew.PCB_TRACK(b) + t.SetStart(pcbnew.VECTOR2I(mm(s["x1"]), mm(s["y1"]))) + t.SetEnd(pcbnew.VECTOR2I(mm(s["x2"]), mm(s["y2"]))) + t.SetWidth(mm(s["w"])) + t.SetLayer(pcbnew.F_Cu if s["layer"] == "F.Cu" else pcbnew.B_Cu) + t.SetNet(nets[s["net"]]) + b.Add(t) + for v in r["vias"]: + t = pcbnew.PCB_VIA(b) + t.SetPosition(pcbnew.VECTOR2I(mm(v["x"]), mm(v["y"]))) + t.SetWidth(mm(v["d"])) + t.SetDrill(mm(v["drill"])) + t.SetViaType(pcbnew.VIATYPE_THROUGH) + t.SetNet(nets[v["net"]]) + b.Add(t) + if a.zones: + for zd in json.load(open(a.zones))["zones"]: + zn = pcbnew.ZONE(b) + zn.SetLayer(pcbnew.F_Cu if zd["layer"] == "F.Cu" else pcbnew.B_Cu) + zn.SetNet(nets[zd["net"]]) + zn.SetZoneName(zd.get("name", zd["net"] + " " + zd["layer"])) + o = zn.Outline() + o.NewOutline() + for (x, y) in zd["pts"]: + o.Append(mm(x), mm(y)) + zn.SetAssignedPriority(zd.get("priority", 0)) + zn.SetLocalClearance(mm(zd.get("clearance", 0.3))) + zn.SetMinThickness(mm(0.25)) + zn.SetPadConnection(pcbnew.ZONE_CONNECTION_THERMAL) + zn.SetThermalReliefGap(mm(0.3)) + zn.SetThermalReliefSpokeWidth(mm(0.4)) + zn.SetIslandRemovalMode(pcbnew.ISLAND_REMOVAL_MODE_ALWAYS) + b.Add(zn) + if b.Zones(): + pcbnew.ZONE_FILLER(b).Fill(b.Zones()) + if a.prune_vias and b.Zones(): + net = nets[a.prune_vias] + ends = [(t.GetStart(), t.GetEnd(), t.GetLayer()) for t in b.GetTracks() if t.GetClass() == "PCB_TRACK" and t.GetNetCode() == net.GetNetCode()] + zones = [z for z in b.Zones() if not z.GetIsRuleArea() and z.GetNetCode() == net.GetNetCode()] + dropped = 0 + for v in [t for t in b.GetTracks() if t.GetClass() == "PCB_VIA" and t.GetNetCode() == net.GetNetCode()]: + p, rad = v.GetPosition(), v.GetWidth(pcbnew.F_Cu) / 2 + if any((e - p).EuclideanNorm() <= rad for s_, e_, _ in ends for e in (s_, e_)): + continue + inF = any(z.IsOnLayer(pcbnew.F_Cu) and z.GetFilledPolysList(pcbnew.F_Cu).Contains(p) for z in zones) + inB = any(z.IsOnLayer(pcbnew.B_Cu) and z.GetFilledPolysList(pcbnew.B_Cu).Contains(p) for z in zones) + if not (inF and inB): + b.Remove(v) + dropped += 1 + if dropped: + pcbnew.ZONE_FILLER(b).Fill(b.Zones()) + print("pruned %d isolated %s vias" % (dropped, a.prune_vias)) + + pro = a.out[:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro).read() if os.path.exists(pro) else None + pcbnew.SaveBoard(a.out, b) + if keep is not None: + open(pro, "w").write(keep) + print("saved %s: %d segments, %d vias added" % (a.out, len(r["segs"]), len(r["vias"]))) + + +if __name__ == "__main__": + main() diff --git a/tools/schgen.py b/tools/schgen.py new file mode 100644 index 0000000..92b3e84 --- /dev/null +++ b/tools/schgen.py @@ -0,0 +1,302 @@ +"""Write KiCad 10 schematics from Python: symbols, pin labels, power symbols, sheets. + +A module's generator (e.g. modules/<name>/tools/gen_sch.py) describes the circuit as +symbols placed on a grid, with every pin connected by a short wire stub and a net label, +power symbol, hierarchical label or no-connect flag. Wires between pins are possible +(Sheet.wire) but labels keep a generated sheet readable without a router. + + from schgen import Sheet + s = Sheet("my-project", "my_block.kicad_sch", sheet_name="My Block", root_uuid=..., sheet_uuid=...) + r = s.add("Device:R", "R1", 50.8, 50.8, value="10k", fp="Resistor_SMD:R_0603_1608Metric") + s.net(r, "1", "SIG") # stub + local label + s.power(r, "2", "GND") # stub + power symbol + s.write("path/my_block.kicad_sch") + +Symbols come from KiCad's shared libraries or the repo's HW library and are flattened into +lib_symbols (`extends` resolved). UUIDs are uuid5 of names, so the same script writes the +same file and a board keeps its links to the schematic. Pin positions follow KiCad's +transform: library Y up, sheet Y down, rotation counter-clockwise on screen. Mirroring is not +supported. Check the result with `kicad-cli sch erc` and `sch export netlist`. +Notes: knowledge/tooling/schgen.md +""" +import math +import os +import uuid + +from sexpr import Q, dump, find, first, parse + +from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 +LIBS = {"HW": os.path.join(ROOT, "libraries/symbols/HW.kicad_sym")} +G = 2.54 +STUB = 2.54 +NS = uuid.UUID("6f1b9a4e-2c55-4f0e-9b7d-3a1f0c8e5d21") +_libcache = {} + + +def uid(*parts): + return Q(str(uuid.uuid5(NS, "/".join(str(p) for p in parts)))) + + +def r4(v): + return round(v + 0.0, 4) + + +def _lib(nick): + if nick not in _libcache: + path = LIBS.get(nick, os.path.join(SYMBOLS, nick + ".kicad_sym")) + _libcache[nick] = {s[1]: s for s in find(parse(open(path).read()), "symbol")} + return _libcache[nick] + + +def load_symbol(lib_id): + """Flattened library symbol renamed to lib_id (the form lib_symbols wants).""" + nick, name = lib_id.split(":") + lib = _lib(nick) + sym = lib[name] + ext = first(sym, "extends") + if ext: + parent = load_symbol(nick + ":" + ext[1]) + props = {p[1]: p for p in find(sym, "property")} + out = [Q(lib_id)] + for item in parent[2:]: + if isinstance(item, list) and item[0] == "property" and item[1] in props: + out.append(props.pop(item[1])) + elif isinstance(item, list) and item[0] == "symbol": + out.append([item[0], Q(item[1].replace(ext[1] + "_", name + "_", 1))] + item[2:]) + else: + out.append(item) + # child-only properties go after the parent's + i = max(k for k, x in enumerate(out) if isinstance(x, list) and x[0] == "property") + out[i + 1:i + 1] = list(props.values()) + return ["symbol"] + out + out = ["symbol", Q(lib_id)] + [x for x in sym[2:]] + out = [x if not (isinstance(x, list) and x[0] == "symbol") else + [x[0], Q(x[1])] + x[2:] for x in out] + return out + + +def _subunits(sym): + """(unit, body style, sub-symbol) for each sub-symbol "Name_U_S".""" + for s in find(sym, "symbol"): + u, st = s[1].rsplit("_", 2)[-2:] + yield int(u), int(st), s + + +def pins_of(sym, unit): + """{number: (x, y, angle)} in library coordinates for one unit (body style 1).""" + pins = {} + for u, st, s in _subunits(sym): + if st not in (0, 1) or u not in (0, unit): + continue + for p in find(s, "pin"): + at = first(p, "at") + num = first(p, "number")[1] + pins[str(num)] = (float(at[1]), float(at[2]), float(at[3])) + return pins + + +def units_of(sym): + return sorted({u for u, st, s in _subunits(sym) if u > 0}) or [1] + + +def _xf(x, y, rot): + """Library point -> sheet offset for a symbol at rotation rot (degrees, CCW on screen).""" + a = math.radians(rot) + sx, sy = x, -y + return (sx * math.cos(a) + sy * math.sin(a), -sx * math.sin(a) + sy * math.cos(a)) + + +def _eff(justify=None, hide=False, size=1.27): + e = ["effects", ["font", ["size", size, size]]] + if justify: + e.append(["justify"] + justify.split()) + out = [] + if hide: + out.append(["hide", "yes"]) + return out + [e] + + +class Symbol: + def __init__(self, sheet, lib_id, ref, x, y, rot, unit): + self.sheet, self.lib_id, self.ref, self.x, self.y, self.rot, self.unit = sheet, lib_id, ref, x, y, rot, unit + self.lib = sheet.symbol(lib_id) + self.pins = pins_of(self.lib, unit) + + def pin(self, num): + """(x, y, outward unit vector) of a pin's connection point on the sheet.""" + px, py, pa = self.pins[str(num)] + dx, dy = _xf(px, py, self.rot) + # the library angle points from the connection point into the body + a = math.radians(pa + 180 + self.rot) + return (r4(self.x + dx), r4(self.y + dy), (round(math.cos(a)), -round(math.sin(a)))) + + +class Sheet: + """One schematic file. For the root sheet leave sheet_uuid None.""" + + def __init__(self, project, filename, root_uuid, sheet_uuid=None, sheet_name=None, paper="A4", page=None): + self.project, self.filename = project, filename + self.root_uuid, self.sheet_uuid, self.sheet_name = root_uuid, sheet_uuid, sheet_name + self.uuid = sheet_uuid or root_uuid + self.path = "/" + root_uuid + ("/" + sheet_uuid if sheet_uuid else "") + self.paper = paper + self.libsyms = {} + self.items = [] + self.npwr = 0 + self.nflg = 0 + self.seq = 0 + + def _uid(self, *parts): + self.seq += 1 + return uid(self.project, self.filename, self.seq, *parts) + + def symbol(self, lib_id): + if lib_id not in self.libsyms: + self.libsyms[lib_id] = load_symbol(lib_id) + return self.libsyms[lib_id] + + # ---------- symbols ---------- + def add(self, lib_id, ref, x, y, rot=0, unit=1, value=None, fp="", fields=None, datasheet=None, + in_bom=True, on_board=True, show_value=True, dnp=False): + s = Symbol(self, lib_id, ref, x, y, rot, unit) + lib = s.lib + props = {p[1]: p for p in find(lib, "property")} + val = value if value is not None else props["Value"][2] + e = ["symbol", ["lib_id", Q(lib_id)], ["at", r4(x), r4(y), rot], ["unit", unit], + ["exclude_from_sim", "no"], ["in_bom", "yes" if in_bom else "no"], + ["on_board", "yes" if on_board else "no"], ["dnp", "yes" if dnp else "no"], + ["uuid", uid(self.project, self.path, ref, unit)]] + + def prop(name, text, hide, at=None): + if at is None: + lp = props.get(name) + if lp is not None: + a = first(lp, "at") + dx, dy = _xf(float(a[1]), float(a[2]), rot) + at = (x + dx, y + dy, float(a[3])) + else: + at = (x, y, 0) + e.append(["property", Q(name), Q(text), ["at", r4(at[0]), r4(at[1]), at[2]]] + _eff(hide=hide)) + + prop("Reference", ref, ref.startswith("#")) + prop("Value", val, not show_value) + prop("Footprint", fp, True) + prop("Datasheet", datasheet if datasheet is not None else (props["Datasheet"][2] if "Datasheet" in props else ""), True) + prop("Description", props["Description"][2] if "Description" in props else "", True) + for k, v in (fields or {}).items(): + prop(k, v, True, (x, y, 0)) + for num in sorted(s.pins): + e.append(["pin", Q(num), ["uuid", uid(self.project, self.path, ref, unit, "pin", num)]]) + e.append(["instances", ["project", Q(self.project), ["path", Q(self.path), ["reference", Q(ref)], ["unit", unit]]]]) + self.items.append(e) + return s + + # ---------- connections ---------- + def _stub(self, sym, num, length=STUB): + x, y, (dx, dy) = sym.pin(num) + ex, ey = r4(x + dx * length), r4(y + dy * length) + if length: + self.wire((x, y), (ex, ey)) + return ex, ey, (dx, dy) + + def wire(self, *pts): + for a, b in zip(pts, pts[1:]): + self.items.append(["wire", ["pts", ["xy", r4(a[0]), r4(a[1])], ["xy", r4(b[0]), r4(b[1])]], + ["stroke", ["width", 0], ["type", "default"]], ["uuid", self._uid("w")]]) + + def junction(self, x, y): + self.items.append(["junction", ["at", r4(x), r4(y)], ["diameter", 0], ["color", 0, 0, 0, 0], + ["uuid", self._uid("j")]]) + + @staticmethod + def _label_at(dx, dy): + """Label angle and justification so the text runs away from the pin.""" + if dx > 0: + return 0, "left bottom" + if dx < 0: + return 180, "right bottom" + if dy < 0: + return 90, "left bottom" + return 270, "right bottom" + + def label(self, name, x, y, dx=1, dy=0): + ang, just = self._label_at(dx, dy) + self.items.append(["label", Q(name), ["at", r4(x), r4(y), ang]] + _eff(just) + [["uuid", self._uid("l", name)]]) + + def net(self, sym, num, name, length=STUB): + """Stub from the pin and a local net label at its end.""" + x, y, (dx, dy) = self._stub(sym, num, length) + self.label(name, x, y, dx, dy) + + def hlabel(self, sym, num, name, shape="input", length=STUB): + x, y, (dx, dy) = self._stub(sym, num, length) + ang, just = self._label_at(dx, dy) + just = just.split()[0] + self.items.append(["hierarchical_label", Q(name), ["shape", shape], ["at", x, y, ang]] + _eff(just) + + [["uuid", self._uid("h", name)]]) + + def global_label(self, name, x, y, ang=0, shape="input"): + just = "left" if ang == 0 else "right" + self.items.append(["global_label", Q(name), ["shape", shape], ["at", r4(x), r4(y), ang]] + _eff(just) + + [["uuid", self._uid("g", name)]]) + + def power(self, sym, num, name, length=STUB): + """Stub from the pin and a power symbol (power:<name>) at its end, turned so that it + points away from the pin (a stub that turned instead could land on the next pin's).""" + x, y, (dx, dy) = self._stub(sym, num, length) + down = name.upper().startswith("GND") or name.startswith("-") + # rotation that turns the symbol's body (down for ground, up for supplies) outward + if down: + rot = {(0, 1): 0, (1, 0): 90, (0, -1): 180, (-1, 0): 270}[(dx, dy)] + else: + rot = {(0, -1): 0, (-1, 0): 90, (0, 1): 180, (1, 0): 270}[(dx, dy)] + self.power_at(name, x, y, rot) + + def power_at(self, name, x, y, rot=0): + self.npwr += 1 + self.add("power:" + name, "#PWR%02d" % self.npwr, x, y, rot, value=name) + + def flag_at(self, x, y): + self.nflg += 1 + self.add("power:PWR_FLAG", "#FLG%02d" % self.nflg, x, y, 0) + + def nc(self, sym, num): + x, y, _ = sym.pin(num) + self.items.append(["no_connect", ["at", x, y], ["uuid", self._uid("nc")]]) + + def nc_at(self, x, y): + self.items.append(["no_connect", ["at", r4(x), r4(y)], ["uuid", self._uid("nc")]]) + + def text(self, s, x, y, size=1.27): + self.items.append(["text", Q(s), ["exclude_from_sim", "no"], ["at", r4(x), r4(y), 0]] + + _eff("left top", size=size) + [["uuid", self._uid("t")]]) + + # ---------- hierarchy ---------- + def sheet(self, name, filename, x, y, w, h, pins, child_uuid, page="2"): + """Sheet symbol on this (root) sheet. pins: [(name, shape)] down the right edge. + Returns {name: (x, y)} of the pin connection points.""" + e = ["sheet", ["at", r4(x), r4(y)], ["size", r4(w), r4(h)], ["exclude_from_sim", "no"], + ["in_bom", "yes"], ["on_board", "yes"], ["dnp", "no"], ["fields_autoplaced", "yes"], + ["stroke", ["width", 0.1524], ["type", "solid"]], ["fill", ["color", 0, 0, 0, 0.0]], + ["uuid", Q(child_uuid)], + ["property", Q("Sheetname"), Q(name), ["at", r4(x), r4(y - 0.635), 0]] + _eff("left bottom"), + ["property", Q("Sheetfile"), Q(filename), ["at", r4(x), r4(y + h + 0.635), 0]] + _eff("left top")] + where = {} + for i, (pn, shape) in enumerate(pins): + px, py = r4(x + w), r4(y + G * (i + 1)) + e.append(["pin", Q(pn), shape, ["at", px, py, 0]] + _eff("right") + [["uuid", uid(child_uuid, "pin", pn)]]) + where[pn] = (px, py) + e.append(["instances", ["project", Q(self.project), ["path", Q(self.path), ["page", Q(page)]]]]) + self.items.append(e) + return where + + # ---------- output ---------- + def write(self, path): + out = ["kicad_sch", ["version", 20250610], ["generator", Q("schgen")], ["generator_version", Q("10.0")], + ["uuid", Q(self.uuid)], ["paper", Q(self.paper)], + ["lib_symbols"] + [self.libsyms[k] for k in sorted(self.libsyms)]] + out += self.items + if not self.sheet_uuid: + out.append(["sheet_instances", ["path", Q("/"), ["page", Q("1")]]]) + with open(path, "w") as f: + f.write(dump(out) + "\n") diff --git a/tools/sexpr.py b/tools/sexpr.py new file mode 100644 index 0000000..ded88cb --- /dev/null +++ b/tools/sexpr.py @@ -0,0 +1,61 @@ +"""Minimal S-expression reader/writer for KiCad files.""" +import re + +class Q(str): + """Quoted string atom.""" + +_tok = re.compile(r'\s*(?:(\()|(\))|"((?:[^"\\]|\\.)*)"|([^\s()"]+))', re.S) + +def parse(text): + stack = [[]] + pos = 0 + n = len(text) + while pos < n: + m = _tok.match(text, pos) + if not m: + if text[pos:].strip() == "": + break + raise ValueError("bad sexpr at %d" % pos) + pos = m.end() + if m.group(1): + stack.append([]) + elif m.group(2): + top = stack.pop() + stack[-1].append(top) + elif m.group(3) is not None: + stack[-1].append(Q(m.group(3).replace('\\"', '"').replace("\\\\", "\\"))) + else: + stack[-1].append(m.group(4)) + return stack[0][0] + +def _atom(a): + if isinstance(a, Q): + return '"' + a.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"' + if isinstance(a, float): + s = ("%.4f" % a).rstrip("0").rstrip(".") + return "0" if s in ("-0", "") else s + return str(a) + +def dump(e, ind=0): + if not isinstance(e, list): + return _atom(e) + if all(not isinstance(x, list) for x in e): + return "(" + " ".join(_atom(x) for x in e) + ")" + out = "(" + " ".join(_atom(x) for x in e if not isinstance(x, list)) + # keep leading atoms on first line, children on new lines + parts = [] + lead = True + for x in e: + if isinstance(x, list): + lead = False + parts.append("\n" + "\t" * (ind + 1) + dump(x, ind + 1)) + elif not lead: + parts.append(" " + _atom(x)) + return out + "".join(parts) + "\n" + "\t" * ind + ")" + +def find(e, key): + return [x for x in e if isinstance(x, list) and x and x[0] == key] + +def first(e, key): + r = find(e, key) + return r[0] if r else None diff --git a/tools/silk_refs.py b/tools/silk_refs.py new file mode 100644 index 0000000..51c4f65 --- /dev/null +++ b/tools/silk_refs.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Place footprint reference designators where they do not collide with copper or each other. + +Run with KiCad's bundled Python after routing: + + $KPY tools/silk_refs.py board.kicad_pcb [out.kicad_pcb] [--size 0.8] [--skip P1,P2] + +For each visible reference (largest parts first) it tries positions around the part's +courtyard: above, below, left, right (horizontal text), then left/right reading vertically, +then the corners, then the same ring 0.6 mm further out. Other parts' silk outlines count as obstacles. +(Smaller text is not tried: it runs into the board's minimum text height.) The first position whose text box +(plus 0.15 mm) clears every pad and via (tracks are under mask), keeps 0.5 mm from the board edge and clears all +references already placed wins. Parts with no free spot keep their reference on F.Fab only +(hidden on silk) and are listed, so nothing ends up over a pad. Pours are ignored: silk on +a pour is fine. + +pcbnew.SaveBoard rewrites the .kicad_pro; it is copied before and restored after. +""" +import argparse +import os + +import pcbnew + +MM = 1e6 + + +def box(b, m=0.0): + return (b.GetLeft() / MM - m, b.GetTop() / MM - m, b.GetRight() / MM + m, b.GetBottom() / MM + m) + + +def inside(outline, b, m): + """Box b grown by m lies inside the board outline: its perimeter sampled every 0.25 mm, so a + box cannot straddle a notch between two connector tabs (the outline's bounding box would let + it hang past the real edge there).""" + x0, y0, x1, y1 = b[0] - m, b[1] - m, b[2] + m, b[3] + m + nx, ny = max(1, int((x1 - x0) / 0.25)), max(1, int((y1 - y0) / 0.25)) + pts = [(x0 + (x1 - x0) * i / nx, y) for i in range(nx + 1) for y in (y0, y1)] + pts += [(x, y0 + (y1 - y0) * j / ny) for j in range(ny + 1) for x in (x0, x1)] + return all(outline.Contains(pcbnew.VECTOR2I_MM(x, y)) for x, y in pts) + + +def hit(a, b): + return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("board") + ap.add_argument("out", nargs="?") + ap.add_argument("--size", type=float, default=0.8) + ap.add_argument("--skip", default="", help="references to leave alone") + a = ap.parse_args() + out = a.out or a.board + b = pcbnew.LoadBoard(a.board) + skip = set(r for r in a.skip.split(",") if r) + outline = pcbnew.SHAPE_POLY_SET() + b.GetBoardPolygonOutlines(outline, False) + + copper = [] + for f in b.GetFootprints(): + for p in f.Pads(): + copper.append(box(p.GetBoundingBox(), 0.15)) + for t in b.GetTracks(): # tracks are under solder mask; silk may cross them + if t.GetClass() == "PCB_VIA": + copper.append(box(t.GetBoundingBox(), 0.1)) + silk = [] # footprint silk graphics (outlines, pin-1 marks) of other parts + for f in b.GetFootprints(): + for g in f.GraphicalItems(): + if g.GetLayer() == pcbnew.F_SilkS and g.GetClass() != "PCB_TEXT": + silk.append((f.GetReference(), box(g.GetBoundingBox(), 0.1))) + bodies = {} + for f in b.GetFootprints(): + cy = f.GetCourtyard(pcbnew.F_CrtYd) + if cy.OutlineCount(): + bodies[f.GetReference()] = box(cy.BBox()) + + placed, missing = [], [] + fps = sorted([f for f in b.GetFootprints() if f.Reference().IsVisible() and f.GetReference() not in skip + and f.GetLayer() == pcbnew.F_Cu], + key=lambda f: (-(f.GetBoundingBox().GetWidth() * f.GetBoundingBox().GetHeight()), f.GetReference())) + todo = [(f, a.size) for f in fps] + while todo: + f, size = todo.pop(0) + t = f.Reference() + t.SetTextSize(pcbnew.VECTOR2I_MM(size, size)) + t.SetTextThickness(pcbnew.FromMM(size * 0.15)) + t.SetLayer(pcbnew.F_SilkS) + bb = bodies.get(f.GetReference(), box(f.GetBoundingBox())) + cx, cy = (bb[0] + bb[2]) / 2, (bb[1] + bb[3]) / 2 + found = None + for ring in (0.0, 0.6): + x0, y0, x1, y1 = bb[0] - ring, bb[1] - ring, bb[2] + ring, bb[3] + ring + h = size + cands = [(cx, y0 - h * 0.7, 0), (cx, y1 + h * 0.7, 0), (x0 - h, cy, 0), (x1 + h, cy, 0), + (x0 - h * 0.7, cy, 90), (x1 + h * 0.7, cy, 90), + (x0, y0 - h * 0.7, 0), (x1, y0 - h * 0.7, 0), (x0, y1 + h * 0.7, 0), (x1, y1 + h * 0.7, 0)] + for (x, y, rot) in cands: + t.SetTextAngleDegrees(rot) + t.SetPosition(pcbnew.VECTOR2I_MM(x, y)) + if rot == 0 and x < cx - 0.01: + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_RIGHT) + elif rot == 0 and x > cx + 0.01 and abs(y - cy) < 0.01: + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_LEFT) + else: + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_CENTER) + tb = box(t.GetBoundingBox(), 0.15) + if not inside(outline, tb, 0.5): + continue + if any(hit(tb, c) for c in copper) or any(hit(tb, p) for p in placed) or \ + any(r != f.GetReference() and hit(tb, g) for r, g in silk): + continue + found = tb + break + if found: + break + if found: + placed.append(found) + else: + t.SetPosition(pcbnew.VECTOR2I_MM(cx, cy)) + t.SetTextAngleDegrees(0) + t.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_CENTER) + t.SetLayer(pcbnew.F_Fab) + missing.append(f.GetReference()) + pro = out[:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro).read() if os.path.exists(pro) else None + pcbnew.SaveBoard(out, b) + if keep is not None: + open(pro, "w").write(keep) + print("placed %d references; on F.Fab only (no free spot): %s" % (len(placed), ", ".join(missing) or "none")) + + +if __name__ == "__main__": + main() diff --git a/tools/sync_board.py b/tools/sync_board.py new file mode 100644 index 0000000..ca63cc8 --- /dev/null +++ b/tools/sync_board.py @@ -0,0 +1,124 @@ +"""Update a board from its schematic's netlist, like KiCad's Update PCB from Schematic, without the GUI. + +Footprints whose reference is no longer in the netlist are deleted (board-only ones such as +housing posts stay); new symbols get their footprint from the library, placed at --at for the +placer to move. Every footprint gets the netlist's value, LCSC/MPN/Datasheet/Description +fields (and FT Rotation Offset for the JLC plugin), schematic path and pad nets. Footprint changes on existing parts are reported, not +applied. With --strip-routing all tracks and vias go too (for a board that tools/pnr.sh routes +again). Pours, outline, rule areas and positions of existing parts stay. + +usage (KiCad's Python, from the repo root, board closed in KiCad): + kicad-cli sch export netlist -o /tmp/b.net board.kicad_sch + .../Python.framework/Versions/3.9/bin/python3 tools/sync_board.py /tmp/b.net board.kicad_pcb \ + [--at X,Y] [--strip-routing] +""" +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import pcbnew # noqa: E402 +from sexpr import find, first, parse # noqa: E402 + +from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 +KFP = FOOTPRINTS +HWFP = os.path.join(ROOT, "libraries/footprints/HW.pretty") + +ap = argparse.ArgumentParser() +ap.add_argument("netlist") +ap.add_argument("board") +ap.add_argument("--at", default=None, help="X,Y in mm for new footprints (default: board centre)") +ap.add_argument("--strip-routing", action="store_true") +a = ap.parse_args() + +net = parse(open(a.netlist).read()) +comps = {} +for c in find(first(net, "components"), "comp"): + fields = {first(f, "name")[1]: f[2] for f in find(first(c, "fields") or [], "field") if len(f) > 2} + sp = first(c, "sheetpath") + comps[first(c, "ref")[1]] = dict(value=first(c, "value")[1], fp=first(c, "footprint")[1], + path=first(sp, "tstamps")[1] + first(c, "tstamps")[1], + sheet=first(sp, "names")[1], fields=fields) +sheetfiles = {} +for s in find(first(net, "design"), "sheet"): + src = first(first(s, "title_block"), "source")[1] + sheetfiles[first(s, "name")[1]] = os.path.basename(src) +pinnet = {} +for n in find(first(net, "nets"), "net"): + for nd in find(n, "node"): + pinnet[(first(nd, "ref")[1], first(nd, "pin")[1])] = first(n, "name")[1] + +pro = a.board[:-len(".kicad_pcb")] + ".kicad_pro" +keep = open(pro).read() if os.path.exists(pro) else None +b = pcbnew.LoadBoard(a.board) +if a.at: + at = pcbnew.VECTOR2I_MM(*map(float, a.at.split(","))) +else: + at = b.GetBoardEdgesBoundingBox().GetCenter() + +nets = {str(k): v for k, v in b.GetNetsByName().items()} + + +def getnet(name): + if name not in nets: + ni = pcbnew.NETINFO_ITEM(b, name) + b.Add(ni) + nets[name] = ni + return nets[name] + + +have = {} +gone = [] +for fp in b.GetFootprints(): + ref = fp.GetReference() + if ref not in comps and not fp.IsBoardOnly(): # board-only parts (housing posts) have no symbol + gone.append(ref) +for ref in gone: + print("removed", ref) + b.Delete(b.FindFootprintByReference(ref)) # Delete, not Remove: Remove() breaks the bindings (see prune_copper.py) +for fp in b.GetFootprints(): + have[fp.GetReference()] = fp + +for ref, c in sorted(comps.items()): + fp = have.get(ref) + nick, name = c["fp"].split(":") + if fp is None: + fp = pcbnew.FootprintLoad(HWFP if nick == "HW" else os.path.join(KFP, nick + ".pretty"), name) + assert fp, c["fp"] + fp.SetFPID(pcbnew.LIB_ID(nick, name)) + b.Add(fp) + fp.SetReference(ref) + fp.SetPosition(at) + fp.Reference().SetTextSize(pcbnew.VECTOR2I_MM(0.8, 0.8)) + fp.Reference().SetTextThickness(pcbnew.FromMM(0.12)) + print("added", ref, c["value"], c["fp"]) + elif fp.GetFPIDAsString() != c["fp"]: + print("footprint differs, not changed:", ref, fp.GetFPIDAsString(), "->", c["fp"]) + fp.SetValue(c["value"]) + for k in ("LCSC", "MPN", "FT Rotation Offset"): # the last one: JLC plugin CPL correction + if k in c["fields"]: + fp.SetField(k, c["fields"][k]) + fp.GetField(k).SetVisible(False) + for k in ("Datasheet", "Description"): + if k in c["fields"]: + fp.GetField(k).SetText(c["fields"][k]) + fp.SetPath(pcbnew.KIID_PATH(c["path"])) + fp.SetSheetname(c["sheet"].strip("/") or "Root") + if c["sheet"] in sheetfiles: + fp.SetSheetfile(sheetfiles[c["sheet"]]) + for pad in fp.Pads(): + n = pinnet.get((ref, pad.GetNumber())) + old = pad.GetNetname() + if n and n != old: + print("net %s.%s: %s -> %s" % (ref, pad.GetNumber(), old or "-", n)) + pad.SetNet(getnet(n) if n else b.FindNet(0)) + +if a.strip_routing: + tr = list(b.GetTracks()) + for t in tr: + b.Delete(t) + print("removed %d tracks and vias" % len(tr)) + +pcbnew.SaveBoard(a.board, b) +if keep is not None: + open(pro, "w").write(keep) # SaveBoard resets the project's net settings diff --git a/tools/thermal_vias.py b/tools/thermal_vias.py new file mode 100644 index 0000000..744d0d6 --- /dev/null +++ b/tools/thermal_vias.py @@ -0,0 +1,104 @@ +"""Add a grid of thermal vias to the exposed pads of the given footprints, after routing. + +The routers (tools/router-rs, tools/placer) refuse footprints with bottom-side pads, so the +KiCad "_ThermalVias" footprint variants cannot be used. Use the plain exposed-pad footprint, +keep B.Cu clear under the pad with a router cost zone (route.toml), and run this on the routed +board. Each via takes the pad's net; a via is skipped where it would come within the clearance +of B.Cu copper of another net or of another hole. Then the zones are refilled. + +usage (KiCad's Python, from the repo root, board closed in KiCad): + .../Python.framework/Versions/3.9/bin/python3 tools/thermal_vias.py BOARD.kicad_pcb REF [REF ...] \ + [--pitch 1.2] [--via 0.6] [--drill 0.3] +Notes: knowledge/tooling/thermal-vias.md +""" +import argparse +import os + +import pcbnew + +ap = argparse.ArgumentParser() +ap.add_argument("board") +ap.add_argument("refs", nargs="+") +ap.add_argument("--pitch", type=float, default=1.2) +ap.add_argument("--via", type=float, default=0.6) +ap.add_argument("--drill", type=float, default=0.3) +ap.add_argument("--clearance", type=float, default=0.2) +ap.add_argument("--hole", type=float, default=0.25, help="hole-to-hole minimum") +a = ap.parse_args() + +pro = a.board[:-len(".kicad_pcb")] + ".kicad_pro" +keep = open(pro).read() if os.path.exists(pro) else None +b = pcbnew.LoadBoard(a.board) +mm = pcbnew.FromMM +R = mm(a.via / 2) + + +def exposed_pad(fp): + """The footprint's largest SMD pad (the thermal pad).""" + pads = [p for p in fp.Pads() if p.GetAttribute() == pcbnew.PAD_ATTRIB_SMD] + return max(pads, key=lambda p: p.GetSizeX() * p.GetSizeY()) + + +def holes(): + for t in b.GetTracks(): + if t.Type() == pcbnew.PCB_VIA_T: + yield t.GetPosition(), t.GetDrill() // 2 + for fp in b.GetFootprints(): + for p in fp.Pads(): + if p.HasHole(): + yield p.GetPosition(), max(p.GetDrillSizeX(), p.GetDrillSizeY()) // 2 + + +def free(pos, net): + """No B.Cu copper of another net within clearance, no hole closer than the hole rule.""" + probe = pcbnew.SHAPE_CIRCLE(pos, R) + cl = mm(a.clearance) + for t in b.GetTracks(): + if t.GetNetCode() != net and t.IsOnLayer(pcbnew.B_Cu): + if t.GetEffectiveShape(pcbnew.B_Cu).Collide(probe, cl): + return False + for fp in b.GetFootprints(): + for p in fp.Pads(): + if p.GetNetCode() != net and p.IsOnLayer(pcbnew.B_Cu): + if p.GetEffectiveShape(pcbnew.B_Cu).Collide(probe, cl): + return False + for c, r in holes(): + if (c - pos).EuclideanNorm() < mm(a.drill / 2) + r + mm(a.hole): + return False + return True + + +total = 0 +for ref in a.refs: + fp = b.FindFootprintByReference(ref) + assert fp, ref + pad = exposed_pad(fp) + net = pad.GetNetCode() + box = pad.GetBoundingBox() # thermal pads are rectangles; turned 90 degrees the box is still exact + inset = R + mm(0.1) + x0, x1 = box.GetLeft() + inset, box.GetRight() - inset + y0, y1 = box.GetTop() + inset, box.GetBottom() - inset + p = mm(a.pitch) + nx, ny = max(1, int((x1 - x0) // p) + 1), max(1, int((y1 - y0) // p) + 1) + ox, oy = (x0 + x1 - (nx - 1) * p) // 2, (y0 + y1 - (ny - 1) * p) // 2 # centre the grid + added = 0 + for i in range(nx): + for j in range(ny): + pos = pcbnew.VECTOR2I(int(ox + i * p), int(oy + j * p)) + if not pad.HitTest(pos) or not free(pos, net): + continue + v = pcbnew.PCB_VIA(b) + v.SetPosition(pos) + v.SetWidth(mm(a.via)) + v.SetDrill(mm(a.drill)) + v.SetNetCode(net) + b.Add(v) + added += 1 + print("%s: %d vias on %s (grid %dx%d)" % (ref, added, pad.GetNetname(), nx, ny)) + total += added + +pcbnew.ZONE_FILLER(b).Fill(b.Zones()) +pcbnew.SaveBoard(a.board, b) +if keep is not None: + open(pro, "w").write(keep) # SaveBoard resets the project's net settings +print("added", total) diff --git a/tools/threemf_group.py b/tools/threemf_group.py new file mode 100644 index 0000000..1f92df3 --- /dev/null +++ b/tools/threemf_group.py @@ -0,0 +1,48 @@ +"""Group the objects of a 3MF into one object with parts, for multi-colour printing. + + python3 tools/threemf_group.py in.3mf out.3mf [name] + +SolidCraft exports one 3MF object per body (its `objects: component` mode only groups bodies of +placed sub-components). A slicer loads those as separate objects, so a shell and its label inlays +could not get one colour each on one object. This writes a parent object (default name: the +first object's) whose components are all build items, and builds only the parent; the slicer +then loads one object with each body as a part. Build-item transforms are moved onto the +components. +""" +import sys +import zipfile +import xml.etree.ElementTree as ET + +NS = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" +MODEL = "3D/3dmodel.model" + + +def main(): + src, dst = sys.argv[1], sys.argv[2] + ET.register_namespace("", NS) + with zipfile.ZipFile(src) as z: + files = {n: z.read(n) for n in z.namelist()} + root = ET.fromstring(files[MODEL]) + q = lambda tag: "{%s}%s" % (NS, tag) # noqa: E731 + resources, build = root.find(q("resources")), root.find(q("build")) + objects = resources.findall(q("object")) + name = sys.argv[3] if len(sys.argv) > 3 else objects[0].get("name") + parent = ET.SubElement(resources, q("object"), { + "id": str(max(int(o.get("id")) for o in objects) + 1), "type": "model", "name": name}) + comps = ET.SubElement(parent, q("components")) + for item in build.findall(q("item")): + attrs = {"objectid": item.get("objectid")} + if item.get("transform"): + attrs["transform"] = item.get("transform") + ET.SubElement(comps, q("component"), attrs) + build.remove(item) + ET.SubElement(build, q("item"), {"objectid": parent.get("id")}) + files[MODEL] = ET.tostring(root, encoding="UTF-8", xml_declaration=True) + with zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as z: + for n, data in files.items(): + z.writestr(n, data) + print("%s: %d parts in object '%s'" % (dst, len(comps), name)) + + +if __name__ == "__main__": + main() |
