@math.gl/geometry 5.0.0-beta.1 → 5.0.0-beta.3

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 (39) hide show
  1. package/dist/culling/index.cjs +40 -7
  2. package/dist/culling/index.cjs.map +3 -3
  3. package/dist/culling/index.d.ts +2 -0
  4. package/dist/culling/index.d.ts.map +1 -1
  5. package/dist/culling/index.js +1 -0
  6. package/dist/culling/index.js.map +1 -1
  7. package/dist/culling/screen-ray.d.ts +22 -0
  8. package/dist/culling/screen-ray.d.ts.map +1 -0
  9. package/dist/culling/screen-ray.js +55 -0
  10. package/dist/culling/screen-ray.js.map +1 -0
  11. package/dist/index.cjs +272 -34
  12. package/dist/index.cjs.map +3 -3
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/polygon/earcut.d.ts.map +1 -1
  18. package/dist/polygon/earcut.js +100 -34
  19. package/dist/polygon/earcut.js.map +1 -1
  20. package/dist/polygon/subdivide-triangle-mesh.d.ts +10 -0
  21. package/dist/polygon/subdivide-triangle-mesh.d.ts.map +1 -1
  22. package/dist/polygon/subdivide-triangle-mesh.js +13 -3
  23. package/dist/polygon/subdivide-triangle-mesh.js.map +1 -1
  24. package/dist/utils/compose-attribute-provenance.d.ts +13 -0
  25. package/dist/utils/compose-attribute-provenance.d.ts.map +1 -0
  26. package/dist/utils/compose-attribute-provenance.js +63 -0
  27. package/dist/utils/compose-attribute-provenance.js.map +1 -0
  28. package/dist/utils/qualify-surface-transition.d.ts +21 -0
  29. package/dist/utils/qualify-surface-transition.d.ts.map +1 -0
  30. package/dist/utils/qualify-surface-transition.js +140 -0
  31. package/dist/utils/qualify-surface-transition.js.map +1 -0
  32. package/package.json +3 -3
  33. package/src/culling/index.ts +2 -0
  34. package/src/culling/screen-ray.ts +75 -0
  35. package/src/index.ts +4 -0
  36. package/src/polygon/earcut.ts +98 -37
  37. package/src/polygon/subdivide-triangle-mesh.ts +22 -2
  38. package/src/utils/compose-attribute-provenance.ts +74 -0
  39. package/src/utils/qualify-surface-transition.ts +169 -0
@@ -0,0 +1,63 @@
1
+ /** Compose child→intermediate and intermediate→original barycentric provenance.
2
+ * Interpolate attributes only after composition, avoiding repeated integer rounding.
3
+ * More than three distinct contributors rejects: this contract describes source
4
+ * triangles, not arbitrary sparse blending. Zero-weight indices are ignored.
5
+ */
6
+ export function composeAttributeProvenance(parent, child, options = {}) {
7
+ const limit = options.maxVertices ?? 65536;
8
+ if (!Number.isSafeInteger(limit) || limit < 0 || limit > 0xffffffff)
9
+ throw new RangeError('Invalid provenance vertex limit');
10
+ validate(parent);
11
+ validate(child, parent.sourceVertexIndices.length / 3);
12
+ if (child.sourceVertexIndices.length / 3 > limit)
13
+ throw new RangeError('Provenance composition exceeded maxVertices');
14
+ const indices = new Uint32Array(child.sourceVertexIndices.length);
15
+ const weights = new Float64Array(indices.length);
16
+ for (let vertex = 0; vertex < indices.length / 3; vertex++) {
17
+ const contributors = new Map();
18
+ for (let j = 0; j < 3; j++) {
19
+ const weight = child.sourceVertexWeights[3 * vertex + j];
20
+ if (!weight)
21
+ continue;
22
+ const intermediate = child.sourceVertexIndices[3 * vertex + j];
23
+ for (let k = 0; k < 3; k++) {
24
+ const w = weight * parent.sourceVertexWeights[3 * intermediate + k];
25
+ if (!w)
26
+ continue;
27
+ const index = parent.sourceVertexIndices[3 * intermediate + k];
28
+ contributors.set(index, (contributors.get(index) ?? 0) + w);
29
+ }
30
+ }
31
+ if (contributors.size > 3)
32
+ throw new RangeError('Composed vertex spans multiple source triangles');
33
+ const sum = Array.from(contributors.values()).reduce((a, b) => a + b, 0);
34
+ let slot = 3 * vertex;
35
+ for (const [index, weight] of contributors) {
36
+ indices[slot] = index;
37
+ weights[slot++] = weight / sum;
38
+ }
39
+ }
40
+ return { sourceVertexIndices: indices, sourceVertexWeights: weights };
41
+ }
42
+ function validate(p, count = 0x100000000) {
43
+ if (!Number.isSafeInteger(p.sourceVertexIndices.length) ||
44
+ p.sourceVertexIndices.length < 0 ||
45
+ p.sourceVertexIndices.length % 3 ||
46
+ p.sourceVertexIndices.length !== p.sourceVertexWeights.length)
47
+ throw new RangeError('Invalid provenance lengths');
48
+ for (let i = 0; i < p.sourceVertexIndices.length; i += 3) {
49
+ let sum = 0;
50
+ for (let j = 0; j < 3; j++) {
51
+ const w = p.sourceVertexWeights[i + j], index = p.sourceVertexIndices[i + j];
52
+ if (!Number.isFinite(w) ||
53
+ w < 0 ||
54
+ w > 1 ||
55
+ (w > 0 && (!Number.isSafeInteger(index) || index < 0 || index >= count)))
56
+ throw new RangeError('Invalid provenance contributor');
57
+ sum += w;
58
+ }
59
+ if (Math.abs(sum - 1) > 1e-10)
60
+ throw new RangeError('Provenance weights must sum to one');
61
+ }
62
+ }
63
+ //# sourceMappingURL=compose-attribute-provenance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose-attribute-provenance.js","sourceRoot":"","sources":["../../src/utils/compose-attribute-provenance.ts"],"names":[],"mappings":"AAKA;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CACxC,MAAwC,EACxC,KAAuC,EACvC,UAAkC,EAAE;IAEpC,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,IAAI,KAAK,CAAC;IAC3C,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,UAAU;QACjE,MAAM,IAAI,UAAU,CAAC,iCAAiC,CAAC,CAAC;IAC1D,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,mBAAmB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACvD,IAAI,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,CAAC,GAAG,KAAK;QAC9C,MAAM,IAAI,UAAU,CAAC,6CAA6C,CAAC,CAAC;IACt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B,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACvC,IACE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACnB,CAAC,GAAG,CAAC;gBACL,CAAC,GAAG,CAAC;gBACL,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC;gBAExE,MAAM,IAAI,UAAU,CAAC,gCAAgC,CAAC,CAAC;YACzD,GAAG,IAAI,CAAC,CAAC;QACX,CAAC;QACD,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,KAAK;YAAE,MAAM,IAAI,UAAU,CAAC,oCAAoC,CAAC,CAAC;IAC5F,CAAC;AACH,CAAC"}
@@ -0,0 +1,21 @@
1
+ import type { TriangleMesh } from "../polygon/subdivide-triangle-mesh.js";
2
+ export type SurfaceTransitionQualification = {
3
+ /** A fixed indexed disk stays a graph over XY throughout linear vertex interpolation. */
4
+ scope: 'convex-xy-disk-linear';
5
+ minimumProjectedDoubleArea: number;
6
+ boundary: Uint32Array;
7
+ };
8
+ /** Qualify a conservative subset of 3D mesh morphs, without time sampling.
9
+ * Input is an oriented, connected triangulated disk. Both endpoints share indices.
10
+ * Every triangle must retain positive XY orientation and the boundary must stay
11
+ * convex throughout linear vertex motion. Quadratic extrema test the full [0,1].
12
+ * This excludes holes, folded surfaces, most global globe meshes and curved vertex
13
+ * trajectories. It qualifies the piecewise-linear mesh, not its underlying smooth
14
+ * projection or a camera's approximation error. Floating-point margins reject
15
+ * near-degeneracy; this is not a formal interval-arithmetic certificate.
16
+ */
17
+ export declare function qualifySurfaceTransition(mesh: TriangleMesh, targetPositions: ArrayLike<number>, options?: {
18
+ minimumDoubleArea?: number;
19
+ maxChecks?: number;
20
+ }): SurfaceTransitionQualification;
21
+ //# sourceMappingURL=qualify-surface-transition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"qualify-surface-transition.d.ts","sourceRoot":"","sources":["../../src/utils/qualify-surface-transition.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,YAAY,EAAC,8CAA2C;AAErE,MAAM,MAAM,8BAA8B,GAAG;IAC3C,yFAAyF;IACzF,KAAK,EAAE,uBAAuB,CAAC;IAC/B,0BAA0B,EAAE,MAAM,CAAC;IACnC,QAAQ,EAAE,WAAW,CAAC;CACvB,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,YAAY,EAClB,eAAe,EAAE,SAAS,CAAC,MAAM,CAAC,EAClC,OAAO,GAAE;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAM,GAC7D,8BAA8B,CAiIhC"}
@@ -0,0 +1,140 @@
1
+ /** Qualify a conservative subset of 3D mesh morphs, without time sampling.
2
+ * Input is an oriented, connected triangulated disk. Both endpoints share indices.
3
+ * Every triangle must retain positive XY orientation and the boundary must stay
4
+ * convex throughout linear vertex motion. Quadratic extrema test the full [0,1].
5
+ * This excludes holes, folded surfaces, most global globe meshes and curved vertex
6
+ * trajectories. It qualifies the piecewise-linear mesh, not its underlying smooth
7
+ * projection or a camera's approximation error. Floating-point margins reject
8
+ * near-degeneracy; this is not a formal interval-arithmetic certificate.
9
+ */
10
+ export function qualifySurfaceTransition(mesh, targetPositions, options = {}) {
11
+ const from = Array.from(mesh.positions), to = Array.from(targetPositions), indices = Array.from(mesh.indices), count = from.length / 3, maxChecks = options.maxChecks ?? 1000000;
12
+ if (!from.length ||
13
+ from.length % 3 ||
14
+ to.length !== from.length ||
15
+ !indices.length ||
16
+ indices.length % 3 ||
17
+ !from.every(Number.isFinite) ||
18
+ !to.every(Number.isFinite) ||
19
+ !indices.every(i => Number.isSafeInteger(i) && i >= 0 && i < count) ||
20
+ !Number.isSafeInteger(maxChecks) ||
21
+ maxChecks < 0)
22
+ throw new RangeError('Invalid surface transition mesh or budget');
23
+ let scale = 0;
24
+ for (const positions of [from, to])
25
+ for (let i = 0; i < indices.length; i += 3)
26
+ for (let j = 0; j < 3; j++) {
27
+ const a = indices[i + j] * 3, b = indices[i + ((j + 1) % 3)] * 3;
28
+ scale = Math.max(scale, Math.hypot(positions[b] - positions[a], positions[b + 1] - positions[a + 1]));
29
+ }
30
+ const margin = options.minimumDoubleArea ?? scale * scale * 1e-12;
31
+ if (!Number.isFinite(margin) || margin <= 0)
32
+ throw new RangeError('Expected positive finite area margin');
33
+ let checks = 0;
34
+ const tick = () => {
35
+ if (++checks > maxChecks)
36
+ throw new RangeError('Surface qualification exceeded maxChecks');
37
+ };
38
+ const edges = new Map(), used = new Set(indices);
39
+ let minimum = Infinity;
40
+ const orientation = (a, b, c, t) => {
41
+ // Interpolate relative edges, avoiding cancellation from translating a patch
42
+ // across large world-coordinate origins before subtracting vertex positions.
43
+ const edge = (v, k) => (from[3 * v + k] - from[3 * a + k]) * (1 - t) + (to[3 * v + k] - to[3 * a + k]) * t;
44
+ return edge(b, 0) * edge(c, 1) - edge(b, 1) * edge(c, 0);
45
+ };
46
+ const minimumOrientation = (a, b, c) => {
47
+ tick();
48
+ return quadraticMinimum(t => orientation(a, b, c, t));
49
+ };
50
+ for (let i = 0; i < indices.length; i += 3) {
51
+ const tri = indices.slice(i, i + 3);
52
+ const area = minimumOrientation(tri[0], tri[1], tri[2]);
53
+ if (area < margin)
54
+ throw new RangeError('Triangle collapses or reverses during transition');
55
+ minimum = Math.min(minimum, area);
56
+ for (let j = 0; j < 3; j++) {
57
+ const a = tri[j], b = tri[(j + 1) % 3], key = a < b ? `${a}:${b}` : `${b}:${a}`, edge = edges.get(key);
58
+ if (edge) {
59
+ if (edge.faces !== 1 || edge.a !== b || edge.b !== a)
60
+ throw new RangeError('Expected oriented manifold edges');
61
+ edge.faces++;
62
+ }
63
+ else
64
+ edges.set(key, { a, b, faces: 1 });
65
+ }
66
+ }
67
+ const next = new Map();
68
+ for (const edge of edges.values())
69
+ if (edge.faces === 1) {
70
+ if (next.has(edge.a))
71
+ throw new RangeError('Nonmanifold boundary');
72
+ next.set(edge.a, edge.b);
73
+ }
74
+ if (!next.size || used.size !== count || used.size - edges.size + indices.length / 3 !== 1)
75
+ throw new RangeError('Expected a triangulated disk without unused vertices');
76
+ const start = next.keys().next().value, boundary = [];
77
+ const visitedBoundary = new Set();
78
+ let v = start;
79
+ do {
80
+ if (visitedBoundary.has(v) || !next.has(v))
81
+ throw new RangeError('Expected one boundary cycle');
82
+ visitedBoundary.add(v);
83
+ boundary.push(v);
84
+ v = next.get(v);
85
+ } while (v !== start);
86
+ if (boundary.length !== next.size)
87
+ throw new RangeError('Multiple boundary cycles');
88
+ // Every boundary vertex stays left of each directed support edge. This allows
89
+ // collinear refinement vertices while rejecting a nonconvex or crossing outline.
90
+ for (let i = 0; i < boundary.length; i++) {
91
+ const a = boundary[i], b = boundary[(i + 1) % boundary.length];
92
+ // Distinct boundary vertices rule out multiple winding of a convex outline
93
+ // (a locally positive double-cover fan would otherwise pass support tests).
94
+ for (let j = i + 1; j < boundary.length; j++) {
95
+ tick();
96
+ const c = boundary[j];
97
+ const separation = quadraticMinimum(t => {
98
+ const dx = (from[3 * c] - from[3 * a]) * (1 - t) + (to[3 * c] - to[3 * a]) * t, dy = (from[3 * c + 1] - from[3 * a + 1]) * (1 - t) + (to[3 * c + 1] - to[3 * a + 1]) * t;
99
+ return dx * dx + dy * dy;
100
+ });
101
+ if (separation < margin)
102
+ throw new RangeError('Boundary vertices meet during transition');
103
+ }
104
+ for (const c of boundary)
105
+ if (c !== a && c !== b && minimumOrientation(a, b, c) < -margin * 1e-3)
106
+ throw new RangeError('Boundary is not convex throughout transition');
107
+ }
108
+ // Euler characteristic plus one boundary is insufficient if a closed component
109
+ // is present. Explicitly require connectivity of the vertex graph.
110
+ const neighbors = Array.from({ length: count }, () => []);
111
+ for (const { a, b } of edges.values()) {
112
+ neighbors[a].push(b);
113
+ neighbors[b].push(a);
114
+ }
115
+ const seen = new Set([start]), queue = [start];
116
+ for (let i = 0; i < queue.length; i++)
117
+ for (const n of neighbors[queue[i]])
118
+ if (!seen.has(n)) {
119
+ seen.add(n);
120
+ queue.push(n);
121
+ }
122
+ if (seen.size !== count)
123
+ throw new RangeError('Disconnected surface mesh');
124
+ return {
125
+ scope: 'convex-xy-disk-linear',
126
+ minimumProjectedDoubleArea: minimum,
127
+ boundary: new Uint32Array(boundary)
128
+ };
129
+ }
130
+ function quadraticMinimum(value) {
131
+ const f = value(0), g = value(1), h = value(0.5), a = 2 * (f + g - 2 * h), b = g - f - a;
132
+ if (![f, g, h, a, b].every(Number.isFinite))
133
+ throw new RangeError('Nonfinite surface orientation polynomial');
134
+ const t = a > 0 ? -b / (2 * a) : -1;
135
+ const result = Math.min(f, g, t > 0 && t < 1 ? value(t) : Infinity);
136
+ if (!Number.isFinite(result))
137
+ throw new RangeError('Nonfinite surface orientation');
138
+ return result;
139
+ }
140
+ //# sourceMappingURL=qualify-surface-transition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"qualify-surface-transition.js","sourceRoot":"","sources":["../../src/utils/qualify-surface-transition.ts"],"names":[],"mappings":"AAYA;;;;;;;;GAQG;AACH,MAAM,UAAU,wBAAwB,CACtC,IAAkB,EAClB,eAAkC,EAClC,UAA4D,EAAE;IAE9D,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EACrC,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,EAChC,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,EAClC,KAAK,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EACvB,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC;IAC3C,IACE,CAAC,IAAI,CAAC,MAAM;QACZ,IAAI,CAAC,MAAM,GAAG,CAAC;QACf,EAAE,CAAC,MAAM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I,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,+BAA+B,CAAC,CAAC;IACpF,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
- "version": "5.0.0-beta.1",
9
+ "version": "5.0.0-beta.3",
10
10
  "keywords": [
11
11
  "geometry",
12
12
  "gltf",
@@ -41,8 +41,8 @@
41
41
  "THIRD-PARTY-NOTICES.md"
42
42
  ],
43
43
  "dependencies": {
44
- "@math.gl/core": "5.0.0-beta.1"
44
+ "@math.gl/core": "5.0.0-beta.3"
45
45
  },
46
46
  "sideEffects": false,
47
- "gitHead": "13b9fae96e2df2010f5528a199316f47c044200b"
47
+ "gitHead": "5b20f706e26c9c5cfb252202e503fb98517a7350"
48
48
  }
@@ -38,6 +38,8 @@ export type {QueryPoint, TriangleRayHit} from './queries';
38
38
 
39
39
  export {intersectOrientedBoxes2D} from './oriented-box-2d';
40
40
  export type {OrientedBox2D} from './oriented-box-2d';
41
+ export {unprojectScreenRay} from './screen-ray';
42
+ export type {ScreenRay, ScreenRayViewport} from './screen-ray';
41
43
 
42
44
  export {
43
45
  getOrientedBoundingBoxQuaternion,
@@ -0,0 +1,75 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {Matrix4} from '@math.gl/core';
6
+
7
+ /** Top-origin viewport rectangle in the same units as the supplied screen position. */
8
+ export type ScreenRayViewport = {
9
+ x?: number;
10
+ y?: number;
11
+ width: number;
12
+ height: number;
13
+ };
14
+
15
+ /** A finite near-to-far segment: origin + direction reaches the far endpoint. */
16
+ export type ScreenRay = {
17
+ origin: [number, number, number];
18
+ direction: [number, number, number];
19
+ };
20
+
21
+ /**
22
+ * Unproject a top-origin screen position through an inverse clip matrix.
23
+ * The column-major matrix maps clip coordinates to the caller's output space;
24
+ * include any desired placement or coordinate conversion in it beforehand.
25
+ * The depth range defaults to WebGL/deck.gl clip coordinates [-1, 1]; use [0, 1]
26
+ * for a zero-to-one clip convention. Positions outside the viewport are allowed.
27
+ * Returns null for invalid or degenerate input or an unbounded segment.
28
+ */
29
+ export function unprojectScreenRay(
30
+ inverseClipMatrix: Readonly<ArrayLike<number>>,
31
+ viewport: ScreenRayViewport,
32
+ pixel: readonly [number, number],
33
+ depthRange: readonly [number, number] = [-1, 1]
34
+ ): ScreenRay | null {
35
+ const x = viewport.x ?? 0;
36
+ const y = viewport.y ?? 0;
37
+ if (
38
+ inverseClipMatrix.length !== 16 ||
39
+ !Array.from(inverseClipMatrix).every(Number.isFinite) ||
40
+ ![x, y, viewport.width, viewport.height, ...pixel, ...depthRange].every(Number.isFinite) ||
41
+ viewport.width <= 0 ||
42
+ viewport.height <= 0 ||
43
+ pixel.length !== 2 ||
44
+ depthRange.length !== 2 ||
45
+ depthRange[0] === depthRange[1]
46
+ )
47
+ return null;
48
+
49
+ const matrix = new Matrix4(Array.from(inverseClipMatrix));
50
+ const determinant = matrix.determinant();
51
+ if (!Number.isFinite(determinant) || determinant === 0) return null;
52
+ const horizontal = (2 * (pixel[0] - x)) / viewport.width - 1;
53
+ const vertical = 1 - (2 * (pixel[1] - y)) / viewport.height;
54
+ const points = depthRange.map(depth => matrix.transform([horizontal, vertical, depth, 1]));
55
+ if (points.some(point => point[3] === 0 || !point.every(Number.isFinite))) return null;
56
+ // A sign change crosses w=0 between endpoints, so the projected segment is unbounded.
57
+ if (points[0][3] < 0 !== points[1][3] < 0) return null;
58
+ const origin: [number, number, number] = [
59
+ points[0][0] / points[0][3],
60
+ points[0][1] / points[0][3],
61
+ points[0][2] / points[0][3]
62
+ ];
63
+ const direction: [number, number, number] = [
64
+ points[1][0] / points[1][3] - origin[0],
65
+ points[1][1] / points[1][3] - origin[1],
66
+ points[1][2] / points[1][3] - origin[2]
67
+ ];
68
+ const distance = Math.hypot(...direction);
69
+ return origin.every(Number.isFinite) &&
70
+ direction.every(Number.isFinite) &&
71
+ Number.isFinite(distance) &&
72
+ distance > 0
73
+ ? {origin, direction}
74
+ : null;
75
+ }
package/src/index.ts CHANGED
@@ -200,3 +200,7 @@ export type {
200
200
  ClipTriangleMeshOptions,
201
201
  ClippedTriangleMesh
202
202
  } from './polygon/clip-triangle-mesh';
203
+
204
+ export {composeAttributeProvenance} from './utils/compose-attribute-provenance';
205
+ export {qualifySurfaceTransition} from './utils/qualify-surface-transition';
206
+ export type {SurfaceTransitionQualification} from './utils/qualify-surface-transition';
@@ -33,7 +33,7 @@
33
33
  /* eslint-disable */
34
34
 
35
35
  import type {NumericArray} from '@math.gl/core';
36
- import {getPolygonSignedArea, DimIndex, Plane2D} from './polygon-utils';
36
+ import {DimIndex, Plane2D} from './polygon-utils';
37
37
 
38
38
  /**
39
39
  * Computes a triangulation of a polygon
@@ -51,6 +51,25 @@ export function earcut(
51
51
  areas?: NumericArray,
52
52
  plane: Plane2D = 'xy'
53
53
  ): number[] {
54
+ // Keep nested calls from numeric array getters isolated.
55
+ const savedIndex = vertexPoolIndex;
56
+ const savedQueue = activeHoleQueue;
57
+ if (!holeQueues[callDepth]) holeQueues[callDepth] = [];
58
+ activeHoleQueue = holeQueues[callDepth];
59
+ callDepth++;
60
+ try {
61
+ return triangulate(positions, holeIndices, dim, areas, plane);
62
+ } finally {
63
+ activeHoleQueue.length = 0;
64
+ activeHoleQueue = savedQueue;
65
+ vertexPoolIndex = savedIndex;
66
+ callDepth--;
67
+ // Do not retain arbitrarily large object graphs after a one-off polygon.
68
+ if (callDepth === 0 && vertexPool.length > 65536) vertexPool.length = 0;
69
+ }
70
+ }
71
+
72
+ function triangulate(positions, holeIndices, dim, areas, plane): number[] {
54
73
  const hasHoles = holeIndices && holeIndices.length;
55
74
  const outerLen = hasHoles ? holeIndices[0] * dim : positions.length;
56
75
  let outerNode = linkedList(positions, 0, outerLen, dim, true, areas && areas[0], plane);
@@ -70,12 +89,14 @@ export function earcut(
70
89
 
71
90
  // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
72
91
  if (positions.length > 80 * dim) {
73
- minX = maxX = positions[0];
74
- minY = maxY = positions[1];
92
+ const i0 = DimIndex[plane[0]];
93
+ const i1 = DimIndex[plane[1]];
94
+ minX = maxX = positions[i0];
95
+ minY = maxY = positions[i1];
75
96
 
76
97
  for (let i = dim; i < outerLen; i += dim) {
77
- x = positions[i];
78
- y = positions[i + 1];
98
+ x = positions[i + i0];
99
+ y = positions[i + i1];
79
100
  if (x < minX) minX = x;
80
101
  if (y < minY) minY = y;
81
102
  if (x > maxX) maxX = x;
@@ -87,7 +108,7 @@ export function earcut(
87
108
  invSize = invSize !== 0 ? 32767 / invSize : 0;
88
109
  }
89
110
 
90
- earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
111
+ earcutLinked(outerNode, triangles, minX, minY, invSize, 0);
91
112
 
92
113
  return triangles;
93
114
  }
@@ -102,22 +123,40 @@ function linkedList(
102
123
  area: number | undefined,
103
124
  plane: Plane2D
104
125
  ): Vertex {
126
+ if (start >= end) return null;
105
127
  let i;
106
128
  let last;
129
+ const i0 = DimIndex[plane[0]];
130
+ const i1 = DimIndex[plane[1]];
107
131
  if (area === undefined) {
108
- area = getPolygonSignedArea(data, {start, end, size: dim, plane});
109
- }
110
-
111
- let i0 = DimIndex[plane[0]];
112
- let i1 = DimIndex[plane[1]];
113
- // Note that the signed area calculation in math.gl
114
- // has the opposite sign to that which was originally
115
- // present in earcut, thus the `< 0` is reversed
116
- if (clockwise === area < 0) {
117
- for (i = start; i < end; i += dim) last = insertNode(i, data[i + i0], data[i + i1], last);
132
+ // Combine coordinate reads and area accumulation, as in loaders.gl.
133
+ let sum = 0;
134
+ let previousX = data[end - dim + i0];
135
+ let previousY = data[end - dim + i1];
136
+ for (i = start; i < end; i += dim) {
137
+ const x = data[i + i0];
138
+ const y = data[i + i1];
139
+ sum += (x - previousX) * (y + previousY);
140
+ last = insertNode(i / dim, x, y, last);
141
+ previousX = x;
142
+ previousY = y;
143
+ }
144
+ if (last && clockwise !== sum / 2 < 0) {
145
+ let node = last;
146
+ do {
147
+ const next = node.next;
148
+ node.next = node.prev;
149
+ node.prev = next;
150
+ node = next;
151
+ } while (node !== last);
152
+ // Preserve the starting vertex and triangle order of reverse insertion.
153
+ last = last.prev;
154
+ }
155
+ } else if (clockwise === area < 0) {
156
+ for (i = start; i < end; i += dim) last = insertNode(i / dim, data[i + i0], data[i + i1], last);
118
157
  } else {
119
158
  for (i = end - dim; i >= start; i -= dim)
120
- last = insertNode(i, data[i + i0], data[i + i1], last);
159
+ last = insertNode(i / dim, data[i + i0], data[i + i1], last);
121
160
  }
122
161
 
123
162
  if (last && equals(last, last.next)) {
@@ -152,7 +191,7 @@ function filterPoints(start, end?) {
152
191
  }
153
192
 
154
193
  // main ear slicing loop which triangulates a polygon (given as a linked list)
155
- function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass?) {
194
+ function earcutLinked(ear, triangles, minX, minY, invSize, pass?) {
156
195
  if (!ear) return;
157
196
 
158
197
  // interlink polygon nodes in z-order
@@ -169,9 +208,9 @@ function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass?) {
169
208
 
170
209
  if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
171
210
  // cut off the triangle
172
- triangles.push((prev.i / dim) | 0);
173
- triangles.push((ear.i / dim) | 0);
174
- triangles.push((next.i / dim) | 0);
211
+ triangles.push(prev.i);
212
+ triangles.push(ear.i);
213
+ triangles.push(next.i);
175
214
 
176
215
  removeNode(ear);
177
216
 
@@ -188,16 +227,16 @@ function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass?) {
188
227
  if (ear === stop) {
189
228
  // try filtering points and slicing again
190
229
  if (!pass) {
191
- earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
230
+ earcutLinked(filterPoints(ear), triangles, minX, minY, invSize, 1);
192
231
 
193
232
  // if this didn't work, try curing all small self-intersections locally
194
233
  } else if (pass === 1) {
195
- ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
196
- earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
234
+ ear = cureLocalIntersections(filterPoints(ear), triangles);
235
+ earcutLinked(ear, triangles, minX, minY, invSize, 2);
197
236
 
198
237
  // as a last resort, try splitting the remaining polygon into two
199
238
  } else if (pass === 2) {
200
- splitEarcut(ear, triangles, dim, minX, minY, invSize);
239
+ splitEarcut(ear, triangles, minX, minY, invSize);
201
240
  }
202
241
 
203
242
  break;
@@ -336,7 +375,7 @@ function isEarHashed(ear, minX, minY, invSize) {
336
375
  }
337
376
 
338
377
  // go through all polygon nodes and cure small local self-intersections
339
- function cureLocalIntersections(start, triangles, dim) {
378
+ function cureLocalIntersections(start, triangles) {
340
379
  let p = start;
341
380
  do {
342
381
  const a = p.prev;
@@ -348,9 +387,9 @@ function cureLocalIntersections(start, triangles, dim) {
348
387
  locallyInside(a, b) &&
349
388
  locallyInside(b, a)
350
389
  ) {
351
- triangles.push((a.i / dim) | 0);
352
- triangles.push((p.i / dim) | 0);
353
- triangles.push((b.i / dim) | 0);
390
+ triangles.push(a.i);
391
+ triangles.push(p.i);
392
+ triangles.push(b.i);
354
393
 
355
394
  // remove two nodes involved
356
395
  removeNode(p);
@@ -365,7 +404,7 @@ function cureLocalIntersections(start, triangles, dim) {
365
404
  }
366
405
 
367
406
  // try splitting polygon into two and triangulate them independently
368
- function splitEarcut(start, triangles, dim, minX, minY, invSize) {
407
+ function splitEarcut(start, triangles, minX, minY, invSize) {
369
408
  // look for a valid diagonal that divides the polygon into two
370
409
  let a = start;
371
410
  do {
@@ -380,8 +419,8 @@ function splitEarcut(start, triangles, dim, minX, minY, invSize) {
380
419
  c = filterPoints(c, c.next);
381
420
 
382
421
  // run earcut on each half
383
- earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
384
- earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
422
+ earcutLinked(a, triangles, minX, minY, invSize, 0);
423
+ earcutLinked(c, triangles, minX, minY, invSize, 0);
385
424
  return;
386
425
  }
387
426
  b = b.next;
@@ -399,7 +438,8 @@ function eliminateHoles(
399
438
  areas: NumericArray | undefined,
400
439
  plane: Plane2D
401
440
  ): Vertex {
402
- const queue = [];
441
+ const queue = activeHoleQueue;
442
+ queue.length = 0;
403
443
  let i;
404
444
  let len;
405
445
  let start;
@@ -410,6 +450,7 @@ function eliminateHoles(
410
450
  start = holeIndices[i] * dim;
411
451
  end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
412
452
  list = linkedList(data, start, end, dim, false, areas && areas[i + 1], plane);
453
+ if (!list) continue;
413
454
  if (list === list.next) list.steiner = true;
414
455
  queue.push(getLeftmost(list));
415
456
  }
@@ -724,8 +765,8 @@ function middleInside(a, b) {
724
765
  // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
725
766
  // if one belongs to the outer ring and another to a hole, it merges it into a single ring
726
767
  function splitPolygon(a, b) {
727
- const a2 = new Vertex(a.i, a.x, a.y);
728
- const b2 = new Vertex(b.i, b.x, b.y);
768
+ const a2 = allocateVertex(a.i, a.x, a.y);
769
+ const b2 = allocateVertex(b.i, b.x, b.y);
729
770
  const an = a.next;
730
771
  const bp = b.prev;
731
772
 
@@ -746,7 +787,7 @@ function splitPolygon(a, b) {
746
787
 
747
788
  // create a node and optionally link it with previous one (in a circular doubly linked list)
748
789
  function insertNode(i, x, y, last) {
749
- const p = new Vertex(i, x, y);
790
+ const p = allocateVertex(i, x, y);
750
791
 
751
792
  if (!last) {
752
793
  p.prev = p;
@@ -768,8 +809,28 @@ function removeNode(p) {
768
809
  if (p.nextZ) p.nextZ.prevZ = p.prevZ;
769
810
  }
770
811
 
812
+ // Reuse scratch nodes and queues across calls; no input or output arrays are retained.
813
+ const vertexPool: Vertex[] = [];
814
+ let vertexPoolIndex = 0;
815
+ const holeQueues: Vertex[][] = [];
816
+ let activeHoleQueue: Vertex[] = [];
817
+ let callDepth = 0;
818
+
819
+ function allocateVertex(i: number, x: number, y: number): Vertex {
820
+ let vertex = vertexPool[vertexPoolIndex];
821
+ if (!vertex) vertexPool[vertexPoolIndex] = vertex = new Vertex(i, x, y);
822
+ vertexPoolIndex++;
823
+ vertex.i = i;
824
+ vertex.x = x;
825
+ vertex.y = y;
826
+ vertex.prev = vertex.next = vertex.prevZ = vertex.nextZ = null;
827
+ vertex.z = 0;
828
+ vertex.steiner = false;
829
+ return vertex;
830
+ }
831
+
771
832
  class Vertex {
772
- // vertex index in coordinates array
833
+ // vertex index, independent of coordinate stride
773
834
  i: number;
774
835
 
775
836
  // vertex coordinates