@vizhub/quadstream 0.2.0 → 0.3.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 +2 -0
- package/README.md +366 -44
- package/dist/geometry-wire.d.ts +8 -0
- package/dist/geometry-wire.js +76 -0
- package/dist/geometry.d.ts +3 -1
- package/dist/geometry.js +115 -5
- package/dist/index.d.ts +15 -1
- package/dist/index.js +8 -1
- package/dist/lod-scheduler.d.ts +15 -0
- package/dist/lod-scheduler.js +85 -0
- package/dist/reconstruct.d.ts +15 -1
- package/dist/reconstruct.js +68 -29
- package/dist/spherical-clip.d.ts +95 -0
- package/dist/spherical-clip.js +557 -0
- package/dist/spherical-cull.d.ts +25 -0
- package/dist/spherical-cull.js +93 -0
- package/dist/spherical-dataset.d.ts +30 -6
- package/dist/spherical-dataset.js +129 -108
- package/dist/spherical-geometry.js +76 -44
- package/dist/spherical-preprocess.d.ts +19 -0
- package/dist/spherical-preprocess.js +144 -0
- package/dist/spherical-repair.d.ts +17 -0
- package/dist/spherical-repair.js +100 -0
- package/dist/spherical-robust-dataset.d.ts +27 -0
- package/dist/spherical-robust-dataset.js +89 -0
- package/dist/spherical-view-clipper.d.ts +22 -0
- package/dist/spherical-view-clipper.js +85 -0
- package/dist/types.d.ts +5 -1
- package/package.json +11 -7
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,8 @@ First planned experimental npm release of the modern Quadstream library.
|
|
|
10
10
|
- CLI for build, inspect, validate, query and benchmark.
|
|
11
11
|
- MapLibre integration and experimental in-memory spherical reconstruction.
|
|
12
12
|
- Standalone map and globe demos with regression tests.
|
|
13
|
+
- Globe: spring-smoothed pointer navigation and continuous keyboard
|
|
14
|
+
"spaceship" flight (thrust + viscous drag) with tuning sliders.
|
|
13
15
|
- MIT license for modern implementation; legacy license terms preserved.
|
|
14
16
|
- ESM package, TypeScript declarations and clean-install tarball validation.
|
|
15
17
|
|
package/README.md
CHANGED
|
@@ -8,9 +8,8 @@ for a map or globe, or serialize planar geometry into independently loadable
|
|
|
8
8
|
binary partitions. The TypeScript-first core is ESM with no runtime dependencies,
|
|
9
9
|
and requires no VizHub account, map framework or server.
|
|
10
10
|
|
|
11
|
-
> **Experimental 0.1.0
|
|
12
|
-
>
|
|
13
|
-
> expensive; do not use it for safety-critical geometry.
|
|
11
|
+
> **Experimental 0.1.0.** Reference validation can be expensive; do not use it
|
|
12
|
+
> for safety-critical geometry.
|
|
14
13
|
|
|
15
14
|
## Features
|
|
16
15
|
|
|
@@ -23,13 +22,13 @@ and requires no VizHub account, map framework or server.
|
|
|
23
22
|
|
|
24
23
|
## Install
|
|
25
24
|
|
|
26
|
-
|
|
25
|
+
Install from npm when version 0.1.0 is available (Node.js 20+, ESM):
|
|
27
26
|
|
|
28
27
|
```sh
|
|
29
28
|
npm install @vizhub/quadstream
|
|
30
29
|
```
|
|
31
30
|
|
|
32
|
-
|
|
31
|
+
Alternatively, build from a checkout:
|
|
33
32
|
|
|
34
33
|
```sh
|
|
35
34
|
git clone https://github.com/vizhub-studio/quadstream.git
|
|
@@ -47,19 +46,29 @@ examples use the package's public import path. From a checkout, examples in
|
|
|
47
46
|
## Quick start: planar geometry
|
|
48
47
|
|
|
49
48
|
```js
|
|
50
|
-
import { buildQuadstream } from
|
|
49
|
+
import { buildQuadstream } from "@vizhub/quadstream";
|
|
51
50
|
|
|
52
51
|
const source = {
|
|
53
|
-
type:
|
|
54
|
-
features: [
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
52
|
+
type: "FeatureCollection",
|
|
53
|
+
features: [
|
|
54
|
+
{
|
|
55
|
+
type: "Feature",
|
|
56
|
+
id: "square",
|
|
57
|
+
properties: { value: 42 },
|
|
58
|
+
geometry: {
|
|
59
|
+
type: "Polygon",
|
|
60
|
+
coordinates: [
|
|
61
|
+
[
|
|
62
|
+
[0, 0],
|
|
63
|
+
[10, 0],
|
|
64
|
+
[10, 10],
|
|
65
|
+
[0, 10],
|
|
66
|
+
[0, 0],
|
|
67
|
+
],
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
],
|
|
63
72
|
};
|
|
64
73
|
|
|
65
74
|
const dataset = buildQuadstream(source, { maxLevel: 12 });
|
|
@@ -80,14 +89,17 @@ great-circle globe geometry.
|
|
|
80
89
|
|
|
81
90
|
```js
|
|
82
91
|
import {
|
|
83
|
-
exportPartitions,
|
|
84
|
-
|
|
92
|
+
exportPartitions,
|
|
93
|
+
QuadstreamSession,
|
|
94
|
+
QuadstreamLoader,
|
|
95
|
+
fetchFromBundle,
|
|
96
|
+
} from "@vizhub/quadstream";
|
|
85
97
|
|
|
86
98
|
const bundle = exportPartitions(dataset, { fileDepth: 3 });
|
|
87
99
|
const session = new QuadstreamSession(bundle.manifest);
|
|
88
100
|
const loader = new QuadstreamLoader(session, fetchFromBundle(bundle), {
|
|
89
101
|
concurrency: 4,
|
|
90
|
-
cacheBytes: 1024 * 1024
|
|
102
|
+
cacheBytes: 1024 * 1024,
|
|
91
103
|
});
|
|
92
104
|
|
|
93
105
|
const frame = await loader.loadLatest({ level: 4 });
|
|
@@ -111,29 +123,75 @@ degrees with D3 spherical winding (clockwise small polygon interiors).
|
|
|
111
123
|
The following example assumes a TopoJSON atlas is already loaded:
|
|
112
124
|
|
|
113
125
|
```js
|
|
114
|
-
import {
|
|
126
|
+
import {
|
|
127
|
+
buildSphericalQuadstream,
|
|
128
|
+
importSphericalTopoJSON,
|
|
129
|
+
} from "@vizhub/quadstream";
|
|
115
130
|
|
|
116
|
-
const countries = importSphericalTopoJSON(atlas,
|
|
131
|
+
const countries = importSphericalTopoJSON(atlas, "countries");
|
|
117
132
|
const globe = buildSphericalQuadstream(countries, { maxLevel: 20 });
|
|
118
133
|
const { geojson, valid, promotedArcs } = globe.query({ level: 8.5 });
|
|
119
134
|
// Supply geojson to your D3 geoPath renderer.
|
|
120
135
|
```
|
|
121
136
|
|
|
122
137
|
Spherical queries reconstruct global geometry in memory. Fractional detail uses
|
|
123
|
-
stable vertex-ID hashing
|
|
124
|
-
|
|
138
|
+
stable vertex-ID hashing for nominal priorities and topology-safe preprocessing
|
|
139
|
+
for corrected activation thresholds, without query-time promotion. They do not support
|
|
125
140
|
planar viewport bounds, v1 partition serialization or network streaming.
|
|
126
141
|
They may reject inputs that cannot be validated in the reference hemisphere
|
|
127
142
|
chart. See [spherical semantics](https://github.com/vizhub-studio/quadstream/blob/master/docs/SPHERICAL.md).
|
|
128
143
|
|
|
144
|
+
### Spherical visibility and clipping
|
|
145
|
+
|
|
146
|
+
The geometry library also provides renderer-independent visibility helpers:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
import {
|
|
150
|
+
lonLatVector,
|
|
151
|
+
computeFeatureCaps,
|
|
152
|
+
filterSphericalFeatures,
|
|
153
|
+
clipWindow,
|
|
154
|
+
clipToWindow,
|
|
155
|
+
} from "@vizhub/quadstream";
|
|
156
|
+
|
|
157
|
+
const [x, y, z] = lonLatVector([10, 45]);
|
|
158
|
+
const window = clipWindow(x, y, z, Math.PI / 12);
|
|
159
|
+
const caps = computeFeatureCaps(countries);
|
|
160
|
+
const visible = filterSphericalFeatures(countries, window, caps);
|
|
161
|
+
const { geojson, stats } = clipToWindow(visible, window);
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Centers are unit vectors and angular radii are in radians. Clipping
|
|
165
|
+
windows support radii from zero up to (but excluding) a hemisphere;
|
|
166
|
+
nondegenerate polygon output requires a positive radius. The input uses
|
|
167
|
+
D3 spherical winding and minor great-circle arcs. Clipping accepts only
|
|
168
|
+
Polygon and MultiPolygon feature collections; culling conservatively
|
|
169
|
+
keeps line geometry. Supplied caps must correspond to the features in
|
|
170
|
+
order and conservatively bound their current geometry. Caps are based on
|
|
171
|
+
vertices with a fixed margin; they are not certified bounds for arbitrary
|
|
172
|
+
large-interior or malformed spherical polygons. Boundary walks approximate
|
|
173
|
+
small circles by great-circle segments, and the existing polygon
|
|
174
|
+
reconstruction is not a general-purpose topology-preserving intersection
|
|
175
|
+
operation. The functions do not mutate inputs, but can reuse input
|
|
176
|
+
features and rings by reference. Treat those as immutable. Statistics
|
|
177
|
+
report output features, vertices, ring outcomes and classified positions.
|
|
178
|
+
|
|
179
|
+
These are post-query rendering helpers, not viewport-aware spherical
|
|
180
|
+
reconstruction or network streaming. Camera projection, padded-window
|
|
181
|
+
caching and D3 rendering remain application concerns.
|
|
182
|
+
|
|
129
183
|
## Interactive demos
|
|
130
184
|
|
|
185
|
+
The React/Vite globe is published via GitHub Pages at
|
|
186
|
+
<https://vizhub-studio.github.io/quadstream/> (after the first successful deployment).
|
|
187
|
+
See the [deployment and local development instructions](quadstream-globe/README.md).
|
|
188
|
+
|
|
131
189
|
From a checkout, install dependencies and build, then run either command:
|
|
132
190
|
|
|
133
|
-
| Demo
|
|
134
|
-
|
|
|
135
|
-
| Progressive map
|
|
136
|
-
| Orthographic globe | `npm run demo:globe` | D3 Canvas,
|
|
191
|
+
| Demo | Command | What it demonstrates |
|
|
192
|
+
| ------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
193
|
+
| Progressive map | `npm run demo:map` | Canvas/MapLibre, detail levels, shared arcs, simulated partition latency |
|
|
194
|
+
| Orthographic globe | `npm run demo:globe` | D3 Canvas, Visionscarto 110m/50m inputs, zoom-gated US state/county boundaries, pinch zoom, rotation, worker-based LOD and original/reconstructed comparison |
|
|
137
195
|
|
|
138
196
|
Open the local URL printed by the server (normally http://127.0.0.1:4173/).
|
|
139
197
|
The demos are not included in the npm artifact. The globe downloads the full
|
|
@@ -143,7 +201,7 @@ and [globe demo](https://github.com/vizhub-studio/quadstream/blob/master/docs/GL
|
|
|
143
201
|
|
|
144
202
|
## CLI
|
|
145
203
|
|
|
146
|
-
After installing the
|
|
204
|
+
After installing the package, run its executable with
|
|
147
205
|
`npx --no-install quadstream` (or use `node bin/quadstream.mjs` from a built checkout):
|
|
148
206
|
|
|
149
207
|
```sh
|
|
@@ -160,15 +218,15 @@ for input restrictions, bounds, exit codes and static staging.
|
|
|
160
218
|
|
|
161
219
|
## Public API guide
|
|
162
220
|
|
|
163
|
-
| API
|
|
164
|
-
|
|
|
165
|
-
| `buildQuadstream`, `QuadstreamDataset`
|
|
166
|
-
| `buildSphericalQuadstream`, `SphericalQuadstreamDataset`, `importSphericalTopoJSON` | In-memory D3-style geographic reconstruction
|
|
167
|
-
| `importGeoJSON`, `exportGeoJSON`, `importTopoJSON`, `exportTopoJSON`
|
|
168
|
-
| `exportPartitions`, `validateManifest`, `MANIFEST_VERSION`
|
|
169
|
-
| `QuadstreamSession`, `QuadstreamLoader`, `fetchFromBundle`
|
|
170
|
-
| `ProgressiveMap`, `attachMapLibre`, `mapLibreBounds`
|
|
171
|
-
| `buildTopology`, `buildSparseQuadtree`, `buildBlgTree`, `createSpatialIndex`
|
|
221
|
+
| API | Purpose |
|
|
222
|
+
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
|
|
223
|
+
| `buildQuadstream`, `QuadstreamDataset` | Build planar multiresolution geometry and query by detail/bounds |
|
|
224
|
+
| `buildSphericalQuadstream`, `SphericalQuadstreamDataset`, `importSphericalTopoJSON` | In-memory D3-style geographic reconstruction |
|
|
225
|
+
| `importGeoJSON`, `exportGeoJSON`, `importTopoJSON`, `exportTopoJSON` | Planar geographic interchange |
|
|
226
|
+
| `exportPartitions`, `validateManifest`, `MANIFEST_VERSION` | Versioned planar artifacts |
|
|
227
|
+
| `QuadstreamSession`, `QuadstreamLoader`, `fetchFromBundle` | Partial reconstruction and injected async delivery |
|
|
228
|
+
| `ProgressiveMap`, `attachMapLibre`, `mapLibreBounds` | Renderer-independent orchestration and MapLibre integration |
|
|
229
|
+
| `buildTopology`, `buildSparseQuadtree`, `buildBlgTree`, `createSpatialIndex` | Lower-level algorithm building blocks |
|
|
172
230
|
|
|
173
231
|
See the [export list](https://github.com/vizhub-studio/quadstream/blob/master/src/index.ts)
|
|
174
232
|
and included TypeScript declarations for complete signatures and utilities.
|
|
@@ -314,10 +372,12 @@ culling. Exported helpers include `canonicalLonLat`, `lonLatVector`,
|
|
|
314
372
|
`sphericalPolygonSignature`, and `validSphericalPolygon`. Supporting types are
|
|
315
373
|
`UnitVector`, `CubeFace`, `SphericalCell`, `SphericalPriorities`,
|
|
316
374
|
`SphericalChart`, `SphericalPolygonSignature`, and `SphericalQueryOptions`.
|
|
317
|
-
Spherical queries support fractional levels.
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
375
|
+
Spherical queries support fractional levels. Preprocessing validates descending
|
|
376
|
+
vertex-removal batches on a conservative tenth-level grid, retaining unsafe
|
|
377
|
+
vertices at level zero. `activationLevels` exposes the corrected thresholds;
|
|
378
|
+
`retainedVertices` counts rejected removals. The legacy `promotedArcs` query
|
|
379
|
+
field is always zero. `valid: false` indicates a reconstruction invariant
|
|
380
|
+
failure, not a request for a finer level. No global full-detail fallback is applied. See [spherical semantics](docs/SPHERICAL.md) for winding,
|
|
321
381
|
poles, seams, charts, and topology junctions.
|
|
322
382
|
|
|
323
383
|
Spherical reconstruction applies three additional safeguards:
|
|
@@ -330,12 +390,11 @@ Spherical reconstruction applies three additional safeguards:
|
|
|
330
390
|
- closed rings that would reconstruct with fewer than three distinct vertices
|
|
331
391
|
are restored from their source path rather than emitted as degenerate rings.
|
|
332
392
|
|
|
333
|
-
These safeguards and
|
|
334
|
-
the
|
|
393
|
+
These safeguards and topology-safe preprocessing preserve shared-arc identity
|
|
394
|
+
without promoting the query to a finer level. The globe demo separately isolates malformed
|
|
335
395
|
source features, so one invalid atlas feature does not force its whole
|
|
336
396
|
coordinate-connected component to full detail.
|
|
337
397
|
|
|
338
|
-
|
|
339
398
|
## How it works
|
|
340
399
|
|
|
341
400
|
Quadstream deduplicates exact shared vertices and arcs, assigns deterministic
|
|
@@ -346,6 +405,269 @@ on six cube faces. A packed planar spatial index selects viewport candidates.
|
|
|
346
405
|
The versioned planar binary format stores checksummed vertex batches separately
|
|
347
406
|
from topology metadata.
|
|
348
407
|
|
|
408
|
+
## Algorithmic complexity and computational geometry
|
|
409
|
+
|
|
410
|
+
These are analytical bounds for the current implementation, not performance
|
|
411
|
+
measurements or guarantees about an idealized Quadstream algorithm. We count
|
|
412
|
+
fixed-width numeric operations and assume expected constant-time Map/Set
|
|
413
|
+
operations and conventional comparison sorting. Space bounds include working
|
|
414
|
+
data and results unless described as auxiliary. Add the size of feature
|
|
415
|
+
properties, identifiers and other metadata when these are not constant-sized.
|
|
416
|
+
|
|
417
|
+
### Notation
|
|
418
|
+
|
|
419
|
+
- N: input coordinate occurrences, including repeated shared boundaries;
|
|
420
|
+
V: distinct vertices; F: features.
|
|
421
|
+
- A: distinct arcs; M: total vertex positions stored across distinct arcs
|
|
422
|
+
(including repeated endpoints); R: arc references across feature paths.
|
|
423
|
+
- For a query, T is the sum of the full arc lengths across the selected
|
|
424
|
+
references, K is the reconstructed coordinate count, and J is the number
|
|
425
|
+
of selected features. A subscript "all" denotes the whole dataset.
|
|
426
|
+
- L: number of detail levels (currently at most 26); P: partitions;
|
|
427
|
+
B: bytes processed; U: distinct cached query levels.
|
|
428
|
+
- Q: sum of squared vertex counts of individual polygon components being
|
|
429
|
+
validated, counting all rings of each component. For K coordinates,
|
|
430
|
+
Q is at most K². Line validation contributes linear work instead.
|
|
431
|
+
|
|
432
|
+
Shared boundaries make V, M and N different quantities. In particular,
|
|
433
|
+
repeated arc references may make T much larger than the number of distinct
|
|
434
|
+
vertices selected by BLG. For topology built from ordinary supported input,
|
|
435
|
+
V, M, R and F are O(N); a serialized manifest can describe a different
|
|
436
|
+
reference workload.
|
|
437
|
+
|
|
438
|
+
### Geometry predicates and preprocessing
|
|
439
|
+
|
|
440
|
+
| Algorithm | Time | Space and explanation |
|
|
441
|
+
| ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
442
|
+
| Coordinate normalization, bounding boxes, signed area (shoelace), ray-cast point-in-ring, great-circle path checks | O(n) for n positions | O(1) auxiliary for scans; O(n) if materializing normalized coordinates |
|
|
443
|
+
| Orientation, segment intersection, bounds intersection/union, cell addressing, angular distance and individual spherical projections | O(1) | O(1); fixed-dimensional arithmetic |
|
|
444
|
+
| Simple-ring validation | O(n²) worst case | O(1) auxiliary; tests nonadjacent segment pairs |
|
|
445
|
+
| Polygon validation (shell and holes) | O(n²) worst case | O(1) auxiliary planar space; ring simplicity, edge-pair intersection and containment tests |
|
|
446
|
+
| Exact-coordinate topology and reversible shared-arc interning | O(N + sum(d_e log d_e) + Q) | O(N); hash interning and adjacency scans, sorting the owner set of each edge e with d_e distinct owning paths |
|
|
447
|
+
| Sparse planar quadtree and six-face spherical priorities | O(V log V + VL) | O(V); deterministic sorting, at most L probes per vertex, one stored occupied cell per vertex |
|
|
448
|
+
| BLG min-Cartesian tree construction | O(m) per arc of length m; O(M) overall | O(m) per arc; each node is pushed and popped at most once on the monotone stack |
|
|
449
|
+
| BLG invariant checking | O(m) | O(m) visited set and traversal |
|
|
450
|
+
| Packed static bounding-volume hierarchy | O(F log F) | O(F) for fixed bucket size; sorting and packing progressively smaller groups |
|
|
451
|
+
| Spherical hemisphere chart construction | O(n) | O(n) vector arrays; individual gnomonic projection is O(1) |
|
|
452
|
+
| Spherical polygon signature and validation | O(n²) | O(n) projected working arrays; minor great-circle edges map to straight segments within the supported open hemisphere |
|
|
453
|
+
|
|
454
|
+
The topology owner-set sorting term is bounded by O(N log N) in the
|
|
455
|
+
fixed-width model. Without source validity checking, topology construction
|
|
456
|
+
would be expected near-linear for ordinary bounded edge ownership. It is not
|
|
457
|
+
a planar arrangement or a general-purpose noding algorithm: crossings and
|
|
458
|
+
differently digitized edges are not split or snapped to infer shared borders.
|
|
459
|
+
|
|
460
|
+
The planar quadtree computes cell addresses directly at each level, rather
|
|
461
|
+
than materializing the complete 4^L grid or descending a pointer tree. The
|
|
462
|
+
spherical variant chooses the dominant Cartesian axis of a unit vector to
|
|
463
|
+
select a cube face, then uses the analogous sparse occupancy test. Neither
|
|
464
|
+
guarantees logarithmic insertion independent of the configured depth and
|
|
465
|
+
coordinate distribution. Dense clusters can exhaust the available levels.
|
|
466
|
+
|
|
467
|
+
Spherical preprocessing also tests whether removing a vertex would reverse
|
|
468
|
+
projected winding or collapse a ring. After a linear projection and area
|
|
469
|
+
pass, each signed-area update takes O(1). For rings with at most 32 stored
|
|
470
|
+
coordinates, it additionally validates the entire candidate polygon.
|
|
471
|
+
For polygon p with n_p coordinates and s_p candidates in these short rings,
|
|
472
|
+
this adds O(sum_p(s_p n_p²)) time in the worst case, with O(N) peak working
|
|
473
|
+
geometry. A polygon with many short holes can therefore incur superquadratic
|
|
474
|
+
preprocessing (a loose O(N³) dataset-wide bound); the short-ring threshold
|
|
475
|
+
does not bound the size of its containing polygon.
|
|
476
|
+
|
|
477
|
+
Combining the phases, planar build time is
|
|
478
|
+
O(N + sum(d_e log d_e) + Q + V log V + VL + M + F log F),
|
|
479
|
+
with O(N + V + M + F) geometry storage. The spherical build substitutes
|
|
480
|
+
spherical predicates, adds the short-ring candidate term above and retains
|
|
481
|
+
the canonical source and signatures, but does not build a planar spatial index.
|
|
482
|
+
|
|
483
|
+
### Level-of-detail selection and query complexity
|
|
484
|
+
|
|
485
|
+
| Algorithm | Time | Space and explanation |
|
|
486
|
+
| ---------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
487
|
+
| BLG threshold traversal | O(t + 1), with t nodes passing the traversal threshold; O(m) worst case | O(h + k) for tree height h and k emitted positions; h can be m |
|
|
488
|
+
| Fractional BLG selection | Same traversal bound | Stable vertex-ID hash is O(1); rejected fractional-level candidates are still visited |
|
|
489
|
+
| Viewport feature lookup | O(w + J log(J + 1)) | O(w + J) conservative auxiliary bound; w counts visited nodes and tested entries; O(F + J log(J + 1)) worst case |
|
|
490
|
+
| Arc/path reconstruction before polygon validation | O(T + K + J) | O(T + K + J) conservative bound for full-ID scans, reversed copies, temporary paths and output |
|
|
491
|
+
| Planar feature reconstruction with validity checking | O(T + K + J + Q) | Same linear working storage; quadratic time does not imply quadratic storage |
|
|
492
|
+
| Spherical topology-safe preprocessing | O(V (T_all + Q_full)) conservative worst-case time; validated batches normally reduce checks | O(V + T_all + A) working storage, plus source and trees |
|
|
493
|
+
|
|
494
|
+
BLG is a min-heap on detail priority and an inorder sequence on path
|
|
495
|
+
position. An entire subtree can be skipped when its root exceeds the
|
|
496
|
+
traversal threshold. For integer levels, t equals k; fractional levels
|
|
497
|
+
also visit next-level candidates that fail their stable hash threshold.
|
|
498
|
+
Selection does not require a balanced tree, and no O(log m) worst-case tree
|
|
499
|
+
height is promised. The iterative traversal avoids call-stack overflow.
|
|
500
|
+
|
|
501
|
+
Importantly, current feature reconstruction collects all original arc IDs
|
|
502
|
+
for potential collapsed-ring restoration, even when BLG emits very few
|
|
503
|
+
vertices. It also repeats selection for each arc reference rather than
|
|
504
|
+
memoizing a shared arc's selected sequence across features. Consequently,
|
|
505
|
+
end-to-end reconstruction is not yet an O(K)-only algorithm. Exact shared
|
|
506
|
+
arcs ensure that both traversal directions refer to the same priority
|
|
507
|
+
sequence; arc reversal and stitching preserve shared coordinate identity.
|
|
508
|
+
|
|
509
|
+
The packed spatial index prunes disjoint bounding volumes, tests candidates
|
|
510
|
+
in intersecting leaves, then sorts results by original ordinal. There is
|
|
511
|
+
no guaranteed O(log F + J) query bound for heavily overlapping boxes.
|
|
512
|
+
Viewport lookup selects whole features rather than clipping their edges.
|
|
513
|
+
|
|
514
|
+
A cold validated planar query first reconstructs features globally to
|
|
515
|
+
determine whether the level is valid (up to O(T_all + F + Q_level)), then
|
|
516
|
+
reconstructs the selected features, possibly at full detail. Its cost is
|
|
517
|
+
therefore the global check plus the index lookup and selected reconstruction
|
|
518
|
+
terms above. The global Boolean decision is cached by exact numeric level,
|
|
519
|
+
using O(U) storage; a warm query avoids that global check but still runs
|
|
520
|
+
per-feature polygon validation during reconstruction. Setting
|
|
521
|
+
`validate: false` bypasses the global decision, not the internal planar
|
|
522
|
+
polygon predicates. A global fallback can raise K and Q to their
|
|
523
|
+
full-resolution values. Fractional levels mean U is not generally bounded
|
|
524
|
+
by L in the in-memory planar engine.
|
|
525
|
+
|
|
526
|
+
Spherical queries always reconstruct the global collection directly from the
|
|
527
|
+
corrected BLG trees and perform one diagnostic validation pass. The descending
|
|
528
|
+
preprocessing pass groups candidate removals by affected polygon or line,
|
|
529
|
+
validates batches, and bisects rejected batches. A shared vertex has a single
|
|
530
|
+
activation threshold across all its arcs. Unrelated cross-feature intersections
|
|
531
|
+
are not checked by the reference validator.
|
|
532
|
+
|
|
533
|
+
### Adapters, serialization and progressive loading
|
|
534
|
+
|
|
535
|
+
| Algorithm | Time | Space and explanation |
|
|
536
|
+
| ---------------------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
537
|
+
| GeoJSON normalization / export | O(N) plus planar topology validation | O(N); export validates nonempty results again |
|
|
538
|
+
| TopoJSON delta decode, signed arc reversal and stitching | O(D + T_all) | O(D + T_all); D counts positions in all encoded arcs, including unselected named objects |
|
|
539
|
+
| Planar TopoJSON import/export | Decode or encode linear work plus topology construction | O(N + M + R + D) as applicable; export rebuilds topology after GeoJSON validation |
|
|
540
|
+
| Spherical TopoJSON import | Decode plus spherical signatures and topology validation | Linear geometry storage; includes quadratic polygon checks |
|
|
541
|
+
| Partition assignment and export | O(V + P log P + sum_p(v_p log v_p)) | O(V + P) new records, metadata and binary bytes, sharing existing topology; v_p records in partition p |
|
|
542
|
+
| QSTR encoding/decoding and FNV-1a checksum | O(B) | O(B) output for encoding/decoding, O(1) auxiliary checksum space |
|
|
543
|
+
| Manifest schema and reference validation | O(V + M + R + F + P) | O(V + M + R + F + P) conservative working space for IDs, arc copies and path accounting |
|
|
544
|
+
| Required/missing partition planning and diagnostic bounds filter | O(P) | O(P) worst-case key output; loaded membership is expected O(1) |
|
|
545
|
+
| Session construction | O(V + M + P + F log F) | O(V + M + F + P), including global manifest/tree/index data |
|
|
546
|
+
| Session partition ingestion | O(B) | O(B) temporary records and sets, plus retained parsed vertices; repeat loads still checksum the bytes |
|
|
547
|
+
| Loader ensure-level | O(P + B + e) local work | O(P + C b_max + H + V_loaded) excluding manifest/tree data; e cache evictions, C concurrency, b_max max partition bytes, H raw-byte cache budget |
|
|
548
|
+
| Sorted loaded-key enumeration | O(P_loaded log(P_loaded + 1)) | O(P_loaded) output |
|
|
549
|
+
|
|
550
|
+
QSTR v1 stores 10 header bytes plus 22 bytes per vertex record, so total
|
|
551
|
+
binary payload is exactly 10P + 22V bytes, separate from JSON metadata.
|
|
552
|
+
Partition export sorts keys and the records within each partition, and does
|
|
553
|
+
not perform another geometric simplification. The manifest stores global
|
|
554
|
+
topology, arc sequences, partition membership and vertex priorities, so even
|
|
555
|
+
a coarse client starts with O(V + M + R + F + P) structural information
|
|
556
|
+
before fetching all coordinate bytes.
|
|
557
|
+
|
|
558
|
+
Session queries combine the O(P) missing-key scan with the planar index and
|
|
559
|
+
reconstruction bounds. They perform global validity checks only once all
|
|
560
|
+
partitions are loaded; incomplete or invalid features can be omitted.
|
|
561
|
+
The session constructor performs its own structural/accounting checks;
|
|
562
|
+
`validateManifest` is the separate full schema validator.
|
|
563
|
+
|
|
564
|
+
The loader uses expected O(1) Map operations for LRU bookkeeping, amortized
|
|
565
|
+
constant eviction work per insertion, and O(B) copying/checksumming/decoding.
|
|
566
|
+
Its raw-byte budget does not evict parsed vertices or global topology.
|
|
567
|
+
Concurrency bounds active workers per request, not network latency or all
|
|
568
|
+
overlapping transport activity; a fetcher ignoring cancellation can keep
|
|
569
|
+
external work alive. Network time depends on request latency, throughput
|
|
570
|
+
and application transport. A conservative planner scans all partitions by
|
|
571
|
+
minimum level, not only those inside the viewport.
|
|
572
|
+
|
|
573
|
+
ProgressiveMap has at most three distinct normal stages (coarse, intermediate,
|
|
574
|
+
target), a bounded retry loop and optional full-detail rescue. Its total work
|
|
575
|
+
is the sum of loader and session-query costs over those stages, including
|
|
576
|
+
global completeness queries and sorted loaded-key diagnostics. It can fetch
|
|
577
|
+
all V records even for a coarse viewport. The MapLibre adapter adds O(1)
|
|
578
|
+
bounds/zoom and generation bookkeeping per event, excluding user callbacks
|
|
579
|
+
and renderer-side processing. There is no production spherical partition
|
|
580
|
+
protocol yet.
|
|
581
|
+
|
|
582
|
+
The CLI parses/serializes JSON in O(B) time and O(B) memory in the usual
|
|
583
|
+
input-size model, then delegates to the above algorithms. Its chunked reader
|
|
584
|
+
still buffers entire input files. Bundle inspect validates the manifest and
|
|
585
|
+
scans partitions; bundle query/validate load every partition, and query
|
|
586
|
+
export can revalidate or rebuild topology. The benchmark repeats build,
|
|
587
|
+
partition export and coarse/full query for each requested iteration; it is
|
|
588
|
+
not a separate simplification algorithm.
|
|
589
|
+
|
|
590
|
+
### Globe and map rendering algorithms
|
|
591
|
+
|
|
592
|
+
The demos add computational geometry and scheduling that are not part of the
|
|
593
|
+
dependency-free core. Let n be the number of input positions in a frame,
|
|
594
|
+
c the number of clipping pieces from an individual ring, z the number of
|
|
595
|
+
generated boundary samples, and s the number of minimap samples per edge.
|
|
596
|
+
|
|
597
|
+
| Algorithm | Time | Space and explanation |
|
|
598
|
+
| --------------------------------------------------------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
599
|
+
| Atlas cleanup and degenerate-ring filtering | O(n) | O(n) for cleaned paths |
|
|
600
|
+
| Exact-coordinate-connected feature groups | O((n + F)F) conservative worst-case bound | O(n + F); union-find with path halving but no rank/size balancing |
|
|
601
|
+
| D3 area/containment compatibility checks | O(n) coordinate visits for fixed probe count | Excludes D3 internals; compares source and candidate |
|
|
602
|
+
| Feature/ring spherical cap and unit-vector preprocessing | O(n) | O(F) for feature caps; O(n) for cached per-ring vectors |
|
|
603
|
+
| Cached feature-cap visibility filtering | O(F) | O(F) worst-case result; dot-product cone test is O(1) per cap |
|
|
604
|
+
| Minor-arc/cone crossings and winding scan | O(n) per ring | O(n) flags and retained pieces; crossing of one minor arc is O(1) |
|
|
605
|
+
| Ring clipping and boundary walk | O(n + c² + z) | O(n + c + z); each exit scans all entry azimuths |
|
|
606
|
+
| Padded-window clipping cache hit | O(1) | Reuses existing output; drawing still costs work |
|
|
607
|
+
| Geometry worker packing/unpacking | O(n + F) | O(n + F) typed buffers and reconstructed arrays |
|
|
608
|
+
| Zoom hysteresis, quantization, gesture updates and latest-generation checks | O(1) per ordinary update | O(active pointers) gesture state; worker queue coalescing scans pending messages linearly |
|
|
609
|
+
| Minimap viewport sampling | O(s) | O(s) projected boundary samples |
|
|
610
|
+
| Planar Canvas path/segment diagnostics | O(n) expected | O(n) shared-segment map; excludes Canvas rasterization |
|
|
611
|
+
|
|
612
|
+
Ring clipping scans original edges for crossings, then pairs each exit with
|
|
613
|
+
the next entry in the required winding direction by exhaustive search.
|
|
614
|
+
For a collection the quadratic term is the sum of c² across processed rings.
|
|
615
|
+
Each piece has at most a fixed number of boundary samples at the current
|
|
616
|
+
four-degree step, so z is O(n) at that setting. A finer configurable step
|
|
617
|
+
would increase the output term. The cached padded cone avoids recomputing
|
|
618
|
+
clipping on every small camera movement; it does not accelerate the global
|
|
619
|
+
spherical engine query or change the original topology.
|
|
620
|
+
|
|
621
|
+
The globe's fallback preprocessing can attempt a whole collection, individual
|
|
622
|
+
features, a valid subset, and connected components. A constant number of
|
|
623
|
+
dataset-wide build attempts (some divided into disjoint groups) plus
|
|
624
|
+
component grouping and compatibility checks bounds that path; it can still
|
|
625
|
+
be costly. The component algorithm's loose bound above does not claim the
|
|
626
|
+
inverse-Ackermann guarantee of union-by-rank plus path compression.
|
|
627
|
+
|
|
628
|
+
The demo caches up to 48 worker geometry frames and four client frames.
|
|
629
|
+
With K_max maximum frame size their geometry can occupy O((48 + 4)K_max)
|
|
630
|
+
space, in addition to source data, topology, in-flight messages and
|
|
631
|
+
per-frame clipping caches. Worker wire encoding stores two Float64 values
|
|
632
|
+
per coordinate plus Int32 counts for features/polygons/rings; transfer avoids
|
|
633
|
+
an extra buffer copy where supported but not packing/unpacking work.
|
|
634
|
+
Cancellation is cooperative, and one expensive feature can exceed a nominal
|
|
635
|
+
time slice.
|
|
636
|
+
|
|
637
|
+
D3 projection, adaptive resampling and clipping, Canvas rasterization,
|
|
638
|
+
MapLibre triangulation and GPU rendering are external to these bounds.
|
|
639
|
+
Geometry traversal is linear in supplied coordinates before adaptive
|
|
640
|
+
resampling; projected sample count, pixel area and renderer internals
|
|
641
|
+
determine actual rendering work. The minimap also draws full-globe context
|
|
642
|
+
even when the main view is culled.
|
|
643
|
+
|
|
644
|
+
### What these bounds imply
|
|
645
|
+
|
|
646
|
+
- The principal asymptotic bottleneck is pairwise geometric validation, not
|
|
647
|
+
Cartesian-tree construction. Spherical preprocessing candidate checks can
|
|
648
|
+
multiply that cost, in exchange for direct query reconstruction.
|
|
649
|
+
- The sparse hierarchy reduces stored grid cells from a potential O(4^L)
|
|
650
|
+
per face to O(V), and shared topology stores each distinct arc once.
|
|
651
|
+
Neither fact makes all feature queries output-sensitive.
|
|
652
|
+
- Reducing validation complexity with robust sweep-line or spatially indexed
|
|
653
|
+
intersection tests is a candidate improvement, not an implemented
|
|
654
|
+
O(n log n) guarantee. Any replacement must preserve the required
|
|
655
|
+
intersection, containment, winding and shared-boundary semantics.
|
|
656
|
+
- Avoiding unconditional full-ID scans, memoizing shared-arc selections,
|
|
657
|
+
indexing arc-to-feature dependencies, and sorting clipping events instead
|
|
658
|
+
of pairing them exhaustively are possible future optimizations. They must
|
|
659
|
+
retain deterministic output and existing validity/fallback behavior.
|
|
660
|
+
- A fair benchmark should separately measure input topology, priority
|
|
661
|
+
construction, BLG, preprocessing validation, cold/warm queries,
|
|
662
|
+
partition metadata and payload bytes, peak memory, and rendering. Compare
|
|
663
|
+
datasets with different vertex counts, feature overlap, hole counts and
|
|
664
|
+
shared-boundary ratios; vertex count alone does not characterize cost.
|
|
665
|
+
|
|
666
|
+
These bounds do not establish topological equivalence for arbitrary
|
|
667
|
+
overlapping geographic features, a screen-space error bound, or a production
|
|
668
|
+
latency guarantee. See the implementation in [src/](src/), the
|
|
669
|
+
[globe demo](examples/globe/) and [roadmap](plans/PROJECT_ROADMAP.md).
|
|
670
|
+
|
|
349
671
|
## Geometry semantics and limitations
|
|
350
672
|
|
|
351
673
|
- Supported shapes: Polygon, MultiPolygon, LineString and MultiLineString.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { FeatureCollection } from "./types.js";
|
|
2
|
+
export interface PackedGeometry {
|
|
3
|
+
coords: Float64Array;
|
|
4
|
+
meta: Int32Array;
|
|
5
|
+
}
|
|
6
|
+
/** Transferable geometry only; feature order and metadata are supplied by the original. */
|
|
7
|
+
export declare function packGeometry(geojson: FeatureCollection): PackedGeometry;
|
|
8
|
+
export declare function unpackGeometry(original: FeatureCollection, coords: Float64Array, meta: Int32Array): FeatureCollection;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
function polygons(g) {
|
|
2
|
+
if (g.type === "Polygon")
|
|
3
|
+
return [g.coordinates];
|
|
4
|
+
if (g.type === "MultiPolygon")
|
|
5
|
+
return g.coordinates;
|
|
6
|
+
throw new Error("Packed geometry supports only Polygon and MultiPolygon");
|
|
7
|
+
}
|
|
8
|
+
/** Transferable geometry only; feature order and metadata are supplied by the original. */
|
|
9
|
+
export function packGeometry(geojson) {
|
|
10
|
+
let metaLen = 0, coordCount = 0;
|
|
11
|
+
for (const f of geojson.features) {
|
|
12
|
+
const polys = polygons(f.geometry);
|
|
13
|
+
metaLen++;
|
|
14
|
+
for (const rings of polys) {
|
|
15
|
+
metaLen += 1 + rings.length;
|
|
16
|
+
for (const ring of rings)
|
|
17
|
+
coordCount += ring.length * 2;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const meta = new Int32Array(metaLen), coords = new Float64Array(coordCount);
|
|
21
|
+
let mi = 0, ci = 0;
|
|
22
|
+
for (const f of geojson.features) {
|
|
23
|
+
const polys = polygons(f.geometry);
|
|
24
|
+
meta[mi++] = polys.length;
|
|
25
|
+
for (const rings of polys) {
|
|
26
|
+
meta[mi++] = rings.length;
|
|
27
|
+
for (const ring of rings) {
|
|
28
|
+
meta[mi++] = ring.length;
|
|
29
|
+
for (const [x, y] of ring) {
|
|
30
|
+
if (!Number.isFinite(x) || !Number.isFinite(y))
|
|
31
|
+
throw new Error("Non-finite coordinate");
|
|
32
|
+
coords[ci++] = x;
|
|
33
|
+
coords[ci++] = y;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { coords, meta };
|
|
39
|
+
}
|
|
40
|
+
export function unpackGeometry(original, coords, meta) {
|
|
41
|
+
let mi = 0, ci = 0;
|
|
42
|
+
const next = (limit) => {
|
|
43
|
+
const n = meta[mi++];
|
|
44
|
+
if (n === undefined || n < 0 || n > limit)
|
|
45
|
+
throw new Error("Malformed geometry metadata");
|
|
46
|
+
return n;
|
|
47
|
+
};
|
|
48
|
+
const features = original.features.map((f) => {
|
|
49
|
+
polygons(f.geometry);
|
|
50
|
+
const count = next(meta.length - mi - 1);
|
|
51
|
+
if (f.geometry.type === "Polygon" && count !== 1)
|
|
52
|
+
throw new Error("Malformed polygon");
|
|
53
|
+
const polys = [];
|
|
54
|
+
for (let p = 0; p < count; p++) {
|
|
55
|
+
const rings = [], nr = next(meta.length - mi - 1);
|
|
56
|
+
for (let r = 0; r < nr; r++) {
|
|
57
|
+
const ring = [], np = next(Math.floor((coords.length - ci) / 2));
|
|
58
|
+
for (let k = 0; k < np; k++) {
|
|
59
|
+
const x = coords[ci++], y = coords[ci++];
|
|
60
|
+
if (!Number.isFinite(x) || !Number.isFinite(y))
|
|
61
|
+
throw new Error("Non-finite coordinate");
|
|
62
|
+
ring.push([x, y]);
|
|
63
|
+
}
|
|
64
|
+
rings.push(ring);
|
|
65
|
+
}
|
|
66
|
+
polys.push(rings);
|
|
67
|
+
}
|
|
68
|
+
const geometry = f.geometry.type === "Polygon"
|
|
69
|
+
? { type: "Polygon", coordinates: polys[0] }
|
|
70
|
+
: { type: "MultiPolygon", coordinates: polys };
|
|
71
|
+
return { ...f, geometry };
|
|
72
|
+
});
|
|
73
|
+
if (mi !== meta.length || ci !== coords.length)
|
|
74
|
+
throw new Error("Trailing geometry data");
|
|
75
|
+
return { type: "FeatureCollection", features };
|
|
76
|
+
}
|
package/dist/geometry.d.ts
CHANGED
|
@@ -7,7 +7,9 @@ export declare function assertBounds(b: Bounds): Bounds;
|
|
|
7
7
|
export declare function signedArea(ring: readonly Position[]): number;
|
|
8
8
|
/** Includes touching endpoints; callers skip adjacent polygon edges. */
|
|
9
9
|
export declare function segmentsIntersect(a: Position, b: Position, c: Position, d: Position): boolean;
|
|
10
|
-
/** O(n^2) reference predicate;
|
|
10
|
+
/** O(n^2) reference predicate; retained as the oracle for the indexed validator. */
|
|
11
|
+
export declare function simpleClosedRingReference(ring: readonly Position[]): boolean;
|
|
12
|
+
/** Sweep-and-prune over segment boxes; exact predicates only on overlapping candidates. */
|
|
11
13
|
export declare function simpleClosedRing(ring: readonly Position[]): boolean;
|
|
12
14
|
export declare function pointInRing(p: Position, ring: readonly Position[]): boolean;
|
|
13
15
|
export declare function validPolygon(rings: readonly Position[][]): boolean;
|