@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
package/dist/loader.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
function abortError() {
|
|
2
|
+
const e = new Error("Quadstream load aborted");
|
|
3
|
+
e.name = "AbortError";
|
|
4
|
+
return e;
|
|
5
|
+
}
|
|
6
|
+
function abortable(promise, signal) {
|
|
7
|
+
if (signal.aborted)
|
|
8
|
+
return Promise.reject(abortError());
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const onAbort = () => {
|
|
11
|
+
signal.removeEventListener("abort", onAbort);
|
|
12
|
+
reject(abortError());
|
|
13
|
+
};
|
|
14
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
15
|
+
promise.then((value) => {
|
|
16
|
+
signal.removeEventListener("abort", onAbort);
|
|
17
|
+
resolve(value);
|
|
18
|
+
}, (error) => {
|
|
19
|
+
signal.removeEventListener("abort", onAbort);
|
|
20
|
+
reject(error);
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** Optional, transport-independent loader around a validated progressive session. */
|
|
25
|
+
export class QuadstreamLoader {
|
|
26
|
+
session;
|
|
27
|
+
fetchPartition;
|
|
28
|
+
concurrency;
|
|
29
|
+
cacheLimit;
|
|
30
|
+
cache = new Map();
|
|
31
|
+
cachedBytes = 0;
|
|
32
|
+
latestRequest;
|
|
33
|
+
constructor(session, fetchPartition, options = {}) {
|
|
34
|
+
this.session = session;
|
|
35
|
+
this.fetchPartition = fetchPartition;
|
|
36
|
+
const { concurrency = 4, cacheBytes = 16 * 1024 * 1024 } = options;
|
|
37
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 32)
|
|
38
|
+
throw new Error("concurrency must be an integer between 1 and 32");
|
|
39
|
+
if (!Number.isSafeInteger(cacheBytes) || cacheBytes < 0)
|
|
40
|
+
throw new Error("cacheBytes must be a nonnegative safe integer");
|
|
41
|
+
this.concurrency = concurrency;
|
|
42
|
+
this.cacheLimit = cacheBytes;
|
|
43
|
+
}
|
|
44
|
+
get cachedPartitionKeys() {
|
|
45
|
+
return [...this.cache.keys()];
|
|
46
|
+
}
|
|
47
|
+
get cacheSizeBytes() {
|
|
48
|
+
return this.cachedBytes;
|
|
49
|
+
}
|
|
50
|
+
remember(key, bytes) {
|
|
51
|
+
if (bytes.byteLength > this.cacheLimit)
|
|
52
|
+
return;
|
|
53
|
+
const old = this.cache.get(key);
|
|
54
|
+
if (old) {
|
|
55
|
+
this.cachedBytes -= old.byteLength;
|
|
56
|
+
this.cache.delete(key);
|
|
57
|
+
}
|
|
58
|
+
this.cache.set(key, bytes.slice());
|
|
59
|
+
this.cachedBytes += bytes.byteLength;
|
|
60
|
+
while (this.cachedBytes > this.cacheLimit) {
|
|
61
|
+
const oldest = this.cache.keys().next().value;
|
|
62
|
+
this.cachedBytes -= this.cache.get(oldest).byteLength;
|
|
63
|
+
this.cache.delete(oldest);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Lazily fetch partitions required for this level. Already ingested keys are skipped. */
|
|
67
|
+
async ensureLevel(level, options = {}) {
|
|
68
|
+
const keys = this.session.missingKeys(level);
|
|
69
|
+
if (!keys.length)
|
|
70
|
+
return;
|
|
71
|
+
const controller = new AbortController();
|
|
72
|
+
const onAbort = () => controller.abort();
|
|
73
|
+
if (options.signal?.aborted)
|
|
74
|
+
throw abortError();
|
|
75
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
76
|
+
let next = 0;
|
|
77
|
+
try {
|
|
78
|
+
const worker = async () => {
|
|
79
|
+
while (next < keys.length) {
|
|
80
|
+
if (controller.signal.aborted)
|
|
81
|
+
throw abortError();
|
|
82
|
+
const key = keys[next++];
|
|
83
|
+
try {
|
|
84
|
+
let bytes = this.cache.get(key);
|
|
85
|
+
if (bytes) {
|
|
86
|
+
this.cache.delete(key);
|
|
87
|
+
this.cache.set(key, bytes); // refresh LRU
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
bytes = await abortable(this.fetchPartition(key, { signal: controller.signal }), controller.signal);
|
|
91
|
+
}
|
|
92
|
+
if (controller.signal.aborted)
|
|
93
|
+
throw abortError();
|
|
94
|
+
// load() validates checksum, length, record IDs, levels and duplicate records.
|
|
95
|
+
this.session.load(key, bytes);
|
|
96
|
+
this.remember(key, bytes);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
controller.abort();
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
await Promise.all(Array.from({ length: Math.min(this.concurrency, keys.length) }, () => worker()));
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Supersede the preceding latest-view request without clearing valid stored geometry. */
|
|
111
|
+
async loadLatest(query = {}) {
|
|
112
|
+
this.latestRequest?.abort();
|
|
113
|
+
const controller = new AbortController();
|
|
114
|
+
this.latestRequest = controller;
|
|
115
|
+
try {
|
|
116
|
+
await this.ensureLevel(query.level ?? this.session.manifest.maxLevel - 1, { signal: controller.signal });
|
|
117
|
+
if (controller.signal.aborted)
|
|
118
|
+
throw abortError();
|
|
119
|
+
return this.session.query(query);
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
if (this.latestRequest === controller)
|
|
123
|
+
this.latestRequest = undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
cancelLatest() {
|
|
127
|
+
this.latestRequest?.abort();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** In-memory adapter for examples and deterministic end-to-end tests. */
|
|
131
|
+
export function fetchFromBundle(bundle) {
|
|
132
|
+
return async (key) => {
|
|
133
|
+
const bytes = bundle.partitions.get(key);
|
|
134
|
+
if (!bytes)
|
|
135
|
+
throw new Error(`Missing partition in bundle: ${key}`);
|
|
136
|
+
return bytes.slice();
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
function fail(field) {
|
|
2
|
+
throw new Error("Invalid manifest: " + field);
|
|
3
|
+
}
|
|
4
|
+
function object(v, f) {
|
|
5
|
+
if (!v || typeof v !== "object" || Array.isArray(v))
|
|
6
|
+
return fail(f);
|
|
7
|
+
return v;
|
|
8
|
+
}
|
|
9
|
+
function array(v, f) {
|
|
10
|
+
if (!Array.isArray(v))
|
|
11
|
+
return fail(f);
|
|
12
|
+
return v;
|
|
13
|
+
}
|
|
14
|
+
function integer(v, min, max, f) {
|
|
15
|
+
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > max)
|
|
16
|
+
return fail(f);
|
|
17
|
+
return v;
|
|
18
|
+
}
|
|
19
|
+
function bounds(v, f) {
|
|
20
|
+
const b = array(v, f);
|
|
21
|
+
if (b.length !== 4 ||
|
|
22
|
+
b.some((x) => typeof x !== "number" || !Number.isFinite(x)) ||
|
|
23
|
+
Number(b[0]) > Number(b[2]) ||
|
|
24
|
+
Number(b[1]) > Number(b[3]))
|
|
25
|
+
fail(f);
|
|
26
|
+
}
|
|
27
|
+
export const MANIFEST_VERSION = 1;
|
|
28
|
+
/** Runtime v1 schema and cross-reference checks for untrusted JSON manifests. */
|
|
29
|
+
export function validateManifest(input) {
|
|
30
|
+
const m = object(input, "root");
|
|
31
|
+
if (m.format !== "quadstream" || m.version !== MANIFEST_VERSION)
|
|
32
|
+
throw new Error("Unsupported Quadstream manifest version");
|
|
33
|
+
const max = integer(m.maxLevel, 1, 26, "maxLevel");
|
|
34
|
+
integer(m.fileDepth, 1, max, "fileDepth");
|
|
35
|
+
bounds(m.bounds, "bounds");
|
|
36
|
+
const vertices = array(m.vertices, "vertices").map((v, i) => {
|
|
37
|
+
const x = object(v, "vertex");
|
|
38
|
+
if (x.id !== i || typeof x.critical !== "boolean")
|
|
39
|
+
fail("vertex metadata");
|
|
40
|
+
return integer(x.level, 0, max - 1, "vertex level");
|
|
41
|
+
});
|
|
42
|
+
if (!vertices.length)
|
|
43
|
+
fail("empty vertices");
|
|
44
|
+
const arcs = array(m.arcs, "arcs").map((v, i) => {
|
|
45
|
+
const a = object(v, "arc");
|
|
46
|
+
if (a.id !== i)
|
|
47
|
+
fail("arc id");
|
|
48
|
+
const ids = array(a.vertexIds, "arc vertexIds").map((x) => integer(x, 0, vertices.length - 1, "vertex reference"));
|
|
49
|
+
if (ids.length < 2)
|
|
50
|
+
fail("short arc");
|
|
51
|
+
return ids;
|
|
52
|
+
});
|
|
53
|
+
const featureIds = new Set();
|
|
54
|
+
const features = array(m.features, "features");
|
|
55
|
+
if (!features.length)
|
|
56
|
+
fail("empty features");
|
|
57
|
+
for (const raw of features) {
|
|
58
|
+
const f = object(raw, "feature");
|
|
59
|
+
if (typeof f.id !== "string" || featureIds.has(f.id))
|
|
60
|
+
fail("feature id");
|
|
61
|
+
featureIds.add(f.id);
|
|
62
|
+
object(f.properties, "properties");
|
|
63
|
+
bounds(f.bounds, "feature bounds");
|
|
64
|
+
const type = f.geometryType;
|
|
65
|
+
if (type !== "Polygon" &&
|
|
66
|
+
type !== "MultiPolygon" &&
|
|
67
|
+
type !== "LineString" &&
|
|
68
|
+
type !== "MultiLineString")
|
|
69
|
+
fail("geometry type");
|
|
70
|
+
const closed = type === "Polygon" || type === "MultiPolygon";
|
|
71
|
+
const paths = array(f.paths, "paths");
|
|
72
|
+
for (const rawPath of paths) {
|
|
73
|
+
const p = object(rawPath, "path");
|
|
74
|
+
if (p.closed !== closed)
|
|
75
|
+
fail("path closed");
|
|
76
|
+
const refs = array(p.arcs, "path arcs");
|
|
77
|
+
if (!refs.length)
|
|
78
|
+
fail("empty path");
|
|
79
|
+
let start, end;
|
|
80
|
+
for (const value of refs) {
|
|
81
|
+
const ref = integer(value, -arcs.length, arcs.length, "arc reference");
|
|
82
|
+
if (!ref)
|
|
83
|
+
fail("zero arc reference");
|
|
84
|
+
const a = arcs[Math.abs(ref) - 1], first = ref > 0 ? a[0] : a.at(-1), last = ref > 0 ? a.at(-1) : a[0];
|
|
85
|
+
if (end !== undefined && end !== first)
|
|
86
|
+
fail("disconnected path");
|
|
87
|
+
start ??= first;
|
|
88
|
+
end = last;
|
|
89
|
+
}
|
|
90
|
+
if (closed && start !== end)
|
|
91
|
+
fail("unclosed path");
|
|
92
|
+
}
|
|
93
|
+
const groups = array(f.groups, "groups"), used = new Set();
|
|
94
|
+
if (!groups.length ||
|
|
95
|
+
((type === "Polygon" || type === "LineString") && groups.length !== 1))
|
|
96
|
+
fail("group count");
|
|
97
|
+
for (const rawGroup of groups) {
|
|
98
|
+
const group = array(rawGroup, "group");
|
|
99
|
+
if (!group.length || (!closed && group.length !== 1))
|
|
100
|
+
fail("group size");
|
|
101
|
+
for (const value of group) {
|
|
102
|
+
const i = integer(value, 0, paths.length - 1, "path reference");
|
|
103
|
+
if (used.has(i))
|
|
104
|
+
fail("duplicate path reference");
|
|
105
|
+
used.add(i);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (used.size !== paths.length)
|
|
109
|
+
fail("path accounting");
|
|
110
|
+
}
|
|
111
|
+
const keys = new Set(), assigned = new Set();
|
|
112
|
+
for (const raw of array(m.partitions, "partitions")) {
|
|
113
|
+
const p = object(raw, "partition");
|
|
114
|
+
if (typeof p.key !== "string" ||
|
|
115
|
+
!/^(base|[0-9]{1,2}_[0-9]{1,8}_[0-9]{1,8})$/.test(p.key) ||
|
|
116
|
+
keys.has(p.key))
|
|
117
|
+
fail("partition key");
|
|
118
|
+
keys.add(p.key);
|
|
119
|
+
bounds(p.bounds, "partition bounds");
|
|
120
|
+
if (typeof p.checksum !== "string" || !/^[0-9a-f]{8}$/.test(p.checksum))
|
|
121
|
+
fail("checksum");
|
|
122
|
+
const ids = array(p.vertexIds, "partition vertexIds");
|
|
123
|
+
if (!ids.length ||
|
|
124
|
+
ids.length > 1_000_000 ||
|
|
125
|
+
p.byteLength !== 10 + 22 * ids.length)
|
|
126
|
+
fail("partition byte length or record count");
|
|
127
|
+
let min = max;
|
|
128
|
+
for (const rawId of ids) {
|
|
129
|
+
const id = integer(rawId, 0, vertices.length - 1, "partition vertex reference");
|
|
130
|
+
if (assigned.has(id))
|
|
131
|
+
fail("duplicate partition vertex");
|
|
132
|
+
assigned.add(id);
|
|
133
|
+
min = Math.min(min, vertices[id]);
|
|
134
|
+
}
|
|
135
|
+
if (p.minLevel !== min)
|
|
136
|
+
fail("partition minLevel");
|
|
137
|
+
}
|
|
138
|
+
if (assigned.size !== vertices.length)
|
|
139
|
+
fail("partition vertex accounting");
|
|
140
|
+
return input;
|
|
141
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { MapFrame, ProgressiveMapClient } from "./progressive-map.js";
|
|
2
|
+
import type { Bounds } from "./types.js";
|
|
3
|
+
interface MapBounds {
|
|
4
|
+
getWest(): number;
|
|
5
|
+
getSouth(): number;
|
|
6
|
+
getEast(): number;
|
|
7
|
+
getNorth(): number;
|
|
8
|
+
}
|
|
9
|
+
export interface MapLibreLike {
|
|
10
|
+
getZoom(): number;
|
|
11
|
+
getBounds(): MapBounds;
|
|
12
|
+
getSource(id: string): unknown;
|
|
13
|
+
on(event: "movestart" | "moveend", listener: () => void): unknown;
|
|
14
|
+
off(event: "movestart" | "moveend", listener: () => void): unknown;
|
|
15
|
+
}
|
|
16
|
+
export interface MapLibreAdapterOptions {
|
|
17
|
+
sourceId: string;
|
|
18
|
+
maxLevel: number;
|
|
19
|
+
levelForZoom?: (zoom: number) => number;
|
|
20
|
+
onFrame?: (frame: MapFrame) => void;
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
onLoading?: () => void;
|
|
23
|
+
}
|
|
24
|
+
/** Conservative global query for wrap, invalid bounds or dateline crossing. */
|
|
25
|
+
export declare function mapLibreBounds(b: MapBounds): Bounds | undefined;
|
|
26
|
+
export declare function attachMapLibre(map: MapLibreLike, client: ProgressiveMapClient, options: MapLibreAdapterOptions): {
|
|
27
|
+
refresh: () => Promise<void>;
|
|
28
|
+
dispose(): void;
|
|
29
|
+
};
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/** Conservative global query for wrap, invalid bounds or dateline crossing. */
|
|
2
|
+
export function mapLibreBounds(b) {
|
|
3
|
+
const w = b.getWest(), s = b.getSouth(), e = b.getEast(), n = b.getNorth();
|
|
4
|
+
if (![w, s, e, n].every(Number.isFinite) ||
|
|
5
|
+
w < -180 ||
|
|
6
|
+
e > 180 ||
|
|
7
|
+
w > e ||
|
|
8
|
+
e - w >= 360 ||
|
|
9
|
+
s > n ||
|
|
10
|
+
s > 90 ||
|
|
11
|
+
n < -90)
|
|
12
|
+
return undefined;
|
|
13
|
+
return [w, Math.max(-90, s), e, Math.min(90, n)];
|
|
14
|
+
}
|
|
15
|
+
export function attachMapLibre(map, client, options) {
|
|
16
|
+
if (!Number.isInteger(options.maxLevel) ||
|
|
17
|
+
options.maxLevel < 1 ||
|
|
18
|
+
options.maxLevel > 26)
|
|
19
|
+
throw new Error("Invalid maxLevel");
|
|
20
|
+
let generation = 0, disposed = false;
|
|
21
|
+
const source = () => {
|
|
22
|
+
const value = map.getSource(options.sourceId);
|
|
23
|
+
if (!value || typeof value.setData !== "function")
|
|
24
|
+
throw new Error("GeoJSON source missing: " + options.sourceId);
|
|
25
|
+
return value;
|
|
26
|
+
};
|
|
27
|
+
source();
|
|
28
|
+
const clear = () => source().setData({ type: "FeatureCollection", features: [] });
|
|
29
|
+
const moving = () => {
|
|
30
|
+
++generation;
|
|
31
|
+
client.cancel();
|
|
32
|
+
try {
|
|
33
|
+
clear();
|
|
34
|
+
options.onLoading?.();
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
options.onError?.(error);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const refresh = async () => {
|
|
41
|
+
if (disposed)
|
|
42
|
+
return;
|
|
43
|
+
const id = ++generation;
|
|
44
|
+
client.cancel();
|
|
45
|
+
try {
|
|
46
|
+
clear();
|
|
47
|
+
options.onLoading?.();
|
|
48
|
+
const zoom = map.getZoom(), level = options.levelForZoom?.(zoom) ?? Math.floor(zoom + 2);
|
|
49
|
+
if (!Number.isFinite(level))
|
|
50
|
+
throw new Error("Invalid detail level");
|
|
51
|
+
await client.request({
|
|
52
|
+
level: Math.max(0, Math.min(options.maxLevel - 1, Math.floor(level))),
|
|
53
|
+
bounds: mapLibreBounds(map.getBounds()),
|
|
54
|
+
}, (frame) => {
|
|
55
|
+
if (disposed || id !== generation)
|
|
56
|
+
return;
|
|
57
|
+
source().setData(frame.result.geojson);
|
|
58
|
+
options.onFrame?.(frame);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (!disposed && id === generation)
|
|
63
|
+
options.onError?.(error);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const moved = () => {
|
|
67
|
+
void refresh();
|
|
68
|
+
};
|
|
69
|
+
map.on("movestart", moving);
|
|
70
|
+
map.on("moveend", moved);
|
|
71
|
+
void refresh();
|
|
72
|
+
return {
|
|
73
|
+
refresh,
|
|
74
|
+
dispose() {
|
|
75
|
+
if (disposed)
|
|
76
|
+
return;
|
|
77
|
+
disposed = true;
|
|
78
|
+
++generation;
|
|
79
|
+
client.cancel();
|
|
80
|
+
map.off("movestart", moving);
|
|
81
|
+
map.off("moveend", moved);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Bounds, PartitionBundle, PartitionRecord, QuadstreamManifest } from "./types.js";
|
|
2
|
+
import { QuadstreamDataset } from "./dataset.js";
|
|
3
|
+
export declare function encodePartition(records: readonly PartitionRecord[]): Uint8Array;
|
|
4
|
+
export declare function decodePartition(bytes: Uint8Array, maxRecords?: number): PartitionRecord[];
|
|
5
|
+
/** FNV-1a detects accidental corruption; this is not an authentication signature. */
|
|
6
|
+
export declare function checksum(bytes: Uint8Array): string;
|
|
7
|
+
export declare function exportPartitions(dataset: QuadstreamDataset, { fileDepth }?: {
|
|
8
|
+
fileDepth?: number;
|
|
9
|
+
}): PartitionBundle;
|
|
10
|
+
/** Conservative request planner: all partitions with relevant importance. No incorrect bbox-only pruning. */
|
|
11
|
+
export declare function requiredPartitionKeys(manifest: QuadstreamManifest, level: number): string[];
|
|
12
|
+
/** Coverage is diagnostic only: a line can cross the view even when its vertices do not. */
|
|
13
|
+
export declare function partitionsWithVerticesInBounds(manifest: QuadstreamManifest, bounds: Bounds): string[];
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { boundsOf, intersects } from "./geometry.js";
|
|
2
|
+
const MAGIC = [81, 83, 84, 82]; // QSTR
|
|
3
|
+
const VERSION = 1, HEADER_BYTES = 10, RECORD_BYTES = 22;
|
|
4
|
+
export function encodePartition(records) {
|
|
5
|
+
if (records.length > (2 ** 32 - 1) / RECORD_BYTES)
|
|
6
|
+
throw new Error("Partition too large");
|
|
7
|
+
const bytes = new Uint8Array(HEADER_BYTES + records.length * RECORD_BYTES);
|
|
8
|
+
bytes.set(MAGIC, 0);
|
|
9
|
+
const view = new DataView(bytes.buffer);
|
|
10
|
+
view.setUint16(4, VERSION, true);
|
|
11
|
+
view.setUint32(6, records.length, true);
|
|
12
|
+
for (let i = 0; i < records.length; i++) {
|
|
13
|
+
const { id, x, y, level } = records[i], offset = HEADER_BYTES + i * RECORD_BYTES;
|
|
14
|
+
if (!Number.isInteger(id) ||
|
|
15
|
+
id < 0 ||
|
|
16
|
+
id > 0xffffffff ||
|
|
17
|
+
!Number.isFinite(x) ||
|
|
18
|
+
!Number.isFinite(y) ||
|
|
19
|
+
!Number.isInteger(level) ||
|
|
20
|
+
level < 0 ||
|
|
21
|
+
level > 65535)
|
|
22
|
+
throw new Error("Invalid partition record");
|
|
23
|
+
view.setUint32(offset, id, true);
|
|
24
|
+
view.setFloat64(offset + 4, x, true);
|
|
25
|
+
view.setFloat64(offset + 12, y, true);
|
|
26
|
+
view.setUint16(offset + 20, level, true);
|
|
27
|
+
}
|
|
28
|
+
return bytes;
|
|
29
|
+
}
|
|
30
|
+
export function decodePartition(bytes, maxRecords = 1_000_000) {
|
|
31
|
+
if (bytes.byteLength < HEADER_BYTES || MAGIC.some((v, i) => bytes[i] !== v))
|
|
32
|
+
throw new Error("Invalid Quadstream partition magic");
|
|
33
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
34
|
+
if (view.getUint16(4, true) !== VERSION)
|
|
35
|
+
throw new Error("Unsupported Quadstream partition version");
|
|
36
|
+
const n = view.getUint32(6, true);
|
|
37
|
+
if (n > maxRecords || bytes.length !== HEADER_BYTES + n * RECORD_BYTES)
|
|
38
|
+
throw new Error("Invalid partition length or record limit");
|
|
39
|
+
const out = [];
|
|
40
|
+
for (let i = 0; i < n; i++) {
|
|
41
|
+
const offset = HEADER_BYTES + i * RECORD_BYTES;
|
|
42
|
+
const record = {
|
|
43
|
+
id: view.getUint32(offset, true),
|
|
44
|
+
x: view.getFloat64(offset + 4, true),
|
|
45
|
+
y: view.getFloat64(offset + 12, true),
|
|
46
|
+
level: view.getUint16(offset + 20, true),
|
|
47
|
+
};
|
|
48
|
+
if (!Number.isFinite(record.x) || !Number.isFinite(record.y))
|
|
49
|
+
throw new Error("Invalid partition coordinate");
|
|
50
|
+
out.push(record);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
/** FNV-1a detects accidental corruption; this is not an authentication signature. */
|
|
55
|
+
export function checksum(bytes) {
|
|
56
|
+
let h = 0x811c9dc5;
|
|
57
|
+
for (const b of bytes) {
|
|
58
|
+
h ^= b;
|
|
59
|
+
h = Math.imul(h, 0x01000193);
|
|
60
|
+
}
|
|
61
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
62
|
+
}
|
|
63
|
+
export function exportPartitions(dataset, { fileDepth = 4 } = {}) {
|
|
64
|
+
if (!Number.isInteger(fileDepth) ||
|
|
65
|
+
fileDepth < 1 ||
|
|
66
|
+
fileDepth > dataset.quadtree.maxLevel)
|
|
67
|
+
throw new Error("Invalid fileDepth");
|
|
68
|
+
const byKey = new Map(), cells = dataset.quadtree.cells;
|
|
69
|
+
for (const cell of cells) {
|
|
70
|
+
const v = dataset.topology.vertices[cell.vertexId];
|
|
71
|
+
const groupLevel = Math.floor(cell.level / fileDepth) * fileDepth;
|
|
72
|
+
const shift = cell.level - groupLevel;
|
|
73
|
+
const key = v.critical || groupLevel === 0
|
|
74
|
+
? "base"
|
|
75
|
+
: `${groupLevel}_${Math.floor(cell.i / 2 ** shift)}_${Math.floor(cell.j / 2 ** shift)}`;
|
|
76
|
+
if (!byKey.has(key))
|
|
77
|
+
byKey.set(key, []);
|
|
78
|
+
byKey.get(key).push({ id: v.id, x: v.x, y: v.y, level: cell.level });
|
|
79
|
+
}
|
|
80
|
+
const partitions = new Map(), infos = [];
|
|
81
|
+
for (const key of [...byKey.keys()].sort((a, b) => a === "base" ? -1 : b === "base" ? 1 : a.localeCompare(b))) {
|
|
82
|
+
const records = byKey.get(key).sort((a, b) => a.id - b.id), bytes = encodePartition(records);
|
|
83
|
+
const bounds = boundsOf(records.map((r) => [r.x, r.y]));
|
|
84
|
+
partitions.set(key, bytes);
|
|
85
|
+
infos.push({
|
|
86
|
+
key,
|
|
87
|
+
byteLength: bytes.byteLength,
|
|
88
|
+
checksum: checksum(bytes),
|
|
89
|
+
vertexIds: records.map((r) => r.id),
|
|
90
|
+
minLevel: records.reduce((min, r) => Math.min(min, r.level), Infinity),
|
|
91
|
+
bounds,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
const manifest = {
|
|
95
|
+
format: "quadstream",
|
|
96
|
+
version: VERSION,
|
|
97
|
+
maxLevel: dataset.quadtree.maxLevel,
|
|
98
|
+
fileDepth,
|
|
99
|
+
bounds: dataset.topology.bounds,
|
|
100
|
+
features: dataset.topology.features,
|
|
101
|
+
arcs: dataset.topology.arcs,
|
|
102
|
+
vertices: dataset.topology.vertices.map((v) => ({
|
|
103
|
+
id: v.id,
|
|
104
|
+
level: dataset.quadtree.levelByVertexId[v.id],
|
|
105
|
+
critical: v.critical,
|
|
106
|
+
})),
|
|
107
|
+
partitions: infos,
|
|
108
|
+
};
|
|
109
|
+
return { manifest, partitions };
|
|
110
|
+
}
|
|
111
|
+
/** Conservative request planner: all partitions with relevant importance. No incorrect bbox-only pruning. */
|
|
112
|
+
export function requiredPartitionKeys(manifest, level) {
|
|
113
|
+
if (!Number.isInteger(level) || level < 0 || level >= manifest.maxLevel)
|
|
114
|
+
throw new Error("Invalid query level");
|
|
115
|
+
return manifest.partitions
|
|
116
|
+
.filter((p) => p.minLevel <= level || p.key === "base")
|
|
117
|
+
.map((p) => p.key);
|
|
118
|
+
}
|
|
119
|
+
/** Coverage is diagnostic only: a line can cross the view even when its vertices do not. */
|
|
120
|
+
export function partitionsWithVerticesInBounds(manifest, bounds) {
|
|
121
|
+
return manifest.partitions
|
|
122
|
+
.filter((p) => intersects(p.bounds, bounds))
|
|
123
|
+
.map((p) => p.key);
|
|
124
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { QuadstreamLoader } from "./loader.js";
|
|
2
|
+
import type { QuadstreamSession } from "./session.js";
|
|
3
|
+
import type { QueryOptions } from "./types.js";
|
|
4
|
+
export type MapQuery = Omit<QueryOptions, "validate">;
|
|
5
|
+
export interface MapFrame {
|
|
6
|
+
result: ReturnType<QuadstreamSession["query"]>;
|
|
7
|
+
targetLevel: number;
|
|
8
|
+
final: boolean;
|
|
9
|
+
loadedPartitions: number;
|
|
10
|
+
totalPartitions: number;
|
|
11
|
+
}
|
|
12
|
+
export interface ProgressiveMapClient {
|
|
13
|
+
request(query: MapQuery, onFrame: (frame: MapFrame) => void): Promise<void>;
|
|
14
|
+
cancel(): void;
|
|
15
|
+
}
|
|
16
|
+
/** Staged, renderer-independent queries. Partial frames explicitly report omissions. */
|
|
17
|
+
export declare class ProgressiveMap implements ProgressiveMapClient {
|
|
18
|
+
readonly loader: QuadstreamLoader;
|
|
19
|
+
private active?;
|
|
20
|
+
private readonly retries;
|
|
21
|
+
private readonly retryDelay;
|
|
22
|
+
constructor(loader: QuadstreamLoader, options?: {
|
|
23
|
+
retries?: number;
|
|
24
|
+
retryDelayMs?: number;
|
|
25
|
+
});
|
|
26
|
+
cancel(): void;
|
|
27
|
+
request(query: MapQuery, onFrame: (frame: MapFrame) => void): Promise<void>;
|
|
28
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
function aborted() {
|
|
2
|
+
const e = new Error("Map request cancelled");
|
|
3
|
+
e.name = "AbortError";
|
|
4
|
+
return e;
|
|
5
|
+
}
|
|
6
|
+
function delay(ms, signal) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
if (signal.aborted) {
|
|
9
|
+
reject(aborted());
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
const cancel = () => {
|
|
13
|
+
clearTimeout(timer);
|
|
14
|
+
reject(aborted());
|
|
15
|
+
};
|
|
16
|
+
const timer = setTimeout(() => {
|
|
17
|
+
signal.removeEventListener("abort", cancel);
|
|
18
|
+
resolve();
|
|
19
|
+
}, ms);
|
|
20
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** Staged, renderer-independent queries. Partial frames explicitly report omissions. */
|
|
24
|
+
export class ProgressiveMap {
|
|
25
|
+
loader;
|
|
26
|
+
active;
|
|
27
|
+
retries;
|
|
28
|
+
retryDelay;
|
|
29
|
+
constructor(loader, options = {}) {
|
|
30
|
+
this.loader = loader;
|
|
31
|
+
this.retries = options.retries ?? 2;
|
|
32
|
+
this.retryDelay = options.retryDelayMs ?? 100;
|
|
33
|
+
if (!Number.isInteger(this.retries) ||
|
|
34
|
+
this.retries < 0 ||
|
|
35
|
+
this.retries > 5 ||
|
|
36
|
+
!Number.isFinite(this.retryDelay) ||
|
|
37
|
+
this.retryDelay < 0 ||
|
|
38
|
+
this.retryDelay > 5000)
|
|
39
|
+
throw new Error("Invalid retry options");
|
|
40
|
+
}
|
|
41
|
+
cancel() {
|
|
42
|
+
this.active?.abort();
|
|
43
|
+
this.active = undefined;
|
|
44
|
+
}
|
|
45
|
+
async request(query, onFrame) {
|
|
46
|
+
this.cancel();
|
|
47
|
+
const controller = new AbortController();
|
|
48
|
+
this.active = controller;
|
|
49
|
+
const { signal } = controller, session = this.loader.session;
|
|
50
|
+
const target = query.level ?? session.manifest.maxLevel - 1;
|
|
51
|
+
const bounds = query.bounds
|
|
52
|
+
? [...query.bounds]
|
|
53
|
+
: undefined;
|
|
54
|
+
const check = () => {
|
|
55
|
+
if (signal.aborted || this.active !== controller)
|
|
56
|
+
throw aborted();
|
|
57
|
+
};
|
|
58
|
+
const ensure = async (level) => {
|
|
59
|
+
for (let attempt = 0;; attempt++) {
|
|
60
|
+
check();
|
|
61
|
+
try {
|
|
62
|
+
await this.loader.ensureLevel(level, { signal });
|
|
63
|
+
check();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
check();
|
|
68
|
+
if (attempt >= this.retries)
|
|
69
|
+
throw error;
|
|
70
|
+
await delay(this.retryDelay * 2 ** attempt, signal);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const emit = (level, final) => {
|
|
75
|
+
check();
|
|
76
|
+
const result = session.query({ level, bounds });
|
|
77
|
+
if (final && !result.complete)
|
|
78
|
+
throw new Error("Incomplete final geometry");
|
|
79
|
+
onFrame({
|
|
80
|
+
result,
|
|
81
|
+
targetLevel: target,
|
|
82
|
+
final,
|
|
83
|
+
loadedPartitions: session.loadedKeys.length,
|
|
84
|
+
totalPartitions: session.manifest.partitions.length,
|
|
85
|
+
});
|
|
86
|
+
check();
|
|
87
|
+
};
|
|
88
|
+
try {
|
|
89
|
+
session.missingKeys(target);
|
|
90
|
+
session.query({ level: target, bounds }); // validate bounds before fetching
|
|
91
|
+
for (const level of [...new Set([0, Math.floor(target / 2), target])]) {
|
|
92
|
+
await ensure(level);
|
|
93
|
+
const global = session.query({ level });
|
|
94
|
+
if (level === target) {
|
|
95
|
+
if (!global.complete) {
|
|
96
|
+
emit(level, false);
|
|
97
|
+
await ensure(session.manifest.maxLevel - 1);
|
|
98
|
+
if (!session.query({ level }).complete)
|
|
99
|
+
throw new Error("Incomplete global geometry");
|
|
100
|
+
}
|
|
101
|
+
emit(level, true);
|
|
102
|
+
}
|
|
103
|
+
else
|
|
104
|
+
emit(level, false);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
if (this.active === controller)
|
|
109
|
+
this.active = undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|