@multiplatform.one/node-graph 9.0.0 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -129,47 +129,17 @@ export function samplePath(d: string): Point[] {
129
129
  points.push(at);
130
130
  command = "L";
131
131
  } else if (command === "L") {
132
- const to = { x: take(), y: take() };
133
- const steps = Math.max(1, Math.ceil(Math.hypot(to.x - at.x, to.y - at.y) / 4));
134
- for (let step = 1; step <= steps; step += 1) {
135
- const t = step / steps;
136
- points.push({ x: at.x + (to.x - at.x) * t, y: at.y + (to.y - at.y) * t });
137
- }
138
- at = to;
132
+ at = sampleLine(points, at, { x: take(), y: take() });
139
133
  } else if (command === "Q") {
140
- const control = { x: take(), y: take() };
141
- const to = { x: take(), y: take() };
142
- for (let step = 1; step <= 8; step += 1) {
143
- const t = step / 8;
144
- const u = 1 - t;
145
- points.push({
146
- x: u * u * at.x + 2 * u * t * control.x + t * t * to.x,
147
- y: u * u * at.y + 2 * u * t * control.y + t * t * to.y,
148
- });
149
- }
150
- at = to;
134
+ at = sampleQuadratic(points, at, { x: take(), y: take() }, { x: take(), y: take() });
151
135
  } else if (command === "C") {
152
- const first = { x: take(), y: take() };
153
- const second = { x: take(), y: take() };
154
- const to = { x: take(), y: take() };
155
- const steps = Math.max(16, Math.ceil(Math.hypot(to.x - at.x, to.y - at.y) / 4));
156
- for (let step = 1; step <= steps; step += 1) {
157
- const t = step / steps;
158
- const u = 1 - t;
159
- points.push({
160
- x:
161
- u * u * u * at.x +
162
- 3 * u * u * t * first.x +
163
- 3 * u * t * t * second.x +
164
- t * t * t * to.x,
165
- y:
166
- u * u * u * at.y +
167
- 3 * u * u * t * first.y +
168
- 3 * u * t * t * second.y +
169
- t * t * t * to.y,
170
- });
171
- }
172
- at = to;
136
+ at = sampleCubic(
137
+ points,
138
+ at,
139
+ { x: take(), y: take() },
140
+ { x: take(), y: take() },
141
+ { x: take(), y: take() },
142
+ );
173
143
  } else {
174
144
  return points;
175
145
  }
@@ -177,6 +147,40 @@ export function samplePath(d: string): Point[] {
177
147
  return points;
178
148
  }
179
149
 
150
+ function sampleLine(points: Point[], at: Point, to: Point): Point {
151
+ const steps = Math.max(1, Math.ceil(Math.hypot(to.x - at.x, to.y - at.y) / 4));
152
+ for (let step = 1; step <= steps; step += 1) {
153
+ const t = step / steps;
154
+ points.push({ x: at.x + (to.x - at.x) * t, y: at.y + (to.y - at.y) * t });
155
+ }
156
+ return to;
157
+ }
158
+
159
+ function sampleQuadratic(points: Point[], at: Point, control: Point, to: Point): Point {
160
+ for (let step = 1; step <= 8; step += 1) {
161
+ const t = step / 8;
162
+ const u = 1 - t;
163
+ points.push({
164
+ x: u * u * at.x + 2 * u * t * control.x + t * t * to.x,
165
+ y: u * u * at.y + 2 * u * t * control.y + t * t * to.y,
166
+ });
167
+ }
168
+ return to;
169
+ }
170
+
171
+ function sampleCubic(points: Point[], at: Point, first: Point, second: Point, to: Point): Point {
172
+ const steps = Math.max(16, Math.ceil(Math.hypot(to.x - at.x, to.y - at.y) / 4));
173
+ for (let step = 1; step <= steps; step += 1) {
174
+ const t = step / steps;
175
+ const u = 1 - t;
176
+ points.push({
177
+ x: u * u * u * at.x + 3 * u * u * t * first.x + 3 * u * t * t * second.x + t * t * t * to.x,
178
+ y: u * u * u * at.y + 3 * u * u * t * first.y + 3 * u * t * t * second.y + t * t * t * to.y,
179
+ });
180
+ }
181
+ return to;
182
+ }
183
+
180
184
  function distanceToBox(point: Point, box: Rect): number {
181
185
  const dx = Math.max(box.x - point.x, 0, point.x - (box.x + box.width));
182
186
  const dy = Math.max(box.y - point.y, 0, point.y - (box.y + box.height));
@@ -360,6 +364,64 @@ function orthogonalRoute(
360
364
  clearance: number,
361
365
  area: Rect,
362
366
  ): Point[] | null {
367
+ const grid = routeGrid(start, goal, boxes, clearance, area);
368
+ const startX = gridIndex(grid.xs, start.x);
369
+ const startY = gridIndex(grid.ys, start.y);
370
+ const goalX = gridIndex(grid.xs, goal.x);
371
+ const goalY = gridIndex(grid.ys, goal.y);
372
+ if (startX < 0 || startY < 0 || goalX < 0 || goalY < 0) return null;
373
+ if (!gridFree(grid, startX, startY) || !gridFree(grid, goalX, goalY)) return null;
374
+
375
+ const search: RouteSearch = {
376
+ grid,
377
+ goal,
378
+ goalX,
379
+ goalY,
380
+ goalDirection,
381
+ turn: clearance * 4,
382
+ best: new Map<number, number>(),
383
+ from: new Map<number, number>(),
384
+ heap: new Heap(),
385
+ };
386
+ const first = gridKey(grid, startX, startY, startDirection);
387
+ const reached = searchRoute(search, first, startX, startY);
388
+ if (reached === undefined) return null;
389
+ return traceRoute(grid, search.from, reached);
390
+ }
391
+
392
+ interface RouteGrid {
393
+ readonly xs: readonly number[];
394
+ readonly ys: readonly number[];
395
+ readonly rects: readonly Inflated[];
396
+ }
397
+
398
+ interface RouteSearch {
399
+ readonly grid: RouteGrid;
400
+ readonly goal: Point;
401
+ readonly goalX: number;
402
+ readonly goalY: number;
403
+ readonly goalDirection: number;
404
+ readonly turn: number;
405
+ readonly best: Map<number, number>;
406
+ readonly from: Map<number, number>;
407
+ readonly heap: Heap;
408
+ }
409
+
410
+ interface GridNode {
411
+ readonly key: number;
412
+ readonly ix: number;
413
+ readonly iy: number;
414
+ readonly dir: number;
415
+ readonly cost: number;
416
+ }
417
+
418
+ function routeGrid(
419
+ start: Point,
420
+ goal: Point,
421
+ boxes: readonly EdgeObstacle[],
422
+ clearance: number,
423
+ area: Rect,
424
+ ): RouteGrid {
363
425
  const rects = boxes.map((box) => inflate(box, clearance));
364
426
  const xs = lines([
365
427
  start.x,
@@ -375,79 +437,107 @@ function orthogonalRoute(
375
437
  area.y + area.height,
376
438
  ...rects.flatMap((r) => [r.top, r.bottom]),
377
439
  ]);
378
- const columns = xs.length;
379
- const rows = ys.length;
380
- const startX = xs.indexOf(Math.round(start.x * 1000) / 1000);
381
- const startY = ys.indexOf(Math.round(start.y * 1000) / 1000);
382
- const goalX = xs.indexOf(Math.round(goal.x * 1000) / 1000);
383
- const goalY = ys.indexOf(Math.round(goal.y * 1000) / 1000);
384
- if (startX < 0 || startY < 0 || goalX < 0 || goalY < 0) return null;
440
+ return { xs, ys, rects };
441
+ }
385
442
 
386
- const free = (ix: number, iy: number): boolean =>
387
- rects.every((rect) => !strictlyInside(xs[ix], ys[iy], rect));
388
- const open = (ax: number, ay: number, bx: number, by: number): boolean => {
389
- const minX = Math.min(xs[ax], xs[bx]);
390
- const maxX = Math.max(xs[ax], xs[bx]);
391
- const minY = Math.min(ys[ay], ys[by]);
392
- const maxY = Math.max(ys[ay], ys[by]);
393
- return rects.every((rect) => {
394
- if (minY === maxY)
395
- return !(minY > rect.top && minY < rect.bottom && maxX > rect.left && minX < rect.right);
396
- return !(minX > rect.left && minX < rect.right && maxY > rect.top && minY < rect.bottom);
397
- });
398
- };
399
- if (!free(startX, startY) || !free(goalX, goalY)) return null;
400
-
401
- const turn = clearance * 4;
402
- const key = (ix: number, iy: number, dir: number) => (iy * columns + ix) * 4 + dir;
403
- const best = new Map<number, number>();
404
- const from = new Map<number, number>();
405
- const heap = new Heap();
406
- const heuristic = (ix: number, iy: number) =>
407
- Math.abs(xs[ix] - goal.x) + Math.abs(ys[iy] - goal.y);
408
- const first = key(startX, startY, startDirection);
443
+ function gridIndex(values: readonly number[], value: number): number {
444
+ return values.indexOf(Math.round(value * 1000) / 1000);
445
+ }
446
+
447
+ function gridFree(grid: RouteGrid, ix: number, iy: number): boolean {
448
+ return grid.rects.every((rect) => !strictlyInside(grid.xs[ix], grid.ys[iy], rect));
449
+ }
450
+
451
+ function gridOpen(grid: RouteGrid, ax: number, ay: number, bx: number, by: number): boolean {
452
+ const { xs, ys } = grid;
453
+ const minX = Math.min(xs[ax], xs[bx]);
454
+ const maxX = Math.max(xs[ax], xs[bx]);
455
+ const minY = Math.min(ys[ay], ys[by]);
456
+ const maxY = Math.max(ys[ay], ys[by]);
457
+ return grid.rects.every((rect) => {
458
+ if (minY === maxY)
459
+ return !(minY > rect.top && minY < rect.bottom && maxX > rect.left && minX < rect.right);
460
+ return !(minX > rect.left && minX < rect.right && maxY > rect.top && minY < rect.bottom);
461
+ });
462
+ }
463
+
464
+ function canStep(grid: RouteGrid, ix: number, iy: number, nx: number, ny: number): boolean {
465
+ if (nx < 0 || ny < 0 || nx >= grid.xs.length || ny >= grid.ys.length) return false;
466
+ return gridFree(grid, nx, ny) && gridOpen(grid, ix, iy, nx, ny);
467
+ }
468
+
469
+ function gridKey(grid: RouteGrid, ix: number, iy: number, dir: number): number {
470
+ return (iy * grid.xs.length + ix) * 4 + dir;
471
+ }
472
+
473
+ function gridCell(grid: RouteGrid, key: number): { ix: number; iy: number; dir: number } {
474
+ const columns = grid.xs.length;
475
+ const dir = key % 4;
476
+ const cell = (key - dir) / 4;
477
+ const ix = cell % columns;
478
+ return { ix, iy: (cell - ix) / columns, dir };
479
+ }
480
+
481
+ function routeHeuristic(search: RouteSearch, ix: number, iy: number): number {
482
+ return (
483
+ Math.abs(search.grid.xs[ix] - search.goal.x) + Math.abs(search.grid.ys[iy] - search.goal.y)
484
+ );
485
+ }
486
+
487
+ function bendCost(search: RouteSearch, dir: number, next: number, nx: number, ny: number): number {
488
+ const atGoal = nx === search.goalX && ny === search.goalY;
489
+ return (
490
+ (next === dir ? 0 : search.turn) + (atGoal && next !== search.goalDirection ? search.turn : 0)
491
+ );
492
+ }
493
+
494
+ function searchRoute(
495
+ search: RouteSearch,
496
+ first: number,
497
+ startX: number,
498
+ startY: number,
499
+ ): number | undefined {
500
+ const { best, heap } = search;
409
501
  best.set(first, 0);
410
- heap.push(first, heuristic(startX, startY));
411
- let reached: number | undefined;
502
+ heap.push(first, routeHeuristic(search, startX, startY));
412
503
  let budget = 200_000;
413
504
  while (heap.size > 0 && budget > 0) {
414
505
  budget -= 1;
415
506
  const current = heap.pop();
416
507
  if (!current) break;
417
- const dir = current.key % 4;
418
- const cell = (current.key - dir) / 4;
419
- const ix = cell % columns;
420
- const iy = (cell - ix) / columns;
508
+ const { ix, iy, dir } = gridCell(search.grid, current.key);
421
509
  const cost = best.get(current.key) ?? Infinity;
422
- if (current.cost - heuristic(ix, iy) > cost + 1e-6) continue;
423
- if (ix === goalX && iy === goalY) {
424
- reached = current.key;
425
- break;
426
- }
427
- for (let next = 0; next < 4; next += 1) {
428
- if (next === (dir + 2) % 4) continue;
429
- const nx = ix + stepX[next];
430
- const ny = iy + stepY[next];
431
- if (nx < 0 || ny < 0 || nx >= columns || ny >= rows) continue;
432
- if (!free(nx, ny) || !open(ix, iy, nx, ny)) continue;
433
- const atGoal = nx === goalX && ny === goalY;
434
- const length = Math.abs(xs[nx] - xs[ix]) + Math.abs(ys[ny] - ys[iy]);
435
- const bend = (next === dir ? 0 : turn) + (atGoal && next !== goalDirection ? turn : 0);
436
- const nextKey = key(nx, ny, next);
437
- const nextCost = cost + length + bend;
438
- if (nextCost < (best.get(nextKey) ?? Infinity)) {
439
- best.set(nextKey, nextCost);
440
- from.set(nextKey, current.key);
441
- heap.push(nextKey, nextCost + heuristic(nx, ny));
442
- }
510
+ if (current.cost - routeHeuristic(search, ix, iy) > cost + 1e-6) continue;
511
+ if (ix === search.goalX && iy === search.goalY) return current.key;
512
+ relaxNeighbours(search, { key: current.key, ix, iy, dir, cost });
513
+ }
514
+ return undefined;
515
+ }
516
+
517
+ function relaxNeighbours(search: RouteSearch, node: GridNode): void {
518
+ const { grid, best, from, heap } = search;
519
+ for (let next = 0; next < 4; next += 1) {
520
+ if (next === (node.dir + 2) % 4) continue;
521
+ const nx = node.ix + stepX[next];
522
+ const ny = node.iy + stepY[next];
523
+ if (!canStep(grid, node.ix, node.iy, nx, ny)) continue;
524
+ const length =
525
+ Math.abs(grid.xs[nx] - grid.xs[node.ix]) + Math.abs(grid.ys[ny] - grid.ys[node.iy]);
526
+ const nextKey = gridKey(grid, nx, ny, next);
527
+ const nextCost = node.cost + length + bendCost(search, node.dir, next, nx, ny);
528
+ if (nextCost < (best.get(nextKey) ?? Infinity)) {
529
+ best.set(nextKey, nextCost);
530
+ from.set(nextKey, node.key);
531
+ heap.push(nextKey, nextCost + routeHeuristic(search, nx, ny));
443
532
  }
444
533
  }
445
- if (reached === undefined) return null;
534
+ }
535
+
536
+ function traceRoute(grid: RouteGrid, from: Map<number, number>, reached: number): Point[] {
446
537
  const route: Point[] = [];
447
538
  for (let at: number | undefined = reached; at !== undefined; at = from.get(at)) {
448
- const cell = (at - (at % 4)) / 4;
449
- const ix = cell % columns;
450
- route.push({ x: xs[ix], y: ys[(cell - ix) / columns] });
539
+ const { ix, iy } = gridCell(grid, at);
540
+ route.push({ x: grid.xs[ix], y: grid.ys[iy] });
451
541
  }
452
542
  return route.reverse();
453
543
  }
@@ -747,23 +837,42 @@ function linkKey(link: EdgeLink): string {
747
837
  return `${link.source}\u0000${link.target}`;
748
838
  }
749
839
 
750
- /**
751
- * Every link that shares a gap with another, or skips a rank, with its course.
752
- * A link that crosses its gap alone gets none and keeps the ordinary route.
753
- *
754
- * Like a layered layout's dummy nodes, a link that skips ranks gets a virtual
755
- * point in each rank it crosses, in the open channel between that rank's
756
- * boxes, so it never runs through a node; each piece then crosses one gap
757
- * like any other edge. In each gap, groups whose spans overlap are one
758
- * conflict set; interval colouring gives the fewest tracks, evenly spaced.
759
- */
760
- function planTracks(
761
- links: readonly EdgeLink[],
762
- boxes: readonly EdgeObstacle[],
763
- side: EdgeSide,
764
- clearance: number,
765
- sharing: TrackSharing,
766
- ): Map<string, Course> {
840
+ interface Passing {
841
+ readonly link: string;
842
+ readonly rank: number;
843
+ readonly slot: number;
844
+ readonly u: number;
845
+ readonly channel: number;
846
+ }
847
+
848
+ interface Piece {
849
+ readonly gap: number;
850
+ readonly key: string;
851
+ }
852
+
853
+ interface Layers {
854
+ readonly spans: Map<string, Span>;
855
+ readonly ranks: Rank[];
856
+ readonly rankOf: Map<Span, number>;
857
+ readonly open: [number, number][][];
858
+ }
859
+
860
+ interface LinkEnds {
861
+ readonly source: Span;
862
+ readonly target: Span;
863
+ readonly rs: number;
864
+ readonly rt: number;
865
+ }
866
+
867
+ interface TrackPlan {
868
+ readonly gaps: Map<number, Map<string, Group>>;
869
+ readonly pieces: Map<string, Piece[]>;
870
+ readonly passing: Passing[];
871
+ readonly virtual: Map<string, number[]>;
872
+ readonly channelOf: Map<string, [number, number][]>;
873
+ }
874
+
875
+ function layersOf(boxes: readonly EdgeObstacle[], side: EdgeSide, clearance: number): Layers {
767
876
  const frame = frames[side];
768
877
  const spans = new Map(boxes.map((box) => [box.id, localSpan(box, frame)]));
769
878
  const ranks = ranksOf([...spans.values()]);
@@ -771,129 +880,247 @@ function planTracks(
771
880
  ranks.forEach((rank, index) => {
772
881
  for (const span of rank.spans) rankOf.set(span, index);
773
882
  });
774
- const open = ranks.map((rank) => channels(rank, clearance));
775
- const gaps = new Map<number, Map<string, Group>>();
776
- const pieces = new Map<string, { gap: number; key: string }[]>();
777
- const passing: { link: string; rank: number; slot: number; u: number; channel: number }[] = [];
778
- const virtual = new Map<string, number[]>();
779
- const channelOf = new Map<string, [number, number][]>();
883
+ return { spans, ranks, rankOf, open: ranks.map((rank) => channels(rank, clearance)) };
884
+ }
885
+
886
+ function forwardEnds(link: EdgeLink, layers: Layers): LinkEnds | undefined {
887
+ const source = layers.spans.get(link.source);
888
+ const target = layers.spans.get(link.target);
889
+ if (!source || !target) return undefined;
890
+ const rs = layers.rankOf.get(source)!;
891
+ const rt = layers.rankOf.get(target)!;
892
+ if (rt <= rs) return undefined;
893
+ return { source, target, rs, rt };
894
+ }
895
+
896
+ function virtualCourse(
897
+ id: string,
898
+ { source, target, rs, rt }: LinkEnds,
899
+ open: readonly [number, number][][],
900
+ ): { us: number[]; passes: Passing[] } {
901
+ const sourceU = (source.u0 + source.u1) / 2;
902
+ const targetU = (target.u0 + target.u1) / 2;
903
+ const us = [sourceU];
904
+ const passes: Passing[] = [];
905
+ for (let rank = rs + 1; rank < rt; rank += 1) {
906
+ const ideal = sourceU + ((targetU - sourceU) * (rank - rs)) / (rt - rs);
907
+ const at = virtualPoint(open[rank], ideal, targetU);
908
+ us.push(at.u);
909
+ passes.push({ link: id, rank, slot: us.length - 1, ...at });
910
+ }
911
+ us.push(targetU);
912
+ return { us, passes };
913
+ }
914
+
915
+ function groupsAt(gaps: Map<number, Map<string, Group>>, gap: number): Map<string, Group> {
916
+ let groups = gaps.get(gap);
917
+ if (!groups) {
918
+ groups = new Map();
919
+ gaps.set(gap, groups);
920
+ }
921
+ return groups;
922
+ }
923
+
924
+ function widenGroup(
925
+ groups: Map<string, Group>,
926
+ key: string,
927
+ lone: boolean,
928
+ a: number,
929
+ b: number,
930
+ ): void {
931
+ const group = groups.get(key);
932
+ if (group) {
933
+ group.u0 = Math.min(group.u0, a, b);
934
+ group.u1 = Math.max(group.u1, a, b);
935
+ } else groups.set(key, { key, lone, u0: Math.min(a, b), u1: Math.max(a, b) });
936
+ }
937
+
938
+ function placePieces(
939
+ gaps: Map<number, Map<string, Group>>,
940
+ link: EdgeLink,
941
+ id: string,
942
+ us: readonly number[],
943
+ { rs, rt }: LinkEnds,
944
+ sharing: TrackSharing,
945
+ ): Piece[] {
946
+ const own: Piece[] = [];
947
+ for (let gap = rs; gap < rt; gap += 1) {
948
+ const last = gap === rt - 1;
949
+ const key = last ? trackKey(sharing, link) : `${id}\u0000${gap}`;
950
+ own.push({ gap, key });
951
+ widenGroup(groupsAt(gaps, gap), key, rt - rs === 1, us[gap - rs], us[gap - rs + 1]);
952
+ }
953
+ return own;
954
+ }
955
+
956
+ function collectPieces(
957
+ links: readonly EdgeLink[],
958
+ layers: Layers,
959
+ sharing: TrackSharing,
960
+ ): TrackPlan {
961
+ const plan: TrackPlan = {
962
+ gaps: new Map(),
963
+ pieces: new Map(),
964
+ passing: [],
965
+ virtual: new Map(),
966
+ channelOf: new Map(),
967
+ };
780
968
  for (const link of links) {
781
- const source = spans.get(link.source);
782
- const target = spans.get(link.target);
783
- if (!source || !target) continue;
784
- const rs = rankOf.get(source)!;
785
- const rt = rankOf.get(target)!;
786
- if (rt <= rs) continue;
969
+ const ends = forwardEnds(link, layers);
970
+ if (!ends) continue;
787
971
  const id = linkKey(link);
788
- if (pieces.has(id)) continue;
789
- const sourceU = (source.u0 + source.u1) / 2;
790
- const targetU = (target.u0 + target.u1) / 2;
791
- const us = [sourceU];
792
- for (let rank = rs + 1; rank < rt; rank += 1) {
793
- const ideal = sourceU + ((targetU - sourceU) * (rank - rs)) / (rt - rs);
794
- const at = virtualPoint(open[rank], ideal, targetU);
795
- us.push(at.u);
796
- passing.push({ link: id, rank, slot: us.length - 1, ...at });
797
- }
798
- us.push(targetU);
799
- virtual.set(id, us);
800
- channelOf.set(
972
+ if (plan.pieces.has(id)) continue;
973
+ const { us, passes } = virtualCourse(id, ends, layers.open);
974
+ plan.passing.push(...passes);
975
+ plan.virtual.set(id, us);
976
+ plan.channelOf.set(
801
977
  id,
802
- passing.filter((pass) => pass.link === id).map((pass) => open[pass.rank][pass.channel]),
978
+ passes.map((pass) => layers.open[pass.rank][pass.channel]),
803
979
  );
804
- const own: { gap: number; key: string }[] = [];
805
- for (let gap = rs; gap < rt; gap += 1) {
806
- const last = gap === rt - 1;
807
- const key = last ? trackKey(sharing, link) : `${id}\u0000${gap}`;
808
- own.push({ gap, key });
809
- let groups = gaps.get(gap);
810
- if (!groups) {
811
- groups = new Map();
812
- gaps.set(gap, groups);
813
- }
814
- const a = us[gap - rs];
815
- const b = us[gap - rs + 1];
816
- const group = groups.get(key);
817
- if (group) {
818
- group.u0 = Math.min(group.u0, a, b);
819
- group.u1 = Math.max(group.u1, a, b);
820
- } else groups.set(key, { key, lone: rt - rs === 1, u0: Math.min(a, b), u1: Math.max(a, b) });
821
- }
822
- pieces.set(id, own);
980
+ plan.pieces.set(id, placePieces(plan.gaps, link, id, us, ends, sharing));
823
981
  }
982
+ return plan;
983
+ }
984
+
985
+ function spreadChannel(
986
+ group: readonly Passing[],
987
+ open: readonly [number, number][][],
988
+ virtual: Map<string, number[]>,
989
+ clearance: number,
990
+ ): void {
991
+ if (group.length < 2) return;
992
+ const [lo, hi] = open[group[0].rank][group[0].channel];
993
+ const sorted = [...group].sort((a, b) => a.u - b.u || a.link.localeCompare(b.link));
994
+ const crowded = sorted.some(
995
+ (pass, index) => index > 0 && pass.u - sorted[index - 1].u < clearance,
996
+ );
997
+ if (!crowded) return;
998
+ const width =
999
+ Number.isFinite(lo) && Number.isFinite(hi) ? hi - lo : clearance * (group.length + 1);
1000
+ const base = Number.isFinite(lo) ? lo : Number.isFinite(hi) ? hi - width : sorted[0].u;
1001
+ const pitch = width / (group.length + 1);
1002
+ sorted.forEach((pass, index) => {
1003
+ virtual.get(pass.link)![pass.slot] = base + pitch * (index + 1);
1004
+ });
1005
+ }
1006
+
1007
+ function spreadChannels(
1008
+ passing: readonly Passing[],
1009
+ open: readonly [number, number][][],
1010
+ virtual: Map<string, number[]>,
1011
+ clearance: number,
1012
+ ): void {
824
1013
  // Links through one channel of one rank take evenly spaced lanes in it.
825
- const byChannel = new Map<string, typeof passing>();
1014
+ const byChannel = new Map<string, Passing[]>();
826
1015
  for (const pass of passing) {
827
1016
  const key = `${pass.rank}:${pass.channel}`;
828
1017
  byChannel.set(key, [...(byChannel.get(key) ?? []), pass]);
829
1018
  }
830
- for (const group of byChannel.values()) {
831
- if (group.length < 2) continue;
832
- const [lo, hi] = open[group[0].rank][group[0].channel];
833
- const sorted = [...group].sort((a, b) => a.u - b.u || a.link.localeCompare(b.link));
834
- const crowded = sorted.some(
835
- (pass, index) => index > 0 && pass.u - sorted[index - 1].u < clearance,
836
- );
837
- if (!crowded) continue;
838
- const width =
839
- Number.isFinite(lo) && Number.isFinite(hi) ? hi - lo : clearance * (group.length + 1);
840
- const base = Number.isFinite(lo) ? lo : Number.isFinite(hi) ? hi - width : sorted[0].u;
841
- const pitch = width / (group.length + 1);
842
- sorted.forEach((pass, index) => {
843
- virtual.get(pass.link)![pass.slot] = base + pitch * (index + 1);
844
- });
1019
+ for (const group of byChannel.values()) spreadChannel(group, open, virtual, clearance);
1020
+ }
1021
+
1022
+ function conflictSets(list: readonly Group[], clearance: number): Group[][] {
1023
+ const parent = list.map((_, index) => index);
1024
+ const root = (index: number): number => {
1025
+ let at = index;
1026
+ while (parent[at] !== at) at = parent[at];
1027
+ return at;
1028
+ };
1029
+ for (let a = 0; a < list.length; a += 1)
1030
+ for (let b = a + 1; b < list.length; b += 1)
1031
+ if (list[a].u0 <= list[b].u1 + clearance && list[b].u0 <= list[a].u1 + clearance)
1032
+ parent[root(b)] = root(a);
1033
+ const sets = new Map<number, Group[]>();
1034
+ for (let index = 0; index < list.length; index += 1) {
1035
+ const at = root(index);
1036
+ sets.set(at, [...(sets.get(at) ?? []), list[index]]);
845
1037
  }
846
- const levels = new Map<string, number>();
847
- for (const [gap, groups] of gaps) {
848
- const lo = ranks[gap].v1 + clearance;
849
- const hi = ranks[gap + 1].v0 - clearance;
850
- if (lo >= hi) continue;
851
- const list = [...groups.values()];
852
- const parent = list.map((_, index) => index);
853
- const root = (index: number): number => {
854
- let at = index;
855
- while (parent[at] !== at) at = parent[at];
856
- return at;
857
- };
858
- for (let a = 0; a < list.length; a += 1)
859
- for (let b = a + 1; b < list.length; b += 1)
860
- if (list[a].u0 <= list[b].u1 + clearance && list[b].u0 <= list[a].u1 + clearance)
861
- parent[root(b)] = root(a);
862
- const sets = new Map<number, Group[]>();
863
- for (let index = 0; index < list.length; index += 1) {
864
- const at = root(index);
865
- sets.set(at, [...(sets.get(at) ?? []), list[index]]);
866
- }
867
- for (const members of sets.values()) {
868
- const sorted = [...members].sort((a, b) => a.u0 - b.u0 || a.key.localeCompare(b.key));
869
- const ends: number[] = [];
870
- const lane = new Map<string, number>();
871
- for (const group of sorted) {
872
- let free = ends.findIndex((end) => end + clearance < group.u0);
873
- if (free < 0) {
874
- free = ends.length;
875
- ends.push(group.u1);
876
- } else ends[free] = group.u1;
877
- lane.set(group.key, free);
878
- }
879
- if (ends.length < 2 && members.every((group) => group.lone)) continue;
880
- const pitch = (hi - lo) / (ends.length + 1);
881
- for (const [key, index] of lane) levels.set(`${gap}\u0000${key}`, lo + pitch * (index + 1));
882
- }
1038
+ return [...sets.values()];
1039
+ }
1040
+
1041
+ function lanesOf(
1042
+ members: readonly Group[],
1043
+ clearance: number,
1044
+ ): { lane: Map<string, number>; count: number } {
1045
+ const sorted = [...members].sort((a, b) => a.u0 - b.u0 || a.key.localeCompare(b.key));
1046
+ const ends: number[] = [];
1047
+ const lane = new Map<string, number>();
1048
+ for (const group of sorted) {
1049
+ let free = ends.findIndex((end) => end + clearance < group.u0);
1050
+ if (free < 0) {
1051
+ free = ends.length;
1052
+ ends.push(group.u1);
1053
+ } else ends[free] = group.u1;
1054
+ lane.set(group.key, free);
1055
+ }
1056
+ return { lane, count: ends.length };
1057
+ }
1058
+
1059
+ function levelGap(
1060
+ gap: number,
1061
+ groups: Map<string, Group>,
1062
+ ranks: readonly Rank[],
1063
+ clearance: number,
1064
+ levels: Map<string, number>,
1065
+ ): void {
1066
+ const lo = ranks[gap].v1 + clearance;
1067
+ const hi = ranks[gap + 1].v0 - clearance;
1068
+ if (lo >= hi) return;
1069
+ for (const members of conflictSets([...groups.values()], clearance)) {
1070
+ const { lane, count } = lanesOf(members, clearance);
1071
+ if (count < 2 && members.every((group) => group.lone)) continue;
1072
+ const pitch = (hi - lo) / (count + 1);
1073
+ for (const [key, index] of lane) levels.set(`${gap}\u0000${key}`, lo + pitch * (index + 1));
883
1074
  }
1075
+ }
1076
+
1077
+ function levelsOf(
1078
+ gaps: Map<number, Map<string, Group>>,
1079
+ ranks: readonly Rank[],
1080
+ clearance: number,
1081
+ ): Map<string, number> {
1082
+ const levels = new Map<string, number>();
1083
+ for (const [gap, groups] of gaps) levelGap(gap, groups, ranks, clearance, levels);
1084
+ return levels;
1085
+ }
1086
+
1087
+ function coursesOf(plan: TrackPlan, levels: Map<string, number>): Map<string, Course> {
884
1088
  const courses = new Map<string, Course>();
885
- for (const [id, own] of pieces) {
1089
+ for (const [id, own] of plan.pieces) {
886
1090
  const vs = own.map(({ gap, key }) => levels.get(`${gap}\u0000${key}`));
887
1091
  if (vs.some((v) => v === undefined)) continue;
888
1092
  courses.set(id, {
889
1093
  vs: vs as number[],
890
- us: virtual.get(id)!.slice(1, -1),
891
- open: channelOf.get(id) ?? [],
1094
+ us: plan.virtual.get(id)!.slice(1, -1),
1095
+ open: plan.channelOf.get(id) ?? [],
892
1096
  });
893
1097
  }
894
1098
  return courses;
895
1099
  }
896
1100
 
1101
+ /**
1102
+ * Every link that shares a gap with another, or skips a rank, with its course.
1103
+ * A link that crosses its gap alone gets none and keeps the ordinary route.
1104
+ *
1105
+ * Like a layered layout's dummy nodes, a link that skips ranks gets a virtual
1106
+ * point in each rank it crosses, in the open channel between that rank's
1107
+ * boxes, so it never runs through a node; each piece then crosses one gap
1108
+ * like any other edge. In each gap, groups whose spans overlap are one
1109
+ * conflict set; interval colouring gives the fewest tracks, evenly spaced.
1110
+ */
1111
+ function planTracks(
1112
+ links: readonly EdgeLink[],
1113
+ boxes: readonly EdgeObstacle[],
1114
+ side: EdgeSide,
1115
+ clearance: number,
1116
+ sharing: TrackSharing,
1117
+ ): Map<string, Course> {
1118
+ const layers = layersOf(boxes, side, clearance);
1119
+ const plan = collectPieces(links, layers, sharing);
1120
+ spreadChannels(plan.passing, layers.open, plan.virtual, clearance);
1121
+ return coursesOf(plan, levelsOf(plan.gaps, layers.ranks, clearance));
1122
+ }
1123
+
897
1124
  const plans = new WeakMap<
898
1125
  readonly EdgeLink[],
899
1126
  WeakMap<readonly EdgeObstacle[], Map<string, Map<string, Course>>>