@vizhub/quadstream 0.0.0-stage → 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/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +396 -2
- package/bin/quadstream.mjs +240 -0
- package/dist/adapters.d.ts +26 -0
- package/dist/adapters.js +229 -0
- package/dist/blg.d.ts +17 -0
- package/dist/blg.js +83 -0
- package/dist/dataset.d.ts +16 -0
- package/dist/dataset.js +61 -0
- package/dist/geometry.d.ts +13 -0
- package/dist/geometry.js +126 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +15 -0
- package/dist/loader.d.ts +34 -0
- package/dist/loader.js +138 -0
- package/dist/manifest-schema.d.ts +4 -0
- package/dist/manifest-schema.js +141 -0
- package/dist/maplibre-adapter.d.ts +30 -0
- package/dist/maplibre-adapter.js +84 -0
- package/dist/partition.d.ts +13 -0
- package/dist/partition.js +124 -0
- package/dist/progressive-map.d.ts +28 -0
- package/dist/progressive-map.js +112 -0
- package/dist/quadtree.d.ts +8 -0
- package/dist/quadtree.js +50 -0
- package/dist/reconstruct.d.ts +13 -0
- package/dist/reconstruct.js +106 -0
- package/dist/session.d.ts +24 -0
- package/dist/session.js +116 -0
- package/dist/spatial-index.d.ts +9 -0
- package/dist/spatial-index.js +63 -0
- package/dist/spherical-dataset.d.ts +31 -0
- package/dist/spherical-dataset.js +284 -0
- package/dist/spherical-geometry.d.ts +39 -0
- package/dist/spherical-geometry.js +197 -0
- package/dist/topology.d.ts +11 -0
- package/dist/topology.js +229 -0
- package/dist/types.d.ts +119 -0
- package/dist/types.js +1 -0
- package/package.json +75 -4
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { buildTopologyWithPolicy } from "./topology.js";
|
|
2
|
+
import { decodeTopoJSON } from "./adapters.js";
|
|
3
|
+
import { buildArcTrees, reconstructFeature } from "./reconstruct.js";
|
|
4
|
+
import { signedArea } from "./geometry.js";
|
|
5
|
+
import { canonicalLonLat, buildSphericalPriorities, projectSpherical, validGreatCirclePath, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
|
|
6
|
+
function polygons(g) {
|
|
7
|
+
return g.type === "Polygon"
|
|
8
|
+
? [g.coordinates]
|
|
9
|
+
: g.type === "MultiPolygon"
|
|
10
|
+
? g.coordinates
|
|
11
|
+
: [];
|
|
12
|
+
}
|
|
13
|
+
function lines(g) {
|
|
14
|
+
return g.type === "LineString"
|
|
15
|
+
? [g.coordinates]
|
|
16
|
+
: g.type === "MultiLineString"
|
|
17
|
+
? g.coordinates
|
|
18
|
+
: [];
|
|
19
|
+
}
|
|
20
|
+
function canonicalGeometry(g) {
|
|
21
|
+
switch (g.type) {
|
|
22
|
+
case "LineString":
|
|
23
|
+
return { type: g.type, coordinates: g.coordinates.map(canonicalLonLat) };
|
|
24
|
+
case "MultiLineString":
|
|
25
|
+
return {
|
|
26
|
+
type: g.type,
|
|
27
|
+
coordinates: g.coordinates.map((p) => p.map(canonicalLonLat)),
|
|
28
|
+
};
|
|
29
|
+
case "Polygon":
|
|
30
|
+
return {
|
|
31
|
+
type: g.type,
|
|
32
|
+
coordinates: g.coordinates.map((p) => p.map(canonicalLonLat)),
|
|
33
|
+
};
|
|
34
|
+
case "MultiPolygon":
|
|
35
|
+
return {
|
|
36
|
+
type: g.type,
|
|
37
|
+
coordinates: g.coordinates.map((p) => p.map((r) => r.map(canonicalLonLat))),
|
|
38
|
+
};
|
|
39
|
+
default:
|
|
40
|
+
throw new Error("Unsupported spherical geometry");
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function sourceGeometry(input) {
|
|
44
|
+
if (input?.type !== "FeatureCollection" ||
|
|
45
|
+
!Array.isArray(input.features) ||
|
|
46
|
+
!input.features.length)
|
|
47
|
+
throw new Error("Expected nonempty geographic FeatureCollection");
|
|
48
|
+
return {
|
|
49
|
+
type: "FeatureCollection",
|
|
50
|
+
features: input.features.map((f) => {
|
|
51
|
+
if (f?.type !== "Feature" || !f.geometry)
|
|
52
|
+
throw new Error("Expected geographic feature");
|
|
53
|
+
return {
|
|
54
|
+
...f,
|
|
55
|
+
properties: f.properties === null ? null : { ...f.properties },
|
|
56
|
+
geometry: canonicalGeometry(f.geometry),
|
|
57
|
+
};
|
|
58
|
+
}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function topology(input) {
|
|
62
|
+
return buildTopologyWithPolicy(input, {
|
|
63
|
+
position: canonicalLonLat,
|
|
64
|
+
ring: (r) => validSphericalPolygon([[...r]]),
|
|
65
|
+
polygon: (r) => validSphericalPolygon(r),
|
|
66
|
+
line: validGreatCirclePath,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function preserveSphericalValidity(topology, source, signatures) {
|
|
70
|
+
const vertexByPosition = new Map(topology.vertices.map((v) => [
|
|
71
|
+
JSON.stringify(canonicalLonLat([v.x, v.y])),
|
|
72
|
+
v,
|
|
73
|
+
]));
|
|
74
|
+
source.features.forEach((feature, featureIndex) => {
|
|
75
|
+
polygons(feature.geometry).forEach((rings, polygonIndex) => {
|
|
76
|
+
rings.forEach((ring, ringIndex) => {
|
|
77
|
+
const ids = ring
|
|
78
|
+
.slice(0, -1)
|
|
79
|
+
.map((p) => vertexByPosition.get(JSON.stringify(p))?.id);
|
|
80
|
+
const projected = ring.map((p) => projectSpherical(p, signatures[featureIndex][polygonIndex].chart)), area = signedArea(projected), sourceSign = signatures[featureIndex][polygonIndex].signs[ringIndex];
|
|
81
|
+
ids.forEach((id, i) => {
|
|
82
|
+
if (id === undefined)
|
|
83
|
+
return;
|
|
84
|
+
const previous = projected[(i + projected.length - 2) % (projected.length - 1)], current = projected[i], next = projected[(i + 1) % (projected.length - 1)], removed = current[0] * next[1] -
|
|
85
|
+
current[1] * next[0] -
|
|
86
|
+
(previous[0] * current[1] - previous[1] * current[0]) +
|
|
87
|
+
(previous[0] * next[1] - previous[1] * next[0]), candidateArea = area - removed / 2;
|
|
88
|
+
let invalidCandidate = false;
|
|
89
|
+
if (ring.length <= 32) {
|
|
90
|
+
const points = [...ring.slice(0, i), ...ring.slice(i + 1, -1)], candidate = [...points, points[0]], candidateRings = rings.map((r, j) => j === ringIndex ? candidate : r);
|
|
91
|
+
invalidCandidate = !validSphericalPolygon(candidateRings, signatures[featureIndex]?.[polygonIndex]);
|
|
92
|
+
}
|
|
93
|
+
if (ring.length <= 4 ||
|
|
94
|
+
Math.sign(candidateArea) !== sourceSign ||
|
|
95
|
+
candidateArea === 0 ||
|
|
96
|
+
invalidCandidate)
|
|
97
|
+
topology.vertices[id].critical = true;
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/** Explicit geographic import: decode only the selected object and validate minor arcs. */
|
|
104
|
+
export function importSphericalTopoJSON(input, objectName) {
|
|
105
|
+
const decoded = sourceGeometry(decodeTopoJSON(input, objectName, canonicalLonLat));
|
|
106
|
+
for (const f of decoded.features)
|
|
107
|
+
for (const p of polygons(f.geometry))
|
|
108
|
+
sphericalPolygonSignature(p);
|
|
109
|
+
topology(decoded);
|
|
110
|
+
return decoded;
|
|
111
|
+
}
|
|
112
|
+
/** Geographic in-memory dataset. No planar viewport index or v1 partition serialization. */
|
|
113
|
+
export class SphericalQuadstreamDataset {
|
|
114
|
+
coordinateMode = "spherical-d3";
|
|
115
|
+
topology;
|
|
116
|
+
priorities;
|
|
117
|
+
arcTrees;
|
|
118
|
+
source;
|
|
119
|
+
signatures;
|
|
120
|
+
constructor(input, { maxLevel = 20 } = {}) {
|
|
121
|
+
this.source = sourceGeometry(input);
|
|
122
|
+
this.signatures = this.source.features.map((f) => polygons(f.geometry).map((p) => sphericalPolygonSignature(p)));
|
|
123
|
+
this.topology = topology(this.source);
|
|
124
|
+
preserveSphericalValidity(this.topology, this.source, this.signatures);
|
|
125
|
+
this.priorities = buildSphericalPriorities(this.topology.vertices, maxLevel);
|
|
126
|
+
this.arcTrees = buildArcTrees(this.topology.arcs, this.priorities.levelByVertexId, this.topology.vertices.map((v) => v.critical));
|
|
127
|
+
}
|
|
128
|
+
query(options = {}) {
|
|
129
|
+
if ("bounds" in options || "validate" in options)
|
|
130
|
+
throw new Error("Spherical queries require global validated retrieval");
|
|
131
|
+
const level = options.level ?? this.priorities.maxLevel - 1;
|
|
132
|
+
if (!Number.isFinite(level) ||
|
|
133
|
+
level < 0 ||
|
|
134
|
+
level >= this.priorities.maxLevel)
|
|
135
|
+
throw new Error("Invalid spherical query level");
|
|
136
|
+
const lookup = (id) => {
|
|
137
|
+
const v = this.topology.vertices[id];
|
|
138
|
+
return v ? [v.x, v.y] : undefined;
|
|
139
|
+
};
|
|
140
|
+
const full = this.priorities.maxLevel - 1;
|
|
141
|
+
const promoted = new Map();
|
|
142
|
+
let promotedArcs = 0;
|
|
143
|
+
const levelOf = (arcId) => promoted.get(arcId) ?? level;
|
|
144
|
+
const check = (i, r) => {
|
|
145
|
+
const p = polygons(r.feature.geometry), s = this.signatures[i];
|
|
146
|
+
return (!r.missing &&
|
|
147
|
+
p.length === s.length &&
|
|
148
|
+
p.every((g, j) => validSphericalPolygon(g, s[j])) &&
|
|
149
|
+
lines(r.feature.geometry).every(validGreatCirclePath));
|
|
150
|
+
};
|
|
151
|
+
const run = (f) => reconstructFeature(f, this.topology.arcs, this.arcTrees, levelOf, lookup, false, false);
|
|
152
|
+
const results = this.topology.features.map(run);
|
|
153
|
+
const ok = results.map((r, i) => check(i, r));
|
|
154
|
+
// Repair: promote every arc of an invalid feature to the next integer
|
|
155
|
+
// level. Arcs are shared, so neighbours always see the same selection.
|
|
156
|
+
for (let pass = 0; pass <= full + 1; pass++) {
|
|
157
|
+
const touched = new Set();
|
|
158
|
+
ok.forEach((good, i) => {
|
|
159
|
+
if (good)
|
|
160
|
+
return;
|
|
161
|
+
for (const path of this.topology.features[i].paths)
|
|
162
|
+
for (const ref of path.arcs) {
|
|
163
|
+
const id = Math.abs(ref) - 1, cur = levelOf(id);
|
|
164
|
+
if (cur >= full)
|
|
165
|
+
continue;
|
|
166
|
+
promoted.set(id, Math.min(full, Math.floor(cur) + 1));
|
|
167
|
+
touched.add(id);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
if (!touched.size)
|
|
171
|
+
break;
|
|
172
|
+
promotedArcs = promoted.size;
|
|
173
|
+
this.topology.features.forEach((f, i) => {
|
|
174
|
+
if (f.paths.some((p) => p.arcs.some((r) => touched.has(Math.abs(r) - 1)))) {
|
|
175
|
+
results[i] = run(f);
|
|
176
|
+
ok[i] = check(i, results[i]);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
const valid = ok.every(Boolean);
|
|
181
|
+
return this.formatResult(level, results, valid, promotedArcs);
|
|
182
|
+
}
|
|
183
|
+
formatResult(level, results, valid, promotedArcs) {
|
|
184
|
+
return {
|
|
185
|
+
geojson: {
|
|
186
|
+
type: "FeatureCollection",
|
|
187
|
+
features: results.map((r, i) => {
|
|
188
|
+
const f = this.source.features[i];
|
|
189
|
+
return {
|
|
190
|
+
type: "Feature",
|
|
191
|
+
...(f.id === undefined ? {} : { id: f.id }),
|
|
192
|
+
properties: f.properties === null ? null : { ...f.properties },
|
|
193
|
+
geometry: r.feature.geometry,
|
|
194
|
+
};
|
|
195
|
+
}),
|
|
196
|
+
},
|
|
197
|
+
level,
|
|
198
|
+
valid,
|
|
199
|
+
promotedArcs,
|
|
200
|
+
usedFallback: false,
|
|
201
|
+
selectedFeatures: results.length,
|
|
202
|
+
selectedVertices: results.reduce((n, r) => n + r.selectedVertices, 0),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
async queryInterruptible(options = {}) {
|
|
206
|
+
if ("bounds" in options || "validate" in options)
|
|
207
|
+
throw new Error("Spherical queries require global validated retrieval");
|
|
208
|
+
const { level: requested, shouldAbort, yieldTurn, sliceMs = 8 } = options;
|
|
209
|
+
const level = requested ?? this.priorities.maxLevel - 1;
|
|
210
|
+
if (!Number.isFinite(level) ||
|
|
211
|
+
level < 0 ||
|
|
212
|
+
level >= this.priorities.maxLevel)
|
|
213
|
+
throw new Error("Invalid spherical query level");
|
|
214
|
+
if (shouldAbort?.())
|
|
215
|
+
return null;
|
|
216
|
+
const lookup = (id) => {
|
|
217
|
+
const v = this.topology.vertices[id];
|
|
218
|
+
return v ? [v.x, v.y] : undefined;
|
|
219
|
+
};
|
|
220
|
+
const full = this.priorities.maxLevel - 1;
|
|
221
|
+
const promoted = new Map();
|
|
222
|
+
let promotedArcs = 0;
|
|
223
|
+
const levelOf = (arcId) => promoted.get(arcId) ?? level;
|
|
224
|
+
const check = (i, r) => {
|
|
225
|
+
const p = polygons(r.feature.geometry), s = this.signatures[i];
|
|
226
|
+
return (!r.missing &&
|
|
227
|
+
p.length === s.length &&
|
|
228
|
+
p.every((g, j) => validSphericalPolygon(g, s[j])) &&
|
|
229
|
+
lines(r.feature.geometry).every(validGreatCirclePath));
|
|
230
|
+
};
|
|
231
|
+
const run = (f) => reconstructFeature(f, this.topology.arcs, this.arcTrees, levelOf, lookup, false, false);
|
|
232
|
+
const results = [];
|
|
233
|
+
const ok = [];
|
|
234
|
+
let sliceStart = performance.now();
|
|
235
|
+
for (let i = 0; i < this.topology.features.length; i++) {
|
|
236
|
+
const r = run(this.topology.features[i]);
|
|
237
|
+
results.push(r);
|
|
238
|
+
ok.push(check(i, r));
|
|
239
|
+
if (yieldTurn && performance.now() - sliceStart >= sliceMs) {
|
|
240
|
+
await yieldTurn();
|
|
241
|
+
if (shouldAbort?.())
|
|
242
|
+
return null;
|
|
243
|
+
sliceStart = performance.now();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
for (let pass = 0; pass <= full + 1; pass++) {
|
|
247
|
+
const touched = new Set();
|
|
248
|
+
ok.forEach((good, i) => {
|
|
249
|
+
if (good)
|
|
250
|
+
return;
|
|
251
|
+
for (const path of this.topology.features[i].paths)
|
|
252
|
+
for (const ref of path.arcs) {
|
|
253
|
+
const id = Math.abs(ref) - 1, cur = levelOf(id);
|
|
254
|
+
if (cur >= full)
|
|
255
|
+
continue;
|
|
256
|
+
promoted.set(id, Math.min(full, Math.floor(cur) + 1));
|
|
257
|
+
touched.add(id);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
if (!touched.size)
|
|
261
|
+
break;
|
|
262
|
+
promotedArcs = promoted.size;
|
|
263
|
+
for (let i = 0; i < this.topology.features.length; i++) {
|
|
264
|
+
const f = this.topology.features[i];
|
|
265
|
+
if (f.paths.some((p) => p.arcs.some((r) => touched.has(Math.abs(r) - 1)))) {
|
|
266
|
+
results[i] = run(f);
|
|
267
|
+
ok[i] = check(i, results[i]);
|
|
268
|
+
if (yieldTurn && performance.now() - sliceStart >= sliceMs) {
|
|
269
|
+
await yieldTurn();
|
|
270
|
+
if (shouldAbort?.())
|
|
271
|
+
return null;
|
|
272
|
+
sliceStart = performance.now();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (shouldAbort?.())
|
|
278
|
+
return null;
|
|
279
|
+
return this.formatResult(level, results, ok.every(Boolean), promotedArcs);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
export function buildSphericalQuadstream(input, options) {
|
|
283
|
+
return new SphericalQuadstreamDataset(input, options);
|
|
284
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Position, Vertex } from "./types.js";
|
|
2
|
+
export type UnitVector = readonly [number, number, number];
|
|
3
|
+
/** Exact seam aliases only; no near-coordinate snapping. */
|
|
4
|
+
export declare function canonicalLonLat(value: unknown): Position;
|
|
5
|
+
export declare function lonLatVector(p: Position): UnitVector;
|
|
6
|
+
export declare function angularDistance(a: Position, b: Position): number;
|
|
7
|
+
export declare function validGreatCirclePath(path: readonly Position[]): boolean;
|
|
8
|
+
export type CubeFace = "+X" | "-X" | "+Y" | "-Y" | "+Z" | "-Z";
|
|
9
|
+
export interface SphericalCell {
|
|
10
|
+
vertexId: number;
|
|
11
|
+
face: CubeFace;
|
|
12
|
+
level: number;
|
|
13
|
+
i: number;
|
|
14
|
+
j: number;
|
|
15
|
+
key: string;
|
|
16
|
+
}
|
|
17
|
+
export interface SphericalPriorities {
|
|
18
|
+
maxLevel: number;
|
|
19
|
+
cells: SphericalCell[];
|
|
20
|
+
levelByVertexId: number[];
|
|
21
|
+
}
|
|
22
|
+
export declare function sphericalCellAddress(p: Position, level: number): Omit<SphericalCell, "vertexId">;
|
|
23
|
+
export declare function buildSphericalPriorities(vertices: readonly Vertex[], maxLevel?: number): SphericalPriorities;
|
|
24
|
+
/** Conservative reference chart: minor geodesics become straight segments in an open hemisphere. */
|
|
25
|
+
export interface SphericalChart {
|
|
26
|
+
center: UnitVector;
|
|
27
|
+
east: UnitVector;
|
|
28
|
+
north: UnitVector;
|
|
29
|
+
}
|
|
30
|
+
export declare function sphericalChart(ring: readonly Position[]): SphericalChart;
|
|
31
|
+
export declare function projectSpherical(p: Position, chart: SphericalChart): Position;
|
|
32
|
+
export interface SphericalPolygonSignature {
|
|
33
|
+
chart: SphericalChart;
|
|
34
|
+
signs: number[];
|
|
35
|
+
}
|
|
36
|
+
/** D3 convention: clockwise shell denotes the small interior. Counterclockwise
|
|
37
|
+
* shells denote the complement; complement polygons with holes are not supported. */
|
|
38
|
+
export declare function sphericalPolygonSignature(rings: readonly Position[][], chart?: SphericalChart): SphericalPolygonSignature;
|
|
39
|
+
export declare function validSphericalPolygon(rings: readonly Position[][], source?: SphericalPolygonSignature): boolean;
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { simpleClosedRing, validPolygon, signedArea } from "./geometry.js";
|
|
2
|
+
const rad = Math.PI / 180;
|
|
3
|
+
const eps = 1e-10;
|
|
4
|
+
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
5
|
+
const cross = (a, b) => [
|
|
6
|
+
a[1] * b[2] - a[2] * b[1],
|
|
7
|
+
a[2] * b[0] - a[0] * b[2],
|
|
8
|
+
a[0] * b[1] - a[1] * b[0],
|
|
9
|
+
];
|
|
10
|
+
const norm = (a) => Math.hypot(...a);
|
|
11
|
+
function unit(a) {
|
|
12
|
+
const n = norm(a);
|
|
13
|
+
if (n < eps)
|
|
14
|
+
throw new Error("Ambiguous spherical direction");
|
|
15
|
+
return [a[0] / n, a[1] / n, a[2] / n];
|
|
16
|
+
}
|
|
17
|
+
/** Exact seam aliases only; no near-coordinate snapping. */
|
|
18
|
+
export function canonicalLonLat(value) {
|
|
19
|
+
if (!Array.isArray(value) ||
|
|
20
|
+
value.length !== 2 ||
|
|
21
|
+
!value.every((x) => typeof x === "number" && Number.isFinite(x)))
|
|
22
|
+
throw new Error("Expected finite longitude/latitude pair");
|
|
23
|
+
const [lon, lat] = value;
|
|
24
|
+
if (lon < -180 || lon > 180 || lat < -90 || lat > 90)
|
|
25
|
+
throw new Error("Longitude/latitude outside geographic range");
|
|
26
|
+
return [
|
|
27
|
+
Math.abs(lat) === 90 ? 0 : lon === 180 ? -180 : lon === 0 ? 0 : lon,
|
|
28
|
+
lat === 0 ? 0 : lat,
|
|
29
|
+
];
|
|
30
|
+
}
|
|
31
|
+
export function lonLatVector(p) {
|
|
32
|
+
const [lon, lat] = canonicalLonLat(p);
|
|
33
|
+
if (Math.abs(lat) === 90)
|
|
34
|
+
return [0, 0, Math.sign(lat)];
|
|
35
|
+
const c = Math.cos(lat * rad), z = Math.sin(lat * rad);
|
|
36
|
+
// Exact cardinal meridians lie on cube-cell boundaries. Avoid trig
|
|
37
|
+
// residuals such as sin(-pi), without snapping nearby longitudes.
|
|
38
|
+
switch (lon) {
|
|
39
|
+
case -180:
|
|
40
|
+
return [-c, 0, z];
|
|
41
|
+
case -90:
|
|
42
|
+
return [0, -c, z];
|
|
43
|
+
case 0:
|
|
44
|
+
return [c, 0, z];
|
|
45
|
+
case 90:
|
|
46
|
+
return [0, c, z];
|
|
47
|
+
default:
|
|
48
|
+
return [c * Math.cos(lon * rad), c * Math.sin(lon * rad), z];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export function angularDistance(a, b) {
|
|
52
|
+
const u = lonLatVector(a), v = lonLatVector(b);
|
|
53
|
+
return Math.atan2(norm(cross(u, v)), dot(u, v));
|
|
54
|
+
}
|
|
55
|
+
export function validGreatCirclePath(path) {
|
|
56
|
+
if (path.length < 2)
|
|
57
|
+
return false;
|
|
58
|
+
for (let i = 1; i < path.length; i++) {
|
|
59
|
+
const d = angularDistance(path[i - 1], path[i]);
|
|
60
|
+
if (d <= eps || Math.PI - d <= eps)
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
export function sphericalCellAddress(p, level) {
|
|
66
|
+
if (!Number.isInteger(level) || level < 0 || level > 25)
|
|
67
|
+
throw new Error("Spherical level must be 0..25");
|
|
68
|
+
const [x, y, z] = lonLatVector(p);
|
|
69
|
+
// Fixed axis order breaks exact and roundoff-sized seam ties.
|
|
70
|
+
const m = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
|
|
71
|
+
let face, u, v;
|
|
72
|
+
if (m - Math.abs(x) <= 1e-15) {
|
|
73
|
+
face = x >= 0 ? "+X" : "-X";
|
|
74
|
+
u = y / Math.abs(x);
|
|
75
|
+
v = z / Math.abs(x);
|
|
76
|
+
}
|
|
77
|
+
else if (m - Math.abs(y) <= 1e-15) {
|
|
78
|
+
face = y >= 0 ? "+Y" : "-Y";
|
|
79
|
+
u = x / Math.abs(y);
|
|
80
|
+
v = z / Math.abs(y);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
face = z >= 0 ? "+Z" : "-Z";
|
|
84
|
+
u = x / Math.abs(z);
|
|
85
|
+
v = y / Math.abs(z);
|
|
86
|
+
}
|
|
87
|
+
const side = 2 ** level, cell = (t) => Math.max(0, Math.min(side - 1, Math.floor(((t + 1) * side) / 2)));
|
|
88
|
+
const i = cell(u), j = cell(v);
|
|
89
|
+
return { face, level, i, j, key: face + ":" + level + ":" + i + ":" + j };
|
|
90
|
+
}
|
|
91
|
+
export function buildSphericalPriorities(vertices, maxLevel = 20) {
|
|
92
|
+
if (!Number.isInteger(maxLevel) || maxLevel < 1 || maxLevel > 26)
|
|
93
|
+
throw new Error("maxLevel must be 1..26");
|
|
94
|
+
const seen = new Set(), ids = new Set();
|
|
95
|
+
const sorted = vertices
|
|
96
|
+
.map((v) => {
|
|
97
|
+
const [x, y] = canonicalLonLat([v.x, v.y]);
|
|
98
|
+
const k = JSON.stringify([x, y]);
|
|
99
|
+
if (seen.has(k) ||
|
|
100
|
+
!Number.isSafeInteger(v.id) ||
|
|
101
|
+
v.id < 0 ||
|
|
102
|
+
v.id >= vertices.length ||
|
|
103
|
+
ids.has(v.id))
|
|
104
|
+
throw new Error("Expected distinct canonical vertices and dense IDs");
|
|
105
|
+
seen.add(k);
|
|
106
|
+
ids.add(v.id);
|
|
107
|
+
return { ...v, x, y };
|
|
108
|
+
})
|
|
109
|
+
.sort((a, b) => Number(b.critical) - Number(a.critical) ||
|
|
110
|
+
a.x - b.x ||
|
|
111
|
+
a.y - b.y ||
|
|
112
|
+
a.id - b.id);
|
|
113
|
+
const occupied = new Set(), cells = [], levelByVertexId = [];
|
|
114
|
+
for (const v of sorted) {
|
|
115
|
+
let found = false;
|
|
116
|
+
for (let level = 0; level < maxLevel; level++) {
|
|
117
|
+
const c = sphericalCellAddress([v.x, v.y], level);
|
|
118
|
+
if (occupied.has(c.key))
|
|
119
|
+
continue;
|
|
120
|
+
occupied.add(c.key);
|
|
121
|
+
cells.push({ ...c, vertexId: v.id });
|
|
122
|
+
levelByVertexId[v.id] = level;
|
|
123
|
+
found = true;
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
if (!found)
|
|
127
|
+
throw new Error("Spherical quadtree capacity exceeded at vertex " + v.id);
|
|
128
|
+
}
|
|
129
|
+
cells.sort((a, b) => a.level - b.level ||
|
|
130
|
+
(a.face < b.face ? -1 : a.face > b.face ? 1 : 0) ||
|
|
131
|
+
a.i - b.i ||
|
|
132
|
+
a.j - b.j ||
|
|
133
|
+
a.vertexId - b.vertexId);
|
|
134
|
+
return { maxLevel, cells, levelByVertexId };
|
|
135
|
+
}
|
|
136
|
+
export function sphericalChart(ring) {
|
|
137
|
+
const points = ring.slice(0, -1).map(lonLatVector);
|
|
138
|
+
let sum = [0, 0, 0];
|
|
139
|
+
for (const p of points)
|
|
140
|
+
sum = [sum[0] + p[0], sum[1] + p[1], sum[2] + p[2]];
|
|
141
|
+
const center = unit(sum);
|
|
142
|
+
if (points.some((p) => dot(p, center) <= eps))
|
|
143
|
+
throw new Error("Ring outside supported open-hemisphere chart");
|
|
144
|
+
const ref = Math.abs(center[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0];
|
|
145
|
+
const east = unit(cross(ref, center)), north = cross(center, east);
|
|
146
|
+
return { center, east, north };
|
|
147
|
+
}
|
|
148
|
+
export function projectSpherical(p, chart) {
|
|
149
|
+
const v = lonLatVector(p), d = dot(v, chart.center);
|
|
150
|
+
if (d <= eps)
|
|
151
|
+
throw new Error("Position outside supported open-hemisphere chart");
|
|
152
|
+
return [dot(v, chart.east) / d, dot(v, chart.north) / d];
|
|
153
|
+
}
|
|
154
|
+
function ringOnChart(ring, chart) {
|
|
155
|
+
const p = ring.map(canonicalLonLat);
|
|
156
|
+
if (p.length < 4 ||
|
|
157
|
+
JSON.stringify(p[0]) !== JSON.stringify(p.at(-1)) ||
|
|
158
|
+
!validGreatCirclePath(p))
|
|
159
|
+
throw new Error("Invalid spherical ring");
|
|
160
|
+
const xy = p.map((v) => projectSpherical(v, chart));
|
|
161
|
+
if (!simpleClosedRing(xy) || Math.abs(signedArea(xy)) <= eps * eps)
|
|
162
|
+
throw new Error("Degenerate or self-intersecting spherical ring");
|
|
163
|
+
// Reject overlapping adjacent great-circle edges (including numerical near-overlap).
|
|
164
|
+
for (let i = 0; i < xy.length - 1; i++) {
|
|
165
|
+
const a = xy[(i + xy.length - 2) % (xy.length - 1)], b = xy[i], c = xy[i + 1];
|
|
166
|
+
const ux = a[0] - b[0], uy = a[1] - b[1], vx = c[0] - b[0], vy = c[1] - b[1];
|
|
167
|
+
if (ux * vx + uy * vy > 0 &&
|
|
168
|
+
Math.abs(ux * vy - uy * vx) <=
|
|
169
|
+
eps * Math.hypot(ux, uy) * Math.hypot(vx, vy))
|
|
170
|
+
throw new Error("Overlapping adjacent spherical edges");
|
|
171
|
+
}
|
|
172
|
+
return xy;
|
|
173
|
+
}
|
|
174
|
+
/** D3 convention: clockwise shell denotes the small interior. Counterclockwise
|
|
175
|
+
* shells denote the complement; complement polygons with holes are not supported. */
|
|
176
|
+
export function sphericalPolygonSignature(rings, chart) {
|
|
177
|
+
if (!rings.length)
|
|
178
|
+
throw new Error("Empty spherical polygon");
|
|
179
|
+
const c = chart ?? sphericalChart(rings[0]);
|
|
180
|
+
const xy = rings.map((r) => ringOnChart(r, c)), signs = xy.map((r) => Math.sign(signedArea(r)));
|
|
181
|
+
if (signs[0] === 1 && rings.length > 1)
|
|
182
|
+
throw new Error("Complement polygons with holes are unsupported");
|
|
183
|
+
if (signs.slice(1).some((s) => s === signs[0]) || !validPolygon(xy))
|
|
184
|
+
throw new Error("Invalid spherical hole winding or containment");
|
|
185
|
+
return { chart: c, signs };
|
|
186
|
+
}
|
|
187
|
+
export function validSphericalPolygon(rings, source) {
|
|
188
|
+
try {
|
|
189
|
+
const result = sphericalPolygonSignature(rings, source?.chart);
|
|
190
|
+
return (!source ||
|
|
191
|
+
(result.signs.length === source.signs.length &&
|
|
192
|
+
result.signs.every((s, i) => s === source.signs[i])));
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { FeatureCollection, Position, Topology } from "./types.js";
|
|
2
|
+
/** Exact coordinate topology: no implicit snapping, deduping almost-equal points, or antimeridian wrapping. */
|
|
3
|
+
export declare function buildTopology(input: FeatureCollection): Topology;
|
|
4
|
+
export interface TopologyPolicy {
|
|
5
|
+
position(value: unknown): Position;
|
|
6
|
+
ring(ring: readonly Position[]): boolean;
|
|
7
|
+
polygon(rings: readonly Position[][]): boolean;
|
|
8
|
+
line?(path: readonly Position[]): boolean;
|
|
9
|
+
}
|
|
10
|
+
/** Internal shared graph construction; coordinate semantics are provided by the caller. */
|
|
11
|
+
export declare function buildTopologyWithPolicy(input: FeatureCollection, policy: TopologyPolicy): Topology;
|