@vizhub/quadstream 0.3.0 → 1.0.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 +6 -0
- package/README.md +28 -624
- package/bin/quadstream.mjs +8 -6
- package/dist/blg.d.ts +3 -0
- package/dist/blg.js +14 -1
- package/dist/cooperative.d.ts +21 -0
- package/dist/cooperative.js +33 -0
- package/dist/dataset.d.ts +8 -4
- package/dist/dataset.js +51 -14
- package/dist/index.d.ts +5 -1
- package/dist/index.js +1 -0
- package/dist/loader.d.ts +1 -1
- package/dist/loader.js +1 -1
- package/dist/progressive-map.d.ts +1 -1
- package/dist/progressive-map.js +12 -8
- package/dist/quadtree.d.ts +2 -0
- package/dist/quadtree.js +12 -0
- package/dist/reconstruct.d.ts +3 -0
- package/dist/reconstruct.js +26 -3
- package/dist/session.d.ts +12 -9
- package/dist/session.js +24 -7
- package/dist/spherical-cull.js +15 -6
- package/dist/spherical-dataset.d.ts +13 -5
- package/dist/spherical-dataset.js +119 -41
- package/dist/spherical-geometry.d.ts +2 -0
- package/dist/spherical-geometry.js +11 -0
- package/dist/spherical-line.d.ts +29 -0
- package/dist/spherical-line.js +221 -0
- package/dist/spherical-preprocess.d.ts +6 -2
- package/dist/spherical-preprocess.js +34 -18
- package/dist/topology.d.ts +3 -0
- package/dist/topology.js +40 -9
- package/package.json +3 -2
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type CooperativeOptions } from "./cooperative.js";
|
|
1
2
|
import { type CollapsedRingPolicy } from "./reconstruct.js";
|
|
2
3
|
import type { SphericalPriorities } from "./spherical-geometry.js";
|
|
3
4
|
import type { FeatureCollection, QueryResult, Topology } from "./types.js";
|
|
@@ -13,7 +14,7 @@ export interface SphericalQueryOptions {
|
|
|
13
14
|
*/
|
|
14
15
|
collapsedRingPolicy?: CollapsedRingPolicy;
|
|
15
16
|
}
|
|
16
|
-
export interface SphericalInterruptOptions extends SphericalQueryOptions {
|
|
17
|
+
export interface SphericalInterruptOptions extends SphericalQueryOptions, CooperativeOptions {
|
|
17
18
|
shouldAbort?: () => boolean;
|
|
18
19
|
yieldTurn?: () => Promise<void>;
|
|
19
20
|
sliceMs?: number;
|
|
@@ -21,6 +22,12 @@ export interface SphericalInterruptOptions extends SphericalQueryOptions {
|
|
|
21
22
|
/** Optional preprocessing policy for explicitly retained polygon exteriors. */
|
|
22
23
|
export interface SphericalBuildOptions {
|
|
23
24
|
maxLevel?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Reuse the built topology and grow maxLevel on an explicit quadtree capacity
|
|
27
|
+
* failure, up to the supported maximum. Defaults to false so callers still
|
|
28
|
+
* observe the explicit failure.
|
|
29
|
+
*/
|
|
30
|
+
escalateCapacity?: boolean;
|
|
24
31
|
/** Feature ID to source polygon index; only the selected exterior is visible at level zero. */
|
|
25
32
|
alwaysVisiblePolygons?: ReadonlyMap<string, number>;
|
|
26
33
|
}
|
|
@@ -43,13 +50,14 @@ export declare class SphericalQuadstreamDataset {
|
|
|
43
50
|
readonly ringActivation: readonly (readonly number[])[];
|
|
44
51
|
private readonly source;
|
|
45
52
|
private readonly signatures;
|
|
46
|
-
constructor(
|
|
53
|
+
private constructor();
|
|
47
54
|
private pathActivation;
|
|
48
55
|
/** Nominal-level polygon eligibility, independent of corrected vertex thresholds. */
|
|
49
56
|
private visibility;
|
|
50
57
|
private session;
|
|
51
|
-
|
|
58
|
+
static create(input: FeatureCollection, options?: SphericalBuildOptions & CooperativeOptions): Promise<SphericalQuadstreamDataset>;
|
|
52
59
|
private formatResult;
|
|
53
|
-
|
|
60
|
+
query(options?: SphericalQueryOptions & CooperativeOptions): Promise<QueryResult>;
|
|
54
61
|
}
|
|
55
|
-
|
|
62
|
+
/** Cooperative construction with the same deterministic preparation algorithm. */
|
|
63
|
+
export declare function buildSphericalQuadstream(input: FeatureCollection, options?: SphericalBuildOptions & CooperativeOptions): Promise<SphericalQuadstreamDataset>;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { runSync, runCooperative, } from "./cooperative.js";
|
|
2
|
+
import { buildTopologyWithPolicy, buildTopologySteps } from "./topology.js";
|
|
2
3
|
import { decodeTopoJSON } from "./adapters.js";
|
|
3
|
-
import {
|
|
4
|
+
import { reconstructFeatureSteps, } from "./reconstruct.js";
|
|
4
5
|
import { stableBlgRandom } from "./blg.js";
|
|
5
|
-
import {
|
|
6
|
+
import { buildTopologySafeArcTreeSteps } from "./spherical-preprocess.js";
|
|
6
7
|
import { signedArea } from "./geometry.js";
|
|
7
|
-
import { canonicalLonLat,
|
|
8
|
+
import { canonicalLonLat, buildSphericalPrioritiesSteps, projectSpherical, validGreatCirclePath, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
|
|
8
9
|
function polygons(g) {
|
|
9
10
|
return g.type === "Polygon"
|
|
10
11
|
? [g.coordinates]
|
|
@@ -122,6 +123,51 @@ function activationLevel(level, random) {
|
|
|
122
123
|
? 0
|
|
123
124
|
: level - random + (random === 1 ? ACTIVATION_EPSILON : 0);
|
|
124
125
|
}
|
|
126
|
+
function* buildSphericalPrioritiesWithEscalation(vertices, maxLevel, escalateCapacity) {
|
|
127
|
+
for (let level = maxLevel;; level++) {
|
|
128
|
+
try {
|
|
129
|
+
return yield* buildSphericalPrioritiesSteps(vertices, level);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
const message = String(error?.message ?? error);
|
|
133
|
+
if (!escalateCapacity ||
|
|
134
|
+
!message.includes("capacity exceeded") ||
|
|
135
|
+
level >= 26)
|
|
136
|
+
throw error;
|
|
137
|
+
yield {
|
|
138
|
+
stage: "Increase regional resolution",
|
|
139
|
+
completed: level - maxLevel + 1,
|
|
140
|
+
total: 26 - maxLevel,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function* prepareSpherical(input, maxLevel, escalateCapacity = false) {
|
|
146
|
+
yield { stage: "Normalize geometry" };
|
|
147
|
+
const source = sourceGeometry(input);
|
|
148
|
+
const signatures = [];
|
|
149
|
+
for (const f of source.features) {
|
|
150
|
+
if (signatures.length % 32 === 0)
|
|
151
|
+
yield {
|
|
152
|
+
stage: "Validate source",
|
|
153
|
+
completed: signatures.length,
|
|
154
|
+
total: source.features.length,
|
|
155
|
+
};
|
|
156
|
+
signatures.push(polygons(f.geometry).map((p) => sphericalPolygonSignature(p)));
|
|
157
|
+
}
|
|
158
|
+
yield { stage: "Construct topology" };
|
|
159
|
+
const topology = yield* buildTopologySteps(source, {
|
|
160
|
+
position: canonicalLonLat,
|
|
161
|
+
ring: (r) => validSphericalPolygon([[...r]]),
|
|
162
|
+
polygon: (r) => validSphericalPolygon(r),
|
|
163
|
+
line: validGreatCirclePath,
|
|
164
|
+
});
|
|
165
|
+
yield { stage: "Preserve spherical validity" };
|
|
166
|
+
preserveSphericalValidity(topology, source, signatures);
|
|
167
|
+
const priorities = yield* buildSphericalPrioritiesWithEscalation(topology.vertices, maxLevel, escalateCapacity);
|
|
168
|
+
const prepared = yield* buildTopologySafeArcTreeSteps(topology, topology.vertices.map((v) => activationLevel(priorities.levelByVertexId[v.id], v.critical ? 1 : stableBlgRandom(v.id))), signatures);
|
|
169
|
+
return { source, signatures, topology, priorities, prepared };
|
|
170
|
+
}
|
|
125
171
|
/** Geographic in-memory dataset. No planar viewport index or v1 partition serialization. */
|
|
126
172
|
export class SphericalQuadstreamDataset {
|
|
127
173
|
coordinateMode = "spherical-d3";
|
|
@@ -141,16 +187,15 @@ export class SphericalQuadstreamDataset {
|
|
|
141
187
|
ringActivation;
|
|
142
188
|
source;
|
|
143
189
|
signatures;
|
|
144
|
-
constructor(input, { maxLevel = 20, alwaysVisiblePolygons } = {}) {
|
|
145
|
-
|
|
146
|
-
this.
|
|
147
|
-
this.
|
|
148
|
-
|
|
149
|
-
this.priorities =
|
|
150
|
-
|
|
151
|
-
this.
|
|
152
|
-
this.
|
|
153
|
-
this.retainedVertices = prepared.retainedVertices;
|
|
190
|
+
constructor(input, { maxLevel = 20, escalateCapacity = false, alwaysVisiblePolygons, } = {}, prepared) {
|
|
191
|
+
const state = prepared ?? runSync(prepareSpherical(input, maxLevel, escalateCapacity));
|
|
192
|
+
this.source = state.source;
|
|
193
|
+
this.signatures = state.signatures;
|
|
194
|
+
this.topology = state.topology;
|
|
195
|
+
this.priorities = state.priorities;
|
|
196
|
+
this.arcTrees = state.prepared.trees;
|
|
197
|
+
this.activationLevels = state.prepared.activationLevels;
|
|
198
|
+
this.retainedVertices = state.prepared.retainedVertices;
|
|
154
199
|
this.ringActivation = this.topology.features.map((f) => {
|
|
155
200
|
const polygon = alwaysVisiblePolygons?.get(f.id);
|
|
156
201
|
const exterior = polygon !== undefined &&
|
|
@@ -232,14 +277,24 @@ export class SphericalQuadstreamDataset {
|
|
|
232
277
|
p.length === s.length &&
|
|
233
278
|
p.every((g, j) => validSphericalPolygon(g, s[j])) &&
|
|
234
279
|
lines(r.feature.geometry).every(validGreatCirclePath));
|
|
235
|
-
}, run = (f, i) =>
|
|
280
|
+
}, run = (f, i) => reconstructFeatureSteps(f, this.topology.arcs, this.arcTrees, level, lookup, false, drop
|
|
236
281
|
? { collapsed: "drop", hiddenPaths: vis.hidden[i] }
|
|
237
282
|
: { collapsed: "drop" });
|
|
238
283
|
return { level, check, run, vis };
|
|
239
284
|
}
|
|
240
|
-
|
|
285
|
+
static async create(input, options = {}) {
|
|
286
|
+
const prepared = await runCooperative(prepareSpherical(input, options.maxLevel ?? 20, options.escalateCapacity), options);
|
|
287
|
+
options.signal?.throwIfAborted();
|
|
288
|
+
return new SphericalQuadstreamDataset(input, options, prepared);
|
|
289
|
+
}
|
|
290
|
+
/** @internal Synchronous reference for algorithm parity tests. */
|
|
291
|
+
static createSync(input, options) {
|
|
292
|
+
return new SphericalQuadstreamDataset(input, options);
|
|
293
|
+
}
|
|
294
|
+
/** @internal Synchronous reference for algorithm parity tests. */
|
|
295
|
+
querySync(options = {}) {
|
|
241
296
|
const s = this.session(options);
|
|
242
|
-
const results = this.topology.features.map(s.run);
|
|
297
|
+
const results = this.topology.features.map((f, i) => runSync(s.run(f, i)));
|
|
243
298
|
const valid = results.every((r, i) => s.check(i, r));
|
|
244
299
|
return this.formatResult(s, results, valid);
|
|
245
300
|
}
|
|
@@ -271,35 +326,58 @@ export class SphericalQuadstreamDataset {
|
|
|
271
326
|
selectedVertices: results.reduce((n, r) => n + r.selectedVertices, 0),
|
|
272
327
|
};
|
|
273
328
|
}
|
|
329
|
+
async query(options = {}) {
|
|
330
|
+
const result = await this.queryInterruptible(options);
|
|
331
|
+
if (!result)
|
|
332
|
+
throw new DOMException("Aborted", "AbortError");
|
|
333
|
+
return result;
|
|
334
|
+
}
|
|
335
|
+
/** @internal Adapter for the demo's latest-view scheduler. */
|
|
274
336
|
async queryInterruptible(options = {}) {
|
|
275
|
-
const { shouldAbort, yieldTurn, sliceMs =
|
|
276
|
-
const s = this.session(options);
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
let sliceStart = performance.now();
|
|
282
|
-
const tick = async () => {
|
|
283
|
-
if (yieldTurn && performance.now() - sliceStart >= sliceMs) {
|
|
284
|
-
await yieldTurn();
|
|
337
|
+
const { shouldAbort, yieldTurn, sliceMs = 4, signal, onProgress, onSlice, } = options;
|
|
338
|
+
const s = this.session(options), features = this.topology.features;
|
|
339
|
+
function* steps() {
|
|
340
|
+
const results = [];
|
|
341
|
+
let valid = true;
|
|
342
|
+
for (let i = 0; i < features.length; i++) {
|
|
285
343
|
if (shouldAbort?.())
|
|
286
|
-
return
|
|
287
|
-
|
|
344
|
+
return null;
|
|
345
|
+
const work = s.run(features[i], i);
|
|
346
|
+
let step = work.next();
|
|
347
|
+
try {
|
|
348
|
+
while (!step.done) {
|
|
349
|
+
if (shouldAbort?.())
|
|
350
|
+
return null;
|
|
351
|
+
yield step.value;
|
|
352
|
+
step = work.next();
|
|
353
|
+
}
|
|
354
|
+
results.push(step.value);
|
|
355
|
+
if (!s.check(i, step.value))
|
|
356
|
+
valid = false;
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
work.return(undefined);
|
|
360
|
+
}
|
|
288
361
|
}
|
|
289
|
-
|
|
290
|
-
};
|
|
291
|
-
for (let i = 0; i < this.topology.features.length; i++) {
|
|
292
|
-
const r = s.run(this.topology.features[i], i);
|
|
293
|
-
results.push(r);
|
|
294
|
-
ok.push(s.check(i, r));
|
|
295
|
-
if (!(await tick()))
|
|
362
|
+
if (shouldAbort?.())
|
|
296
363
|
return null;
|
|
364
|
+
return finish(results, valid);
|
|
297
365
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
366
|
+
const finish = (results, valid) => this.formatResult(s, results, valid);
|
|
367
|
+
return runCooperative(steps(), {
|
|
368
|
+
yieldTurn,
|
|
369
|
+
sliceMs,
|
|
370
|
+
signal,
|
|
371
|
+
onProgress,
|
|
372
|
+
onSlice,
|
|
373
|
+
});
|
|
301
374
|
}
|
|
302
375
|
}
|
|
303
|
-
|
|
304
|
-
|
|
376
|
+
/** @internal Synchronous reference for algorithm parity tests. */
|
|
377
|
+
export function buildSphericalQuadstreamSync(input, options) {
|
|
378
|
+
return SphericalQuadstreamDataset.createSync(input, options);
|
|
379
|
+
}
|
|
380
|
+
/** Cooperative construction with the same deterministic preparation algorithm. */
|
|
381
|
+
export async function buildSphericalQuadstream(input, options = {}) {
|
|
382
|
+
return SphericalQuadstreamDataset.create(input, options);
|
|
305
383
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Work } from "./cooperative.js";
|
|
1
2
|
import type { Position, Vertex } from "./types.js";
|
|
2
3
|
export type UnitVector = readonly [number, number, number];
|
|
3
4
|
/** Exact seam aliases only; no near-coordinate snapping. */
|
|
@@ -21,6 +22,7 @@ export interface SphericalPriorities {
|
|
|
21
22
|
}
|
|
22
23
|
export declare function sphericalCellAddress(p: Position, level: number): Omit<SphericalCell, "vertexId">;
|
|
23
24
|
export declare function buildSphericalPriorities(vertices: readonly Vertex[], maxLevel?: number): SphericalPriorities;
|
|
25
|
+
export declare function buildSphericalPrioritiesSteps(vertices: readonly Vertex[], maxLevel?: number): Work<SphericalPriorities>;
|
|
24
26
|
/** Conservative reference chart: minor geodesics become straight segments in an open hemisphere. */
|
|
25
27
|
export interface SphericalChart {
|
|
26
28
|
center: UnitVector;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { runSync } from "./cooperative.js";
|
|
1
2
|
import { simpleClosedRing, validPolygon, signedArea } from "./geometry.js";
|
|
2
3
|
const rad = Math.PI / 180;
|
|
3
4
|
const eps = 1e-10;
|
|
@@ -103,6 +104,9 @@ export function sphericalCellAddress(p, level) {
|
|
|
103
104
|
const SIDE_MAX = 2 ** 25;
|
|
104
105
|
const packCell = (face, i, j) => (face * SIDE_MAX + i) * SIDE_MAX + j;
|
|
105
106
|
export function buildSphericalPriorities(vertices, maxLevel = 20) {
|
|
107
|
+
return runSync(buildSphericalPrioritiesSteps(vertices, maxLevel));
|
|
108
|
+
}
|
|
109
|
+
export function* buildSphericalPrioritiesSteps(vertices, maxLevel = 20) {
|
|
106
110
|
if (!Number.isInteger(maxLevel) || maxLevel < 1 || maxLevel > 26)
|
|
107
111
|
throw new Error("maxLevel must be 1..26");
|
|
108
112
|
const seen = new Set(), ids = new Uint8Array(vertices.length);
|
|
@@ -131,7 +135,14 @@ export function buildSphericalPriorities(vertices, maxLevel = 20) {
|
|
|
131
135
|
a.y - b.y ||
|
|
132
136
|
a.id - b.id);
|
|
133
137
|
const occupied = Array.from({ length: maxLevel }, () => new Set()), sides = Array.from({ length: maxLevel }, (_, level) => 2 ** level), cells = [], levelByVertexId = [];
|
|
138
|
+
let processed = 0;
|
|
134
139
|
for (const v of sorted) {
|
|
140
|
+
if (processed++ % 512 === 0)
|
|
141
|
+
yield {
|
|
142
|
+
stage: "Spherical priorities",
|
|
143
|
+
completed: processed - 1,
|
|
144
|
+
total: sorted.length,
|
|
145
|
+
};
|
|
135
146
|
let found = false;
|
|
136
147
|
for (let level = 0; level < maxLevel; level++) {
|
|
137
148
|
const side = sides[level], i = cellIndex(v.face.u, side), j = cellIndex(v.face.v, side), packed = packCell(v.face.face, i, j);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Geometry, Position } from "./types.js";
|
|
2
|
+
import type { UnitVector } from "./spherical-geometry.js";
|
|
3
|
+
import type { SphericalViewCone } from "./spherical-cull.js";
|
|
4
|
+
type LineGeometry = Extract<Geometry, {
|
|
5
|
+
type: "LineString" | "MultiLineString";
|
|
6
|
+
}>;
|
|
7
|
+
export declare function edgeIntersectsCone(a: UnitVector, b: UnitVector, cone: SphericalViewCone): boolean;
|
|
8
|
+
export interface SphericalLineStats {
|
|
9
|
+
sourceVertices: number;
|
|
10
|
+
submittedVertices: number;
|
|
11
|
+
sourceSegments: number;
|
|
12
|
+
rejectedSegments: number;
|
|
13
|
+
clippedSegments: number;
|
|
14
|
+
visitedNodes: number;
|
|
15
|
+
rejectedLines: number;
|
|
16
|
+
cacheHit: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface SphericalLineResult {
|
|
19
|
+
geometry: {
|
|
20
|
+
type: "MultiLineString";
|
|
21
|
+
coordinates: Position[][];
|
|
22
|
+
};
|
|
23
|
+
stats: SphericalLineStats;
|
|
24
|
+
}
|
|
25
|
+
export declare function createSphericalLineClipper({ preserveSegments }?: {
|
|
26
|
+
preserveSegments?: boolean | undefined;
|
|
27
|
+
}): (geometry: LineGeometry, cone: SphericalViewCone) => SphericalLineResult;
|
|
28
|
+
export declare function clipLineToCone(coordinates: Position[], cone: SphericalViewCone): Position[][];
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { isCapVisible, lonLatToVec } from "./spherical-cull.js";
|
|
2
|
+
const EPS = 1e-12;
|
|
3
|
+
const TAU = 2 * Math.PI;
|
|
4
|
+
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
5
|
+
const clamp = (x) => Math.max(-1, Math.min(1, x));
|
|
6
|
+
const cross = (a, b) => [
|
|
7
|
+
a[1] * b[2] - a[2] * b[1],
|
|
8
|
+
a[2] * b[0] - a[0] * b[2],
|
|
9
|
+
a[0] * b[1] - a[1] * b[0],
|
|
10
|
+
];
|
|
11
|
+
const angle = (a, b) => Math.atan2(Math.hypot(...cross(a, b)), dot(a, b));
|
|
12
|
+
const unit = (a) => {
|
|
13
|
+
const length = Math.hypot(...a);
|
|
14
|
+
return [a[0] / length, a[1] / length, a[2] / length];
|
|
15
|
+
};
|
|
16
|
+
const center = (cap) => [cap.cx, cap.cy, cap.cz];
|
|
17
|
+
const capAt = (v, radiusRad) => ({
|
|
18
|
+
cx: v[0],
|
|
19
|
+
cy: v[1],
|
|
20
|
+
cz: v[2],
|
|
21
|
+
radiusRad: Math.min(Math.PI, radiusRad + EPS),
|
|
22
|
+
});
|
|
23
|
+
const fullCap = () => capAt([1, 0, 0], Math.PI);
|
|
24
|
+
const view = (cone) => [
|
|
25
|
+
cone.vx,
|
|
26
|
+
cone.vy,
|
|
27
|
+
cone.vz,
|
|
28
|
+
];
|
|
29
|
+
const visibleCap = (cap, cone) => isCapVisible(cap, { ...cone, viewRadius: cone.viewRadius + EPS });
|
|
30
|
+
const contained = (cap, cone) => angle(center(cap), view(cone)) + cap.radiusRad <= cone.viewRadius - EPS;
|
|
31
|
+
// The minor great-circle arc can cross the cone even if both endpoints are outside.
|
|
32
|
+
// Near-antipodal arcs have no uniquely stable tangent: keep them for D3.
|
|
33
|
+
function arcInterval(a, b, cone) {
|
|
34
|
+
const normal = cross(a, b);
|
|
35
|
+
const length = angle(a, b);
|
|
36
|
+
if (Math.hypot(...normal) < EPS) {
|
|
37
|
+
if (dot(a, b) < 0 || dot(a, view(cone)) >= Math.cos(cone.viewRadius) - EPS)
|
|
38
|
+
return { start: 0, end: length, length };
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const tangent = cross(unit(normal), a);
|
|
42
|
+
const x = dot(a, view(cone)), y = dot(tangent, view(cone));
|
|
43
|
+
const amplitude = Math.hypot(x, y);
|
|
44
|
+
const threshold = Math.cos(cone.viewRadius) - EPS;
|
|
45
|
+
if (amplitude < EPS)
|
|
46
|
+
return threshold <= EPS ? { start: 0, end: length, length, tangent } : null;
|
|
47
|
+
if (threshold > amplitude)
|
|
48
|
+
return null;
|
|
49
|
+
if (threshold <= -amplitude)
|
|
50
|
+
return { start: 0, end: length, length, tangent };
|
|
51
|
+
const phase = Math.atan2(y, x), half = Math.acos(clamp(threshold / amplitude));
|
|
52
|
+
// A view cone is at most a hemisphere. Its intersection with a minor arc
|
|
53
|
+
// is connected (up to numerical tolerance at the hemisphere boundary).
|
|
54
|
+
let start = Infinity, end = -Infinity;
|
|
55
|
+
for (const shift of [-TAU, 0, TAU]) {
|
|
56
|
+
const lo = Math.max(0, phase + shift - half);
|
|
57
|
+
const hi = Math.min(length, phase + shift + half);
|
|
58
|
+
if (lo <= hi) {
|
|
59
|
+
start = Math.min(start, lo);
|
|
60
|
+
end = Math.max(end, hi);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return start <= end ? { start, end, length, tangent } : null;
|
|
64
|
+
}
|
|
65
|
+
export function edgeIntersectsCone(a, b, cone) {
|
|
66
|
+
return arcInterval(a, b, cone) !== null;
|
|
67
|
+
}
|
|
68
|
+
function pointAt(a, tangent, t) {
|
|
69
|
+
const x = a[0] * Math.cos(t) + tangent[0] * Math.sin(t);
|
|
70
|
+
const y = a[1] * Math.cos(t) + tangent[1] * Math.sin(t);
|
|
71
|
+
const z = a[2] * Math.cos(t) + tangent[2] * Math.sin(t);
|
|
72
|
+
return [
|
|
73
|
+
(Math.atan2(y, x) * 180) / Math.PI,
|
|
74
|
+
(Math.atan2(z, Math.hypot(x, y)) * 180) / Math.PI,
|
|
75
|
+
];
|
|
76
|
+
}
|
|
77
|
+
function mergeCaps(a, b) {
|
|
78
|
+
if (a.radiusRad >= Math.PI || b.radiusRad >= Math.PI)
|
|
79
|
+
return fullCap();
|
|
80
|
+
const av = center(a), bv = center(b);
|
|
81
|
+
const sum = [av[0] + bv[0], av[1] + bv[1], av[2] + bv[2]];
|
|
82
|
+
if (Math.hypot(...sum) < EPS)
|
|
83
|
+
return fullCap();
|
|
84
|
+
const v = unit(sum);
|
|
85
|
+
return capAt(v, Math.max(angle(v, av) + a.radiusRad, angle(v, bv) + b.radiusRad));
|
|
86
|
+
}
|
|
87
|
+
function leafCap(vectors, start, end) {
|
|
88
|
+
const v = vectors[start];
|
|
89
|
+
// A cap smaller than a hemisphere is geodesically convex. Otherwise
|
|
90
|
+
// fail open: endpoint containment alone cannot bound a great-circle arc.
|
|
91
|
+
let radius = 0;
|
|
92
|
+
for (let i = start + 1; i <= end; i++)
|
|
93
|
+
radius = Math.max(radius, angle(v, vectors[i]));
|
|
94
|
+
return radius < Math.PI / 2 - EPS ? capAt(v, radius) : fullCap();
|
|
95
|
+
}
|
|
96
|
+
function buildNode(vectors, start, end) {
|
|
97
|
+
if (end - start <= 32)
|
|
98
|
+
return { start, end, cap: leafCap(vectors, start, end) };
|
|
99
|
+
const mid = (start + end) >>> 1;
|
|
100
|
+
const left = buildNode(vectors, start, mid), right = buildNode(vectors, mid, end);
|
|
101
|
+
return { start, end, left, right, cap: mergeCaps(left.cap, right.cap) };
|
|
102
|
+
}
|
|
103
|
+
// Geometry frames are immutable. Weak keys permit eviction with the LOD cache.
|
|
104
|
+
// Only camera-independent vectors and cap trees persist across view changes.
|
|
105
|
+
export function createSphericalLineClipper({ preserveSegments = false } = {}) {
|
|
106
|
+
const indexes = new WeakMap();
|
|
107
|
+
return (geometry, cone) => {
|
|
108
|
+
let index = indexes.get(geometry);
|
|
109
|
+
if (!index) {
|
|
110
|
+
const lines = (geometry.type === "LineString"
|
|
111
|
+
? [geometry.coordinates]
|
|
112
|
+
: geometry.coordinates)
|
|
113
|
+
.filter((points) => points.length >= 2)
|
|
114
|
+
.map((points) => {
|
|
115
|
+
const vectors = points.map(([lon, lat]) => lonLatToVec(lon, lat));
|
|
116
|
+
return {
|
|
117
|
+
points,
|
|
118
|
+
vectors,
|
|
119
|
+
root: buildNode(vectors, 0, vectors.length - 1),
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
index = {
|
|
123
|
+
lines,
|
|
124
|
+
sourceVertices: lines.reduce((n, line) => n + line.points.length, 0),
|
|
125
|
+
sourceSegments: lines.reduce((n, line) => n + line.points.length - 1, 0),
|
|
126
|
+
};
|
|
127
|
+
indexes.set(geometry, index);
|
|
128
|
+
}
|
|
129
|
+
const prev = index.lastCone;
|
|
130
|
+
if (prev &&
|
|
131
|
+
index.lastResult &&
|
|
132
|
+
prev.vx === cone.vx &&
|
|
133
|
+
prev.vy === cone.vy &&
|
|
134
|
+
prev.vz === cone.vz &&
|
|
135
|
+
prev.viewRadius === cone.viewRadius)
|
|
136
|
+
return {
|
|
137
|
+
...index.lastResult,
|
|
138
|
+
stats: { ...index.lastResult.stats, cacheHit: true },
|
|
139
|
+
};
|
|
140
|
+
const stats = {
|
|
141
|
+
sourceVertices: index.sourceVertices,
|
|
142
|
+
sourceSegments: index.sourceSegments,
|
|
143
|
+
submittedVertices: 0,
|
|
144
|
+
rejectedSegments: 0,
|
|
145
|
+
clippedSegments: 0,
|
|
146
|
+
visitedNodes: 0,
|
|
147
|
+
rejectedLines: 0,
|
|
148
|
+
cacheHit: false,
|
|
149
|
+
};
|
|
150
|
+
const coordinates = [];
|
|
151
|
+
for (const { points, vectors, root } of index.lines) {
|
|
152
|
+
let current;
|
|
153
|
+
const append = (part) => {
|
|
154
|
+
if (current && current.at(-1) === part[0]) {
|
|
155
|
+
for (let i = 1; i < part.length; i++)
|
|
156
|
+
current.push(part[i]);
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
current = part.slice();
|
|
160
|
+
coordinates.push(current);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
const visit = (node) => {
|
|
164
|
+
stats.visitedNodes++;
|
|
165
|
+
if (!visibleCap(node.cap, cone)) {
|
|
166
|
+
stats.rejectedSegments += node.end - node.start;
|
|
167
|
+
if (node === root)
|
|
168
|
+
stats.rejectedLines++;
|
|
169
|
+
current = undefined;
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (contained(node.cap, cone)) {
|
|
173
|
+
append(points.slice(node.start, node.end + 1));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (node.left && node.right) {
|
|
177
|
+
visit(node.left);
|
|
178
|
+
visit(node.right);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
for (let i = node.start; i < node.end; i++) {
|
|
182
|
+
const a = vectors[i], b = vectors[i + 1];
|
|
183
|
+
const interval = arcInterval(a, b, cone);
|
|
184
|
+
if (!interval) {
|
|
185
|
+
stats.rejectedSegments++;
|
|
186
|
+
current = undefined;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
// Rendering consumers need the original endpoints: changing them
|
|
190
|
+
// changes D3's adaptive resampling and the rasterized stroke.
|
|
191
|
+
if (preserveSegments) {
|
|
192
|
+
append([points[i], points[i + 1]]);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const { start, end, length, tangent } = interval;
|
|
196
|
+
const atStart = start <= EPS, atEnd = length - end <= EPS;
|
|
197
|
+
if (!atStart || !atEnd)
|
|
198
|
+
stats.clippedSegments++;
|
|
199
|
+
const first = atStart || !tangent ? points[i] : pointAt(a, tangent, start);
|
|
200
|
+
const last = atEnd || !tangent ? points[i + 1] : pointAt(a, tangent, end);
|
|
201
|
+
append([first, last]);
|
|
202
|
+
if (!atEnd)
|
|
203
|
+
current = undefined;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
visit(root);
|
|
207
|
+
}
|
|
208
|
+
stats.submittedVertices = coordinates.reduce((n, line) => n + line.length, 0);
|
|
209
|
+
const result = {
|
|
210
|
+
geometry: { type: "MultiLineString", coordinates },
|
|
211
|
+
stats,
|
|
212
|
+
};
|
|
213
|
+
index.lastCone = { ...cone };
|
|
214
|
+
index.lastResult = result;
|
|
215
|
+
return result;
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
export function clipLineToCone(coordinates, cone) {
|
|
219
|
+
return createSphericalLineClipper()({ type: "LineString", coordinates }, cone)
|
|
220
|
+
.geometry.coordinates;
|
|
221
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Work } from "./cooperative.js";
|
|
1
2
|
import { type BlgTree } from "./blg.js";
|
|
2
3
|
import { type SphericalPolygonSignature } from "./spherical-geometry.js";
|
|
3
4
|
import type { Topology } from "./types.js";
|
|
@@ -12,8 +13,11 @@ import type { Topology } from "./types.js";
|
|
|
12
13
|
* This uses the existing per-polygon/line reference validator, not a global
|
|
13
14
|
* intersection arrangement for unrelated boundaries.
|
|
14
15
|
*/
|
|
15
|
-
|
|
16
|
+
interface PreparedArcTrees {
|
|
16
17
|
trees: BlgTree[];
|
|
17
18
|
activationLevels: number[];
|
|
18
19
|
retainedVertices: number;
|
|
19
|
-
}
|
|
20
|
+
}
|
|
21
|
+
export declare function buildTopologySafeArcTrees(topology: Topology, nominalActivation: readonly number[], signatures: readonly SphericalPolygonSignature[][]): PreparedArcTrees;
|
|
22
|
+
export declare function buildTopologySafeArcTreeSteps(topology: Topology, nominalActivation: readonly number[], signatures: readonly SphericalPolygonSignature[][]): Work<PreparedArcTrees>;
|
|
23
|
+
export {};
|
|
@@ -1,17 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { runSync } from "./cooperative.js";
|
|
2
|
+
import { buildBlgTreeSteps } from "./blg.js";
|
|
2
3
|
import { validGreatCirclePath, validSphericalPolygon, } from "./spherical-geometry.js";
|
|
3
|
-
/**
|
|
4
|
-
* Build a nested hierarchy by removing vertices from valid full detail.
|
|
5
|
-
* Batch at conservative tenth-LOD boundaries; when a batch fails, bisect it
|
|
6
|
-
* until we identify individually unsafe removals. Rejected vertices remain
|
|
7
|
-
* at level zero. Every accepted transition is validated in its actual context.
|
|
8
|
-
*
|
|
9
|
-
* The source quadtree priorities and ring visibility thresholds are not
|
|
10
|
-
* changed. A shared vertex has one removal decision across all of its owners.
|
|
11
|
-
* This uses the existing per-polygon/line reference validator, not a global
|
|
12
|
-
* intersection arrangement for unrelated boundaries.
|
|
13
|
-
*/
|
|
14
4
|
export function buildTopologySafeArcTrees(topology, nominalActivation, signatures) {
|
|
5
|
+
return runSync(buildTopologySafeArcTreeSteps(topology, nominalActivation, signatures));
|
|
6
|
+
}
|
|
7
|
+
export function* buildTopologySafeArcTreeSteps(topology, nominalActivation, signatures) {
|
|
15
8
|
const { vertices, arcs, features } = topology;
|
|
16
9
|
const positions = vertices.map(({ x, y }) => [x, y]);
|
|
17
10
|
const anchors = new Uint8Array(vertices.length);
|
|
@@ -22,6 +15,12 @@ export function buildTopologySafeArcTrees(topology, nominalActivation, signature
|
|
|
22
15
|
const groups = [];
|
|
23
16
|
const owners = Array.from({ length: vertices.length }, () => []);
|
|
24
17
|
for (let fi = 0; fi < features.length; fi++) {
|
|
18
|
+
if (fi % 32 === 0)
|
|
19
|
+
yield {
|
|
20
|
+
stage: "Validation groups",
|
|
21
|
+
completed: fi,
|
|
22
|
+
total: features.length,
|
|
23
|
+
};
|
|
25
24
|
const feature = features[fi];
|
|
26
25
|
const paths = feature.paths.map((path) => {
|
|
27
26
|
const ids = [];
|
|
@@ -75,7 +74,7 @@ export function buildTopologySafeArcTrees(topology, nominalActivation, signature
|
|
|
75
74
|
? validSphericalPolygon(coordinates, signature)
|
|
76
75
|
: coordinates.every(validGreatCirclePath);
|
|
77
76
|
}
|
|
78
|
-
function remove(batch, tick) {
|
|
77
|
+
function* remove(batch, tick) {
|
|
79
78
|
const affected = new Set();
|
|
80
79
|
for (const id of batch) {
|
|
81
80
|
active[id] = 0;
|
|
@@ -83,11 +82,13 @@ export function buildTopologySafeArcTrees(topology, nominalActivation, signature
|
|
|
83
82
|
affected.add(owner);
|
|
84
83
|
}
|
|
85
84
|
let valid = true;
|
|
86
|
-
for (const group of affected)
|
|
85
|
+
for (const group of affected) {
|
|
86
|
+
yield undefined;
|
|
87
87
|
if (!validGroup(group)) {
|
|
88
88
|
valid = false;
|
|
89
89
|
break;
|
|
90
90
|
}
|
|
91
|
+
}
|
|
91
92
|
if (valid) {
|
|
92
93
|
for (const id of batch)
|
|
93
94
|
activationLevels[id] = tick / 10;
|
|
@@ -100,12 +101,18 @@ export function buildTopologySafeArcTrees(topology, nominalActivation, signature
|
|
|
100
101
|
return;
|
|
101
102
|
}
|
|
102
103
|
const middle = Math.floor(batch.length / 2);
|
|
103
|
-
remove(batch.slice(0, middle), tick);
|
|
104
|
-
remove(batch.slice(middle), tick);
|
|
104
|
+
yield* remove(batch.slice(0, middle), tick);
|
|
105
|
+
yield* remove(batch.slice(middle), tick);
|
|
105
106
|
}
|
|
106
107
|
// Independent candidate components avoid revalidating unrelated countries
|
|
107
108
|
// when a local batch needs bisection. Group owners are shared across arcs.
|
|
109
|
+
let completed = 0;
|
|
108
110
|
for (const tick of [...batches.keys()].sort((a, b) => b - a)) {
|
|
111
|
+
yield {
|
|
112
|
+
stage: "Validate simplification",
|
|
113
|
+
completed: completed++,
|
|
114
|
+
total: batches.size,
|
|
115
|
+
};
|
|
109
116
|
const batch = batches.get(tick);
|
|
110
117
|
const parent = new Map(batch.map((id) => [id, id]));
|
|
111
118
|
const firstByGroup = new Map();
|
|
@@ -133,12 +140,21 @@ export function buildTopologySafeArcTrees(topology, nominalActivation, signature
|
|
|
133
140
|
components.get(key).push(id);
|
|
134
141
|
}
|
|
135
142
|
for (const component of components.values())
|
|
136
|
-
remove(component, tick);
|
|
143
|
+
yield* remove(component, tick);
|
|
137
144
|
}
|
|
138
145
|
// Encode the corrected threshold in the existing integer-level/fractional
|
|
139
146
|
// BLG representation. Use the same subtraction as selectBlgPositions.
|
|
140
147
|
const levels = activationLevels.map(Math.ceil);
|
|
141
148
|
const random = activationLevels.map((level) => Number.isInteger(level) ? 0 : 1 - (level - Math.floor(level)));
|
|
142
|
-
const trees =
|
|
149
|
+
const trees = [];
|
|
150
|
+
for (const arc of arcs) {
|
|
151
|
+
if (trees.length % 128 === 0)
|
|
152
|
+
yield {
|
|
153
|
+
stage: "Build BLG trees",
|
|
154
|
+
completed: trees.length,
|
|
155
|
+
total: arcs.length,
|
|
156
|
+
};
|
|
157
|
+
trees.push(yield* buildBlgTreeSteps(arc.vertexIds.map((id) => levels[id]), arc.vertexIds.map((id) => random[id])));
|
|
158
|
+
}
|
|
143
159
|
return { trees, activationLevels, retainedVertices };
|
|
144
160
|
}
|