orthogonal-router 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +75 -2
- package/dist/grid.d.ts +29 -0
- package/dist/grid.js +131 -0
- package/dist/heap.d.ts +15 -0
- package/dist/heap.js +62 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +60 -0
- package/dist/nudge.d.ts +11 -0
- package/dist/nudge.js +127 -0
- package/dist/search.d.ts +33 -0
- package/dist/search.js +133 -0
- package/dist/types.d.ts +54 -0
- package/dist/types.js +1 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2023 FINOS
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,76 @@
|
|
|
1
|
-
#
|
|
1
|
+
# orthogonal-router
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Routes connectors between rectangles in right angles, around obstacles, and spreads apart the lines that share a track. It has no dependencies and is licensed under Apache-2.0.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install orthogonal-router
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Example
|
|
10
|
+
|
|
11
|
+
A small architecture: two clients, a backend group with four services, and an audit log outside the group.
|
|
12
|
+
|
|
13
|
+

|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import { routeConnectors } from 'orthogonal-router';
|
|
17
|
+
|
|
18
|
+
const shapes = [
|
|
19
|
+
{ id: 'web', x: 40, y: 40, width: 140, height: 50 },
|
|
20
|
+
{ id: 'mobile', x: 260, y: 40, width: 140, height: 50 },
|
|
21
|
+
// A group drawn around other shapes. Connectors may cross it, at a cost.
|
|
22
|
+
{ id: 'backend', kind: 'cluster', x: 20, y: 150, width: 560, height: 290 },
|
|
23
|
+
{ id: 'api', x: 60, y: 200, width: 140, height: 50 },
|
|
24
|
+
{ id: 'cache', x: 230, y: 290, width: 140, height: 50 },
|
|
25
|
+
{ id: 'auth', x: 400, y: 200, width: 140, height: 50 },
|
|
26
|
+
{ id: 'orders', x: 60, y: 370, width: 140, height: 50 },
|
|
27
|
+
{ id: 'db', x: 400, y: 370, width: 140, height: 50 },
|
|
28
|
+
{ id: 'audit', x: 660, y: 40, width: 140, height: 50 },
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
const connectors = [
|
|
32
|
+
{ id: 'web-api', source: { shape: 'web' }, target: { shape: 'api' } },
|
|
33
|
+
{ id: 'mobile-api', source: { shape: 'mobile' }, target: { shape: 'api' } },
|
|
34
|
+
{ id: 'api-auth', source: { shape: 'api' }, target: { shape: 'auth' } },
|
|
35
|
+
{ id: 'api-db', source: { shape: 'api' }, target: { shape: 'db' } },
|
|
36
|
+
{ id: 'orders-db', source: { shape: 'orders' }, target: { shape: 'db' } },
|
|
37
|
+
{ id: 'auth-db', source: { shape: 'auth' }, target: { shape: 'db' } },
|
|
38
|
+
// `sides` limits where a connector may attach.
|
|
39
|
+
{ id: 'db-audit', source: { shape: 'db', sides: ['right'] }, target: { shape: 'audit' } },
|
|
40
|
+
{ id: 'web-audit', source: { shape: 'web', sides: ['top'] }, target: { shape: 'audit', sides: ['top'] } },
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
const { routes, failed } = routeConnectors(shapes, connectors, { buffer: 12, spacing: 14 });
|
|
44
|
+
|
|
45
|
+
// Each route is a list of points from the border of the source to the border of the target, so it draws as a polyline.
|
|
46
|
+
const lines = [...routes.values()].map(
|
|
47
|
+
(points) => `<polyline points="${points.map((p) => `${p.x},${p.y}`).join(' ')}" fill="none" stroke="#2563eb"/>`,
|
|
48
|
+
);
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
In the diagram:
|
|
52
|
+
|
|
53
|
+
- **API → Database** goes around **Cache**, which is an obstacle.
|
|
54
|
+
- **API → Auth** and **API → Database** leave the same side of **API**, and **Orders → Database** and **API → Database** enter the same side of **Database**. The router spreads them `spacing` apart.
|
|
55
|
+
- **Database → Audit log** may leave only the right side of **Database**, and **Web app → Audit log** may use only the top sides, so it runs above the top row.
|
|
56
|
+
- **Mobile app → API** and **Web app → API** cross into the **Backend** cluster once each, as **API** is in it.
|
|
57
|
+
|
|
58
|
+
`npm run example` runs [examples/architecture.mjs](examples/architecture.mjs), which routes this architecture and writes the diagram to `docs/example.svg`. CI fails when the diagram no longer matches the router's output.
|
|
59
|
+
|
|
60
|
+
## How it works
|
|
61
|
+
|
|
62
|
+
- An `obstacle` shape (the default) is never crossed. A `cluster` shape, such as a group drawn around other shapes, may be crossed, at a cost for each entry.
|
|
63
|
+
- Each connector attaches to the middle of a side. `sides` limits which sides it may use.
|
|
64
|
+
- The search is A* over a sparse orthogonal visibility grid, with a cost for length, bends and cluster entries. Then the segments that share a track are spread `spacing` apart, in the order that crosses the fewest other segments.
|
|
65
|
+
- The result is deterministic: the same input gives the same routes.
|
|
66
|
+
|
|
67
|
+
## Options
|
|
68
|
+
|
|
69
|
+
| Option | Default | |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `buffer` | 8 | Clear space around each obstacle |
|
|
72
|
+
| `bendPenalty` | 40 | Cost of a bend |
|
|
73
|
+
| `clusterCrossingPenalty` | 400 | Cost of each cluster entry |
|
|
74
|
+
| `spacing` | 6 | Distance between parallel segments on one track |
|
|
75
|
+
| `maxExpansions` | 200000 | Search limit for one connector |
|
|
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 |
|
package/dist/grid.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Box, Point } from './types.js';
|
|
2
|
+
export declare const round: (value: number) => number;
|
|
3
|
+
/**
|
|
4
|
+
* The sparse orthogonal visibility grid: lines through the edges of each obstacle grown by the buffer, the edges of
|
|
5
|
+
* each cluster and the ports. A route runs along these lines and turns where they cross. As no obstacle edge lies
|
|
6
|
+
* between two neighbouring lines, a step between them is free when its midpoint is outside every obstacle.
|
|
7
|
+
*/
|
|
8
|
+
export declare class Grid {
|
|
9
|
+
private readonly clusters;
|
|
10
|
+
readonly xs: number[];
|
|
11
|
+
readonly ys: number[];
|
|
12
|
+
private readonly xIndex;
|
|
13
|
+
private readonly yIndex;
|
|
14
|
+
private readonly obstacles;
|
|
15
|
+
private readonly clusterIndex;
|
|
16
|
+
constructor(obstacles: Box[], clusters: Box[], buffer: number, ports: Point[]);
|
|
17
|
+
/** The grid node of a point that lies on two grid lines. */
|
|
18
|
+
node(point: Point): number | undefined;
|
|
19
|
+
point(node: number): Point;
|
|
20
|
+
/** The neighbour in a direction (0 right, 1 down, 2 left, 3 up), or undefined at the edge of the grid. */
|
|
21
|
+
step(node: number, direction: number): number | undefined;
|
|
22
|
+
blocked(x: number, y: number): boolean;
|
|
23
|
+
/** The clusters that a step from `from` to `to` enters: those around its midpoint but not around its start. */
|
|
24
|
+
entries(from: Point, to: Point): number;
|
|
25
|
+
/** The indexes of the clusters around the point. */
|
|
26
|
+
clustersAround(point: Point): number[];
|
|
27
|
+
/** True when the cluster with this index is around the point. */
|
|
28
|
+
inCluster(index: number, point: Point): boolean;
|
|
29
|
+
}
|
package/dist/grid.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
const PRECISION = 1000;
|
|
2
|
+
export const round = (value) => Math.round(value * PRECISION) / PRECISION;
|
|
3
|
+
/** Strictly inside: a point on the border is outside, so a route may run along it. */
|
|
4
|
+
const inside = (box, x, y) => x > box.x && x < box.x + box.width && y > box.y && y < box.y + box.height;
|
|
5
|
+
/** A bucket index of boxes, for the many point tests of a search. */
|
|
6
|
+
class BoxIndex {
|
|
7
|
+
boxes;
|
|
8
|
+
buckets = new Map();
|
|
9
|
+
cell;
|
|
10
|
+
constructor(boxes) {
|
|
11
|
+
this.boxes = boxes;
|
|
12
|
+
const sizes = boxes.map((box) => Math.max(box.width, box.height)).sort((a, b) => a - b);
|
|
13
|
+
this.cell = Math.max(32, sizes[sizes.length >> 1] ?? 32);
|
|
14
|
+
boxes.forEach((box, i) => {
|
|
15
|
+
for (let cx = Math.floor(box.x / this.cell); cx <= Math.floor((box.x + box.width) / this.cell); cx++) {
|
|
16
|
+
for (let cy = Math.floor(box.y / this.cell); cy <= Math.floor((box.y + box.height) / this.cell); cy++) {
|
|
17
|
+
const key = `${cx},${cy}`;
|
|
18
|
+
const bucket = this.buckets.get(key);
|
|
19
|
+
if (bucket)
|
|
20
|
+
bucket.push(i);
|
|
21
|
+
else
|
|
22
|
+
this.buckets.set(key, [i]);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
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
|
+
}
|
|
31
|
+
/** The indexes of the boxes around the point. */
|
|
32
|
+
around(x, y) {
|
|
33
|
+
const bucket = this.buckets.get(`${Math.floor(x / this.cell)},${Math.floor(y / this.cell)}`);
|
|
34
|
+
return bucket ? bucket.filter((i) => inside(this.boxes[i], x, y)) : [];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The sparse orthogonal visibility grid: lines through the edges of each obstacle grown by the buffer, the edges of
|
|
39
|
+
* each cluster and the ports. A route runs along these lines and turns where they cross. As no obstacle edge lies
|
|
40
|
+
* between two neighbouring lines, a step between them is free when its midpoint is outside every obstacle.
|
|
41
|
+
*/
|
|
42
|
+
export class Grid {
|
|
43
|
+
clusters;
|
|
44
|
+
xs;
|
|
45
|
+
ys;
|
|
46
|
+
xIndex;
|
|
47
|
+
yIndex;
|
|
48
|
+
obstacles;
|
|
49
|
+
clusterIndex;
|
|
50
|
+
constructor(obstacles, clusters, buffer, ports) {
|
|
51
|
+
this.clusters = clusters;
|
|
52
|
+
const grown = obstacles.map((box) => ({
|
|
53
|
+
x: box.x - buffer,
|
|
54
|
+
y: box.y - buffer,
|
|
55
|
+
width: box.width + 2 * buffer,
|
|
56
|
+
height: box.height + 2 * buffer,
|
|
57
|
+
}));
|
|
58
|
+
this.obstacles = new BoxIndex(grown);
|
|
59
|
+
this.clusterIndex = new BoxIndex(clusters);
|
|
60
|
+
const xs = new Set();
|
|
61
|
+
const ys = new Set();
|
|
62
|
+
const all = [...grown, ...clusters];
|
|
63
|
+
for (const box of all) {
|
|
64
|
+
xs.add(round(box.x)).add(round(box.x + box.width));
|
|
65
|
+
ys.add(round(box.y)).add(round(box.y + box.height));
|
|
66
|
+
}
|
|
67
|
+
// Just inside and just outside each cluster, so a route need not run on its border.
|
|
68
|
+
for (const box of clusters) {
|
|
69
|
+
const gap = Math.max(buffer, 4);
|
|
70
|
+
xs.add(round(box.x - gap)).add(round(box.x + gap)).add(round(box.x + box.width - gap)).add(round(box.x + box.width + gap));
|
|
71
|
+
ys.add(round(box.y - gap)).add(round(box.y + gap)).add(round(box.y + box.height - gap)).add(round(box.y + box.height + gap));
|
|
72
|
+
}
|
|
73
|
+
for (const port of ports) {
|
|
74
|
+
xs.add(round(port.x));
|
|
75
|
+
ys.add(round(port.y));
|
|
76
|
+
}
|
|
77
|
+
// A ring outside everything, so a route can always go round.
|
|
78
|
+
if (all.length) {
|
|
79
|
+
const margin = 4 * Math.max(buffer, 8);
|
|
80
|
+
xs.add(round(Math.min(...all.map((b) => b.x)) - margin)).add(round(Math.max(...all.map((b) => b.x + b.width)) + margin));
|
|
81
|
+
ys.add(round(Math.min(...all.map((b) => b.y)) - margin)).add(round(Math.max(...all.map((b) => b.y + b.height)) + margin));
|
|
82
|
+
}
|
|
83
|
+
this.xs = [...xs].sort((a, b) => a - b);
|
|
84
|
+
this.ys = [...ys].sort((a, b) => a - b);
|
|
85
|
+
this.xIndex = new Map(this.xs.map((x, i) => [x, i]));
|
|
86
|
+
this.yIndex = new Map(this.ys.map((y, i) => [y, i]));
|
|
87
|
+
}
|
|
88
|
+
/** The grid node of a point that lies on two grid lines. */
|
|
89
|
+
node(point) {
|
|
90
|
+
const xi = this.xIndex.get(round(point.x));
|
|
91
|
+
const yi = this.yIndex.get(round(point.y));
|
|
92
|
+
return xi === undefined || yi === undefined ? undefined : yi * this.xs.length + xi;
|
|
93
|
+
}
|
|
94
|
+
point(node) {
|
|
95
|
+
return { x: this.xs[node % this.xs.length], y: this.ys[Math.floor(node / this.xs.length)] };
|
|
96
|
+
}
|
|
97
|
+
/** The neighbour in a direction (0 right, 1 down, 2 left, 3 up), or undefined at the edge of the grid. */
|
|
98
|
+
step(node, direction) {
|
|
99
|
+
const width = this.xs.length;
|
|
100
|
+
const xi = node % width;
|
|
101
|
+
const yi = Math.floor(node / width);
|
|
102
|
+
switch (direction) {
|
|
103
|
+
case 0: return xi + 1 < width ? node + 1 : undefined;
|
|
104
|
+
case 1: return yi + 1 < this.ys.length ? node + width : undefined;
|
|
105
|
+
case 2: return xi > 0 ? node - 1 : undefined;
|
|
106
|
+
default: return yi > 0 ? node - width : undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
blocked(x, y) {
|
|
110
|
+
return this.obstacles.some(x, y);
|
|
111
|
+
}
|
|
112
|
+
/** The clusters that a step from `from` to `to` enters: those around its midpoint but not around its start. */
|
|
113
|
+
entries(from, to) {
|
|
114
|
+
if (this.clusters.length === 0)
|
|
115
|
+
return 0;
|
|
116
|
+
let count = 0;
|
|
117
|
+
for (const i of this.clusterIndex.around((from.x + to.x) / 2, (from.y + to.y) / 2)) {
|
|
118
|
+
if (!inside(this.clusters[i], from.x, from.y))
|
|
119
|
+
count++;
|
|
120
|
+
}
|
|
121
|
+
return count;
|
|
122
|
+
}
|
|
123
|
+
/** The indexes of the clusters around the point. */
|
|
124
|
+
clustersAround(point) {
|
|
125
|
+
return this.clusters.length === 0 ? [] : this.clusterIndex.around(point.x, point.y);
|
|
126
|
+
}
|
|
127
|
+
/** True when the cluster with this index is around the point. */
|
|
128
|
+
inCluster(index, point) {
|
|
129
|
+
return inside(this.clusters[index], point.x, point.y);
|
|
130
|
+
}
|
|
131
|
+
}
|
package/dist/heap.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** A binary min-heap of numbers keyed by a priority. Ties keep insertion order, so a search is deterministic. */
|
|
2
|
+
export declare class MinHeap {
|
|
3
|
+
private readonly priorities;
|
|
4
|
+
private readonly orders;
|
|
5
|
+
private readonly values;
|
|
6
|
+
private next;
|
|
7
|
+
get size(): number;
|
|
8
|
+
push(value: number, priority: number): void;
|
|
9
|
+
/** The value with the lowest priority. Undefined when the heap is empty. */
|
|
10
|
+
pop(): number | undefined;
|
|
11
|
+
private less;
|
|
12
|
+
private swap;
|
|
13
|
+
private up;
|
|
14
|
+
private down;
|
|
15
|
+
}
|
package/dist/heap.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** A binary min-heap of numbers keyed by a priority. Ties keep insertion order, so a search is deterministic. */
|
|
2
|
+
export class MinHeap {
|
|
3
|
+
priorities = [];
|
|
4
|
+
orders = [];
|
|
5
|
+
values = [];
|
|
6
|
+
next = 0;
|
|
7
|
+
get size() {
|
|
8
|
+
return this.values.length;
|
|
9
|
+
}
|
|
10
|
+
push(value, priority) {
|
|
11
|
+
this.values.push(value);
|
|
12
|
+
this.priorities.push(priority);
|
|
13
|
+
this.orders.push(this.next++);
|
|
14
|
+
this.up(this.values.length - 1);
|
|
15
|
+
}
|
|
16
|
+
/** The value with the lowest priority. Undefined when the heap is empty. */
|
|
17
|
+
pop() {
|
|
18
|
+
if (this.values.length === 0)
|
|
19
|
+
return undefined;
|
|
20
|
+
const top = this.values[0];
|
|
21
|
+
const last = this.values.length - 1;
|
|
22
|
+
this.swap(0, last);
|
|
23
|
+
this.values.pop();
|
|
24
|
+
this.priorities.pop();
|
|
25
|
+
this.orders.pop();
|
|
26
|
+
this.down(0);
|
|
27
|
+
return top;
|
|
28
|
+
}
|
|
29
|
+
less(a, b) {
|
|
30
|
+
return this.priorities[a] < this.priorities[b] || (this.priorities[a] === this.priorities[b] && this.orders[a] < this.orders[b]);
|
|
31
|
+
}
|
|
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]];
|
|
36
|
+
}
|
|
37
|
+
up(i) {
|
|
38
|
+
while (i > 0) {
|
|
39
|
+
const parent = (i - 1) >> 1;
|
|
40
|
+
if (!this.less(i, parent))
|
|
41
|
+
return;
|
|
42
|
+
this.swap(i, parent);
|
|
43
|
+
i = parent;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
down(i) {
|
|
47
|
+
const n = this.values.length;
|
|
48
|
+
for (;;) {
|
|
49
|
+
const left = 2 * i + 1;
|
|
50
|
+
const right = left + 1;
|
|
51
|
+
let smallest = i;
|
|
52
|
+
if (left < n && this.less(left, smallest))
|
|
53
|
+
smallest = left;
|
|
54
|
+
if (right < n && this.less(right, smallest))
|
|
55
|
+
smallest = right;
|
|
56
|
+
if (smallest === i)
|
|
57
|
+
return;
|
|
58
|
+
this.swap(i, smallest);
|
|
59
|
+
i = smallest;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Connector, RouteResult, RouterOptions, Shape } from './types.js';
|
|
2
|
+
export type { Box, Connector, ConnectorEnd, Point, RouteResult, RouterOptions, Shape, Side } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Routes each connector in right angles from a side of its source shape to a side of its target shape, around the
|
|
5
|
+
* obstacles. Each connector is routed on its own, so a change to one connector moves no other route except where
|
|
6
|
+
* they share a track. Then the segments that share a track are spread apart.
|
|
7
|
+
*
|
|
8
|
+
* Where the shapes are too close for the buffer, the connector is routed again with half the buffer, then with none.
|
|
9
|
+
*/
|
|
10
|
+
export declare function routeConnectors(shapes: Shape[], connectors: Connector[], options?: RouterOptions): RouteResult;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Grid } from './grid.js';
|
|
2
|
+
import { nudge } from './nudge.js';
|
|
3
|
+
import { portsOf, search, windowAround } from './search.js';
|
|
4
|
+
const ALL_SIDES = ['top', 'right', 'bottom', 'left'];
|
|
5
|
+
const DEFAULTS = {
|
|
6
|
+
buffer: 8,
|
|
7
|
+
bendPenalty: 40,
|
|
8
|
+
clusterCrossingPenalty: 400,
|
|
9
|
+
spacing: 6,
|
|
10
|
+
maxExpansions: 200_000,
|
|
11
|
+
windowMargin: 400,
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Routes each connector in right angles from a side of its source shape to a side of its target shape, around the
|
|
15
|
+
* obstacles. Each connector is routed on its own, so a change to one connector moves no other route except where
|
|
16
|
+
* they share a track. Then the segments that share a track are spread apart.
|
|
17
|
+
*
|
|
18
|
+
* Where the shapes are too close for the buffer, the connector is routed again with half the buffer, then with none.
|
|
19
|
+
*/
|
|
20
|
+
export function routeConnectors(shapes, connectors, options = {}) {
|
|
21
|
+
const o = { ...DEFAULTS, ...options };
|
|
22
|
+
const byId = new Map(shapes.map((shape) => [shape.id, shape]));
|
|
23
|
+
const obstacles = shapes.filter((shape) => (shape.kind ?? 'obstacle') === 'obstacle');
|
|
24
|
+
const clusters = shapes.filter((shape) => shape.kind === 'cluster');
|
|
25
|
+
const costs = { bend: o.bendPenalty, cluster: o.clusterCrossingPenalty, maxExpansions: o.maxExpansions };
|
|
26
|
+
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);
|
|
28
|
+
const portsAt = (buffer, end) => portsOf(byId.get(end.shape), end.sides ?? ALL_SIDES, buffer);
|
|
29
|
+
const grids = new Map();
|
|
30
|
+
const gridFor = (buffer) => {
|
|
31
|
+
let grid = grids.get(buffer);
|
|
32
|
+
if (!grid) {
|
|
33
|
+
const ports = valid.flatMap((c) => [...portsAt(buffer, c.source), ...portsAt(buffer, c.target)]);
|
|
34
|
+
grid = new Grid(obstacles, clusters, buffer, ports.map((port) => port.out));
|
|
35
|
+
grids.set(buffer, grid);
|
|
36
|
+
}
|
|
37
|
+
return grid;
|
|
38
|
+
};
|
|
39
|
+
const buffers = [...new Set([o.buffer, o.buffer / 2, 0])];
|
|
40
|
+
const routed = [];
|
|
41
|
+
for (const connector of valid) {
|
|
42
|
+
let points;
|
|
43
|
+
for (const buffer of buffers) {
|
|
44
|
+
const sources = portsAt(buffer, connector.source);
|
|
45
|
+
const targets = portsAt(buffer, connector.target);
|
|
46
|
+
// 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);
|
|
49
|
+
if (points)
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
if (!points) {
|
|
53
|
+
failed.push(connector.id);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
routed.push({ id: connector.id, points, ends: { source: byId.get(connector.source.shape), target: byId.get(connector.target.shape) } });
|
|
57
|
+
}
|
|
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 };
|
|
60
|
+
}
|
package/dist/nudge.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Box, Point } from './types.js';
|
|
2
|
+
export interface RouteEnds {
|
|
3
|
+
source: Box;
|
|
4
|
+
target: Box;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Spreads apart the segments that lie on the same track and overlap, `spacing` apart, in the order that crosses the
|
|
8
|
+
* fewest other segments, and within the free space between the obstacles beside the track. Horizontal segments
|
|
9
|
+
* first, then vertical ones. An end segment moves its end along the side of its shape.
|
|
10
|
+
*/
|
|
11
|
+
export declare function nudge(routes: Point[][], ends: RouteEnds[], obstacles: Box[], spacing: number): Point[][];
|
package/dist/nudge.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { simplify } from './search.js';
|
|
2
|
+
const EPS = 1e-6;
|
|
3
|
+
/**
|
|
4
|
+
* Spreads apart the segments that lie on the same track and overlap, `spacing` apart, in the order that crosses the
|
|
5
|
+
* fewest other segments, and within the free space between the obstacles beside the track. Horizontal segments
|
|
6
|
+
* first, then vertical ones. An end segment moves its end along the side of its shape.
|
|
7
|
+
*/
|
|
8
|
+
export function nudge(routes, ends, obstacles, spacing) {
|
|
9
|
+
const moved = routes.map((points) => points.map((p) => ({ ...p })));
|
|
10
|
+
for (const horizontal of [true, false])
|
|
11
|
+
spread(moved, ends, obstacles, spacing, horizontal);
|
|
12
|
+
return moved.map(simplify);
|
|
13
|
+
}
|
|
14
|
+
function spread(routes, ends, obstacles, spacing, horizontal) {
|
|
15
|
+
const along = (p) => (horizontal ? p.x : p.y);
|
|
16
|
+
const across = (p) => (horizontal ? p.y : p.x);
|
|
17
|
+
const tracks = new Map();
|
|
18
|
+
routes.forEach((points, route) => {
|
|
19
|
+
for (let k = 0; k + 1 < points.length; k++) {
|
|
20
|
+
const a = points[k];
|
|
21
|
+
const b = points[k + 1];
|
|
22
|
+
if (Math.abs(across(a) - across(b)) > EPS || Math.abs(along(a) - along(b)) < EPS)
|
|
23
|
+
continue;
|
|
24
|
+
const turn = (end, neighbour) => neighbour < 0 || neighbour >= points.length ? 0 : Math.sign(across(points[neighbour]) - across(points[end]));
|
|
25
|
+
const forward = along(b) > along(a);
|
|
26
|
+
const segment = {
|
|
27
|
+
route, k, pos: across(a),
|
|
28
|
+
lo: Math.min(along(a), along(b)),
|
|
29
|
+
hi: Math.max(along(a), along(b)),
|
|
30
|
+
turnLo: forward ? turn(k, k - 1) : turn(k + 1, k + 2),
|
|
31
|
+
turnHi: forward ? turn(k + 1, k + 2) : turn(k, k - 1),
|
|
32
|
+
};
|
|
33
|
+
const key = Math.round(segment.pos * 1000);
|
|
34
|
+
tracks.set(key, [...(tracks.get(key) ?? []), segment]);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
for (const segments of tracks.values()) {
|
|
38
|
+
segments.sort((a, b) => a.lo - b.lo || a.route - b.route);
|
|
39
|
+
let group = [];
|
|
40
|
+
let reach = -Infinity;
|
|
41
|
+
for (const segment of [...segments, undefined]) {
|
|
42
|
+
if (segment && segment.lo < reach - EPS) {
|
|
43
|
+
group.push(segment);
|
|
44
|
+
reach = Math.max(reach, segment.hi);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (group.length > 1)
|
|
48
|
+
place(group, routes, ends, obstacles, spacing, horizontal);
|
|
49
|
+
if (!segment)
|
|
50
|
+
break;
|
|
51
|
+
group = [segment];
|
|
52
|
+
reach = segment.hi;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Negative when `a` goes before `b`, that is above or to the left. Seen from each end of the shared stretch, the
|
|
58
|
+
* segment that leaves first goes to the side it turns to, so that it does not cross the other.
|
|
59
|
+
*/
|
|
60
|
+
function order(a, b) {
|
|
61
|
+
const byEnd = (aAt, bAt, aTurn, bTurn, firstIsLarger) => {
|
|
62
|
+
if (Math.abs(aAt - bAt) < EPS)
|
|
63
|
+
return aTurn - bTurn;
|
|
64
|
+
const aFirst = firstIsLarger ? aAt > bAt : aAt < bAt;
|
|
65
|
+
return aFirst ? aTurn : -bTurn;
|
|
66
|
+
};
|
|
67
|
+
return Math.sign(byEnd(a.lo, b.lo, a.turnLo, b.turnLo, true))
|
|
68
|
+
|| Math.sign(byEnd(a.hi, b.hi, a.turnHi, b.turnHi, false))
|
|
69
|
+
|| a.route - b.route
|
|
70
|
+
|| a.k - b.k;
|
|
71
|
+
}
|
|
72
|
+
function place(group, routes, ends, obstacles, spacing, horizontal) {
|
|
73
|
+
const sorted = insertionSort(group, order);
|
|
74
|
+
const pos = group[0].pos;
|
|
75
|
+
const lo = Math.min(...group.map((s) => s.lo));
|
|
76
|
+
const hi = Math.max(...group.map((s) => s.hi));
|
|
77
|
+
// The free channel: from the nearest obstacle on one side of the track to the nearest on the other.
|
|
78
|
+
let low = -Infinity;
|
|
79
|
+
let high = Infinity;
|
|
80
|
+
for (const box of obstacles) {
|
|
81
|
+
const start = horizontal ? box.x : box.y;
|
|
82
|
+
const end = start + (horizontal ? box.width : box.height);
|
|
83
|
+
if (end <= lo + EPS || start >= hi - EPS)
|
|
84
|
+
continue;
|
|
85
|
+
const near = horizontal ? box.y : box.x;
|
|
86
|
+
const far = near + (horizontal ? box.height : box.width);
|
|
87
|
+
if (far <= pos + EPS)
|
|
88
|
+
low = Math.max(low, far);
|
|
89
|
+
else if (near >= pos - EPS)
|
|
90
|
+
high = Math.min(high, near);
|
|
91
|
+
}
|
|
92
|
+
low += spacing;
|
|
93
|
+
high -= spacing;
|
|
94
|
+
const n = sorted.length;
|
|
95
|
+
const step = high - low >= spacing * (n - 1) ? spacing : Math.max(0, (high - low) / (n - 1));
|
|
96
|
+
const half = (step * (n - 1)) / 2;
|
|
97
|
+
const centre = high - low >= 2 * half ? Math.min(Math.max(pos, low + half), high - half) : pos;
|
|
98
|
+
sorted.forEach((segment, i) => {
|
|
99
|
+
const points = routes[segment.route];
|
|
100
|
+
let at = centre - half + i * step;
|
|
101
|
+
// An end segment slides its end along the side of the shape, so it must stay on that side.
|
|
102
|
+
const last = points.length - 2;
|
|
103
|
+
for (const [isEnd, box] of [[segment.k === 0, ends[segment.route].source], [segment.k === last, ends[segment.route].target]]) {
|
|
104
|
+
if (!isEnd)
|
|
105
|
+
continue;
|
|
106
|
+
const from = (horizontal ? box.y : box.x) + 2;
|
|
107
|
+
const to = (horizontal ? box.y + box.height : box.x + box.width) - 2;
|
|
108
|
+
at = Math.min(Math.max(at, from), to);
|
|
109
|
+
}
|
|
110
|
+
for (const p of [points[segment.k], points[segment.k + 1]]) {
|
|
111
|
+
if (horizontal)
|
|
112
|
+
p.y = at;
|
|
113
|
+
else
|
|
114
|
+
p.x = at;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function insertionSort(items, compare) {
|
|
119
|
+
const sorted = [];
|
|
120
|
+
for (const item of items) {
|
|
121
|
+
let i = sorted.length;
|
|
122
|
+
while (i > 0 && compare(item, sorted[i - 1]) < 0)
|
|
123
|
+
i--;
|
|
124
|
+
sorted.splice(i, 0, item);
|
|
125
|
+
}
|
|
126
|
+
return sorted;
|
|
127
|
+
}
|
package/dist/search.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Grid } from './grid.js';
|
|
2
|
+
import type { Box, Point, Side } from './types.js';
|
|
3
|
+
/** Directions: 0 right, 1 down, 2 left, 3 up. */
|
|
4
|
+
export declare const OUTWARD: Record<Side, number>;
|
|
5
|
+
export interface Port {
|
|
6
|
+
side: Side;
|
|
7
|
+
/** The middle of the side, on the shape's border. */
|
|
8
|
+
at: Point;
|
|
9
|
+
/** `at` moved out by the buffer: where the route leaves the stub. */
|
|
10
|
+
out: Point;
|
|
11
|
+
}
|
|
12
|
+
export declare function portsOf(box: Box, sides: Side[], buffer: number): Port[];
|
|
13
|
+
export interface SearchCosts {
|
|
14
|
+
bend: number;
|
|
15
|
+
cluster: number;
|
|
16
|
+
maxExpansions: number;
|
|
17
|
+
}
|
|
18
|
+
/** The area a search may use. */
|
|
19
|
+
export interface Window {
|
|
20
|
+
x0: number;
|
|
21
|
+
y0: number;
|
|
22
|
+
x1: number;
|
|
23
|
+
y1: number;
|
|
24
|
+
}
|
|
25
|
+
/** The box around the ports, grown by `margin` on each side. */
|
|
26
|
+
export declare function windowAround(ports: Port[], margin: number): Window;
|
|
27
|
+
/**
|
|
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.
|
|
30
|
+
*/
|
|
31
|
+
export declare function search(grid: Grid, sources: Port[], targets: Port[], costs: SearchCosts, window?: Window): Point[] | undefined;
|
|
32
|
+
/** Without repeated points and without points in the middle of a straight line. */
|
|
33
|
+
export declare function simplify(points: Point[]): Point[];
|
package/dist/search.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { MinHeap } from './heap.js';
|
|
2
|
+
/** Directions: 0 right, 1 down, 2 left, 3 up. */
|
|
3
|
+
export const OUTWARD = { right: 0, bottom: 1, left: 2, top: 3 };
|
|
4
|
+
const DX = [1, 0, -1, 0];
|
|
5
|
+
const DY = [0, 1, 0, -1];
|
|
6
|
+
/** Weights the estimate a little, so that of the many routes with the same cost the search follows the one nearest the target. A route is at most 0.1% longer than the cheapest. */
|
|
7
|
+
const TIE_BREAK = 1.001;
|
|
8
|
+
export function portsOf(box, sides, buffer) {
|
|
9
|
+
return sides.map((side) => {
|
|
10
|
+
const cx = box.x + box.width / 2;
|
|
11
|
+
const cy = box.y + box.height / 2;
|
|
12
|
+
const at = side === 'top' ? { x: cx, y: box.y }
|
|
13
|
+
: side === 'bottom' ? { x: cx, y: box.y + box.height }
|
|
14
|
+
: side === 'left' ? { x: box.x, y: cy } : { x: box.x + box.width, y: cy };
|
|
15
|
+
const d = OUTWARD[side];
|
|
16
|
+
return { side, at, out: { x: at.x + DX[d] * buffer, y: at.y + DY[d] * buffer } };
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/** The box around the ports, grown by `margin` on each side. */
|
|
20
|
+
export function windowAround(ports, margin) {
|
|
21
|
+
const xs = ports.map((p) => p.out.x);
|
|
22
|
+
const ys = ports.map((p) => p.out.y);
|
|
23
|
+
return { x0: Math.min(...xs) - margin, y0: Math.min(...ys) - margin, x1: Math.max(...xs) + margin, y1: Math.max(...ys) + margin };
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 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.
|
|
28
|
+
*/
|
|
29
|
+
export function search(grid, sources, targets, costs, window) {
|
|
30
|
+
const goals = new Map();
|
|
31
|
+
for (const port of targets) {
|
|
32
|
+
const node = grid.node(port.out);
|
|
33
|
+
if (node === undefined)
|
|
34
|
+
continue;
|
|
35
|
+
goals.set(node, [...(goals.get(node) ?? []), port]);
|
|
36
|
+
}
|
|
37
|
+
if (goals.size === 0)
|
|
38
|
+
return undefined;
|
|
39
|
+
// A route must enter each cluster that is around every target port and not around its current point, so those
|
|
40
|
+
// entries are part of a lower bound on the cost still to come. With nested clusters this keeps the search local.
|
|
41
|
+
const [first, ...rest] = targets.map((t) => grid.clustersAround(t.out));
|
|
42
|
+
const targetClusters = (first ?? []).filter((i) => rest.every((around) => around.includes(i)));
|
|
43
|
+
const heuristic = (p) => {
|
|
44
|
+
let entries = 0;
|
|
45
|
+
for (const i of targetClusters)
|
|
46
|
+
if (!grid.inCluster(i, p))
|
|
47
|
+
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;
|
|
49
|
+
};
|
|
50
|
+
// 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();
|
|
53
|
+
const heap = new MinHeap();
|
|
54
|
+
const stateCount = grid.xs.length * grid.ys.length * 4;
|
|
55
|
+
const finished = new Map();
|
|
56
|
+
const sourceOf = new Map();
|
|
57
|
+
for (const port of sources) {
|
|
58
|
+
const node = grid.node(port.out);
|
|
59
|
+
if (node === undefined)
|
|
60
|
+
continue;
|
|
61
|
+
const state = node * 4 + OUTWARD[port.side];
|
|
62
|
+
if (best.has(state))
|
|
63
|
+
continue;
|
|
64
|
+
best.set(state, 0);
|
|
65
|
+
sourceOf.set(state, port);
|
|
66
|
+
heap.push(state, heuristic(port.out));
|
|
67
|
+
}
|
|
68
|
+
let expansions = 0;
|
|
69
|
+
for (let state = heap.pop(); state !== undefined; state = heap.pop()) {
|
|
70
|
+
if (state >= stateCount) {
|
|
71
|
+
const { state: last, port } = finished.get(state);
|
|
72
|
+
return rebuild(grid, parent, sourceOf, last, port);
|
|
73
|
+
}
|
|
74
|
+
if (++expansions > costs.maxExpansions)
|
|
75
|
+
return undefined;
|
|
76
|
+
const node = Math.floor(state / 4);
|
|
77
|
+
const direction = state % 4;
|
|
78
|
+
const cost = best.get(state);
|
|
79
|
+
const here = grid.point(node);
|
|
80
|
+
for (const port of goals.get(node) ?? []) {
|
|
81
|
+
const inward = (OUTWARD[port.side] + 2) % 4;
|
|
82
|
+
const total = cost + (direction === inward ? 0 : costs.bend);
|
|
83
|
+
const done = stateCount + finished.size;
|
|
84
|
+
finished.set(done, { state, port });
|
|
85
|
+
heap.push(done, total);
|
|
86
|
+
}
|
|
87
|
+
for (let turn = 0; turn < 4; turn++) {
|
|
88
|
+
if (turn === (direction + 2) % 4)
|
|
89
|
+
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))
|
|
95
|
+
continue;
|
|
96
|
+
if (grid.blocked((here.x + there.x) / 2, (here.y + there.y) / 2))
|
|
97
|
+
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);
|
|
100
|
+
const nextState = next * 4 + turn;
|
|
101
|
+
const known = best.get(nextState);
|
|
102
|
+
if (known !== undefined && known <= nextCost)
|
|
103
|
+
continue;
|
|
104
|
+
best.set(nextState, nextCost);
|
|
105
|
+
parent.set(nextState, state);
|
|
106
|
+
heap.push(nextState, nextCost + TIE_BREAK * heuristic(there));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
function rebuild(grid, parent, sourceOf, last, target) {
|
|
112
|
+
const nodes = [];
|
|
113
|
+
let state = last;
|
|
114
|
+
while (parent.has(state)) {
|
|
115
|
+
nodes.push(grid.point(Math.floor(state / 4)));
|
|
116
|
+
state = parent.get(state);
|
|
117
|
+
}
|
|
118
|
+
nodes.push(grid.point(Math.floor(state / 4)));
|
|
119
|
+
nodes.reverse();
|
|
120
|
+
const source = sourceOf.get(state);
|
|
121
|
+
return simplify([{ ...source.at }, ...nodes, { ...target.at }]);
|
|
122
|
+
}
|
|
123
|
+
/** Without repeated points and without points in the middle of a straight line. */
|
|
124
|
+
export function simplify(points) {
|
|
125
|
+
const distinct = points.filter((p, i) => i === 0 || Math.abs(p.x - points[i - 1].x) > 1e-6 || Math.abs(p.y - points[i - 1].y) > 1e-6);
|
|
126
|
+
return distinct.filter((p, i) => {
|
|
127
|
+
if (i === 0 || i === distinct.length - 1)
|
|
128
|
+
return true;
|
|
129
|
+
const a = distinct[i - 1];
|
|
130
|
+
const b = distinct[i + 1];
|
|
131
|
+
return !((Math.abs(a.x - p.x) < 1e-6 && Math.abs(b.x - p.x) < 1e-6) || (Math.abs(a.y - p.y) < 1e-6 && Math.abs(b.y - p.y) < 1e-6));
|
|
132
|
+
});
|
|
133
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export interface Point {
|
|
2
|
+
x: number;
|
|
3
|
+
y: number;
|
|
4
|
+
}
|
|
5
|
+
export interface Box {
|
|
6
|
+
x: number;
|
|
7
|
+
y: number;
|
|
8
|
+
width: number;
|
|
9
|
+
height: number;
|
|
10
|
+
}
|
|
11
|
+
export type Side = 'top' | 'right' | 'bottom' | 'left';
|
|
12
|
+
export interface Shape extends Box {
|
|
13
|
+
id: string;
|
|
14
|
+
/**
|
|
15
|
+
* `obstacle` (the default): connectors go around the shape.
|
|
16
|
+
* `cluster`: a group drawn around other shapes. Connectors may cross it, but each entry costs
|
|
17
|
+
* `clusterCrossingPenalty`, so a connector goes around a cluster that it does not start or end in.
|
|
18
|
+
*/
|
|
19
|
+
kind?: 'obstacle' | 'cluster';
|
|
20
|
+
}
|
|
21
|
+
export interface ConnectorEnd {
|
|
22
|
+
/** The id of the shape. */
|
|
23
|
+
shape: string;
|
|
24
|
+
/** The sides the connector may attach to. Default: all four. */
|
|
25
|
+
sides?: Side[];
|
|
26
|
+
}
|
|
27
|
+
export interface Connector {
|
|
28
|
+
id: string;
|
|
29
|
+
source: ConnectorEnd;
|
|
30
|
+
target: ConnectorEnd;
|
|
31
|
+
}
|
|
32
|
+
export interface RouterOptions {
|
|
33
|
+
/** The clear space kept around each obstacle. Default 8. */
|
|
34
|
+
buffer?: number;
|
|
35
|
+
/** The cost of a bend, in the same units as length. Default 40. */
|
|
36
|
+
bendPenalty?: number;
|
|
37
|
+
/** The cost of each entry into a cluster. Default 400. */
|
|
38
|
+
clusterCrossingPenalty?: number;
|
|
39
|
+
/** The distance between parallel segments that share a track. Default 6. */
|
|
40
|
+
spacing?: number;
|
|
41
|
+
/** The search steps allowed for one connector before it fails. Default 200000. */
|
|
42
|
+
maxExpansions?: number;
|
|
43
|
+
/**
|
|
44
|
+
* How far a route may first stray from the box around its ends. Only when no route lies in that area does the
|
|
45
|
+
* search use the whole diagram. Default 400.
|
|
46
|
+
*/
|
|
47
|
+
windowMargin?: number;
|
|
48
|
+
}
|
|
49
|
+
export interface RouteResult {
|
|
50
|
+
/** Each routed connector's points, from the source shape's border to the target shape's border. */
|
|
51
|
+
routes: Map<string, Point[]>;
|
|
52
|
+
/** The connectors with no route: an unknown shape, a loop, or no path. */
|
|
53
|
+
failed: string[];
|
|
54
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "orthogonal-router",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Routes connectors between rectangles in right angles, around obstacles, and spreads apart the lines that share a track. No dependencies.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Matthew Bain <matt@rocketstack.co>",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/rocketstack-matt/orthogonal-router.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/rocketstack-matt/orthogonal-router#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/rocketstack-matt/orthogonal-router/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"keywords": [
|
|
29
|
+
"orthogonal",
|
|
30
|
+
"edge routing",
|
|
31
|
+
"connector",
|
|
32
|
+
"diagram",
|
|
33
|
+
"graph",
|
|
34
|
+
"layout",
|
|
35
|
+
"manhattan",
|
|
36
|
+
"libavoid"
|
|
37
|
+
],
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=22"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc -p tsconfig.build.json",
|
|
43
|
+
"typecheck": "tsc --noEmit",
|
|
44
|
+
"test": "vitest run",
|
|
45
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build",
|
|
46
|
+
"example": "npm run build && node examples/architecture.mjs"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"typescript": "^7.0.2",
|
|
50
|
+
"vitest": "^5.1.2"
|
|
51
|
+
}
|
|
52
|
+
}
|