-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathdiff_pair_routing.py
More file actions
4386 lines (3906 loc) · 221 KB
/
Copy pathdiff_pair_routing.py
File metadata and controls
4386 lines (3906 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Differential pair routing functions.
Routes differential pairs (P and N nets) together using centerline + offset approach.
"""
from __future__ import annotations
import math
import numpy as np
from typing import List, Optional, Tuple, Dict
from kicad_parser import PCBData, Segment, Via
from routing_config import GridRouteConfig, GridCoord, DiffPairNet, REFERENCE_GRID_STEP
from routing_utils import segment_length, build_layer_map, pos_key
from connectivity import (
find_connected_groups, find_stub_free_ends, get_stub_direction, get_net_endpoints,
get_stub_segments, get_stub_vias, calculate_stub_via_barrel_length
)
from obstacle_map import check_line_clearance
from geometry_utils import simplify_path, segments_intersect_tuple
# Note: Layer switching is now done upfront in route.py, not during routing
# Import Rust router
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'rust_router'))
try:
from grid_router import GridObstacleMap, GridRouter, PoseRouter
except ImportError:
GridObstacleMap = None
GridRouter = None
PoseRouter = None
# Map direction (dx, dy) to theta_idx (0-7) for pose-based routing
# DIRECTIONS in Rust: E(1,0)=0, NE(1,-1)=1, N(0,-1)=2, NW(-1,-1)=3, W(-1,0)=4, SW(-1,1)=5, S(0,1)=6, SE(1,1)=7
DIRECTION_TO_THETA = {
(1, 0): 0, # East
(1, -1): 1, # NE
(0, -1): 2, # North
(-1, -1): 3, # NW
(-1, 0): 4, # West
(-1, 1): 5, # SW
(0, 1): 6, # South
(1, 1): 7, # SE
}
def direction_to_theta_idx(dx: float, dy: float) -> int:
"""Convert a direction vector (dx, dy) to a theta_idx (0-7) for pose-based routing."""
if abs(dx) < 0.01 and abs(dy) < 0.01:
return 0 # Default to East if no direction
# Normalize
length = math.sqrt(dx*dx + dy*dy)
ndx = dx / length
ndy = dy / length
# Find the angle and map to nearest 45-degree direction
angle = math.atan2(-ndy, ndx) # Note: negate y because grid y increases downward
# Convert to [0, 2*pi) range
if angle < 0:
angle += 2 * math.pi
# Map angle to theta_idx (each sector is 45 degrees = pi/4)
# Add pi/8 to center each sector around the direction
theta_idx = int((angle + math.pi/8) / (math.pi/4)) % 8
return theta_idx
def _footprint_pad_centroid(pcb_data: PCBData, net_id: int, x: float, y: float,
tolerance: float = 0.05) -> Optional[Tuple[float, float]]:
"""Find the pad of net_id at (x, y) and return the centroid of all pads on its footprint."""
for pad in pcb_data.pads_by_net.get(net_id, []):
if abs(pad.global_x - x) < tolerance and abs(pad.global_y - y) < tolerance:
footprint = pcb_data.footprints.get(pad.component_ref)
if footprint and footprint.pads:
cx = sum(p.global_x for p in footprint.pads) / len(footprint.pads)
cy = sum(p.global_y for p in footprint.pads) / len(footprint.pads)
return (cx, cy)
return None
def get_pair_end_direction(pcb_data: PCBData, p_net_id: int, n_net_id: int,
p_segments: List[Segment], n_segments: List[Segment],
p_x: float, p_y: float, n_x: float, n_y: float,
layer_name: str,
other_center: Optional[Tuple[float, float]] = None
) -> Tuple[float, float, bool]:
"""
Compute the escape direction for one end of a differential pair.
Normally this is the average of the P and N stub directions. When both
endpoints are bare pads (no stub segments), the stub directions are (0,0)
and the setback machinery would degenerate to the pad-pair center, letting
the offset P/N tracks cross the partner net's pads. In that case we
synthesize a direction perpendicular to the P-N pad axis, pointing away
from the owning component's pad centroid (falling back to "toward the
other end of the route").
Returns (dir_x, dir_y, synthesized). The direction is normalized, or (0,0)
if no direction could be determined. synthesized is True when the direction
came from pad geometry rather than stub segments.
"""
p_dir = get_stub_direction(p_segments, p_x, p_y, layer_name)
n_dir = get_stub_direction(n_segments, n_x, n_y, layer_name)
dir_x = (p_dir[0] + n_dir[0]) / 2
dir_y = (p_dir[1] + n_dir[1]) / 2
dir_len = math.sqrt(dir_x * dir_x + dir_y * dir_y)
if dir_len > 1e-6:
dir_x, dir_y = dir_x / dir_len, dir_y / dir_len
# get_stub_direction expects the stub FREE END; the multipoint diff-pair
# path passes the PAD position instead, so for a pad with an escape stub
# (e.g. a fanned-out QFN pin) it returns the direction reversed - pointing
# INTO the component body, which backs the centerline setback into the
# chip and the route dies on the pad field.
#
# Correct it ONLY when the query point IS a pad of the owning component
# (_footprint_pad_centroid returns non-None), which is exactly the buggy
# case. A true free-end terminal is not at a pad -> centroid is None -> no
# orientation, so a genuine stub that legitimately doesn't point straight
# outward is left untouched (avoids false-flipping free-end stubs).
#
# When the query point is a pad: orient the escape away from the
# component's pad centroid; but if that centroid coincides with the
# terminal center (a 2-pad component - resistor/2-pin part - whose two pads
# ARE the pair), there is no "body" to point away from, so orient toward
# the other terminal instead.
centroid = (_footprint_pad_centroid(pcb_data, p_net_id, p_x, p_y) or
_footprint_pad_centroid(pcb_data, n_net_id, n_x, n_y))
if centroid:
cx, cy = (p_x + n_x) / 2, (p_y + n_y) / 2
if math.hypot(cx - centroid[0], cy - centroid[1]) > 0.05:
away = (cx - centroid[0], cy - centroid[1]) # away from body
elif other_center is not None:
away = (other_center[0] - cx, other_center[1] - cy) # toward other end
else:
away = None
if away is not None and dir_x * away[0] + dir_y * away[1] < 0:
dir_x, dir_y = -dir_x, -dir_y
return (dir_x, dir_y, False)
# Bare pads (or cancelling stub directions): synthesize from pad geometry.
axis_x, axis_y = p_x - n_x, p_y - n_y
axis_len = math.sqrt(axis_x * axis_x + axis_y * axis_y)
if axis_len < 1e-6:
return (0.0, 0.0, False)
perp_x, perp_y = -axis_y / axis_len, axis_x / axis_len
center_x, center_y = (p_x + n_x) / 2, (p_y + n_y) / 2
# Prefer escaping away from the owning component's body (pad centroid)
centroid = (_footprint_pad_centroid(pcb_data, p_net_id, p_x, p_y) or
_footprint_pad_centroid(pcb_data, n_net_id, n_x, n_y))
if centroid:
dot = perp_x * (center_x - centroid[0]) + perp_y * (center_y - centroid[1])
if abs(dot) > 0.05:
return (perp_x, perp_y, True) if dot > 0 else (-perp_x, -perp_y, True)
# Symmetric component (e.g. 2-pad resistor): escape toward the other end
if other_center is not None:
dot = perp_x * (other_center[0] - center_x) + perp_y * (other_center[1] - center_y)
if abs(dot) > 0.05:
return (perp_x, perp_y, True) if dot > 0 else (-perp_x, -perp_y, True)
return (perp_x, perp_y, True)
def _setback_ladder(setback, spacing_mm, pad_gap_half, config):
"""Candidate setback radii to scan, preferred first (issue #90).
The old single fixed-radius search failed whole pairs whenever every
angle on that one ring was blocked - dense terminals (0402 resistor
rows, SOT-23s, USB-C) often have an open ring nearer or farther.
The geometric floor is the longitudinal room the P/N connector fan
needs to taper from the pad separation down to the pair spacing at
<= ~45 degrees: |pad_gap/2 - spacing| plus a grid step of margin,
never less than 2*spacing. Below that the connectors would kink.
Above the configured setback, 1.5x and 2x are also tried - sometimes
the neighborhood only opens up farther out.
"""
floor = max(2 * spacing_mm,
abs(pad_gap_half - spacing_mm) + config.grid_step)
# Pinch retry (#246): route at EXACTLY the configured setback, no expansion, so the
# caller's chosen radius is the one actually used (the scan drives the radius itself).
if getattr(config, 'diff_pair_setback_no_ladder', False):
return [setback]
# The configured/default setback is always rung 1, even below the floor -
# an explicit --diff-pair-centerline-setback must be honored as given.
ladder = [setback]
for s in (0.75 * setback, 0.5 * setback, floor,
1.5 * setback, 2 * setback):
s = max(s, floor)
if all(abs(s - e) > 1e-6 for e in ladder):
ladder.append(s)
return ladder
def _launch_assoc_tol(config):
"""Distance within which a via/THT pad is treated as belonging to (escaping)
a diff-pair terminal: hand- or auto-placed escape vias sit at/near the pad or
stub tip, offset by up to ~a via radius, not grid-coincident (watchy USB_D).
Stays below a fine pad pitch so it can't grab a neighbour terminal's via."""
return max(config.grid_step * 1.5, config.via_size * 0.75 + config.track_width / 2)
def _endpoint_launch_layer_indices(pcb_data, net_id, x, y, config, tol=None):
"""Routing-layer indices a coupled launch may use at endpoint (x, y) of `net_id`.
A diff-pair terminal that sits on a through-via or a through-hole pad can
launch on ANY routing layer that copper spans, not just the stub's layer --
the existing barrel already ties the layers together (issue #195). Returns
the set of indices into config.layers that an existing via/THT pad of this
net at (x, y) connects. The router uses this to retry the setback search on
an open inner layer when the stub layer's corridor is jammed.
"""
if tol is None:
tol = _launch_assoc_tol(config)
copper = getattr(pcb_data.board_info, 'copper_layers', None) or list(config.layers)
cu_index = {name: i for i, name in enumerate(copper)}
routing_idx = {name: i for i, name in enumerate(config.layers)}
def _span_all():
return {ridx for lname, ridx in routing_idx.items() if lname in cu_index}
spanned = set()
# Through-vias: span from their top to bottom copper layer.
for via in pcb_data.vias:
if via.net_id != net_id:
continue
if abs(via.x - x) > tol or abs(via.y - y) > tol:
continue
vlayers = via.layers or ['F.Cu', 'B.Cu']
v_idxs = [cu_index[l] for l in vlayers if l in cu_index]
if not v_idxs:
continue
lo, hi = min(v_idxs), max(v_idxs)
for lname, ridx in routing_idx.items():
if lname in cu_index and lo <= cu_index[lname] <= hi:
spanned.add(ridx)
# PLATED through-hole pads span every copper layer, like a via barrel
# (NPTH holes have no copper -- #328).
from kicad_parser import pad_is_plated_through
for pad in pcb_data.pads_by_net.get(net_id, []):
if pad_is_plated_through(pad) and \
abs(pad.global_x - x) <= tol and abs(pad.global_y - y) <= tol:
spanned |= _span_all()
break
return spanned
def _pt_seg_dist(px, py, ax, ay, bx, by):
"""Distance from point (px,py) to segment (ax,ay)-(bx,by)."""
dx, dy = bx - ax, by - ay
L2 = dx * dx + dy * dy
if L2 <= 1e-12:
return math.hypot(px - ax, py - ay)
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / L2))
return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
def _terminal_escape_vias(pcb_data, p_net_id, n_net_id, p_term, n_term, config):
"""The pair's own escape/terminal vias sitting at the P/N launch terminals.
These are excluded from the routing obstacle map (own-net), so the setback
search is blind to them -- a per-half offset connector can then graze the
PARTNER half's escape via (issue #165 / watchy USB_D). Returns a list of
(x, y, size, net_id) for vias of either net within the launch-association
tolerance of either terminal.
"""
tol = _launch_assoc_tol(config)
out = []
for via in getattr(pcb_data, 'vias', None) or []:
if via.net_id not in (p_net_id, n_net_id):
continue
if (math.hypot(via.x - p_term[0], via.y - p_term[1]) <= tol or
math.hypot(via.x - n_term[0], via.y - n_term[1]) <= tol):
# Guard size like obstacle_map does, so a 0/missing size can't shrink
# the graze clearance and let a real partner-via graze slip through.
out.append((via.x, via.y, via.size if via.size > 0 else config.via_size, via.net_id))
return out
def _make_offset_connector_check(p_term, n_term, escape_vias, spacing_mm, config):
"""Build an offset_check(launch_x, launch_y, dir_x, dir_y) -> bool closure.
For a candidate setback launch point, the P and N tracks sit at +-spacing
perpendicular to the launch direction; each terminal runs a short connector
to its offset launch point. This returns False if either connector would
clip the *partner* terminal's escape via (the gap the obstacle map misses),
so the setback search rejects that candidate and picks a clearing one.
Returns None when there are no escape vias to avoid (no behaviour change).
"""
if not escape_vias:
return None
# A via this close to a terminal IS that terminal's own launch via (it need
# not sit exactly on the stub tip) -- the connector legitimately starts on
# it, so don't count it as a graze of its own leg.
own_tol = _launch_assoc_tol(config)
def _leg_grazes(term, off):
for vx, vy, vsize, _ in escape_vias:
# skip the via at this terminal (its own launch via)
if math.hypot(vx - term[0], vy - term[1]) <= own_tol:
continue
need = config.clearance + config.track_width / 2 + vsize / 2
if _pt_seg_dist(vx, vy, term[0], term[1], off[0], off[1]) < need:
return True
return False
def check(lx, ly, dx, dy):
px, py = -dy, dx # perpendicular
off_a = (lx + px * spacing_mm, ly + py * spacing_mm)
off_b = (lx - px * spacing_mm, ly - py * spacing_mm)
# Assign each terminal to its nearer offset launch point (the route's
# likely polarity). Rejecting both assignments over-rejects tight-but-
# legal launches (e.g. #195's 0.5mm-pitch escape vias), so use the
# nearest assignment only.
def d2(a, b):
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
if d2(p_term, off_a) + d2(n_term, off_b) <= d2(p_term, off_b) + d2(n_term, off_a):
legs = ((p_term, off_a), (n_term, off_b))
else:
legs = ((p_term, off_b), (n_term, off_a))
return not (_leg_grazes(*legs[0]) or _leg_grazes(*legs[1]))
return check
def _find_open_positions_multilayer(center_x, center_y, dir_x, dir_y, layer_idx,
alt_layers, setback, pad_gap_half, label,
layer_names, spacing_mm, config, obstacles,
connector_obstacles, coord, neighbor_stubs,
offset_check=None):
"""_find_open_positions_laddered, but free to launch on an alternate routing
layer reachable through the endpoint's via/THT barrel (issue #195).
Tries the stub layer first and keeps it when it yields a clean (non-rotated)
launch -- unchanged behaviour. Only when the stub layer is fully blocked or
can launch solely by rotating sideways does it retry the alternate layers
(e.g. an open inner layer under a chip) for a clean launch. Returns
(candidates, used_setback, rotated, launch_layer_idx).
"""
cands, used, rotated = _find_open_positions_laddered(
center_x, center_y, dir_x, dir_y, layer_idx, setback, pad_gap_half,
label, layer_names, spacing_mm, config, obstacles, connector_obstacles,
coord, neighbor_stubs, offset_check=offset_check)
if cands and not rotated:
return cands, used, rotated, layer_idx
fallback = (cands, used, rotated, layer_idx) if cands else None
for alt in alt_layers:
if alt == layer_idx:
continue
a_cands, a_used, a_rot = _find_open_positions_laddered(
center_x, center_y, dir_x, dir_y, alt, setback, pad_gap_half,
label, layer_names, spacing_mm, config, obstacles,
connector_obstacles, coord, neighbor_stubs, offset_check=offset_check)
if a_cands and not a_rot:
print(f" {label}: {layer_names[layer_idx]} corridor jammed - "
f"launching on {layer_names[alt]} (reachable through the endpoint via)")
return a_cands, a_used, a_rot, alt
if fallback is None and a_cands:
fallback = (a_cands, a_used, a_rot, alt)
if fallback is not None:
return fallback
return [], setback, False, layer_idx
def _find_open_positions_laddered(center_x, center_y, dir_x, dir_y, layer_idx,
setback, pad_gap_half, label, layer_names,
spacing_mm, config, obstacles,
connector_obstacles, coord, neighbor_stubs,
offset_check=None):
"""_find_open_positions over a ladder of setback radii (issue #90).
Returns (candidates, used_setback, rotated); `rotated` is True when the
position was only found by rotating the launch direction away from the
escape direction (the centerline route must then wrap around the
endpoint, like a flipped attempt).
"""
ladder = _setback_ladder(setback, spacing_mm, pad_gap_half, config)
for i, s in enumerate(ladder):
candidates = _find_open_positions(
center_x, center_y, dir_x, dir_y, layer_idx, s, label,
layer_names, spacing_mm, config, obstacles,
connector_obstacles, coord, neighbor_stubs,
quiet_failure=True, offset_check=offset_check)
if candidates:
if i > 0:
print(f" {label}: setback {ladder[0]:.2f}mm blocked, "
f"using {s:.2f}mm")
return candidates, s, False
# Full-sweep fallback: the angle fan only covers +-max_setback_angle
# around the escape direction, but buried terminals (SOT-23 chains,
# USB-C row-to-row legs) often only open sideways or backwards.
# Re-run the ladder with the launch direction rotated 90/180/270 deg -
# together with the fan this covers the whole circle.
for rot_deg in (90, -90, 180):
rot = math.radians(rot_deg)
rdx = dir_x * math.cos(rot) - dir_y * math.sin(rot)
rdy = dir_x * math.sin(rot) + dir_y * math.cos(rot)
for s in ladder:
candidates = _find_open_positions(
center_x, center_y, rdx, rdy, layer_idx, s, label,
layer_names, spacing_mm, config, obstacles,
connector_obstacles, coord, neighbor_stubs,
quiet_failure=True, offset_check=offset_check)
if candidates:
print(f" {label}: escape direction blocked at every "
f"setback - launching rotated {rot_deg:+d}deg at {s:.2f}mm")
return candidates, s, True
print(f" Error: {label} - no valid position at any setback/direction "
f"(ladder {', '.join(f'{s:.2f}' for s in ladder)}mm x full sweep)")
return [], setback, False
def _find_open_positions(center_x, center_y, dir_x, dir_y, layer_idx, setback,
label, layer_names, spacing_mm, config, obstacles,
connector_obstacles, coord, neighbor_stubs,
quiet_failure=False, offset_check=None):
"""Find open position for setback, preferring 0° but angling away from nearby stubs if needed.
Only angles away from 0° if the nearest unrouted stub is too close (within
required diff pair clearance). Returns list with best candidate first.
Each candidate is (gx, gy, dx, dy, angle_deg, dist_to_nearest_stub).
"""
current_layer = layer_names[layer_idx]
# Required clearance from centerline to neighboring stub
# P/N tracks are at ±spacing_mm from centerline, need config.clearance to other stub
# Add factor of 2 for extra margin to ensure future routes have room
required_clearance = 2 * (spacing_mm + config.clearance)
# Generate angles: 0, then ±max/4, ±max/2, ±3*max/4, ±max
max_angle = config.max_setback_angle
angles_deg = [0,
max_angle / 4, -max_angle / 4,
max_angle / 2, -max_angle / 2,
3 * max_angle / 4, -3 * max_angle / 4,
max_angle, -max_angle]
def check_angle_valid(angle_deg):
"""Check if angle is valid (not blocked). Returns (gx, gy, dx, dy, x, y) or None."""
angle_rad = math.radians(angle_deg)
cos_a = math.cos(angle_rad)
sin_a = math.sin(angle_rad)
dx = dir_x * cos_a - dir_y * sin_a
dy = dir_x * sin_a + dir_y * cos_a
x = center_x + dx * setback
y = center_y + dy * setback
gx, gy = coord.to_grid(x, y)
if obstacles.is_blocked(gx, gy, layer_idx):
return None
if not check_line_clearance(connector_obstacles, center_x, center_y, x, y, layer_idx, config):
return None
# Probe ahead
probe_dist = config.grid_step * 3
probe_x = x + dx * probe_dist
probe_y = y + dy * probe_dist
probe_gx, probe_gy = coord.to_grid(probe_x, probe_y)
if obstacles.is_blocked(probe_gx, probe_gy, layer_idx):
return None
# Reject if a per-half offset connector from this launch would clip a
# partner escape via (the own-net via the obstacle map excludes) -- #165.
if offset_check is not None and not offset_check(x, y, dx, dy):
return None
return (gx, gy, dx, dy, x, y)
def find_nearest_stub(x, y):
"""Find nearest same-layer stub from position (x, y). Returns (dist, stub_x, stub_y) or (inf, None, None)."""
min_dist = float('inf')
closest = (None, None)
if neighbor_stubs:
for stub_x, stub_y, stub_layer in neighbor_stubs:
if stub_layer != current_layer:
continue
dist = math.sqrt((x - stub_x)**2 + (y - stub_y)**2)
if dist < min_dist:
min_dist = dist
closest = (stub_x, stub_y)
return min_dist, closest[0], closest[1]
# Check 0° first
zero_result = check_angle_valid(0)
if zero_result:
gx, gy, dx, dy, x, y = zero_result
dist, stub_x, stub_y = find_nearest_stub(x, y)
# Collect all valid angles as fallbacks (sorted by angle magnitude)
other_candidates = []
for angle_deg in sorted(angles_deg, key=abs):
if angle_deg == 0:
continue
result = check_angle_valid(angle_deg)
if result:
ax, ay, adx, ady, ax_pos, ay_pos = result
a_dist, _, _ = find_nearest_stub(ax_pos, ay_pos)
other_candidates.append((ax, ay, adx, ady, angle_deg, a_dist))
if dist >= required_clearance:
# 0° is valid and has enough clearance - use it as primary
if config.verbose:
if stub_x is not None:
print(f" {label} 0.0°: OK (nearest stub at ({stub_x:.1f},{stub_y:.1f}) dist={dist:.2f}mm >= {required_clearance:.2f}mm)")
else:
print(f" {label} 0.0°: OK (no nearby stubs on {current_layer})")
return [(gx, gy, dx, dy, 0.0, dist)] + other_candidates
# 0° is valid but too close to stub - need to angle away
if config.verbose:
print(f" {label} 0.0°: too close to stub at ({stub_x:.1f},{stub_y:.1f}) dist={dist:.2f}mm < {required_clearance:.2f}mm")
# Determine which direction to angle based on stub position
# Cross product: positive means stub is on left (+angle side)
stub_vec_x = stub_x - center_x
stub_vec_y = stub_y - center_y
cross = dir_x * stub_vec_y - dir_y * stub_vec_x
# Angle away from stub: if stub on left (cross > 0), go negative angle
preferred_sign = -1 if cross > 0 else 1
# Find the best angle that clears
best_clearing_angle = None
for cand in other_candidates:
if cand[4] * preferred_sign > 0 and cand[5] >= required_clearance:
best_clearing_angle = cand
if config.verbose:
print(f" {label} {cand[4]:+.1f}°: OK (cleared to {cand[5]:.2f}mm)")
break
if best_clearing_angle:
# Put clearing angle first, then 0°, then others
remaining = [c for c in other_candidates if c != best_clearing_angle]
return [best_clearing_angle, (gx, gy, dx, dy, 0.0, dist)] + remaining
else:
# No angle clears - use 0° as primary anyway
if config.verbose:
print(f" {label} using 0.0° (no angle clears {required_clearance:.2f}mm)")
return [(gx, gy, dx, dy, 0.0, dist)] + other_candidates
# 0° is blocked - find any valid angle, prefer smaller angles
if config.verbose:
print(f" {label} 0.0°: blocked")
valid_candidates = []
for angle_deg in sorted(angles_deg, key=abs):
if angle_deg == 0:
continue
result = check_angle_valid(angle_deg)
if result:
gx, gy, dx, dy, x, y = result
dist, _, _ = find_nearest_stub(x, y)
valid_candidates.append((gx, gy, dx, dy, angle_deg, dist))
if config.verbose:
print(f" {label} {angle_deg:+.1f}°: OK (dist={dist:.2f}mm)")
if not valid_candidates:
if not quiet_failure:
print(f" Error: {label} - no valid position at setback={setback:.2f}mm (all angles blocked)")
return []
# Sort by clearance (larger better), then by angle magnitude (smaller better)
valid_candidates.sort(key=lambda c: (c[5], -abs(c[4])), reverse=True)
return valid_candidates
def _collect_setback_blocked_cells(center_x, center_y, dir_x, dir_y, layer_idx, setback,
config, obstacles, connector_obstacles, coord):
"""Collect blocked cells at setback positions for rip-up analysis.
Called only after _find_open_positions returns empty list.
"""
max_angle = config.max_setback_angle
angles_deg = [0,
max_angle / 4, -max_angle / 4,
max_angle / 2, -max_angle / 2,
3 * max_angle / 4, -3 * max_angle / 4,
max_angle, -max_angle]
blocked = []
step = config.grid_step / 2
for angle_deg in angles_deg:
angle_rad = math.radians(angle_deg)
cos_a = math.cos(angle_rad)
sin_a = math.sin(angle_rad)
dx = dir_x * cos_a - dir_y * sin_a
dy = dir_x * sin_a + dir_y * cos_a
x = center_x + dx * setback
y = center_y + dy * setback
gx, gy = coord.to_grid(x, y)
# Collect blocked setback position
if obstacles.is_blocked(gx, gy, layer_idx):
if (gx, gy, layer_idx) not in blocked:
blocked.append((gx, gy, layer_idx))
# Collect blocked cells along connector path
length = math.sqrt((x - center_x)**2 + (y - center_y)**2)
if length > 0:
path_dx = (x - center_x) / length
path_dy = (y - center_y) / length
dist = 0.0
while dist <= length:
px = center_x + path_dx * dist
py = center_y + path_dy * dist
pgx, pgy = coord.to_grid(px, py)
if connector_obstacles.is_blocked(pgx, pgy, layer_idx):
if (pgx, pgy, layer_idx) not in blocked:
blocked.append((pgx, pgy, layer_idx))
dist += step
# Also collect "probe ahead" blocked cells (3 grid cells ahead of setback)
# This catches cases where setback and connector are clear but routing direction is blocked
probe_dist = config.grid_step * 3
probe_x = x + dx * probe_dist
probe_y = y + dy * probe_dist
probe_gx, probe_gy = coord.to_grid(probe_x, probe_y)
if obstacles.is_blocked(probe_gx, probe_gy, layer_idx):
if (probe_gx, probe_gy, layer_idx) not in blocked:
blocked.append((probe_gx, probe_gy, layer_idx))
return blocked
def _detect_polarity(simplified_path, coord,
p_src_x, p_src_y, n_src_x, n_src_y,
p_tgt_x, p_tgt_y, n_tgt_x, n_tgt_y,
config):
"""
Detect which side of the centerline P should be on and whether polarity swap is needed.
Detection only - whether the mismatch is resolved by a pad swap, an
opposite-side connector flip, or a skip is decided by the caller.
Args:
simplified_path: List of (gx, gy, layer) representing simplified centerline
coord: GridCoord for coordinate conversion
p_src_x, p_src_y: P source position in mm
n_src_x, n_src_y: N source position in mm
p_tgt_x, p_tgt_y: P target position in mm
n_tgt_x, n_tgt_y: N target position in mm
config: Routing config
Returns:
(p_sign, polarity_swap_needed, has_layer_change)
- p_sign: +1 or -1, which perpendicular side P should be offset to
- polarity_swap_needed: True if source and target polarities differ
- has_layer_change: True if path has vias (layer changes)
"""
# Determine which side of the centerline P is on
# Use the first segment direction of the simplified path
if len(simplified_path) >= 2:
first_gx, first_gy, _ = simplified_path[0]
second_gx, second_gy, _ = simplified_path[1]
first_x, first_y = coord.to_float(first_gx, first_gy)
second_x, second_y = coord.to_float(second_gx, second_gy)
path_dir_x = second_x - first_x
path_dir_y = second_y - first_y
else:
path_dir_x, path_dir_y = 1.0, 0.0
# Vector from source midpoint to P source position
src_midpoint_x = (p_src_x + n_src_x) / 2
src_midpoint_y = (p_src_y + n_src_y) / 2
to_p_dx = p_src_x - src_midpoint_x
to_p_dy = p_src_y - src_midpoint_y
# Cross product: determines which side of the path direction P is on at source
src_cross = path_dir_x * to_p_dy - path_dir_y * to_p_dx
src_p_sign = +1 if src_cross >= 0 else -1
# Calculate target polarity using path direction at target end
# Path arrives at target, so use negative of last segment direction
if len(simplified_path) >= 2:
last_gx1, last_gy1, _ = simplified_path[-2]
last_gx2, last_gy2, _ = simplified_path[-1]
last_cx1, last_cy1 = coord.to_float(last_gx1, last_gy1)
last_cx2, last_cy2 = coord.to_float(last_gx2, last_gy2)
last_len = math.sqrt((last_cx2 - last_cx1)**2 + (last_cy2 - last_cy1)**2)
if last_len > 0.001:
tgt_path_dir_x = (last_cx2 - last_cx1) / last_len
tgt_path_dir_y = (last_cy2 - last_cy1) / last_len
else:
tgt_path_dir_x, tgt_path_dir_y = path_dir_x, path_dir_y
else:
tgt_path_dir_x, tgt_path_dir_y = path_dir_x, path_dir_y
# Vector from target midpoint to P target position
tgt_midpoint_x = (p_tgt_x + n_tgt_x) / 2
tgt_midpoint_y = (p_tgt_y + n_tgt_y) / 2
tgt_to_p_dx = p_tgt_x - tgt_midpoint_x
tgt_to_p_dy = p_tgt_y - tgt_midpoint_y
# Cross product: determines which side of the path direction P is on at target
tgt_cross = tgt_path_dir_x * tgt_to_p_dy - tgt_path_dir_y * tgt_to_p_dx
tgt_p_sign = +1 if tgt_cross >= 0 else -1
# Check if polarity differs between source and target
polarity_swap_needed = (src_p_sign != tgt_p_sign)
# Check if path has layer changes (vias)
has_layer_change = False
for i in range(len(simplified_path) - 1):
if simplified_path[i][2] != simplified_path[i + 1][2]:
has_layer_change = True
break
# Always use source polarity
p_sign = src_p_sign
return p_sign, polarity_swap_needed, has_layer_change
def _calculate_parallel_extension(p_stub, n_stub, p_route, n_route, stub_dir, p_sign):
"""Calculate extensions for P and N tracks to make their connectors parallel.
The key insight: for connectors to be parallel, the extending track must
extend along the stub direction until its connector is parallel to the
non-extended track's connector.
Formula derivation:
- V_p = R_p - S_p (direct connector for P)
- V_n = R_n - S_n (direct connector for N)
- For P extended by E: V_p' = V_p - E*D
- For V_p' || V_n: (V_p - E*D) × V_n = 0
- E = (V_p × V_n) / (D × V_n)
Returns (p_extension, n_extension) where one will be positive, the other 0.
"""
dx, dy = stub_dir
# Direct connector vectors
v_p = (p_route[0] - p_stub[0], p_route[1] - p_stub[1])
v_n = (n_route[0] - n_stub[0], n_route[1] - n_stub[1])
# Cross product of connector vectors: tells us if connectors are already parallel
# and which direction the divergence is
v_cross = v_p[0] * v_n[1] - v_p[1] * v_n[0]
# If connectors are nearly parallel, no extension needed
if abs(v_cross) < 0.0001:
return 0.0, 0.0
# Cross product D × V_n (for extending P)
d_cross_vn = dx * v_n[1] - dy * v_n[0]
# Cross product D × V_p (for extending N)
d_cross_vp = dx * v_p[1] - dy * v_p[0]
# Calculate extensions for both tracks
# E_p = (V_p × V_n) / (D × V_n) makes V_p' parallel to V_n
# E_n = (V_n × V_p) / (D × V_p) = -v_cross / d_cross_vp makes V_n' parallel to V_p
p_ext = v_cross / d_cross_vn if abs(d_cross_vn) > 0.0001 else 0.0
n_ext = -v_cross / d_cross_vp if abs(d_cross_vp) > 0.0001 else 0.0
# Use whichever extension is positive (extending in stub direction)
# If both are positive, prefer the one for the "outside" track
if p_ext > 0.001 and n_ext > 0.001:
# Both positive - use the outside track based on geometry
is_p_outside = (v_cross > 0 and p_sign < 0) or (v_cross < 0 and p_sign > 0)
if is_p_outside:
return p_ext, 0.0
else:
return 0.0, n_ext
elif p_ext > 0.001:
return p_ext, 0.0
elif n_ext > 0.001:
return 0.0, n_ext
return 0.0, 0.0
def _routing_copper_layers(pcb_data, config) -> List[str]:
"""Copper layer names for check_drc's pad/via layer-wildcard expansion: the
board's copper segment layers unioned with the configured routing layers."""
layers = {s.layer for s in pcb_data.segments if s.layer.endswith('.Cu')}
layers.update(config.layers)
return list(layers)
def _rect_ray_exit(hx: float, hy: float, dx: float, dy: float) -> float:
"""Distance from an axis-aligned rectangle's center to its boundary along the
unit direction (dx, dy). hx, hy are the half-extents."""
tx = hx / abs(dx) if abs(dx) > 1e-9 else float('inf')
ty = hy / abs(dy) if abs(dy) > 1e-9 else float('inf')
return min(tx, ty)
def _ellipse_ray_exit(a: float, b: float, dx: float, dy: float) -> float:
"""Distance from an ellipse center (semi-axes a, b) to its boundary along the
unit direction (dx, dy). For a circle (a == b) this is just the radius."""
denom = (dx / a) ** 2 + (dy / b) ** 2 if a > 1e-9 and b > 1e-9 else 0.0
return 1.0 / math.sqrt(denom) if denom > 1e-12 else float('inf')
def _pad_edge_launch(pcb_data, net_id, cx, cy, route_x, route_y, config, tol=0.05):
"""Issue #165 (tier-2 root-cause 2): move a bare-pad connector launch point
from the pad CENTER to the pad edge facing the route, so the connector leaves
the pad toward the route instead of cutting back across the (long) pad field
- e.g. a 1.45mm USB-C pad whose center-launched connector grazes a neighbour.
Only fires when (cx, cy) actually sits on a pad of net_id (a bare-pad
endpoint - its coords ARE the pad center); a stub-tip launch point is away
from any pad center, so no pad is found and the launch is left untouched
(the connector must stay attached to the existing stub). Returns
(x, y, shift): the shifted launch point (clamped to stay inside the pad copper
and never past the route start) and how far along the route direction it
moved (0.0 when no pad / no move) -- the caller subtracts that from the
centerline setback so the setback point stays put instead of being pushed
past the pad into a downstream blockage (issue #166).
"""
pad, best = None, tol
for p in pcb_data.pads_by_net.get(net_id, []):
d = math.hypot(p.global_x - cx, p.global_y - cy)
if d <= best:
best, pad = d, p
if pad is None:
return cx, cy, 0.0
dx, dy = route_x - cx, route_y - cy
norm = math.hypot(dx, dy)
if norm < 1e-6:
return cx, cy, 0.0
dx, dy = dx / norm, dy / norm
# Rotate the direction into the pad's local frame for diagonal pads, matching
# check_drc's R(-rect_rotation) convention, so the axis-aligned exit applies.
ldx, ldy = dx, dy
if pad.rect_rotation:
rad = math.radians(pad.rect_rotation)
cr, sr = math.cos(rad), math.sin(rad)
ldx, ldy = dx * cr + dy * sr, -dx * sr + dy * cr
# Round pads use the ellipse boundary so the launch stays on copper (the rect
# bounding box would put it in a corner outside a circle/oval).
if pad.shape in ('circle', 'oval'):
reach = _ellipse_ray_exit(pad.size_x / 2, pad.size_y / 2, ldx, ldy)
else:
reach = _rect_ray_exit(pad.size_x / 2, pad.size_y / 2, ldx, ldy)
if not math.isfinite(reach) or reach <= 0:
return cx, cy, 0.0
# Stay just inside the pad edge so the track endpoint lands on pad copper,
# and never launch past the route's first point (very short connectors).
margin = min(config.track_width / 2, reach * 0.25)
shift = min(reach - margin, max(0.0, norm - config.track_width / 2))
if shift <= 1e-6:
return cx, cy, 0.0
return cx + dx * shift, cy + dy * shift, shift
def _create_gnd_vias(simplified_path, coord, config, layer_names, spacing_mm, gnd_net_id, gnd_via_dirs):
"""Create GND vias at layer changes in the centerline path.
Args:
simplified_path: List of (gx, gy, layer_idx) grid points
coord: GridCoord for conversions
config: GridRouteConfig
layer_names: List of layer names
spacing_mm: P/N offset from centerline
gnd_net_id: Net ID for GND vias
gnd_via_dirs: List of directions (+1=ahead, -1=behind) from Rust router
Returns:
List of Via objects for GND connections
"""
gnd_vias = []
if gnd_net_id is None or len(simplified_path) < 2:
return gnd_vias
# Calculate GND via perpendicular offset: track edge + clearance + via radius
# Use max track width for clearance since track width varies by layer
max_track_width = config.get_max_track_width()
gnd_via_perp_mm = spacing_mm + max_track_width/2 + config.clearance + config.via_size/2
via_via_dist_mm = config.via_size + config.clearance
# Track which layer change we're processing to get direction from gnd_via_dirs
via_idx = 0
# Find layer changes in centerline path
for i in range(len(simplified_path) - 1):
gx1, gy1, layer1 = simplified_path[i]
gx2, gy2, layer2 = simplified_path[i + 1]
if layer1 != layer2:
# Layer change - calculate centerline position and direction
cx, cy = coord.to_float(gx1, gy1)
# Get heading direction (from via to next point)
next_cx, next_cy = coord.to_float(gx2, gy2)
dx = next_cx - cx
dy = next_cy - cy
length = math.sqrt(dx*dx + dy*dy)
if length > 0.001:
dx /= length
dy /= length
else:
# Fallback: use direction from previous point
if i > 0:
prev_gx, prev_gy, _ = simplified_path[i - 1]
prev_cx, prev_cy = coord.to_float(prev_gx, prev_gy)
dx = cx - prev_cx
dy = cy - prev_cy
length = math.sqrt(dx*dx + dy*dy)
if length > 0.001:
dx /= length
dy /= length
else:
dx, dy = 1.0, 0.0
else:
dx, dy = 1.0, 0.0
# Perpendicular direction: rotate 90° -> (-dy, dx)
perp_x = -dy
perp_y = dx
# Get GND via direction from Rust router (1=ahead, -1=behind)
gnd_dir = gnd_via_dirs[via_idx] if via_idx < len(gnd_via_dirs) else 1
via_idx += 1
# GND via positions: perpendicular offset + along-heading offset
gnd_p_x = cx + perp_x * gnd_via_perp_mm + dx * via_via_dist_mm * gnd_dir
gnd_p_y = cy + perp_y * gnd_via_perp_mm + dy * via_via_dist_mm * gnd_dir
gnd_n_x = cx - perp_x * gnd_via_perp_mm + dx * via_via_dist_mm * gnd_dir
gnd_n_y = cy - perp_y * gnd_via_perp_mm + dy * via_via_dist_mm * gnd_dir
# Create GND vias (free=True prevents KiCad auto-assigning net)
gnd_vias.append(Via(
x=gnd_p_x, y=gnd_p_y,
size=config.via_size,
drill=config.via_drill,
layers=["F.Cu", "B.Cu"], # Always through-hole
net_id=gnd_net_id,
free=True
))
gnd_vias.append(Via(
x=gnd_n_x, y=gnd_n_y,
size=config.via_size,
drill=config.via_drill,
layers=["F.Cu", "B.Cu"], # Always through-hole
net_id=gnd_net_id,
free=True
))
return gnd_vias
def _make_route_data(pose_path, p_src_x, p_src_y, n_src_x, n_src_y,
p_tgt_x, p_tgt_y, n_tgt_x, n_tgt_y,
src_dir_x, src_dir_y, tgt_dir_x, tgt_dir_y,
src_actual_dir, tgt_actual_dir,
center_src_x, center_src_y, center_tgt_x, center_tgt_y,
via_spacing, src_angle, tgt_angle, gnd_via_dirs=None):
"""Build route_data dictionary with all routing result info."""
return {
'pose_path': pose_path,
'p_src_x': p_src_x, 'p_src_y': p_src_y,
'n_src_x': n_src_x, 'n_src_y': n_src_y,
'p_tgt_x': p_tgt_x, 'p_tgt_y': p_tgt_y,
'n_tgt_x': n_tgt_x, 'n_tgt_y': n_tgt_y,
'src_dir_x': src_dir_x, 'src_dir_y': src_dir_y,
'tgt_dir_x': tgt_dir_x, 'tgt_dir_y': tgt_dir_y,
'src_actual_dir_x': src_actual_dir[0], 'src_actual_dir_y': src_actual_dir[1],
'tgt_actual_dir_x': tgt_actual_dir[0], 'tgt_actual_dir_y': tgt_actual_dir[1],
'center_src_x': center_src_x, 'center_src_y': center_src_y,
'center_tgt_x': center_tgt_x, 'center_tgt_y': center_tgt_y,
'via_spacing': via_spacing,
'best_src_angle': src_angle, 'best_tgt_angle': tgt_angle,
'gnd_via_dirs': gnd_via_dirs if gnd_via_dirs is not None else [],
}
def _generate_debug_arrows(center_src_x, center_src_y, src_dir_x, src_dir_y,
center_tgt_x, center_tgt_y, tgt_dir_x, tgt_dir_y):
"""Generate stub direction arrows for debug visualization (User.4 layer).
Returns list of ((start_x, start_y), (end_x, end_y)) line segments.
"""
arrows = []
arrow_length = 1.0 # mm
head_length = 0.2 # mm
head_angle = 0.5 # radians (~30 degrees)
for mid_x, mid_y, dir_x, dir_y in [
(center_src_x, center_src_y, src_dir_x, src_dir_y),
(center_tgt_x, center_tgt_y, tgt_dir_x, tgt_dir_y)
]:
# Arrow shaft
tip_x = mid_x + dir_x * arrow_length
tip_y = mid_y + dir_y * arrow_length
arrows.append(((mid_x, mid_y), (tip_x, tip_y)))