@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.
@@ -1,3 +1,4 @@
1
+ import { type CollapsedRingPolicy } from "./reconstruct.js";
1
2
  import type { SphericalPriorities } from "./spherical-geometry.js";
2
3
  import type { FeatureCollection, QueryResult, Topology } from "./types.js";
3
4
  import type { BlgTree } from "./blg.js";
@@ -5,27 +6,50 @@ import type { BlgTree } from "./blg.js";
5
6
  export declare function importSphericalTopoJSON(input: unknown, objectName: string): FeatureCollection;
6
7
  export interface SphericalQueryOptions {
7
8
  level?: number;
9
+ /**
10
+ * "restore" (default) keeps every polygon. "drop" hides each polygon (and
11
+ * hole) whose ring has fewer than 3 distinct quadtree-activated vertices at
12
+ * the query level, except for explicitly retained polygon exteriors.
13
+ */
14
+ collapsedRingPolicy?: CollapsedRingPolicy;
8
15
  }
9
16
  export interface SphericalInterruptOptions extends SphericalQueryOptions {
10
17
  shouldAbort?: () => boolean;
11
18
  yieldTurn?: () => Promise<void>;
12
19
  sliceMs?: number;
13
20
  }
21
+ /** Optional preprocessing policy for explicitly retained polygon exteriors. */
22
+ export interface SphericalBuildOptions {
23
+ maxLevel?: number;
24
+ /** Feature ID to source polygon index; only the selected exterior is visible at level zero. */
25
+ alwaysVisiblePolygons?: ReadonlyMap<string, number>;
26
+ }
14
27
  /** Geographic in-memory dataset. No planar viewport index or v1 partition serialization. */
15
28
  export declare class SphericalQuadstreamDataset {
16
29
  readonly coordinateMode: "spherical-d3";
17
30
  readonly topology: Topology;
18
31
  readonly priorities: SphericalPriorities;
19
32
  readonly arcTrees: readonly BlgTree[];
33
+ /** Corrected global vertex thresholds, independent of query order. */
34
+ readonly activationLevels: readonly number[];
35
+ /** Vertices retained at all levels because a removal failed validation. */
36
+ readonly retainedVertices: number;
37
+ /**
38
+ * Per feature and path: the lowest level at which the closed ring has 3
39
+ * distinct vertices activated by the sparse quadtree (the third-smallest
40
+ * vertex activation level), or Infinity when it never does. Open paths and
41
+ * explicitly retained exteriors are 0.
42
+ */
43
+ readonly ringActivation: readonly (readonly number[])[];
20
44
  private readonly source;
21
45
  private readonly signatures;
22
- constructor(input: FeatureCollection, { maxLevel }?: {
23
- maxLevel?: number;
24
- });
46
+ constructor(input: FeatureCollection, { maxLevel, alwaysVisiblePolygons }?: SphericalBuildOptions);
47
+ private pathActivation;
48
+ /** Nominal-level polygon eligibility, independent of corrected vertex thresholds. */
49
+ private visibility;
50
+ private session;
25
51
  query(options?: SphericalQueryOptions): QueryResult;
26
52
  private formatResult;
27
53
  queryInterruptible(options?: SphericalInterruptOptions): Promise<QueryResult | null>;
28
54
  }
29
- export declare function buildSphericalQuadstream(input: FeatureCollection, options?: {
30
- maxLevel?: number;
31
- }): SphericalQuadstreamDataset;
55
+ export declare function buildSphericalQuadstream(input: FeatureCollection, options?: SphericalBuildOptions): SphericalQuadstreamDataset;
@@ -1,6 +1,8 @@
1
1
  import { buildTopologyWithPolicy } from "./topology.js";
2
2
  import { decodeTopoJSON } from "./adapters.js";
3
- import { buildArcTrees, reconstructFeature } from "./reconstruct.js";
3
+ import { reconstructFeature } from "./reconstruct.js";
4
+ import { stableBlgRandom } from "./blg.js";
5
+ import { buildTopologySafeArcTrees } from "./spherical-preprocess.js";
4
6
  import { signedArea } from "./geometry.js";
5
7
  import { canonicalLonLat, buildSphericalPriorities, projectSpherical, validGreatCirclePath, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
6
8
  function polygons(g) {
@@ -109,23 +111,111 @@ export function importSphericalTopoJSON(input, objectName) {
109
111
  topology(decoded);
110
112
  return decoded;
111
113
  }
114
+ const ACTIVATION_EPSILON = 1e-9;
115
+ /**
116
+ * Level at which a vertex becomes selected in its arc's BLG tree. Selection at
117
+ * level L is `level <= floor(L)` or, for the next level, `random >= 1 - frac`,
118
+ * i.e. L >= level - random: a stable per-vertex threshold, so selections nest.
119
+ */
120
+ function activationLevel(level, random) {
121
+ return level === 0
122
+ ? 0
123
+ : level - random + (random === 1 ? ACTIVATION_EPSILON : 0);
124
+ }
112
125
  /** Geographic in-memory dataset. No planar viewport index or v1 partition serialization. */
113
126
  export class SphericalQuadstreamDataset {
114
127
  coordinateMode = "spherical-d3";
115
128
  topology;
116
129
  priorities;
117
130
  arcTrees;
131
+ /** Corrected global vertex thresholds, independent of query order. */
132
+ activationLevels;
133
+ /** Vertices retained at all levels because a removal failed validation. */
134
+ retainedVertices;
135
+ /**
136
+ * Per feature and path: the lowest level at which the closed ring has 3
137
+ * distinct vertices activated by the sparse quadtree (the third-smallest
138
+ * vertex activation level), or Infinity when it never does. Open paths and
139
+ * explicitly retained exteriors are 0.
140
+ */
141
+ ringActivation;
118
142
  source;
119
143
  signatures;
120
- constructor(input, { maxLevel = 20 } = {}) {
144
+ constructor(input, { maxLevel = 20, alwaysVisiblePolygons } = {}) {
121
145
  this.source = sourceGeometry(input);
122
146
  this.signatures = this.source.features.map((f) => polygons(f.geometry).map((p) => sphericalPolygonSignature(p)));
123
147
  this.topology = topology(this.source);
124
148
  preserveSphericalValidity(this.topology, this.source, this.signatures);
125
149
  this.priorities = buildSphericalPriorities(this.topology.vertices, maxLevel);
126
- this.arcTrees = buildArcTrees(this.topology.arcs, this.priorities.levelByVertexId, this.topology.vertices.map((v) => v.critical));
150
+ const prepared = buildTopologySafeArcTrees(this.topology, this.topology.vertices.map((v) => activationLevel(this.priorities.levelByVertexId[v.id], v.critical ? 1 : stableBlgRandom(v.id))), this.signatures);
151
+ this.arcTrees = prepared.trees;
152
+ this.activationLevels = prepared.activationLevels;
153
+ this.retainedVertices = prepared.retainedVertices;
154
+ this.ringActivation = this.topology.features.map((f) => {
155
+ const polygon = alwaysVisiblePolygons?.get(f.id);
156
+ const exterior = polygon !== undefined &&
157
+ (f.geometryType === "Polygon" || f.geometryType === "MultiPolygon")
158
+ ? f.groups[polygon]?.[0]
159
+ : undefined;
160
+ return f.paths.map((path, i) => i === exterior ? 0 : this.pathActivation(path));
161
+ });
127
162
  }
128
- query(options = {}) {
163
+ pathActivation(path) {
164
+ if (!path.closed)
165
+ return 0;
166
+ // Arc endpoints are always selected (topology anchors, three per closed
167
+ // ring), so they cannot define visibility: use each vertex's own priority.
168
+ const best = new Map();
169
+ for (const ref of path.arcs)
170
+ for (const id of this.topology.arcs[Math.abs(ref) - 1].vertexIds) {
171
+ const a = activationLevel(this.priorities.levelByVertexId[id], this.topology.vertices[id].critical ? 1 : stableBlgRandom(id));
172
+ if (a < (best.get(id) ?? Infinity))
173
+ best.set(id, a);
174
+ }
175
+ let m1 = Infinity, m2 = Infinity, m3 = Infinity;
176
+ for (const a of best.values()) {
177
+ if (a < m1)
178
+ [m1, m2, m3] = [a, m1, m2];
179
+ else if (a < m2)
180
+ [m2, m3] = [a, m2];
181
+ else if (a < m3)
182
+ m3 = a;
183
+ }
184
+ return m3;
185
+ }
186
+ /** Nominal-level polygon eligibility, independent of corrected vertex thresholds. */
187
+ visibility(level) {
188
+ let hiddenPolygons = 0;
189
+ const hidden = [], signatures = [];
190
+ this.topology.features.forEach((f, i) => {
191
+ const act = this.ringActivation[i], source = this.signatures[i];
192
+ let set;
193
+ const sigs = [];
194
+ if (f.geometryType === "Polygon" || f.geometryType === "MultiPolygon")
195
+ f.groups.forEach((group, j) => {
196
+ if (act[group[0]] > level) {
197
+ (set ??= new Set()).add(group[0]);
198
+ hiddenPolygons++;
199
+ return;
200
+ }
201
+ const shown = group.filter((p) => act[p] <= level);
202
+ for (const p of group)
203
+ if (!shown.includes(p))
204
+ (set ??= new Set()).add(p);
205
+ const sig = source[j];
206
+ sigs.push(shown.length === group.length
207
+ ? sig
208
+ : {
209
+ chart: sig.chart,
210
+ signs: sig.signs.filter((_, k) => act[group[k]] <= level),
211
+ });
212
+ });
213
+ hidden.push(set);
214
+ signatures.push(sigs);
215
+ });
216
+ return { hidden, signatures, hiddenPolygons };
217
+ }
218
+ session(options) {
129
219
  if ("bounds" in options || "validate" in options)
130
220
  throw new Error("Spherical queries require global validated retrieval");
131
221
  const level = options.level ?? this.priorities.maxLevel - 1;
@@ -133,54 +223,27 @@ export class SphericalQuadstreamDataset {
133
223
  level < 0 ||
134
224
  level >= this.priorities.maxLevel)
135
225
  throw new Error("Invalid spherical query level");
136
- const lookup = (id) => {
226
+ const drop = options.collapsedRingPolicy === "drop", vis = drop ? this.visibility(level) : undefined, lookup = (id) => {
137
227
  const v = this.topology.vertices[id];
138
228
  return v ? [v.x, v.y] : undefined;
139
- };
140
- const full = this.priorities.maxLevel - 1;
141
- const promoted = new Map();
142
- let promotedArcs = 0;
143
- const levelOf = (arcId) => promoted.get(arcId) ?? level;
144
- const check = (i, r) => {
145
- const p = polygons(r.feature.geometry), s = this.signatures[i];
229
+ }, check = (i, r) => {
230
+ const p = polygons(r.feature.geometry).filter((g) => g.length), s = vis ? vis.signatures[i] : this.signatures[i];
146
231
  return (!r.missing &&
147
232
  p.length === s.length &&
148
233
  p.every((g, j) => validSphericalPolygon(g, s[j])) &&
149
234
  lines(r.feature.geometry).every(validGreatCirclePath));
150
- };
151
- const run = (f) => reconstructFeature(f, this.topology.arcs, this.arcTrees, levelOf, lookup, false, false);
152
- const results = this.topology.features.map(run);
153
- const ok = results.map((r, i) => check(i, r));
154
- // Repair: promote every arc of an invalid feature to the next integer
155
- // level. Arcs are shared, so neighbours always see the same selection.
156
- for (let pass = 0; pass <= full + 1; pass++) {
157
- const touched = new Set();
158
- ok.forEach((good, i) => {
159
- if (good)
160
- return;
161
- for (const path of this.topology.features[i].paths)
162
- for (const ref of path.arcs) {
163
- const id = Math.abs(ref) - 1, cur = levelOf(id);
164
- if (cur >= full)
165
- continue;
166
- promoted.set(id, Math.min(full, Math.floor(cur) + 1));
167
- touched.add(id);
168
- }
169
- });
170
- if (!touched.size)
171
- break;
172
- promotedArcs = promoted.size;
173
- this.topology.features.forEach((f, i) => {
174
- if (f.paths.some((p) => p.arcs.some((r) => touched.has(Math.abs(r) - 1)))) {
175
- results[i] = run(f);
176
- ok[i] = check(i, results[i]);
177
- }
178
- });
179
- }
180
- const valid = ok.every(Boolean);
181
- return this.formatResult(level, results, valid, promotedArcs);
235
+ }, run = (f, i) => reconstructFeature(f, this.topology.arcs, this.arcTrees, level, lookup, false, false, drop
236
+ ? { collapsed: "drop", hiddenPaths: vis.hidden[i] }
237
+ : { collapsed: "drop" });
238
+ return { level, check, run, vis };
182
239
  }
183
- formatResult(level, results, valid, promotedArcs) {
240
+ query(options = {}) {
241
+ const s = this.session(options);
242
+ const results = this.topology.features.map(s.run);
243
+ const valid = results.every((r, i) => s.check(i, r));
244
+ return this.formatResult(s, results, valid);
245
+ }
246
+ formatResult(s, results, valid) {
184
247
  return {
185
248
  geojson: {
186
249
  type: "FeatureCollection",
@@ -194,89 +257,47 @@ export class SphericalQuadstreamDataset {
194
257
  };
195
258
  }),
196
259
  },
197
- level,
260
+ level: s.level,
198
261
  valid,
199
- promotedArcs,
262
+ promotedArcs: 0,
263
+ ...(s.vis
264
+ ? {
265
+ hiddenPolygons: s.vis.hiddenPolygons,
266
+ hiddenRings: results.reduce((n, r) => n + r.hiddenRings, 0),
267
+ }
268
+ : {}),
200
269
  usedFallback: false,
201
270
  selectedFeatures: results.length,
202
271
  selectedVertices: results.reduce((n, r) => n + r.selectedVertices, 0),
203
272
  };
204
273
  }
205
274
  async queryInterruptible(options = {}) {
206
- if ("bounds" in options || "validate" in options)
207
- throw new Error("Spherical queries require global validated retrieval");
208
- const { level: requested, shouldAbort, yieldTurn, sliceMs = 8 } = options;
209
- const level = requested ?? this.priorities.maxLevel - 1;
210
- if (!Number.isFinite(level) ||
211
- level < 0 ||
212
- level >= this.priorities.maxLevel)
213
- throw new Error("Invalid spherical query level");
275
+ const { shouldAbort, yieldTurn, sliceMs = 8 } = options;
276
+ const s = this.session(options);
214
277
  if (shouldAbort?.())
215
278
  return null;
216
- const lookup = (id) => {
217
- const v = this.topology.vertices[id];
218
- return v ? [v.x, v.y] : undefined;
219
- };
220
- const full = this.priorities.maxLevel - 1;
221
- const promoted = new Map();
222
- let promotedArcs = 0;
223
- const levelOf = (arcId) => promoted.get(arcId) ?? level;
224
- const check = (i, r) => {
225
- const p = polygons(r.feature.geometry), s = this.signatures[i];
226
- return (!r.missing &&
227
- p.length === s.length &&
228
- p.every((g, j) => validSphericalPolygon(g, s[j])) &&
229
- lines(r.feature.geometry).every(validGreatCirclePath));
230
- };
231
- const run = (f) => reconstructFeature(f, this.topology.arcs, this.arcTrees, levelOf, lookup, false, false);
232
279
  const results = [];
233
280
  const ok = [];
234
281
  let sliceStart = performance.now();
235
- for (let i = 0; i < this.topology.features.length; i++) {
236
- const r = run(this.topology.features[i]);
237
- results.push(r);
238
- ok.push(check(i, r));
282
+ const tick = async () => {
239
283
  if (yieldTurn && performance.now() - sliceStart >= sliceMs) {
240
284
  await yieldTurn();
241
285
  if (shouldAbort?.())
242
- return null;
286
+ return false;
243
287
  sliceStart = performance.now();
244
288
  }
245
- }
246
- for (let pass = 0; pass <= full + 1; pass++) {
247
- const touched = new Set();
248
- ok.forEach((good, i) => {
249
- if (good)
250
- return;
251
- for (const path of this.topology.features[i].paths)
252
- for (const ref of path.arcs) {
253
- const id = Math.abs(ref) - 1, cur = levelOf(id);
254
- if (cur >= full)
255
- continue;
256
- promoted.set(id, Math.min(full, Math.floor(cur) + 1));
257
- touched.add(id);
258
- }
259
- });
260
- if (!touched.size)
261
- break;
262
- promotedArcs = promoted.size;
263
- for (let i = 0; i < this.topology.features.length; i++) {
264
- const f = this.topology.features[i];
265
- if (f.paths.some((p) => p.arcs.some((r) => touched.has(Math.abs(r) - 1)))) {
266
- results[i] = run(f);
267
- ok[i] = check(i, results[i]);
268
- if (yieldTurn && performance.now() - sliceStart >= sliceMs) {
269
- await yieldTurn();
270
- if (shouldAbort?.())
271
- return null;
272
- sliceStart = performance.now();
273
- }
274
- }
275
- }
289
+ return true;
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()))
296
+ return null;
276
297
  }
277
298
  if (shouldAbort?.())
278
299
  return null;
279
- return this.formatResult(level, results, ok.every(Boolean), promotedArcs);
300
+ return this.formatResult(s, results, ok.every(Boolean));
280
301
  }
281
302
  }
282
303
  export function buildSphericalQuadstream(input, options) {
@@ -28,8 +28,8 @@ export function canonicalLonLat(value) {
28
28
  lat === 0 ? 0 : lat,
29
29
  ];
30
30
  }
31
- export function lonLatVector(p) {
32
- const [lon, lat] = canonicalLonLat(p);
31
+ /** Vector of an already canonical (validated, seam-aliased) longitude/latitude. */
32
+ function canonicalVector(lon, lat) {
33
33
  if (Math.abs(lat) === 90)
34
34
  return [0, 0, Math.sign(lat)];
35
35
  const c = Math.cos(lat * rad), z = Math.sin(lat * rad);
@@ -48,77 +48,105 @@ export function lonLatVector(p) {
48
48
  return [c * Math.cos(lon * rad), c * Math.sin(lon * rad), z];
49
49
  }
50
50
  }
51
+ export function lonLatVector(p) {
52
+ const [lon, lat] = canonicalLonLat(p);
53
+ return canonicalVector(lon, lat);
54
+ }
51
55
  export function angularDistance(a, b) {
52
56
  const u = lonLatVector(a), v = lonLatVector(b);
53
57
  return Math.atan2(norm(cross(u, v)), dot(u, v));
54
58
  }
55
- export function validGreatCirclePath(path) {
56
- if (path.length < 2)
59
+ function validVectorPath(vectors) {
60
+ if (vectors.length < 2)
57
61
  return false;
58
- for (let i = 1; i < path.length; i++) {
59
- const d = angularDistance(path[i - 1], path[i]);
62
+ for (let i = 1; i < vectors.length; i++) {
63
+ const u = vectors[i - 1], v = vectors[i], d = Math.atan2(norm(cross(u, v)), dot(u, v));
60
64
  if (d <= eps || Math.PI - d <= eps)
61
65
  return false;
62
66
  }
63
67
  return true;
64
68
  }
65
- export function sphericalCellAddress(p, level) {
66
- if (!Number.isInteger(level) || level < 0 || level > 25)
67
- throw new Error("Spherical level must be 0..25");
68
- const [x, y, z] = lonLatVector(p);
69
+ export function validGreatCirclePath(path) {
70
+ if (path.length < 2)
71
+ return false;
72
+ return validVectorPath(path.map(lonLatVector));
73
+ }
74
+ const FACES = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"];
75
+ function faceCoords([x, y, z]) {
69
76
  // Fixed axis order breaks exact and roundoff-sized seam ties.
70
77
  const m = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
71
- let face, u, v;
72
- if (m - Math.abs(x) <= 1e-15) {
73
- face = x >= 0 ? "+X" : "-X";
74
- u = y / Math.abs(x);
75
- v = z / Math.abs(x);
76
- }
77
- else if (m - Math.abs(y) <= 1e-15) {
78
- face = y >= 0 ? "+Y" : "-Y";
79
- u = x / Math.abs(y);
80
- v = z / Math.abs(y);
81
- }
82
- else {
83
- face = z >= 0 ? "+Z" : "-Z";
84
- u = x / Math.abs(z);
85
- v = y / Math.abs(z);
86
- }
87
- const side = 2 ** level, cell = (t) => Math.max(0, Math.min(side - 1, Math.floor(((t + 1) * side) / 2)));
88
- const i = cell(u), j = cell(v);
89
- return { face, level, i, j, key: face + ":" + level + ":" + i + ":" + j };
78
+ if (m - Math.abs(x) <= 1e-15)
79
+ return { face: x >= 0 ? 0 : 1, u: y / Math.abs(x), v: z / Math.abs(x) };
80
+ if (m - Math.abs(y) <= 1e-15)
81
+ return { face: y >= 0 ? 2 : 3, u: x / Math.abs(y), v: z / Math.abs(y) };
82
+ return { face: z >= 0 ? 4 : 5, u: x / Math.abs(z), v: y / Math.abs(z) };
83
+ }
84
+ function cellIndex(t, side) {
85
+ return Math.max(0, Math.min(side - 1, Math.floor(((t + 1) * side) / 2)));
90
86
  }
87
+ function assertLevel(level) {
88
+ if (!Number.isInteger(level) || level < 0 || level > 25)
89
+ throw new Error("Spherical level must be 0..25");
90
+ }
91
+ export function sphericalCellAddress(p, level) {
92
+ assertLevel(level);
93
+ const { face, u, v } = faceCoords(lonLatVector(p)), side = 2 ** level, i = cellIndex(u, side), j = cellIndex(v, side), name = FACES[face];
94
+ return {
95
+ face: name,
96
+ level,
97
+ i,
98
+ j,
99
+ key: name + ":" + level + ":" + i + ":" + j,
100
+ };
101
+ }
102
+ // Face and indices pack into one exact double: 6 * 2^50 < 2^53.
103
+ const SIDE_MAX = 2 ** 25;
104
+ const packCell = (face, i, j) => (face * SIDE_MAX + i) * SIDE_MAX + j;
91
105
  export function buildSphericalPriorities(vertices, maxLevel = 20) {
92
106
  if (!Number.isInteger(maxLevel) || maxLevel < 1 || maxLevel > 26)
93
107
  throw new Error("maxLevel must be 1..26");
94
- const seen = new Set(), ids = new Set();
108
+ const seen = new Set(), ids = new Uint8Array(vertices.length);
95
109
  const sorted = vertices
96
110
  .map((v) => {
97
111
  const [x, y] = canonicalLonLat([v.x, v.y]);
98
- const k = JSON.stringify([x, y]);
112
+ const k = x + "," + y;
99
113
  if (seen.has(k) ||
100
114
  !Number.isSafeInteger(v.id) ||
101
115
  v.id < 0 ||
102
116
  v.id >= vertices.length ||
103
- ids.has(v.id))
117
+ ids[v.id])
104
118
  throw new Error("Expected distinct canonical vertices and dense IDs");
105
119
  seen.add(k);
106
- ids.add(v.id);
107
- return { ...v, x, y };
120
+ ids[v.id] = 1;
121
+ return {
122
+ id: v.id,
123
+ critical: v.critical,
124
+ x,
125
+ y,
126
+ face: faceCoords(canonicalVector(x, y)),
127
+ };
108
128
  })
109
129
  .sort((a, b) => Number(b.critical) - Number(a.critical) ||
110
130
  a.x - b.x ||
111
131
  a.y - b.y ||
112
132
  a.id - b.id);
113
- const occupied = new Set(), cells = [], levelByVertexId = [];
133
+ const occupied = Array.from({ length: maxLevel }, () => new Set()), sides = Array.from({ length: maxLevel }, (_, level) => 2 ** level), cells = [], levelByVertexId = [];
114
134
  for (const v of sorted) {
115
135
  let found = false;
116
136
  for (let level = 0; level < maxLevel; level++) {
117
- const c = sphericalCellAddress([v.x, v.y], level);
118
- if (occupied.has(c.key))
137
+ const side = sides[level], i = cellIndex(v.face.u, side), j = cellIndex(v.face.v, side), packed = packCell(v.face.face, i, j);
138
+ if (occupied[level].has(packed))
119
139
  continue;
120
- occupied.add(c.key);
121
- cells.push({ ...c, vertexId: v.id });
140
+ occupied[level].add(packed);
141
+ const face = FACES[v.face.face];
142
+ cells.push({
143
+ vertexId: v.id,
144
+ face,
145
+ level,
146
+ i,
147
+ j,
148
+ key: face + ":" + level + ":" + i + ":" + j,
149
+ });
122
150
  levelByVertexId[v.id] = level;
123
151
  found = true;
124
152
  break;
@@ -146,18 +174,22 @@ export function sphericalChart(ring) {
146
174
  return { center, east, north };
147
175
  }
148
176
  export function projectSpherical(p, chart) {
149
- const v = lonLatVector(p), d = dot(v, chart.center);
177
+ return projectVector(lonLatVector(p), chart);
178
+ }
179
+ function projectVector(v, chart) {
180
+ const d = dot(v, chart.center);
150
181
  if (d <= eps)
151
182
  throw new Error("Position outside supported open-hemisphere chart");
152
183
  return [dot(v, chart.east) / d, dot(v, chart.north) / d];
153
184
  }
154
185
  function ringOnChart(ring, chart) {
155
- const p = ring.map(canonicalLonLat);
186
+ const p = ring.map(canonicalLonLat), vectors = p.map(([lon, lat]) => canonicalVector(lon, lat));
156
187
  if (p.length < 4 ||
157
- JSON.stringify(p[0]) !== JSON.stringify(p.at(-1)) ||
158
- !validGreatCirclePath(p))
188
+ p[0][0] !== p[p.length - 1][0] ||
189
+ p[0][1] !== p[p.length - 1][1] ||
190
+ !validVectorPath(vectors))
159
191
  throw new Error("Invalid spherical ring");
160
- const xy = p.map((v) => projectSpherical(v, chart));
192
+ const xy = vectors.map((v) => projectVector(v, chart));
161
193
  if (!simpleClosedRing(xy) || Math.abs(signedArea(xy)) <= eps * eps)
162
194
  throw new Error("Degenerate or self-intersecting spherical ring");
163
195
  // Reject overlapping adjacent great-circle edges (including numerical near-overlap).
@@ -0,0 +1,19 @@
1
+ import { type BlgTree } from "./blg.js";
2
+ import { type SphericalPolygonSignature } from "./spherical-geometry.js";
3
+ import type { Topology } from "./types.js";
4
+ /**
5
+ * Build a nested hierarchy by removing vertices from valid full detail.
6
+ * Batch at conservative tenth-LOD boundaries; when a batch fails, bisect it
7
+ * until we identify individually unsafe removals. Rejected vertices remain
8
+ * at level zero. Every accepted transition is validated in its actual context.
9
+ *
10
+ * The source quadtree priorities and ring visibility thresholds are not
11
+ * changed. A shared vertex has one removal decision across all of its owners.
12
+ * This uses the existing per-polygon/line reference validator, not a global
13
+ * intersection arrangement for unrelated boundaries.
14
+ */
15
+ export declare function buildTopologySafeArcTrees(topology: Topology, nominalActivation: readonly number[], signatures: readonly SphericalPolygonSignature[][]): {
16
+ trees: BlgTree[];
17
+ activationLevels: number[];
18
+ retainedVertices: number;
19
+ };