@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
@@ -0,0 +1,557 @@
1
+ // Render-side spherical clipping to the visible cone. Rings that cross the
2
+ // cone boundary keep their inside vertices plus the exact boundary crossings;
3
+ // every outside run collapses to a walk along the (padded) cone boundary, in
4
+ // the winding direction that preserves the polygon's interior side. Source
5
+ // geometry and Quadstream topology are never modified.
6
+ import { isCapVisible, lonLatToVec, computeFeatureCap, } from "./spherical-cull.js";
7
+ const DEG = 180 / Math.PI;
8
+ const TAU = Math.PI * 2;
9
+ const WALK_STEP_RAD = (4 * Math.PI) / 180;
10
+ const CAP_MARGIN_RAD = 0.02;
11
+ // d3 spherical winding: material lies to the right of an exterior ring, so the
12
+ // boundary walk goes clockwise (decreasing azimuth). Holes are clipped as the
13
+ // region they enclose, which lies to their left.
14
+ const EXTERIOR = -1;
15
+ const HOLE = 1;
16
+ export function clipWindow(cx, cy, cz, radius) {
17
+ if (!Number.isFinite(radius) ||
18
+ radius < 0 ||
19
+ radius >= Math.PI / 2 ||
20
+ !Number.isFinite(cx) ||
21
+ !Number.isFinite(cy) ||
22
+ !Number.isFinite(cz) ||
23
+ Math.abs(Math.hypot(cx, cy, cz) - 1) > 1e-9)
24
+ throw new Error("Expected a unit center and clipping radius in [0, pi/2)");
25
+ const ex = Math.abs(cz) < 0.9 ? [0, 0, 1] : [1, 0, 0], d = ex[0] * cx + ex[1] * cy + ex[2] * cz;
26
+ let ux = ex[0] - d * cx, uy = ex[1] - d * cy, uz = ex[2] - d * cz;
27
+ const ul = Math.hypot(ux, uy, uz);
28
+ ux /= ul;
29
+ uy /= ul;
30
+ uz /= ul;
31
+ return {
32
+ cx,
33
+ cy,
34
+ cz,
35
+ radius,
36
+ cosR: Math.cos(radius),
37
+ sinR: Math.sin(radius),
38
+ ux,
39
+ uy,
40
+ uz,
41
+ bx: cy * uz - cz * uy,
42
+ by: cz * ux - cx * uz,
43
+ bz: cx * uy - cy * ux,
44
+ // Fields consumed by isCapVisible.
45
+ vx: cx,
46
+ vy: cy,
47
+ vz: cz,
48
+ viewRadius: radius,
49
+ };
50
+ }
51
+ function toLonLat(x, y, z) {
52
+ return [
53
+ Math.atan2(y, x) * DEG,
54
+ Math.asin(Math.max(-1, Math.min(1, z))) * DEG,
55
+ ];
56
+ }
57
+ function circlePoint(w, phi) {
58
+ const c = Math.cos(phi), s = Math.sin(phi);
59
+ return toLonLat(w.cx * w.cosR + w.sinR * (w.ux * c + w.bx * s), w.cy * w.cosR + w.sinR * (w.uy * c + w.by * s), w.cz * w.cosR + w.sinR * (w.uz * c + w.bz * s));
60
+ }
61
+ function azimuth(w, x, y, z) {
62
+ return Math.atan2(x * w.bx + y * w.by + z * w.bz, x * w.ux + y * w.uy + z * w.uz);
63
+ }
64
+ const mod = (a) => ((a % TAU) + TAU) % TAU;
65
+ // Points strictly between two boundary azimuths, walking in `side` direction.
66
+ function walk(w, from, to, side, out) {
67
+ const delta = mod(side < 0 ? from - to : to - from);
68
+ if (delta < 1e-9 || delta > TAU - 1e-9)
69
+ return;
70
+ const steps = Math.ceil(delta / WALK_STEP_RAD);
71
+ for (let k = 1; k < steps; k++)
72
+ out.push(circlePoint(w, from + (side * delta * k) / steps));
73
+ }
74
+ export function circleRing(w, side = EXTERIOR) {
75
+ const n = Math.ceil(TAU / WALK_STEP_RAD), ring = [];
76
+ for (let k = 0; k < n; k++)
77
+ ring.push(circlePoint(w, (side * TAU * k) / n));
78
+ ring.push(ring[0]);
79
+ return ring;
80
+ }
81
+ // Crossings of the minor arc A->B with the window boundary, in travel order
82
+ // along the canonical (lexicographically ordered) orientation so shared
83
+ // borders produce bit-identical points on both neighbours.
84
+ function arcCrossings(w, a0, a1, a2, b0, b1, b2) {
85
+ const swapped = a0 > b0 || (a0 === b0 && (a1 > b1 || (a1 === b1 && a2 > b2)));
86
+ let ax = a0, ay = a1, az = a2, bx = b0, by = b1, bz = b2;
87
+ if (swapped) {
88
+ ax = b0;
89
+ ay = b1;
90
+ az = b2;
91
+ bx = a0;
92
+ by = a1;
93
+ bz = a2;
94
+ }
95
+ let nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx;
96
+ const sinL = Math.hypot(nx, ny, nz);
97
+ if (sinL < 1e-14)
98
+ return null;
99
+ nx /= sinL;
100
+ ny /= sinL;
101
+ nz /= sinL;
102
+ const cn = w.cx * nx + w.cy * ny + w.cz * nz;
103
+ let px = w.cx - cn * nx, py = w.cy - cn * ny, pz = w.cz - cn * nz;
104
+ const cosD = Math.hypot(px, py, pz);
105
+ if (cosD < 1e-12 || cosD < w.cosR)
106
+ return null;
107
+ px /= cosD;
108
+ py /= cosD;
109
+ pz /= cosD;
110
+ const theta = Math.acos(Math.min(1, w.cosR / cosD)), ct = Math.cos(theta), st = Math.sin(theta),
111
+ // Travel direction at p: n x p.
112
+ tx = ny * pz - nz * py, ty = nz * px - nx * pz, tz = nx * py - ny * px, first = [
113
+ px * ct - tx * st,
114
+ py * ct - ty * st,
115
+ pz * ct - tz * st,
116
+ ], second = [
117
+ px * ct + tx * st,
118
+ py * ct + ty * st,
119
+ pz * ct + tz * st,
120
+ ];
121
+ const L = Math.atan2(sinL, ax * bx + ay * by + az * bz), alpha = (q) => Math.atan2(nx * (ay * q[2] - az * q[1]) +
122
+ ny * (az * q[0] - ax * q[2]) +
123
+ nz * (ax * q[1] - ay * q[0]), ax * q[0] + ay * q[1] + az * q[2]);
124
+ return { first, second, swapped, alpha, L };
125
+ }
126
+ // Outside -> outside edge: both crossings must lie on the arc.
127
+ function throughCrossings(w, A, B) {
128
+ const c = arcCrossings(w, A[0], A[1], A[2], B[0], B[1], B[2]);
129
+ if (!c)
130
+ return null;
131
+ const eps = 1e-12, a1 = c.alpha(c.first), a2 = c.alpha(c.second);
132
+ if (a1 < -eps || a1 > c.L + eps || a2 < -eps || a2 > c.L + eps)
133
+ return null;
134
+ return c.swapped ? [c.second, c.first] : [c.first, c.second];
135
+ }
136
+ function exitPoint(w, A, B) {
137
+ const c = arcCrossings(w, A[0], A[1], A[2], B[0], B[1], B[2]);
138
+ if (!c)
139
+ return null;
140
+ return c.swapped ? c.first : c.second;
141
+ }
142
+ function entryPoint(w, A, B) {
143
+ const c = arcCrossings(w, A[0], A[1], A[2], B[0], B[1], B[2]);
144
+ if (!c)
145
+ return null;
146
+ return c.swapped ? c.second : c.first;
147
+ }
148
+ export function ringInfo(ring) {
149
+ let n = ring.length;
150
+ if (n > 1 &&
151
+ ring[0][0] === ring[n - 1][0] &&
152
+ ring[0][1] === ring[n - 1][1])
153
+ n--;
154
+ const xyz = new Float64Array(n * 3);
155
+ let sx = 0, sy = 0, sz = 0;
156
+ for (let i = 0; i < n; i++) {
157
+ const [x, y, z] = lonLatToVec(ring[i][0], ring[i][1]);
158
+ xyz[i * 3] = x;
159
+ xyz[i * 3 + 1] = y;
160
+ xyz[i * 3 + 2] = z;
161
+ sx += x;
162
+ sy += y;
163
+ sz += z;
164
+ }
165
+ const len = Math.hypot(sx, sy, sz);
166
+ let cap;
167
+ if (!n)
168
+ cap = { cx: 1, cy: 0, cz: 0, radiusRad: 0 };
169
+ else if (len < 1e-6)
170
+ cap = { cx: 1, cy: 0, cz: 0, radiusRad: Math.PI };
171
+ else {
172
+ const cx = sx / len, cy = sy / len, cz = sz / len;
173
+ let minDot = 1;
174
+ for (let i = 0; i < n; i++) {
175
+ const d = cx * xyz[i * 3] + cy * xyz[i * 3 + 1] + cz * xyz[i * 3 + 2];
176
+ if (d < minDot)
177
+ minDot = d;
178
+ }
179
+ cap = {
180
+ cx,
181
+ cy,
182
+ cz,
183
+ radiusRad: Math.min(Math.PI, Math.acos(Math.max(-1, Math.min(1, minDot))) + CAP_MARGIN_RAD),
184
+ };
185
+ }
186
+ return { ring, n, xyz, cap };
187
+ }
188
+ // Winding of the ring around the window centre as azimuth sum. With no edge
189
+ // entering the cone, the whole cone is on one side of the ring.
190
+ function windingAroundCenter(w, info) {
191
+ const { xyz, n } = info;
192
+ let total = 0;
193
+ for (let i = 0; i < n; i++) {
194
+ const j = (i + 1) % n, ax = xyz[i * 3], ay = xyz[i * 3 + 1], az = xyz[i * 3 + 2], bx = xyz[j * 3], by = xyz[j * 3 + 1], bz = xyz[j * 3 + 2], da = ax * w.cx + ay * w.cy + az * w.cz, db = bx * w.cx + by * w.cy + bz * w.cz, atx = ax - da * w.cx, aty = ay - da * w.cy, atz = az - da * w.cz, btx = bx - db * w.cx, bty = by - db * w.cy, btz = bz - db * w.cz;
195
+ if (Math.hypot(atx, aty, atz) < 1e-12 || Math.hypot(btx, bty, btz) < 1e-12)
196
+ continue;
197
+ total += Math.atan2((aty * btz - atz * bty) * w.cx +
198
+ (atz * btx - atx * btz) * w.cy +
199
+ (atx * bty - aty * btx) * w.cz, atx * btx + aty * bty + atz * btz);
200
+ }
201
+ return total;
202
+ }
203
+ const NEAR = 2e-9, SORT_MIN = 12;
204
+ function pairDelta(p, q, side) {
205
+ const delta = mod(side < 0 ? p.to - q.from : q.from - p.to);
206
+ return delta > TAU - 1e-9 ? 0 : delta;
207
+ }
208
+ /** Reference O(c^2) pairing: the first entry met walking from each exit. */
209
+ export function pairPiecesReference(pieces, side = EXTERIOR) {
210
+ return pieces.map((p) => {
211
+ let best = 0, bestDelta = Infinity;
212
+ pieces.forEach((q, m) => {
213
+ const d = pairDelta(p, q, side);
214
+ if (d < bestDelta) {
215
+ bestDelta = d;
216
+ best = m;
217
+ }
218
+ });
219
+ return best;
220
+ });
221
+ }
222
+ /**
223
+ * Sorted-event pairing: entries are ordered by azimuth, each exit binary
224
+ * searches its neighbourhood and the exact reference delta rule decides among
225
+ * the few candidates, so ties, wraparound and epsilon behave identically.
226
+ */
227
+ export function pairPieces(pieces, side = EXTERIOR) {
228
+ const c = pieces.length;
229
+ if (c < SORT_MIN)
230
+ return pairPiecesReference(pieces, side);
231
+ const keys = pieces.map((q) => mod(q.from)), order = Array.from(keys.keys()).sort((a, b) => keys[a] - keys[b] || a - b), sorted = order.map((i) => keys[i]);
232
+ const lowerBound = (v) => {
233
+ let lo = 0, hi = c;
234
+ while (lo < hi) {
235
+ const mid = (lo + hi) >> 1;
236
+ if (sorted[mid] < v)
237
+ lo = mid + 1;
238
+ else
239
+ hi = mid;
240
+ }
241
+ return lo;
242
+ };
243
+ return pieces.map((p) => {
244
+ const t = mod(p.to), cand = [];
245
+ // Walk away from the exit along the boundary in the pairing direction.
246
+ const dir = side < 0 ? -1 : 1;
247
+ const dist = (k) => mod(dir * (sorted[k] - t) + NEAR);
248
+ let k = side < 0 ? lowerBound(t + NEAR + 1e-300) - 1 : lowerBound(t - NEAR);
249
+ k = ((k % c) + c) % c;
250
+ for (let seen = 0; seen < c; seen++, k = (((k + dir) % c) + c) % c) {
251
+ const d = dist(k);
252
+ if (d > 2 * NEAR) {
253
+ // First strictly beyond the cluster, plus numerically equal neighbours.
254
+ cand.push(order[k]);
255
+ const f = sorted[k];
256
+ for (let j = (((k + dir) % c) + c) % c, n = 1; n < c; n++) {
257
+ if (Math.abs(sorted[j] - f) > 1e-12)
258
+ break;
259
+ cand.push(order[j]);
260
+ j = (((j + dir) % c) + c) % c;
261
+ }
262
+ break;
263
+ }
264
+ cand.push(order[k]);
265
+ }
266
+ cand.sort((a, b) => a - b);
267
+ let best = cand[0], bestDelta = Infinity;
268
+ for (const m of cand) {
269
+ const d = pairDelta(p, pieces[m], side);
270
+ if (d < bestDelta) {
271
+ bestDelta = d;
272
+ best = m;
273
+ }
274
+ }
275
+ return best;
276
+ });
277
+ }
278
+ /**
279
+ * Clip one ring to the window. Status:
280
+ * - inside: every vertex inside, `ring` is the original array
281
+ * - clipped: `rings` are new closed rings (a ring that dips in and out of
282
+ * the window can split into several)
283
+ * - wraps: no crossing and the ring's material side (exterior) or enclosed
284
+ * region (hole) covers the whole window
285
+ * - away: no crossing and the window is on the other side
286
+ */
287
+ export function clipRingReference(w, info, side = EXTERIOR) {
288
+ const { xyz, n, ring } = info;
289
+ if (n < 3)
290
+ return { status: "away" };
291
+ const inside = new Uint8Array(n);
292
+ let start = -1;
293
+ for (let i = 0; i < n; i++) {
294
+ inside[i] =
295
+ xyz[i * 3] * w.cx + xyz[i * 3 + 1] * w.cy + xyz[i * 3 + 2] * w.cz >=
296
+ w.cosR
297
+ ? 1
298
+ : 0;
299
+ if (!inside[i] && start < 0)
300
+ start = i;
301
+ }
302
+ if (start < 0)
303
+ return { status: "inside", ring };
304
+ const vec = (i) => [
305
+ xyz[i * 3],
306
+ xyz[i * 3 + 1],
307
+ xyz[i * 3 + 2],
308
+ ], pieces = [];
309
+ let cur = null;
310
+ for (let k = 0; k < n; k++) {
311
+ const i = (start + k) % n, j = (i + 1) % n;
312
+ if (!inside[i] && !inside[j]) {
313
+ const pair = throughCrossings(w, vec(i), vec(j));
314
+ if (pair)
315
+ pieces.push({
316
+ pts: [toLonLat(...pair[0]), toLonLat(...pair[1])],
317
+ from: azimuth(w, ...pair[0]),
318
+ to: azimuth(w, ...pair[1]),
319
+ });
320
+ }
321
+ else if (inside[i] && !inside[j]) {
322
+ const x = exitPoint(w, vec(i), vec(j)) ?? vec(i);
323
+ cur.pts.push(toLonLat(...x));
324
+ cur.to = azimuth(w, ...x);
325
+ pieces.push(cur);
326
+ cur = null;
327
+ }
328
+ else if (!inside[i] && inside[j]) {
329
+ const x = entryPoint(w, vec(i), vec(j)) ?? vec(j);
330
+ cur = { pts: [toLonLat(...x), ring[j]], from: azimuth(w, ...x), to: 0 };
331
+ }
332
+ else
333
+ cur.pts.push(ring[j]);
334
+ }
335
+ return assemblePieces(w, info, side, pieces);
336
+ }
337
+ /**
338
+ * Stream the ring in the reference's cyclic order, starting at the first
339
+ * exterior vertex. Classify each position exactly once; the initial inside
340
+ * prefix is known when the traversal wraps. No per-ring visibility bitmap.
341
+ * Keep outside endpoints only long enough to test their actual joining edge.
342
+ */
343
+ export function clipRing(w, info, side = EXTERIOR, work) {
344
+ const { xyz, n, ring } = info;
345
+ if (n < 3)
346
+ return { status: "away" };
347
+ const inside = (i) => xyz[i * 3] * w.cx + xyz[i * 3 + 1] * w.cy + xyz[i * 3 + 2] * w.cz >=
348
+ w.cosR;
349
+ let start = 0;
350
+ while (start < n && inside(start))
351
+ start++;
352
+ if (work) {
353
+ work.classified += n;
354
+ work.inside += start;
355
+ if (start < n)
356
+ work.outside++;
357
+ }
358
+ if (start === n)
359
+ return { status: "inside", ring };
360
+ const vec = (i) => [
361
+ xyz[i * 3],
362
+ xyz[i * 3 + 1],
363
+ xyz[i * 3 + 2],
364
+ ], pieces = [];
365
+ let previousInside = false, cur = null;
366
+ for (let k = 0; k < n; k++) {
367
+ const i = (start + k) % n, j = (i + 1) % n, currentInside = j <= start ? j < start : inside(j);
368
+ if (work && j > start) {
369
+ if (currentInside)
370
+ work.inside++;
371
+ else
372
+ work.outside++;
373
+ }
374
+ if (!previousInside && !currentInside) {
375
+ const pair = throughCrossings(w, vec(i), vec(j));
376
+ if (pair)
377
+ pieces.push({
378
+ pts: [toLonLat(...pair[0]), toLonLat(...pair[1])],
379
+ from: azimuth(w, ...pair[0]),
380
+ to: azimuth(w, ...pair[1]),
381
+ });
382
+ }
383
+ else if (previousInside && !currentInside) {
384
+ const x = exitPoint(w, vec(i), vec(j)) ?? vec(i);
385
+ cur.pts.push(toLonLat(...x));
386
+ cur.to = azimuth(w, ...x);
387
+ pieces.push(cur);
388
+ cur = null;
389
+ }
390
+ else if (!previousInside && currentInside) {
391
+ const x = entryPoint(w, vec(i), vec(j)) ?? vec(j);
392
+ cur = { pts: [toLonLat(...x), ring[j]], from: azimuth(w, ...x), to: 0 };
393
+ }
394
+ else
395
+ cur.pts.push(ring[j]);
396
+ previousInside = currentInside;
397
+ }
398
+ return assemblePieces(w, info, side, pieces);
399
+ }
400
+ function assemblePieces(w, info, side, pieces) {
401
+ if (!pieces.length) {
402
+ const total = windingAroundCenter(w, info);
403
+ return {
404
+ status: (side === EXTERIOR ? total < -Math.PI : total > Math.PI)
405
+ ? "wraps"
406
+ : "away",
407
+ };
408
+ }
409
+ // Pair every exit with the first entry met walking along the boundary, so
410
+ // disjoint pieces of one ring become separate rings.
411
+ const next = pairPieces(pieces, side);
412
+ const used = new Uint8Array(pieces.length), rings = [];
413
+ for (let s = 0; s < pieces.length; s++) {
414
+ if (used[s])
415
+ continue;
416
+ const out = [];
417
+ for (let m = s; !used[m]; m = next[m]) {
418
+ used[m] = 1;
419
+ for (const pt of pieces[m].pts)
420
+ out.push(pt);
421
+ walk(w, pieces[m].to, pieces[next[m]].from, side, out);
422
+ }
423
+ out.push(out[0]);
424
+ if (out.length >= 4)
425
+ rings.push(out);
426
+ }
427
+ return rings.length ? { status: "clipped", rings } : { status: "away" };
428
+ }
429
+ function polygonsOf(geometry) {
430
+ return geometry?.type === "Polygon"
431
+ ? [geometry.coordinates]
432
+ : geometry?.type === "MultiPolygon"
433
+ ? geometry.coordinates
434
+ : [];
435
+ }
436
+ // Ring vectors are built on first use: features whose cap misses the window
437
+ // never pay the per-vertex trigonometry.
438
+ export function buildFeatureInfo(feature, cap = computeFeatureCap(feature)) {
439
+ const polys = polygonsOf(feature.geometry), built = polys.map((poly) => new Array(poly.length));
440
+ return {
441
+ cap,
442
+ ring: (pi, ri) => (built[pi][ri] ??= ringInfo(polys[pi][ri])),
443
+ };
444
+ }
445
+ /** Uncached clip of a collection to an explicit window. */
446
+ export function clipToWindow(geojson, w) {
447
+ for (const f of geojson.features)
448
+ if (f.geometry.type !== "Polygon" && f.geometry.type !== "MultiPolygon")
449
+ throw new Error("Spherical clipping supports Polygon and MultiPolygon only");
450
+ const infos = [];
451
+ return clipFeatureCollection(geojson, w, (i, f) => (infos[i] ??= buildFeatureInfo(f)));
452
+ }
453
+ function capInside(cap, w) {
454
+ const room = w.radius - cap.radiusRad;
455
+ return (room > 0 && cap.cx * w.cx + cap.cy * w.cy + cap.cz * w.cz >= Math.cos(room));
456
+ }
457
+ export function countVertices(geojson) {
458
+ let n = 0;
459
+ for (const f of geojson?.features ?? [])
460
+ for (const poly of polygonsOf(f.geometry))
461
+ for (const ring of poly)
462
+ n += ring.length;
463
+ return n;
464
+ }
465
+ /** Clip every feature to the window; unchanged features keep their identity. */
466
+ export function clipFeatureCollection(geojson, w, getInfo) {
467
+ const stats = {
468
+ features: 0,
469
+ rings: { kept: 0, clipped: 0, wrapped: 0, dropped: 0 },
470
+ vertices: 0,
471
+ stream: { classified: 0, inside: 0, outside: 0 },
472
+ };
473
+ const features = [];
474
+ const feats = geojson?.features ?? [];
475
+ for (let fi = 0; fi < feats.length; fi++) {
476
+ const feature = feats[fi], info = getInfo(fi, feature);
477
+ if (!isCapVisible(info.cap, w))
478
+ continue;
479
+ const polys = polygonsOf(feature.geometry);
480
+ if (capInside(info.cap, w)) {
481
+ features.push(feature);
482
+ stats.features++;
483
+ for (const poly of polys)
484
+ for (const ring of poly) {
485
+ stats.rings.kept++;
486
+ stats.vertices += ring.length;
487
+ }
488
+ continue;
489
+ }
490
+ const outPolys = [];
491
+ let changed = false;
492
+ polys.forEach((poly, pi) => {
493
+ const outRings = [];
494
+ let drop = false, polyChanged = false;
495
+ for (let ri = 0; ri < poly.length && !drop; ri++) {
496
+ const hole = ri > 0, rinfo = info.ring(pi, ri);
497
+ let res;
498
+ if (!isCapVisible(rinfo.cap, w))
499
+ res = { status: "away" };
500
+ else if (capInside(rinfo.cap, w))
501
+ res = { status: "inside", ring: poly[ri] };
502
+ else
503
+ res = clipRing(w, rinfo, hole ? HOLE : EXTERIOR, stats.stream);
504
+ if (res.status === "inside") {
505
+ outRings.push(res.ring);
506
+ stats.rings.kept++;
507
+ }
508
+ else if (res.status === "clipped") {
509
+ outRings.push(...res.rings);
510
+ stats.rings.clipped += res.rings.length;
511
+ polyChanged = true;
512
+ }
513
+ else if (res.status === "wraps") {
514
+ polyChanged = true;
515
+ if (hole)
516
+ drop = true;
517
+ else {
518
+ outRings.push(circleRing(w, EXTERIOR));
519
+ stats.rings.wrapped++;
520
+ }
521
+ }
522
+ else {
523
+ polyChanged = true;
524
+ if (hole)
525
+ continue;
526
+ drop = true;
527
+ }
528
+ }
529
+ if (drop) {
530
+ changed = true;
531
+ stats.rings.dropped++;
532
+ return;
533
+ }
534
+ if (polyChanged)
535
+ changed = true;
536
+ outPolys.push(outRings);
537
+ });
538
+ if (!outPolys.length)
539
+ continue;
540
+ stats.features++;
541
+ if (!changed)
542
+ features.push(feature);
543
+ else {
544
+ const type = feature.geometry.type;
545
+ features.push({
546
+ ...feature,
547
+ geometry: type === "Polygon"
548
+ ? { type, coordinates: outPolys[0] }
549
+ : { type: "MultiPolygon", coordinates: outPolys },
550
+ });
551
+ }
552
+ for (const poly of outPolys)
553
+ for (const ring of poly)
554
+ stats.vertices += ring.length;
555
+ }
556
+ return { geojson: { type: "FeatureCollection", features }, stats };
557
+ }
@@ -0,0 +1,25 @@
1
+ import type { Feature, FeatureCollection } from "./types.js";
2
+ import type { UnitVector } from "./spherical-geometry.js";
3
+ /** Unit-vector center and angular radius, in radians. */
4
+ export interface SphericalCap {
5
+ cx: number;
6
+ cy: number;
7
+ cz: number;
8
+ radiusRad: number;
9
+ }
10
+ export interface SphericalViewCone {
11
+ vx: number;
12
+ vy: number;
13
+ vz: number;
14
+ viewRadius: number;
15
+ }
16
+ export declare function lonLatToVec(lon: number, lat: number): UnitVector;
17
+ export declare function computeFeatureCap(feature: Feature): SphericalCap;
18
+ export declare function computeFeatureCaps(geojson: FeatureCollection): SphericalCap[];
19
+ export declare function isCapVisible(cap: SphericalCap, cone: SphericalViewCone): boolean;
20
+ /** Filter using an explicit view cone. Supplied caps must match this frame
21
+ * by index and conservatively enclose its geometry. Inputs are not modified.
22
+ * The cap construction is intended for small-interior spherical polygons;
23
+ * it is not a proof of containment for arbitrary spherical geometry.
24
+ */
25
+ export declare function filterSphericalFeatures(geojson: FeatureCollection, cone: SphericalViewCone, caps?: readonly SphericalCap[]): FeatureCollection;
@@ -0,0 +1,102 @@
1
+ const RAD = Math.PI / 180;
2
+ const CAP_MARGIN_RAD = 0.02;
3
+ export function lonLatToVec(lon, lat) {
4
+ const lambda = lon * RAD, phi = lat * RAD, cosPhi = Math.cos(phi);
5
+ return [cosPhi * Math.cos(lambda), cosPhi * Math.sin(lambda), Math.sin(phi)];
6
+ }
7
+ function forEachRingCoord(geometry, fn) {
8
+ if (!geometry)
9
+ return;
10
+ if (geometry.type === "Polygon") {
11
+ for (const ring of geometry.coordinates)
12
+ for (const pt of ring)
13
+ fn(pt);
14
+ }
15
+ else if (geometry.type === "MultiPolygon") {
16
+ for (const poly of geometry.coordinates)
17
+ for (const ring of poly)
18
+ for (const pt of ring)
19
+ fn(pt);
20
+ }
21
+ else if (geometry.type === "LineString") {
22
+ for (const pt of geometry.coordinates)
23
+ fn(pt);
24
+ }
25
+ else if (geometry.type === "MultiLineString") {
26
+ for (const line of geometry.coordinates)
27
+ for (const pt of line)
28
+ fn(pt);
29
+ }
30
+ }
31
+ // Scratch unit vectors let the cap use one trig pass instead of two.
32
+ let scratch = new Float64Array(3 * 4096);
33
+ export function computeFeatureCap(feature) {
34
+ let sx = 0, sy = 0, sz = 0, count = 0;
35
+ forEachRingCoord(feature.geometry, ([lon, lat]) => {
36
+ if (count * 3 + 3 > scratch.length) {
37
+ const grown = new Float64Array(scratch.length * 2);
38
+ grown.set(scratch);
39
+ scratch = grown;
40
+ }
41
+ const [x, y, z] = lonLatToVec(lon, lat);
42
+ scratch[count * 3] = x;
43
+ scratch[count * 3 + 1] = y;
44
+ scratch[count * 3 + 2] = z;
45
+ sx += x;
46
+ sy += y;
47
+ sz += z;
48
+ count++;
49
+ });
50
+ if (!count)
51
+ return { cx: 1, cy: 0, cz: 0, radiusRad: 0 };
52
+ const len = Math.hypot(sx, sy, sz);
53
+ if (len < 1e-6)
54
+ return { cx: 1, cy: 0, cz: 0, radiusRad: Math.PI };
55
+ const cx = sx / len, cy = sy / len, cz = sz / len;
56
+ let minDot = 1;
57
+ for (let i = 0; i < count; i++) {
58
+ const dot = cx * scratch[i * 3] +
59
+ cy * scratch[i * 3 + 1] +
60
+ cz * scratch[i * 3 + 2];
61
+ if (dot < minDot)
62
+ minDot = dot;
63
+ }
64
+ const maxAngle = Math.acos(Math.max(-1, Math.min(1, minDot)));
65
+ // A cap below a hemisphere contains every minor arc between its vertices.
66
+ // Larger line caps are not geodesically convex: retain those conservatively.
67
+ if ((feature.geometry.type === "LineString" ||
68
+ feature.geometry.type === "MultiLineString") &&
69
+ maxAngle + CAP_MARGIN_RAD >= Math.PI / 2)
70
+ return { cx, cy, cz, radiusRad: Math.PI };
71
+ return {
72
+ cx,
73
+ cy,
74
+ cz,
75
+ radiusRad: Math.min(Math.PI, maxAngle + CAP_MARGIN_RAD),
76
+ };
77
+ }
78
+ export function computeFeatureCaps(geojson) {
79
+ return (geojson?.features ?? []).map(computeFeatureCap);
80
+ }
81
+ export function isCapVisible(cap, cone) {
82
+ const maxAngle = cap.radiusRad + cone.viewRadius;
83
+ if (maxAngle >= Math.PI)
84
+ return true;
85
+ const dot = cap.cx * cone.vx + cap.cy * cone.vy + cap.cz * cone.vz;
86
+ return dot >= Math.cos(maxAngle);
87
+ }
88
+ /** Filter using an explicit view cone. Supplied caps must match this frame
89
+ * by index and conservatively enclose its geometry. Inputs are not modified.
90
+ * The cap construction is intended for small-interior spherical polygons;
91
+ * it is not a proof of containment for arbitrary spherical geometry.
92
+ */
93
+ export function filterSphericalFeatures(geojson, cone, caps = computeFeatureCaps(geojson)) {
94
+ if (caps.length !== geojson.features.length)
95
+ throw new Error("Spherical caps must match feature count");
96
+ if (!geojson.features.length)
97
+ return geojson;
98
+ return {
99
+ type: "FeatureCollection",
100
+ features: geojson.features.filter((_, i) => isCapVisible(caps[i], cone)),
101
+ };
102
+ }