orthogonal-router 0.1.0 → 0.2.0

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.
package/README.md CHANGED
@@ -74,3 +74,16 @@ In the diagram:
74
74
  | `spacing` | 6 | Distance between parallel segments on one track |
75
75
  | `maxExpansions` | 200000 | Search limit for one connector |
76
76
  | `windowMargin` | 400 | How far a route may first stray from the box around its ends; the whole diagram is searched only when that area has no route |
77
+ | `spread` | true | Spread apart the segments that share a track; set false when you route in parts |
78
+ | `routeOnly` | all | Route only the connectors with these ids; the others still shape the grid |
79
+
80
+ ## Routing in parts
81
+
82
+ Each connector is routed on its own, so a large diagram can be routed in several workers. Give each worker all the connectors, with `spread: false` and its part in `routeOnly`. Then join the parts and call `spreadRoutes(shapes, connectors, routes, options)` once. The result is the same as one `routeConnectors` call.
83
+
84
+ ## Releasing
85
+
86
+ 1. Set the new version in `package.json` with `npm version <version> --no-git-tag-version`, and merge it to `main`.
87
+ 2. Publish a GitHub release with the tag `v<version>`, for example `v0.2.0`.
88
+
89
+ The `Publish` workflow then checks that the tag matches the version, runs the tests and the build, and publishes the package to npm with provenance. It uses npm trusted publishing, so it needs no npm token. The package's trusted publisher on npmjs.com must name this repository and the workflow file `publish.yml`.
package/dist/grid.d.ts CHANGED
@@ -13,7 +13,21 @@ export declare class Grid {
13
13
  private readonly yIndex;
14
14
  private readonly obstacles;
15
15
  private readonly clusterIndex;
16
+ /** Per node and direction: 0 not known yet, else 1 + the clusters a step enters, or -1 when the step is blocked. */
17
+ private readonly steps;
18
+ /** Search state that every search on this grid reuses, so that a search does not allocate the whole grid. */
19
+ readonly scratch: {
20
+ stamp: number;
21
+ stamps: Uint32Array;
22
+ best: Float64Array;
23
+ parent: Int32Array;
24
+ };
16
25
  constructor(obstacles: Box[], clusters: Box[], buffer: number, ports: Point[]);
26
+ /**
27
+ * The clusters that the step from a node in a direction enters, or -1 when an obstacle blocks the step or the
28
+ * grid ends there. A step between neighbouring lines is free when its midpoint is outside every obstacle.
29
+ */
30
+ stepCost(node: number, direction: number): number;
17
31
  /** The grid node of a point that lies on two grid lines. */
18
32
  node(point: Point): number | undefined;
19
33
  point(node: number): Point;
package/dist/grid.js CHANGED
@@ -2,6 +2,8 @@ const PRECISION = 1000;
2
2
  export const round = (value) => Math.round(value * PRECISION) / PRECISION;
3
3
  /** Strictly inside: a point on the border is outside, so a route may run along it. */
4
4
  const inside = (box, x, y) => x > box.x && x < box.x + box.width && y > box.y && y < box.y + box.height;
5
+ /** A numeric key for a bucket: fast to hash, and exact for any bucket index a diagram can have. */
6
+ const bucketKey = (cx, cy) => cx * 4_194_304 + cy;
5
7
  /** A bucket index of boxes, for the many point tests of a search. */
6
8
  class BoxIndex {
7
9
  boxes;
@@ -14,7 +16,7 @@ class BoxIndex {
14
16
  boxes.forEach((box, i) => {
15
17
  for (let cx = Math.floor(box.x / this.cell); cx <= Math.floor((box.x + box.width) / this.cell); cx++) {
16
18
  for (let cy = Math.floor(box.y / this.cell); cy <= Math.floor((box.y + box.height) / this.cell); cy++) {
17
- const key = `${cx},${cy}`;
19
+ const key = bucketKey(cx, cy);
18
20
  const bucket = this.buckets.get(key);
19
21
  if (bucket)
20
22
  bucket.push(i);
@@ -25,12 +27,17 @@ class BoxIndex {
25
27
  });
26
28
  }
27
29
  some(x, y) {
28
- const bucket = this.buckets.get(`${Math.floor(x / this.cell)},${Math.floor(y / this.cell)}`);
29
- return !!bucket && bucket.some((i) => inside(this.boxes[i], x, y));
30
+ const bucket = this.buckets.get(bucketKey(Math.floor(x / this.cell), Math.floor(y / this.cell)));
31
+ if (!bucket)
32
+ return false;
33
+ for (const i of bucket)
34
+ if (inside(this.boxes[i], x, y))
35
+ return true;
36
+ return false;
30
37
  }
31
38
  /** The indexes of the boxes around the point. */
32
39
  around(x, y) {
33
- const bucket = this.buckets.get(`${Math.floor(x / this.cell)},${Math.floor(y / this.cell)}`);
40
+ const bucket = this.buckets.get(bucketKey(Math.floor(x / this.cell), Math.floor(y / this.cell)));
34
41
  return bucket ? bucket.filter((i) => inside(this.boxes[i], x, y)) : [];
35
42
  }
36
43
  }
@@ -47,6 +54,10 @@ export class Grid {
47
54
  yIndex;
48
55
  obstacles;
49
56
  clusterIndex;
57
+ /** Per node and direction: 0 not known yet, else 1 + the clusters a step enters, or -1 when the step is blocked. */
58
+ steps;
59
+ /** Search state that every search on this grid reuses, so that a search does not allocate the whole grid. */
60
+ scratch;
50
61
  constructor(obstacles, clusters, buffer, ports) {
51
62
  this.clusters = clusters;
52
63
  const grown = obstacles.map((box) => ({
@@ -84,6 +95,32 @@ export class Grid {
84
95
  this.ys = [...ys].sort((a, b) => a - b);
85
96
  this.xIndex = new Map(this.xs.map((x, i) => [x, i]));
86
97
  this.yIndex = new Map(this.ys.map((y, i) => [y, i]));
98
+ const nodes = this.xs.length * this.ys.length;
99
+ this.steps = new Int16Array(nodes * 4);
100
+ this.scratch = { stamp: 0, stamps: new Uint32Array(nodes * 4), best: new Float64Array(nodes * 4), parent: new Int32Array(nodes * 4) };
101
+ }
102
+ /**
103
+ * The clusters that the step from a node in a direction enters, or -1 when an obstacle blocks the step or the
104
+ * grid ends there. A step between neighbouring lines is free when its midpoint is outside every obstacle.
105
+ */
106
+ stepCost(node, direction) {
107
+ const slot = node * 4 + direction;
108
+ const known = this.steps[slot];
109
+ if (known !== 0)
110
+ return known < 0 ? -1 : known - 1;
111
+ const next = this.step(node, direction);
112
+ let result = -1;
113
+ if (next !== undefined) {
114
+ const width = this.xs.length;
115
+ const ax = this.xs[node % width];
116
+ const ay = this.ys[Math.floor(node / width)];
117
+ const bx = this.xs[next % width];
118
+ const by = this.ys[Math.floor(next / width)];
119
+ if (!this.obstacles.some((ax + bx) / 2, (ay + by) / 2))
120
+ result = this.entries({ x: ax, y: ay }, { x: bx, y: by });
121
+ }
122
+ this.steps[slot] = result < 0 ? -1 : result + 1;
123
+ return result;
87
124
  }
88
125
  /** The grid node of a point that lies on two grid lines. */
89
126
  node(point) {
package/dist/heap.js CHANGED
@@ -30,9 +30,15 @@ export class MinHeap {
30
30
  return this.priorities[a] < this.priorities[b] || (this.priorities[a] === this.priorities[b] && this.orders[a] < this.orders[b]);
31
31
  }
32
32
  swap(a, b) {
33
- [this.values[a], this.values[b]] = [this.values[b], this.values[a]];
34
- [this.priorities[a], this.priorities[b]] = [this.priorities[b], this.priorities[a]];
35
- [this.orders[a], this.orders[b]] = [this.orders[b], this.orders[a]];
33
+ const value = this.values[a];
34
+ this.values[a] = this.values[b];
35
+ this.values[b] = value;
36
+ const priority = this.priorities[a];
37
+ this.priorities[a] = this.priorities[b];
38
+ this.priorities[b] = priority;
39
+ const order = this.orders[a];
40
+ this.orders[a] = this.orders[b];
41
+ this.orders[b] = order;
36
42
  }
37
43
  up(i) {
38
44
  while (i > 0) {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Connector, RouteResult, RouterOptions, Shape } from './types.js';
1
+ import type { Connector, Point, RouteResult, RouterOptions, Shape } from './types.js';
2
2
  export type { Box, Connector, ConnectorEnd, Point, RouteResult, RouterOptions, Shape, Side } from './types.js';
3
3
  /**
4
4
  * Routes each connector in right angles from a side of its source shape to a side of its target shape, around the
@@ -8,3 +8,8 @@ export type { Box, Connector, ConnectorEnd, Point, RouteResult, RouterOptions, S
8
8
  * Where the shapes are too close for the buffer, the connector is routed again with half the buffer, then with none.
9
9
  */
10
10
  export declare function routeConnectors(shapes: Shape[], connectors: Connector[], options?: RouterOptions): RouteResult;
11
+ /**
12
+ * Spreads apart the segments that share a track, `spacing` apart, as `routeConnectors` does. Use it to join routes
13
+ * that were routed in parts with `spread: false`, for example in several workers.
14
+ */
15
+ export declare function spreadRoutes(shapes: Shape[], connectors: Connector[], routes: Map<string, Point[]>, options?: RouterOptions): Map<string, Point[]>;
package/dist/index.js CHANGED
@@ -9,6 +9,8 @@ const DEFAULTS = {
9
9
  spacing: 6,
10
10
  maxExpansions: 200_000,
11
11
  windowMargin: 400,
12
+ spread: true,
13
+ routeOnly: [],
12
14
  };
13
15
  /**
14
16
  * Routes each connector in right angles from a side of its source shape to a side of its target shape, around the
@@ -24,7 +26,7 @@ export function routeConnectors(shapes, connectors, options = {}) {
24
26
  const clusters = shapes.filter((shape) => shape.kind === 'cluster');
25
27
  const costs = { bend: o.bendPenalty, cluster: o.clusterCrossingPenalty, maxExpansions: o.maxExpansions };
26
28
  const valid = connectors.filter((c) => byId.has(c.source.shape) && byId.has(c.target.shape) && c.source.shape !== c.target.shape);
27
- const failed = connectors.filter((c) => !valid.includes(c)).map((c) => c.id);
29
+ const failed = connectors.filter((c) => !valid.includes(c) && (!options.routeOnly || options.routeOnly.includes(c.id))).map((c) => c.id);
28
30
  const portsAt = (buffer, end) => portsOf(byId.get(end.shape), end.sides ?? ALL_SIDES, buffer);
29
31
  const grids = new Map();
30
32
  const gridFor = (buffer) => {
@@ -37,15 +39,21 @@ export function routeConnectors(shapes, connectors, options = {}) {
37
39
  return grid;
38
40
  };
39
41
  const buffers = [...new Set([o.buffer, o.buffer / 2, 0])];
42
+ const only = options.routeOnly ? new Set(options.routeOnly) : undefined;
40
43
  const routed = [];
41
- for (const connector of valid) {
44
+ for (const connector of only ? valid.filter((c) => only.has(c.id)) : valid) {
42
45
  let points;
43
46
  for (const buffer of buffers) {
44
- const sources = portsAt(buffer, connector.source);
45
- const targets = portsAt(buffer, connector.target);
47
+ const grid = gridFor(buffer);
48
+ const sources = portsAt(buffer, connector.source).filter((port) => !grid.blocked(port.out.x, port.out.y));
49
+ const targets = portsAt(buffer, connector.target).filter((port) => !grid.blocked(port.out.x, port.out.y));
50
+ // A port that the buffer of a shape beside it covers leads nowhere, and a search without ports would
51
+ // look through the whole grid before it gives up.
52
+ if (sources.length === 0 || targets.length === 0)
53
+ continue;
46
54
  // Near its ends first, which is where nearly every route lies, then anywhere.
47
- points = search(gridFor(buffer), sources, targets, costs, windowAround([...sources, ...targets], o.windowMargin))
48
- ?? search(gridFor(buffer), sources, targets, costs);
55
+ points = search(grid, sources, targets, costs, windowAround([...sources, ...targets], o.windowMargin))
56
+ ?? search(grid, sources, targets, costs);
49
57
  if (points)
50
58
  break;
51
59
  }
@@ -55,6 +63,18 @@ export function routeConnectors(shapes, connectors, options = {}) {
55
63
  }
56
64
  routed.push({ id: connector.id, points, ends: { source: byId.get(connector.source.shape), target: byId.get(connector.target.shape) } });
57
65
  }
58
- const nudged = nudge(routed.map((r) => r.points), routed.map((r) => r.ends), obstacles, o.spacing);
59
- return { routes: new Map(routed.map((r, i) => [r.id, nudged[i]])), failed };
66
+ const routes = new Map(routed.map((r) => [r.id, r.points]));
67
+ return { routes: o.spread ? spreadRoutes(shapes, connectors, routes, options) : routes, failed };
68
+ }
69
+ /**
70
+ * Spreads apart the segments that share a track, `spacing` apart, as `routeConnectors` does. Use it to join routes
71
+ * that were routed in parts with `spread: false`, for example in several workers.
72
+ */
73
+ export function spreadRoutes(shapes, connectors, routes, options = {}) {
74
+ const spacing = options.spacing ?? DEFAULTS.spacing;
75
+ const byId = new Map(shapes.map((shape) => [shape.id, shape]));
76
+ const obstacles = shapes.filter((shape) => (shape.kind ?? 'obstacle') === 'obstacle');
77
+ const routed = connectors.filter((c) => routes.has(c.id));
78
+ const nudged = nudge(routed.map((c) => routes.get(c.id)), routed.map((c) => ({ source: byId.get(c.source.shape), target: byId.get(c.target.shape) })), obstacles, spacing);
79
+ return new Map(routed.map((c, i) => [c.id, nudged[i]]));
60
80
  }
package/dist/search.d.ts CHANGED
@@ -26,7 +26,8 @@ export interface Window {
26
26
  export declare function windowAround(ports: Port[], margin: number): Window;
27
27
  /**
28
28
  * The cheapest route, by length plus a cost for each bend and cluster entry, from a source port to a target port. A*
29
- * over (grid node, direction) states: the heuristic is the Manhattan distance to the nearest target port.
29
+ * over (grid node, direction) states: the heuristic is the Manhattan distance and the fewest bends to the nearest
30
+ * target port.
30
31
  */
31
32
  export declare function search(grid: Grid, sources: Port[], targets: Port[], costs: SearchCosts, window?: Window): Point[] | undefined;
32
33
  /** Without repeated points and without points in the middle of a straight line. */
package/dist/search.js CHANGED
@@ -22,9 +22,28 @@ export function windowAround(ports, margin) {
22
22
  const ys = ports.map((p) => p.out.y);
23
23
  return { x0: Math.min(...xs) - margin, y0: Math.min(...ys) - margin, x1: Math.max(...xs) + margin, y1: Math.max(...ys) + margin };
24
24
  }
25
+ /**
26
+ * The fewest bends a route can still make from a point, moving in `direction`, to a point `dx`, `dy` away that it
27
+ * must enter moving in `inward`: the route uses each direction that it must move in at least once, and a route that
28
+ * ends moving the way it started and turns at all turns at least once more.
29
+ */
30
+ function minBends(direction, dx, dy, inward) {
31
+ let used = (1 << direction) | (1 << inward);
32
+ if (dx > 1e-6)
33
+ used |= 1;
34
+ else if (dx < -1e-6)
35
+ used |= 4;
36
+ if (dy > 1e-6)
37
+ used |= 2;
38
+ else if (dy < -1e-6)
39
+ used |= 8;
40
+ const count = (used & 1) + ((used >> 1) & 1) + ((used >> 2) & 1) + ((used >> 3) & 1);
41
+ return direction === inward ? (count > 1 ? count : 0) : count - 1;
42
+ }
25
43
  /**
26
44
  * The cheapest route, by length plus a cost for each bend and cluster entry, from a source port to a target port. A*
27
- * over (grid node, direction) states: the heuristic is the Manhattan distance to the nearest target port.
45
+ * over (grid node, direction) states: the heuristic is the Manhattan distance and the fewest bends to the nearest
46
+ * target port.
28
47
  */
29
48
  export function search(grid, sources, targets, costs, window) {
30
49
  const goals = new Map();
@@ -40,30 +59,44 @@ export function search(grid, sources, targets, costs, window) {
40
59
  // entries are part of a lower bound on the cost still to come. With nested clusters this keeps the search local.
41
60
  const [first, ...rest] = targets.map((t) => grid.clustersAround(t.out));
42
61
  const targetClusters = (first ?? []).filter((i) => rest.every((around) => around.includes(i)));
43
- const heuristic = (p) => {
62
+ const ends = targets.map((t) => ({ x: t.out.x, y: t.out.y, inward: (OUTWARD[t.side] + 2) % 4 }));
63
+ const heuristic = (x, y, direction) => {
44
64
  let entries = 0;
45
65
  for (const i of targetClusters)
46
- if (!grid.inCluster(i, p))
66
+ if (!grid.inCluster(i, { x, y }))
47
67
  entries++;
48
- return Math.min(...targets.map((t) => Math.abs(t.out.x - p.x) + Math.abs(t.out.y - p.y))) + costs.cluster * entries;
68
+ let least = Infinity;
69
+ for (const end of ends) {
70
+ const dx = end.x - x;
71
+ const dy = end.y - y;
72
+ const estimate = Math.abs(dx) + Math.abs(dy) + costs.bend * minBends(direction, dx, dy, end.inward);
73
+ if (estimate < least)
74
+ least = estimate;
75
+ }
76
+ return least + costs.cluster * entries;
49
77
  };
50
78
  // A state is node * 4 + direction. A finished route is a state with the target port encoded past the states.
51
- const best = new Map();
52
- const parent = new Map();
79
+ const scratch = grid.scratch;
80
+ const stamp = ++scratch.stamp;
81
+ const { stamps, best, parent } = scratch;
53
82
  const heap = new MinHeap();
54
- const stateCount = grid.xs.length * grid.ys.length * 4;
83
+ const width = grid.xs.length;
84
+ const stateCount = width * grid.ys.length * 4;
55
85
  const finished = new Map();
56
86
  const sourceOf = new Map();
57
87
  for (const port of sources) {
58
88
  const node = grid.node(port.out);
59
89
  if (node === undefined)
60
90
  continue;
61
- const state = node * 4 + OUTWARD[port.side];
62
- if (best.has(state))
91
+ const direction = OUTWARD[port.side];
92
+ const state = node * 4 + direction;
93
+ if (stamps[state] === stamp)
63
94
  continue;
64
- best.set(state, 0);
95
+ stamps[state] = stamp;
96
+ best[state] = 0;
97
+ parent[state] = -1;
65
98
  sourceOf.set(state, port);
66
- heap.push(state, heuristic(port.out));
99
+ heap.push(state, heuristic(port.out.x, port.out.y, direction));
67
100
  }
68
101
  let expansions = 0;
69
102
  for (let state = heap.pop(); state !== undefined; state = heap.pop()) {
@@ -75,8 +108,9 @@ export function search(grid, sources, targets, costs, window) {
75
108
  return undefined;
76
109
  const node = Math.floor(state / 4);
77
110
  const direction = state % 4;
78
- const cost = best.get(state);
79
- const here = grid.point(node);
111
+ const cost = best[state];
112
+ const hx = grid.xs[node % width];
113
+ const hy = grid.ys[Math.floor(node / width)];
80
114
  for (const port of goals.get(node) ?? []) {
81
115
  const inward = (OUTWARD[port.side] + 2) % 4;
82
116
  const total = cost + (direction === inward ? 0 : costs.bend);
@@ -87,23 +121,22 @@ export function search(grid, sources, targets, costs, window) {
87
121
  for (let turn = 0; turn < 4; turn++) {
88
122
  if (turn === (direction + 2) % 4)
89
123
  continue;
90
- const next = grid.step(node, turn);
91
- if (next === undefined)
92
- continue;
93
- const there = grid.point(next);
94
- if (window && (there.x < window.x0 || there.x > window.x1 || there.y < window.y0 || there.y > window.y1))
124
+ const entries = grid.stepCost(node, turn);
125
+ if (entries < 0)
95
126
  continue;
96
- if (grid.blocked((here.x + there.x) / 2, (here.y + there.y) / 2))
127
+ const next = grid.step(node, turn);
128
+ const tx = grid.xs[next % width];
129
+ const ty = grid.ys[Math.floor(next / width)];
130
+ if (window && (tx < window.x0 || tx > window.x1 || ty < window.y0 || ty > window.y1))
97
131
  continue;
98
- const nextCost = cost + Math.abs(there.x - here.x) + Math.abs(there.y - here.y)
99
- + (turn === direction ? 0 : costs.bend) + costs.cluster * grid.entries(here, there);
132
+ const nextCost = cost + Math.abs(tx - hx) + Math.abs(ty - hy) + (turn === direction ? 0 : costs.bend) + costs.cluster * entries;
100
133
  const nextState = next * 4 + turn;
101
- const known = best.get(nextState);
102
- if (known !== undefined && known <= nextCost)
134
+ if (stamps[nextState] === stamp && best[nextState] <= nextCost)
103
135
  continue;
104
- best.set(nextState, nextCost);
105
- parent.set(nextState, state);
106
- heap.push(nextState, nextCost + TIE_BREAK * heuristic(there));
136
+ stamps[nextState] = stamp;
137
+ best[nextState] = nextCost;
138
+ parent[nextState] = state;
139
+ heap.push(nextState, nextCost + TIE_BREAK * heuristic(tx, ty, turn));
107
140
  }
108
141
  }
109
142
  return undefined;
@@ -111,9 +144,9 @@ export function search(grid, sources, targets, costs, window) {
111
144
  function rebuild(grid, parent, sourceOf, last, target) {
112
145
  const nodes = [];
113
146
  let state = last;
114
- while (parent.has(state)) {
147
+ while (parent[state] >= 0) {
115
148
  nodes.push(grid.point(Math.floor(state / 4)));
116
- state = parent.get(state);
149
+ state = parent[state];
117
150
  }
118
151
  nodes.push(grid.point(Math.floor(state / 4)));
119
152
  nodes.reverse();
package/dist/types.d.ts CHANGED
@@ -45,6 +45,16 @@ export interface RouterOptions {
45
45
  * search use the whole diagram. Default 400.
46
46
  */
47
47
  windowMargin?: number;
48
+ /**
49
+ * Spread apart the segments that share a track. Default true. Set false to route the connectors in parts, for
50
+ * example in several workers, and then join the parts with `spreadRoutes`.
51
+ */
52
+ spread?: boolean;
53
+ /**
54
+ * Route only the connectors with these ids. The other connectors still shape the grid, so each route is the one
55
+ * that a call over all the connectors gives. Default: route them all.
56
+ */
57
+ routeOnly?: string[];
48
58
  }
49
59
  export interface RouteResult {
50
60
  /** Each routed connector's points, from the source shape's border to the target shape's border. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orthogonal-router",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Routes connectors between rectangles in right angles, around obstacles, and spreads apart the lines that share a track. No dependencies.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Matthew Bain <matt@rocketstack.co>",