@vizhub/quadstream 0.2.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +49 -323
  3. package/bin/quadstream.mjs +8 -6
  4. package/dist/blg.d.ts +3 -0
  5. package/dist/blg.js +14 -1
  6. package/dist/cooperative.d.ts +21 -0
  7. package/dist/cooperative.js +33 -0
  8. package/dist/dataset.d.ts +8 -4
  9. package/dist/dataset.js +51 -14
  10. package/dist/geometry-wire.d.ts +8 -0
  11. package/dist/geometry-wire.js +76 -0
  12. package/dist/geometry.d.ts +3 -1
  13. package/dist/geometry.js +115 -5
  14. package/dist/index.d.ts +20 -2
  15. package/dist/index.js +9 -1
  16. package/dist/loader.d.ts +1 -1
  17. package/dist/loader.js +1 -1
  18. package/dist/lod-scheduler.d.ts +15 -0
  19. package/dist/lod-scheduler.js +85 -0
  20. package/dist/progressive-map.d.ts +1 -1
  21. package/dist/progressive-map.js +12 -8
  22. package/dist/quadtree.d.ts +2 -0
  23. package/dist/quadtree.js +12 -0
  24. package/dist/reconstruct.d.ts +18 -1
  25. package/dist/reconstruct.js +94 -32
  26. package/dist/session.d.ts +12 -9
  27. package/dist/session.js +24 -7
  28. package/dist/spherical-clip.d.ts +95 -0
  29. package/dist/spherical-clip.js +557 -0
  30. package/dist/spherical-cull.d.ts +25 -0
  31. package/dist/spherical-cull.js +102 -0
  32. package/dist/spherical-dataset.d.ts +41 -9
  33. package/dist/spherical-dataset.js +221 -122
  34. package/dist/spherical-geometry.d.ts +2 -0
  35. package/dist/spherical-geometry.js +87 -44
  36. package/dist/spherical-line.d.ts +29 -0
  37. package/dist/spherical-line.js +221 -0
  38. package/dist/spherical-preprocess.d.ts +23 -0
  39. package/dist/spherical-preprocess.js +160 -0
  40. package/dist/spherical-repair.d.ts +17 -0
  41. package/dist/spherical-repair.js +100 -0
  42. package/dist/spherical-robust-dataset.d.ts +27 -0
  43. package/dist/spherical-robust-dataset.js +89 -0
  44. package/dist/spherical-view-clipper.d.ts +22 -0
  45. package/dist/spherical-view-clipper.js +85 -0
  46. package/dist/topology.d.ts +3 -0
  47. package/dist/topology.js +40 -9
  48. package/dist/types.d.ts +5 -1
  49. package/package.json +12 -7
@@ -1,3 +1,4 @@
1
+ import { type Work } from "./cooperative.js";
1
2
  import { type BlgTree } from "./blg.js";
2
3
  import type { Arc, Feature, Position, TopologyFeature } from "./types.js";
3
4
  export interface CoordinateLookup {
@@ -8,6 +9,22 @@ export interface ReconstructionResult {
8
9
  missing: boolean;
9
10
  valid: boolean;
10
11
  selectedVertices: number;
12
+ /** Closed rings omitted from the output (hidden or collapsed). */
13
+ hiddenRings: number;
14
+ }
15
+ export type CollapsedRingPolicy = "restore" | "drop";
16
+ export interface ReconstructOptions {
17
+ /**
18
+ * A closed ring with fewer than 3 distinct selected vertices is either
19
+ * restored to its original vertices (default) or dropped: a hidden exterior
20
+ * drops its whole polygon, a hidden hole is filled. Topology anchors keep
21
+ * rings from collapsing in practice; `hiddenPaths` is what hides islands.
22
+ */
23
+ collapsed?: CollapsedRingPolicy;
24
+ /** Path indices that are omitted without being reconstructed. */
25
+ hiddenPaths?: ReadonlySet<number>;
11
26
  }
12
27
  export declare function buildArcTrees(arcs: readonly Arc[], levels: readonly number[], critical?: readonly boolean[]): BlgTree[];
13
- export declare function reconstructFeature(f: TopologyFeature, arcs: readonly Arc[], trees: readonly BlgTree[], level: number | ((arcId: number) => number), lookup: CoordinateLookup, includeMissing?: boolean, planarValidity?: boolean): ReconstructionResult;
28
+ export declare function buildArcTreeSteps(arcs: readonly Arc[], levels: readonly number[], critical?: readonly boolean[]): Work<BlgTree[]>;
29
+ export declare function reconstructFeature(f: TopologyFeature, arcs: readonly Arc[], trees: readonly BlgTree[], level: number | ((arcId: number) => number), lookup: CoordinateLookup, _includeMissing?: boolean, planarValidity?: boolean, options?: ReconstructOptions): ReconstructionResult;
30
+ export declare function reconstructFeatureSteps(f: TopologyFeature, arcs: readonly Arc[], trees: readonly BlgTree[], level: number | ((arcId: number) => number), lookup: CoordinateLookup, planarValidity?: boolean, options?: ReconstructOptions): Work<ReconstructionResult>;
@@ -1,31 +1,81 @@
1
- import { validPolygon, simpleClosedRing } from "./geometry.js";
2
- import { buildBlgTree, selectBlgPositions, stableBlgRandom, } from "./blg.js";
1
+ import { runSync } from "./cooperative.js";
2
+ import { validPolygon } from "./geometry.js";
3
+ import { buildBlgTreeSteps, selectBlgPositionSteps, stableBlgRandom, } from "./blg.js";
3
4
  export function buildArcTrees(arcs, levels, critical = []) {
4
- return arcs.map((arc) => buildBlgTree(arc.vertexIds.map((id, i) => i === 0 || i === arc.vertexIds.length - 1 ? 0 : levels[id]), arc.vertexIds.map((id) => (critical[id] ? 1 : stableBlgRandom(id)))));
5
+ return runSync(buildArcTreeSteps(arcs, levels, critical));
5
6
  }
6
- export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing = false, planarValidity = true) {
7
+ export function* buildArcTreeSteps(arcs, levels, critical = []) {
8
+ const trees = [];
9
+ for (const arc of arcs) {
10
+ if (trees.length % 128 === 0)
11
+ yield {
12
+ stage: "Build BLG trees",
13
+ completed: trees.length,
14
+ total: arcs.length,
15
+ };
16
+ trees.push(yield* buildBlgTreeSteps(arc.vertexIds.map((id, i) => i === 0 || i === arc.vertexIds.length - 1 ? 0 : levels[id]), arc.vertexIds.map((id) => (critical[id] ? 1 : stableBlgRandom(id)))));
17
+ }
18
+ return trees;
19
+ }
20
+ /** True when fewer than 3 distinct positions precede the closing vertex. */
21
+ function distinctBelow3(coords) {
22
+ const n = coords.length - 1;
23
+ let first, second;
24
+ for (let i = 0; i < n; i++) {
25
+ const p = coords[i];
26
+ if (!first)
27
+ first = p;
28
+ else if (p[0] !== first[0] || p[1] !== first[1]) {
29
+ if (!second)
30
+ second = p;
31
+ else if ((p[0] !== second[0] || p[1] !== second[1]) &&
32
+ (first[0] !== second[0] || first[1] !== second[1]))
33
+ return false;
34
+ }
35
+ }
36
+ return true;
37
+ }
38
+ export function reconstructFeature(f, arcs, trees, level, lookup,
39
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
40
+ _includeMissing = false, planarValidity = true, options = {}) {
41
+ return runSync(reconstructFeatureSteps(f, arcs, trees, level, lookup, planarValidity, options));
42
+ }
43
+ export function* reconstructFeatureSteps(f, arcs, trees, level, lookup, planarValidity = true, options = {}) {
7
44
  let missing = false, selectedVertices = 0;
45
+ const dropCollapsed = options.collapsed === "drop";
46
+ const hidden = new Set(options.hiddenPaths);
47
+ // Holes of a hidden exterior go with it, so they are never reconstructed.
48
+ const shellOf = [];
49
+ if (f.geometryType === "Polygon" || f.geometryType === "MultiPolygon")
50
+ for (const group of f.groups)
51
+ for (const p of group) {
52
+ shellOf[p] = group[0];
53
+ if (hidden.has(group[0]))
54
+ hidden.add(p);
55
+ }
8
56
  const paths = [];
9
- for (const path of f.paths) {
10
- const coords = [], allIds = [];
57
+ for (let pathIndex = 0; pathIndex < f.paths.length; pathIndex++) {
58
+ if (pathIndex % 32 === 0)
59
+ yield undefined;
60
+ const path = f.paths[pathIndex];
61
+ if (hidden.has(pathIndex) || hidden.has(shellOf[pathIndex] ?? -1)) {
62
+ hidden.add(pathIndex);
63
+ paths.push([]);
64
+ continue;
65
+ }
66
+ const coords = [];
11
67
  let pathSelectedVertices = 0;
12
68
  for (const ref of path.arcs) {
13
69
  const arcId = Math.abs(ref) - 1, arc = arcs[arcId], tree = trees[arcId];
14
- const positions = selectBlgPositions(tree, typeof level === "number" ? level : level(arcId));
15
- if (ref < 0)
16
- positions.reverse();
17
- const orderedIds = ref < 0 ? [...arc.vertexIds].reverse() : arc.vertexIds;
18
- for (const id of orderedIds)
19
- if (!allIds.length || allIds.at(-1) !== id)
20
- allIds.push(id);
70
+ const positions = yield* selectBlgPositionSteps(tree, typeof level === "number" ? level : level(arcId));
71
+ const last = positions.length - 1;
21
72
  for (let i = 0; i < positions.length; i++) {
22
- const id = arc.vertexIds[positions[i]], xy = lookup(id);
73
+ if (i % 512 === 0)
74
+ yield undefined;
75
+ const id = arc.vertexIds[positions[ref < 0 ? last - i : i]], xy = lookup(id);
23
76
  if (!xy) {
24
77
  missing = true;
25
- if (includeMissing)
26
- continue;
27
- else
28
- continue;
78
+ continue;
29
79
  }
30
80
  if (coords.length &&
31
81
  i === 0 &&
@@ -36,12 +86,26 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
36
86
  pathSelectedVertices++;
37
87
  }
38
88
  }
39
- if (path.closed) {
40
- const distinct = new Set(coords.slice(0, -1).map((p) => p.join(",")));
41
- if (distinct.size < 3) {
42
- coords.length = 0;
43
- pathSelectedVertices = 0;
44
- for (const id of allIds) {
89
+ if (path.closed && dropCollapsed && distinctBelow3(coords)) {
90
+ hidden.add(pathIndex);
91
+ paths.push([]);
92
+ continue;
93
+ }
94
+ if (path.closed && distinctBelow3(coords)) {
95
+ // Collapsed ring: restore every original vertex. Only this rare path
96
+ // pays for walking all arc positions.
97
+ coords.length = 0;
98
+ pathSelectedVertices = 0;
99
+ let lastId = -1;
100
+ for (const ref of path.arcs) {
101
+ const ids = arcs[Math.abs(ref) - 1].vertexIds;
102
+ for (let k = 0; k < ids.length; k++) {
103
+ if (k % 512 === 0)
104
+ yield undefined;
105
+ const id = ids[ref < 0 ? ids.length - 1 - k : k];
106
+ if (id === lastId)
107
+ continue;
108
+ lastId = id;
45
109
  const xy = lookup(id);
46
110
  if (xy &&
47
111
  (!coords.length ||
@@ -62,14 +126,16 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
62
126
  selectedVertices += pathSelectedVertices;
63
127
  paths.push(coords);
64
128
  }
65
- const groups = f.groups.map((group) => group.map((i) => paths[i]));
129
+ const groups = f.groups
130
+ .filter((group) => !hidden.has(group[0]))
131
+ .map((group) => group.filter((i) => !hidden.has(i)).map((i) => paths[i]));
66
132
  let geometry;
67
133
  let valid = true;
68
134
  const checkPolygon = planarValidity ? validPolygon : () => true;
69
135
  switch (f.geometryType) {
70
136
  case "Polygon":
71
- geometry = { type: "Polygon", coordinates: groups[0] };
72
- valid = checkPolygon(groups[0]);
137
+ geometry = { type: "Polygon", coordinates: groups[0] ?? [] };
138
+ valid = !groups[0] || checkPolygon(groups[0]);
73
139
  break;
74
140
  case "MultiPolygon":
75
141
  geometry = { type: "MultiPolygon", coordinates: groups };
@@ -87,11 +153,6 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
87
153
  valid = groups.every((g) => g[0].length >= 2);
88
154
  break;
89
155
  }
90
- // A closed ring whose last segment collapses must not be accepted by accident.
91
- if (planarValidity &&
92
- f.geometryType === "Polygon" &&
93
- !groups[0].every(simpleClosedRing))
94
- valid = false;
95
156
  return {
96
157
  feature: {
97
158
  type: "Feature",
@@ -102,5 +163,6 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
102
163
  missing,
103
164
  valid,
104
165
  selectedVertices,
166
+ hiddenRings: hidden.size,
105
167
  };
106
168
  }
package/dist/session.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type CooperativeOptions } from "./cooperative.js";
1
2
  import type { FeatureCollection, QuadstreamManifest, QueryOptions } from "./types.js";
2
3
  /** Progressive session: validates every partition before changing observable state. */
3
4
  export declare class QuadstreamSession {
@@ -12,13 +13,15 @@ export declare class QuadstreamSession {
12
13
  load(key: string, bytes: Uint8Array): boolean;
13
14
  get loadedKeys(): string[];
14
15
  missingKeys(level: number): string[];
15
- query(options?: QueryOptions): {
16
- geojson: FeatureCollection;
17
- complete: boolean;
18
- level: number;
19
- missingKeys: string[];
20
- omittedFeatures: number;
21
- selectedVertices: number;
22
- usedFallback: boolean;
23
- };
16
+ query(options?: QueryOptions & CooperativeOptions): Promise<SessionQueryResult>;
17
+ private querySteps;
18
+ }
19
+ export interface SessionQueryResult {
20
+ geojson: FeatureCollection;
21
+ complete: boolean;
22
+ level: number;
23
+ missingKeys: string[];
24
+ omittedFeatures: number;
25
+ selectedVertices: number;
26
+ usedFallback: boolean;
24
27
  }
package/dist/session.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { runSync, runCooperative, } from "./cooperative.js";
1
2
  import { assertBounds } from "./geometry.js";
2
- import { buildArcTrees, reconstructFeature } from "./reconstruct.js";
3
+ import { buildArcTrees, reconstructFeatureSteps } from "./reconstruct.js";
3
4
  import { createSpatialIndex } from "./spatial-index.js";
4
5
  import { decodePartition, checksum, requiredPartitionKeys, } from "./partition.js";
5
6
  /** Progressive session: validates every partition before changing observable state. */
@@ -66,7 +67,14 @@ export class QuadstreamSession {
66
67
  missingKeys(level) {
67
68
  return requiredPartitionKeys(this.manifest, level).filter((k) => !this.loaded.has(k));
68
69
  }
70
+ /** @internal Synchronous reference for algorithm parity tests. */
71
+ querySync(options = {}) {
72
+ return runSync(this.querySteps(options, false));
73
+ }
69
74
  query(options = {}) {
75
+ return runCooperative(this.querySteps(options, true), options);
76
+ }
77
+ *querySteps(options, snapshot) {
70
78
  const level = options.level ?? this.manifest.maxLevel - 1;
71
79
  const missingKeys = this.missingKeys(level);
72
80
  if (options.bounds)
@@ -75,24 +83,33 @@ export class QuadstreamSession {
75
83
  ? this.featureIndex.query(options.bounds)
76
84
  : this.manifest.features.map((_, i) => i);
77
85
  const allLoaded = this.loaded.size === this.manifest.partitions.length;
86
+ // A yielding query observes the vertices available at its start, even if
87
+ // another request ingests partitions before reconstruction completes.
88
+ const vertices = snapshot && !allLoaded ? new Map(this.vertices) : this.vertices;
78
89
  let globallyInvalid = false;
79
90
  if (allLoaded && options.validate !== false) {
80
91
  const cached = this.validityCache.get(level);
81
92
  if (cached !== undefined)
82
93
  globallyInvalid = !cached;
83
94
  else {
84
- globallyInvalid = this.manifest.features.some((f) => !reconstructFeature(f, this.manifest.arcs, this.tree, level, (id) => {
85
- const v = this.vertices.get(id);
86
- return v ? [v.x, v.y] : undefined;
87
- }).valid);
95
+ for (const f of this.manifest.features) {
96
+ const result = yield* reconstructFeatureSteps(f, this.manifest.arcs, this.tree, level, (id) => {
97
+ const v = vertices.get(id);
98
+ return v ? [v.x, v.y] : undefined;
99
+ });
100
+ if (!result.valid) {
101
+ globallyInvalid = true;
102
+ break;
103
+ }
104
+ }
88
105
  this.validityCache.set(level, !globallyInvalid);
89
106
  }
90
107
  }
91
108
  let omittedFeatures = 0, selectedVertices = 0;
92
109
  const features = [];
93
110
  for (const i of ids) {
94
- const result = reconstructFeature(this.manifest.features[i], this.manifest.arcs, this.tree, globallyInvalid ? Infinity : level, (id) => {
95
- const v = this.vertices.get(id);
111
+ const result = yield* reconstructFeatureSteps(this.manifest.features[i], this.manifest.arcs, this.tree, globallyInvalid ? Infinity : level, (id) => {
112
+ const v = vertices.get(id);
96
113
  return v ? [v.x, v.y] : undefined;
97
114
  });
98
115
  if (!result.valid || result.missing) {
@@ -0,0 +1,95 @@
1
+ import type { SphericalCap, SphericalViewCone } from "./spherical-cull.js";
2
+ import type { Feature, FeatureCollection, Position } from "./types.js";
3
+ export interface SphericalClipWindow extends SphericalViewCone {
4
+ cx: number;
5
+ cy: number;
6
+ cz: number;
7
+ radius: number;
8
+ cosR: number;
9
+ sinR: number;
10
+ ux: number;
11
+ uy: number;
12
+ uz: number;
13
+ bx: number;
14
+ by: number;
15
+ bz: number;
16
+ }
17
+ interface RingInfo {
18
+ ring: Position[];
19
+ n: number;
20
+ xyz: Float64Array;
21
+ cap: SphericalCap;
22
+ }
23
+ interface Piece {
24
+ pts: Position[];
25
+ from: number;
26
+ to: number;
27
+ }
28
+ type RingResult = {
29
+ status: "away" | "wraps";
30
+ } | {
31
+ status: "inside";
32
+ ring: Position[];
33
+ } | {
34
+ status: "clipped";
35
+ rings: Position[][];
36
+ };
37
+ interface ClipWork {
38
+ classified: number;
39
+ inside: number;
40
+ outside: number;
41
+ }
42
+ interface FeatureInfo {
43
+ cap: SphericalCap;
44
+ ring: (pi: number, ri: number) => RingInfo;
45
+ }
46
+ export interface SphericalClipStats {
47
+ features: number;
48
+ rings: {
49
+ kept: number;
50
+ clipped: number;
51
+ wrapped: number;
52
+ dropped: number;
53
+ };
54
+ vertices: number;
55
+ stream: ClipWork;
56
+ }
57
+ export interface SphericalClipResult {
58
+ geojson: FeatureCollection;
59
+ stats: SphericalClipStats;
60
+ }
61
+ export declare function clipWindow(cx: number, cy: number, cz: number, radius: number): SphericalClipWindow;
62
+ export declare function circleRing(w: SphericalClipWindow, side?: number): Position[];
63
+ export declare function ringInfo(ring: Position[]): RingInfo;
64
+ /** Reference O(c^2) pairing: the first entry met walking from each exit. */
65
+ export declare function pairPiecesReference(pieces: Pick<Piece, "from" | "to">[], side?: number): number[];
66
+ /**
67
+ * Sorted-event pairing: entries are ordered by azimuth, each exit binary
68
+ * searches its neighbourhood and the exact reference delta rule decides among
69
+ * the few candidates, so ties, wraparound and epsilon behave identically.
70
+ */
71
+ export declare function pairPieces(pieces: Pick<Piece, "from" | "to">[], side?: number): number[];
72
+ /**
73
+ * Clip one ring to the window. Status:
74
+ * - inside: every vertex inside, `ring` is the original array
75
+ * - clipped: `rings` are new closed rings (a ring that dips in and out of
76
+ * the window can split into several)
77
+ * - wraps: no crossing and the ring's material side (exterior) or enclosed
78
+ * region (hole) covers the whole window
79
+ * - away: no crossing and the window is on the other side
80
+ */
81
+ export declare function clipRingReference(w: SphericalClipWindow, info: RingInfo, side?: number): RingResult;
82
+ /**
83
+ * Stream the ring in the reference's cyclic order, starting at the first
84
+ * exterior vertex. Classify each position exactly once; the initial inside
85
+ * prefix is known when the traversal wraps. No per-ring visibility bitmap.
86
+ * Keep outside endpoints only long enough to test their actual joining edge.
87
+ */
88
+ export declare function clipRing(w: SphericalClipWindow, info: RingInfo, side?: number, work?: ClipWork): RingResult;
89
+ export declare function buildFeatureInfo(feature: Feature, cap?: SphericalCap): FeatureInfo;
90
+ /** Uncached clip of a collection to an explicit window. */
91
+ export declare function clipToWindow(geojson: FeatureCollection, w: SphericalClipWindow): SphericalClipResult;
92
+ export declare function countVertices(geojson: FeatureCollection | null | undefined): number;
93
+ /** Clip every feature to the window; unchanged features keep their identity. */
94
+ export declare function clipFeatureCollection(geojson: FeatureCollection, w: SphericalClipWindow, getInfo: (i: number, feature: Feature) => FeatureInfo): SphericalClipResult;
95
+ export {};