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

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 (140) hide show
  1. package/README.md +61 -0
  2. package/THIRD-PARTY-NOTICES.md +1 -1
  3. package/dist/color/color-lut-types.d.ts +16 -0
  4. package/dist/color/color-lut-types.d.ts.map +1 -0
  5. package/dist/color/color-lut-types.js +5 -0
  6. package/dist/color/color-lut-types.js.map +1 -0
  7. package/dist/color/index.cjs +132 -0
  8. package/dist/color/index.cjs.map +6 -0
  9. package/dist/color/index.d.ts +4 -0
  10. package/dist/color/index.d.ts.map +1 -0
  11. package/dist/color/index.js +5 -0
  12. package/dist/color/index.js.map +1 -0
  13. package/dist/color/sample-lut.d.ts +13 -0
  14. package/dist/color/sample-lut.d.ts.map +1 -0
  15. package/dist/color/sample-lut.js +132 -0
  16. package/dist/color/sample-lut.js.map +1 -0
  17. package/dist/culling/bounds.d.ts +20 -0
  18. package/dist/culling/bounds.d.ts.map +1 -0
  19. package/dist/culling/bounds.js +121 -0
  20. package/dist/culling/bounds.js.map +1 -0
  21. package/dist/culling/frustum-planes.d.ts +5 -0
  22. package/dist/culling/frustum-planes.d.ts.map +1 -0
  23. package/dist/culling/frustum-planes.js +37 -0
  24. package/dist/culling/frustum-planes.js.map +1 -0
  25. package/dist/culling/geometric-queries.d.ts +34 -0
  26. package/dist/culling/geometric-queries.d.ts.map +1 -0
  27. package/dist/culling/geometric-queries.js +208 -0
  28. package/dist/culling/geometric-queries.js.map +1 -0
  29. package/dist/culling/index.cjs +944 -508
  30. package/dist/culling/index.cjs.map +3 -3
  31. package/dist/culling/index.d.ts +7 -1
  32. package/dist/culling/index.d.ts.map +1 -1
  33. package/dist/culling/index.js +4 -0
  34. package/dist/culling/index.js.map +1 -1
  35. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts +3 -3
  36. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts.map +1 -1
  37. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js +25 -8
  38. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js.map +1 -1
  39. package/dist/culling/lib/culling-volume.d.ts +3 -0
  40. package/dist/culling/lib/culling-volume.d.ts.map +1 -1
  41. package/dist/culling/lib/culling-volume.js +7 -0
  42. package/dist/culling/lib/culling-volume.js.map +1 -1
  43. package/dist/culling/lib/ray.d.ts +5 -0
  44. package/dist/culling/lib/ray.d.ts.map +1 -1
  45. package/dist/culling/lib/ray.js +21 -0
  46. package/dist/culling/lib/ray.js.map +1 -1
  47. package/dist/culling/screen-ray.d.ts +22 -0
  48. package/dist/culling/screen-ray.d.ts.map +1 -0
  49. package/dist/culling/screen-ray.js +55 -0
  50. package/dist/culling/screen-ray.js.map +1 -0
  51. package/dist/curves/adaptive-sampling.d.ts +16 -0
  52. package/dist/curves/adaptive-sampling.d.ts.map +1 -0
  53. package/dist/curves/adaptive-sampling.js +59 -0
  54. package/dist/curves/adaptive-sampling.js.map +1 -0
  55. package/dist/curves/index.d.ts +4 -0
  56. package/dist/curves/index.d.ts.map +1 -1
  57. package/dist/curves/index.js +2 -0
  58. package/dist/curves/index.js.map +1 -1
  59. package/dist/curves/parallel-transport.d.ts +12 -0
  60. package/dist/curves/parallel-transport.d.ts.map +1 -0
  61. package/dist/curves/parallel-transport.js +83 -0
  62. package/dist/curves/parallel-transport.js.map +1 -0
  63. package/dist/index.cjs +1922 -817
  64. package/dist/index.cjs.map +3 -3
  65. package/dist/index.d.ts +15 -3
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +8 -1
  68. package/dist/index.js.map +1 -1
  69. package/dist/lighting/index.cjs +175 -0
  70. package/dist/lighting/index.cjs.map +6 -0
  71. package/dist/lighting/index.d.ts +4 -0
  72. package/dist/lighting/index.d.ts.map +1 -0
  73. package/dist/lighting/index.js +5 -0
  74. package/dist/lighting/index.js.map +1 -0
  75. package/dist/lighting/lighting-types.d.ts +16 -0
  76. package/dist/lighting/lighting-types.d.ts.map +1 -0
  77. package/dist/lighting/lighting-types.js +5 -0
  78. package/dist/lighting/lighting-types.js.map +1 -0
  79. package/dist/lighting/photometry.d.ts +36 -0
  80. package/dist/lighting/photometry.d.ts.map +1 -0
  81. package/dist/lighting/photometry.js +181 -0
  82. package/dist/lighting/photometry.js.map +1 -0
  83. package/dist/polygon/earcut.d.ts.map +1 -1
  84. package/dist/polygon/earcut.js +100 -34
  85. package/dist/polygon/earcut.js.map +1 -1
  86. package/dist/polygon/index.d.ts +2 -0
  87. package/dist/polygon/index.d.ts.map +1 -1
  88. package/dist/polygon/index.js +1 -0
  89. package/dist/polygon/index.js.map +1 -1
  90. package/dist/polygon/pole-of-inaccessibility.d.ts +21 -0
  91. package/dist/polygon/pole-of-inaccessibility.d.ts.map +1 -0
  92. package/dist/polygon/pole-of-inaccessibility.js +285 -0
  93. package/dist/polygon/pole-of-inaccessibility.js.map +1 -0
  94. package/dist/polygon/subdivide-triangle-mesh.d.ts +10 -0
  95. package/dist/polygon/subdivide-triangle-mesh.d.ts.map +1 -1
  96. package/dist/polygon/subdivide-triangle-mesh.js +13 -3
  97. package/dist/polygon/subdivide-triangle-mesh.js.map +1 -1
  98. package/dist/utils/compose-attribute-provenance.d.ts +13 -0
  99. package/dist/utils/compose-attribute-provenance.d.ts.map +1 -0
  100. package/dist/utils/compose-attribute-provenance.js +63 -0
  101. package/dist/utils/compose-attribute-provenance.js.map +1 -0
  102. package/dist/utils/project-bounds.d.ts +44 -0
  103. package/dist/utils/project-bounds.d.ts.map +1 -0
  104. package/dist/utils/project-bounds.js +93 -0
  105. package/dist/utils/project-bounds.js.map +1 -0
  106. package/dist/utils/project-texture-coordinates.d.ts +19 -0
  107. package/dist/utils/project-texture-coordinates.d.ts.map +1 -0
  108. package/dist/utils/project-texture-coordinates.js +49 -0
  109. package/dist/utils/project-texture-coordinates.js.map +1 -0
  110. package/dist/utils/qualify-surface-transition.d.ts +21 -0
  111. package/dist/utils/qualify-surface-transition.d.ts.map +1 -0
  112. package/dist/utils/qualify-surface-transition.js +140 -0
  113. package/dist/utils/qualify-surface-transition.js.map +1 -0
  114. package/package.json +15 -3
  115. package/src/color/color-lut-types.ts +19 -0
  116. package/src/color/index.ts +6 -0
  117. package/src/color/sample-lut.ts +175 -0
  118. package/src/culling/bounds.ts +152 -0
  119. package/src/culling/frustum-planes.ts +41 -0
  120. package/src/culling/geometric-queries.ts +299 -0
  121. package/src/culling/index.ts +39 -1
  122. package/src/culling/lib/bounding-volumes/axis-aligned-bounding-box.ts +26 -8
  123. package/src/culling/lib/culling-volume.ts +9 -1
  124. package/src/culling/lib/ray.ts +21 -0
  125. package/src/culling/screen-ray.ts +75 -0
  126. package/src/curves/adaptive-sampling.ts +85 -0
  127. package/src/curves/index.ts +4 -0
  128. package/src/curves/parallel-transport.ts +104 -0
  129. package/src/index.ts +51 -0
  130. package/src/lighting/index.ts +10 -0
  131. package/src/lighting/lighting-types.ts +20 -0
  132. package/src/lighting/photometry.ts +264 -0
  133. package/src/polygon/earcut.ts +98 -37
  134. package/src/polygon/index.ts +6 -0
  135. package/src/polygon/pole-of-inaccessibility.ts +330 -0
  136. package/src/polygon/subdivide-triangle-mesh.ts +22 -2
  137. package/src/utils/compose-attribute-provenance.ts +74 -0
  138. package/src/utils/project-bounds.ts +154 -0
  139. package/src/utils/project-texture-coordinates.ts +67 -0
  140. package/src/utils/qualify-surface-transition.ts +169 -0
@@ -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
+ }
@@ -0,0 +1,85 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import {Curve} from './curve';
5
+
6
+ export type AdaptiveCurveOptions = {
7
+ tolerance: number;
8
+ maxDepth?: number;
9
+ maxPoints?: number;
10
+ };
11
+ export type AdaptiveCurveSamples = {
12
+ parameters: Float64Array;
13
+ positions: Float64Array;
14
+ /** False means a work limit prevented meeting the sampled chord-error criterion. */
15
+ converged: boolean;
16
+ maxSampledError: number;
17
+ };
18
+
19
+ /** Quarter/midpoint chord-error sampling. This is not a certified bound for arbitrary curves. */
20
+ export function sampleCurveAdaptive(
21
+ curve: Curve,
22
+ options: AdaptiveCurveOptions
23
+ ): AdaptiveCurveSamples {
24
+ const {tolerance, maxDepth = 16, maxPoints = 65536} = options;
25
+ if (
26
+ !Number.isFinite(tolerance) ||
27
+ tolerance <= 0 ||
28
+ !Number.isInteger(maxDepth) ||
29
+ maxDepth < 0 ||
30
+ maxDepth > 30 ||
31
+ !Number.isSafeInteger(maxPoints) ||
32
+ maxPoints < 2
33
+ )
34
+ throw new RangeError('Invalid adaptive sampling budget');
35
+ const parameters = [0],
36
+ positions = [...curve.getPoint(0)];
37
+ let converged = true,
38
+ maxSampledError = 0;
39
+ const stack = [{t0: 0, t1: 1, a: curve.getPoint(0), b: curve.getPoint(1), depth: 0}];
40
+ while (stack.length) {
41
+ const segment = stack.pop()!;
42
+ const {t0, t1, a, b, depth} = segment;
43
+ const localEdge = b.map((x, i) => x - a[i]);
44
+ const samples = [0.25, 0.5, 0.75].map(f => curve.getPoint(t0 + (t1 - t0) * f));
45
+ const localSamples = samples.map(point => point.map((x, i) => x - a[i]));
46
+ const local = [...localEdge, ...localSamples.flat()].every(Number.isFinite);
47
+ const scale = local
48
+ ? Math.max(...localEdge.map(Math.abs), ...localSamples.flat().map(Math.abs), Number.MIN_VALUE)
49
+ : Math.max(...a.map(Math.abs), ...b.map(Math.abs), ...samples.flat().map(Math.abs));
50
+ const edge = local ? localEdge.map(x => x / scale) : b.map((x, i) => x / scale - a[i] / scale);
51
+ const squared = edge.reduce((sum, x) => sum + x * x, 0);
52
+ const measuredError = Math.max(
53
+ ...samples.map((p, sampleIndex) => {
54
+ const offset = local
55
+ ? localSamples[sampleIndex].map(x => x / scale)
56
+ : p.map((x, i) => x / scale - a[i] / scale);
57
+ const t = squared
58
+ ? Math.max(0, Math.min(1, edge.reduce((sum, x, i) => sum + x * offset[i], 0) / squared))
59
+ : 0;
60
+ return Math.hypot(...offset.map((x, i) => x - t * edge[i])) * scale;
61
+ })
62
+ );
63
+ const error = Number.isFinite(measuredError) ? measuredError : Infinity;
64
+ if (
65
+ error > tolerance &&
66
+ depth < maxDepth &&
67
+ parameters.length + stack.length + 2 <= maxPoints
68
+ ) {
69
+ const mid = (t0 + t1) / 2;
70
+ stack.push({t0: mid, t1, a: samples[1], b, depth: depth + 1});
71
+ stack.push({t0, t1: mid, a, b: samples[1], depth: depth + 1});
72
+ } else {
73
+ if (error > tolerance) converged = false;
74
+ maxSampledError = Math.max(maxSampledError, error);
75
+ parameters.push(t1);
76
+ positions.push(...b);
77
+ }
78
+ }
79
+ return {
80
+ parameters: new Float64Array(parameters),
81
+ positions: new Float64Array(positions),
82
+ converged,
83
+ maxSampledError
84
+ };
85
+ }
@@ -13,3 +13,7 @@ export {HermiteCurve} from './hermite-curve';
13
13
  export {CatmullRomCurve} from './catmull-rom-curve';
14
14
  export type {CatmullRomCurveOptions} from './catmull-rom-curve';
15
15
  export {CurveArcLength} from './curve-arc-length';
16
+ export {sampleCurveAdaptive} from './adaptive-sampling';
17
+ export type {AdaptiveCurveOptions, AdaptiveCurveSamples} from './adaptive-sampling';
18
+ export {computeParallelTransportFrames} from './parallel-transport';
19
+ export type {CurveFrames} from './parallel-transport';
@@ -0,0 +1,104 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {CurvePoint} from './curve';
5
+
6
+ export type CurveFrames = {tangents: Float64Array; normals: Float64Array; binormals: Float64Array};
7
+ type V = number[];
8
+ const sub = (a: V, b: V) => a.map((x, i) => x - b[i]);
9
+ const dot = (a: V, b: V) => a.reduce((sum, x, i) => sum + x * b[i], 0);
10
+ const cross = (a: V, b: V): V => [
11
+ a[1] * b[2] - a[2] * b[1],
12
+ a[2] * b[0] - a[0] * b[2],
13
+ a[0] * b[1] - a[1] * b[0]
14
+ ];
15
+ const unit = (a: V) => {
16
+ const length = Math.hypot(...a);
17
+ if (!length) throw new RangeError('Cannot construct a frame for a stationary path');
18
+ return a.map(x => x / length);
19
+ };
20
+ function rotate(v: V, axis: V, angle: number): V {
21
+ const c = Math.cos(angle),
22
+ s = Math.sin(angle),
23
+ d = dot(axis, v),
24
+ k = cross(axis, v);
25
+ return v.map((x, i) => x * c + k[i] * s + axis[i] * d * (1 - c));
26
+ }
27
+ /** Frames on a 3D polyline; repeated points inherit a neighboring direction. Closed paths repeat the first point. */
28
+ export function computeParallelTransportFrames(
29
+ points: readonly CurvePoint[],
30
+ options: {closed?: boolean; initialNormal?: CurvePoint} = {}
31
+ ): CurveFrames {
32
+ if (
33
+ points.length < 2 ||
34
+ points.some(p => p.length !== 3 || Array.from(p).some(x => !Number.isFinite(x)))
35
+ )
36
+ throw new RangeError('Expected at least two finite 3D points');
37
+ const data = points.map(p => Array.from(p)),
38
+ n = data.length,
39
+ closed = options.closed ?? false;
40
+ if (closed && (n < 4 || Math.hypot(...sub(data[0], data[n - 1])) !== 0))
41
+ throw new RangeError('A closed path must repeat its first point');
42
+ // Cache adjacent nonzero directions, then propagate backwards across equal runs.
43
+ // This keeps repeated-point paths linear rather than rescanning each suffix.
44
+ const tangent: V[] = new Array(n);
45
+ const edges: (V | undefined)[] = new Array(n - 1);
46
+ let last: V | undefined;
47
+ for (let i = 0; i < n - 1; i++) {
48
+ const edge = sub(data[i + 1], data[i]);
49
+ if (Math.hypot(...edge) > 0) last = edges[i] = unit(edge);
50
+ }
51
+ if (!last) throw new RangeError('Cannot construct a frame for a stationary path');
52
+ tangent[n - 1] = last;
53
+ for (let i = n - 2; i >= 0; i--) {
54
+ last = edges[i] ?? last;
55
+ tangent[i] = last;
56
+ }
57
+ if (closed) tangent[n - 1] = [...tangent[0]];
58
+ const t = tangent[0];
59
+ let initial = options.initialNormal ? Array.from(options.initialNormal) : [0, 0, 0];
60
+ if (options.initialNormal && (initial.length !== 3 || initial.some(x => !Number.isFinite(x))))
61
+ throw new RangeError('Invalid initial normal');
62
+ // Select an axis by absolute alignment (including negative tangent components).
63
+ if (!options.initialNormal) {
64
+ initial = [0, 0, 0];
65
+ initial[t.map(Math.abs).indexOf(Math.min(...t.map(Math.abs)))] = 1;
66
+ }
67
+ initial = unit(initial);
68
+ const perpendicular = cross(t, initial);
69
+ if (Math.hypot(...perpendicular) <= 1e-12) {
70
+ throw new RangeError('Initial normal must not be parallel to the tangent');
71
+ }
72
+ // A double cross product avoids normalizing a cancellation residual along t.
73
+ const normals: V[] = [unit(cross(perpendicular, t))];
74
+ for (let i = 1; i < n; i++) {
75
+ const axis = cross(tangent[i - 1], tangent[i]),
76
+ length = Math.hypot(...axis),
77
+ cosine = Math.max(-1, Math.min(1, dot(tangent[i - 1], tangent[i])));
78
+ let normal = normals[i - 1];
79
+ if (length > 1e-12)
80
+ normal = rotate(
81
+ normal,
82
+ axis.map(x => x / length),
83
+ Math.atan2(length, cosine)
84
+ );
85
+ // At an exact reversal the previous normal defines the deterministic 180-degree axis.
86
+ normals.push(unit(normal.map((x, j) => x - dot(normal, tangent[i]) * tangent[i][j])));
87
+ }
88
+ if (closed) {
89
+ const mismatch = Math.atan2(
90
+ dot(tangent[0], cross(normals[n - 1], normals[0])),
91
+ dot(normals[n - 1], normals[0])
92
+ );
93
+ const lengths = [0];
94
+ for (let i = 1; i < n; i++)
95
+ lengths.push(lengths[i - 1] + Math.hypot(...sub(data[i], data[i - 1])));
96
+ for (let i = 1; i < n; i++)
97
+ normals[i] = rotate(normals[i], tangent[i], (mismatch * lengths[i]) / lengths[n - 1]);
98
+ }
99
+ return {
100
+ tangents: new Float64Array(tangent.flat()),
101
+ normals: new Float64Array(normals.flat()),
102
+ binormals: new Float64Array(normals.flatMap((normal, i) => cross(tangent[i], normal)))
103
+ };
104
+ }
package/src/index.ts CHANGED
@@ -109,6 +109,8 @@ export {
109
109
  earcut,
110
110
  clipPolygon,
111
111
  clipPolyline,
112
+ getPoleOfInaccessibility,
113
+ DEFAULT_POLE_SEARCH_SEGMENT_TESTS,
112
114
  cutPolygonByGrid,
113
115
  cutPolylineByGrid,
114
116
  cutPolylineByMercatorBounds,
@@ -119,6 +121,7 @@ export {
119
121
  export type {
120
122
  PolygonWinding,
121
123
  WindingDirection,
124
+ PoleSearchBudget,
122
125
  SubdividePolylineOptions,
123
126
  SubdividedPolyline,
124
127
  PolylineEdgeSampler,
@@ -154,6 +157,7 @@ export {
154
157
  export type {
155
158
  CullingResult,
156
159
  ImplicitShape,
160
+ Shape,
157
161
  RayIntersection,
158
162
  BoxShapeProps,
159
163
  CapsuleShapeProps,
@@ -200,3 +204,50 @@ export type {
200
204
  ClipTriangleMeshOptions,
201
205
  ClippedTriangleMesh
202
206
  } from './polygon/clip-triangle-mesh';
207
+
208
+ export {composeAttributeProvenance} from './utils/compose-attribute-provenance';
209
+ export {qualifySurfaceTransition} from './utils/qualify-surface-transition';
210
+ export type {SurfaceTransitionQualification} from './utils/qualify-surface-transition';
211
+
212
+ export {
213
+ extractFrustumPlanes,
214
+ createEmptyBounds,
215
+ isEmptyBounds,
216
+ boundsContainsPoint,
217
+ boundsContainsBounds,
218
+ boundsIntersect,
219
+ unionBounds,
220
+ intersectBounds,
221
+ expandBoundsByPoint,
222
+ expandBounds,
223
+ clampPointToBounds,
224
+ spheresIntersect,
225
+ boundsIntersectSphere
226
+ } from './culling/index';
227
+ export {
228
+ getRayPoint,
229
+ getClosestPointOnRay,
230
+ distanceToRay,
231
+ getClosestPointsRaySegment,
232
+ transformRay,
233
+ getTriangleBarycentric,
234
+ getTriangleArea,
235
+ getTriangleNormal,
236
+ isTriangleFrontFacing,
237
+ triangleContainsPoint,
238
+ interpolateTriangleAttribute,
239
+ intersectPlaneSegment,
240
+ triangleIntersectsBounds
241
+ } from './culling/geometric-queries';
242
+ export type {RaySegmentClosestPoints} from './culling/geometric-queries';
243
+ export {sampleCurveAdaptive, computeParallelTransportFrames} from './curves/index';
244
+ export type {AdaptiveCurveOptions, AdaptiveCurveSamples, CurveFrames} from './curves/index';
245
+
246
+ export {projectBounds} from './utils/project-bounds';
247
+ export type {
248
+ ProjectionSourceBounds,
249
+ ProjectBoundsOptions,
250
+ ProjectedBoundsResult
251
+ } from './utils/project-bounds';
252
+ export {projectTextureCoordinates} from './utils/project-texture-coordinates';
253
+ export type {ProjectTextureCoordinatesOptions} from './utils/project-texture-coordinates';
@@ -0,0 +1,10 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ export {
5
+ createPhotometricSampler,
6
+ integrateLuminousFlux,
7
+ resamplePhotometricProfile
8
+ } from './photometry';
9
+ export type {PhotometricSampler, PhotometricGrid, PhotometricResampleOptions} from './photometry';
10
+ export type {PhotometricProfile, PhotometricSymmetry} from './lighting-types';
@@ -0,0 +1,20 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** Explicit azimuth extension rule; never inferred from a file or its metadata. */
6
+ export type PhotometricSymmetry = 'rotational' | 'quadrant' | 'bilateral' | 'none';
7
+
8
+ /** Format-independent polar/azimuth intensity measurements in degrees and candela. */
9
+ export type PhotometricProfile = {
10
+ /** Ordered polar angles in [0, 180], measured from an application-chosen pole. */
11
+ verticalAngles: ArrayLike<number>;
12
+ /** Ordered azimuth angles in [0, 360], relative to an application-chosen origin. */
13
+ horizontalAngles: ArrayLike<number>;
14
+ /** Candela samples, vertical angle varying fastest. */
15
+ intensities: ArrayLike<number>;
16
+ /** Uniform intensity multiplier; default 1. No lamp, ballast or file metadata is read. */
17
+ intensityScale?: number;
18
+ /** Explicit rotational, quadrant, bilateral or full-circle interpretation. */
19
+ symmetry: PhotometricSymmetry;
20
+ };
@@ -0,0 +1,264 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {PhotometricProfile} from './lighting-types';
5
+
6
+ /** Samples a snapshotted polar/azimuth distribution in candela, using angles in degrees. */
7
+ export type PhotometricSampler = (verticalAngle: number, horizontalAngle: number) => number;
8
+
9
+ /** Options for a regular, renderer-independent angular grid. */
10
+ export type PhotometricResampleOptions = {
11
+ /** Samples from vertical 0 through 180 degrees, including both endpoints; default 181. */
12
+ verticalCount?: number;
13
+ /** Horizontal samples around [0, 360), excluding the duplicate seam; default 360. */
14
+ horizontalCount?: number;
15
+ /** Preserve candela or divide by the measured peak; default none. */
16
+ normalization?: 'none' | 'peak';
17
+ };
18
+
19
+ /** Regular angular samples without texture objects or renderer coordinate transforms. */
20
+ export type PhotometricGrid = {
21
+ /** Vertical samples per row. */
22
+ readonly width: number;
23
+ /** Horizontal rows. */
24
+ readonly height: number;
25
+ /** Row-major intensity samples, vertical angle varying fastest. */
26
+ readonly data: Float64Array;
27
+ /** Vertical sample coordinates in degrees. */
28
+ readonly verticalAngles: Float64Array;
29
+ /** Horizontal sample coordinates in degrees. */
30
+ readonly horizontalAngles: Float64Array;
31
+ /** Physical candela or peak-relative values. */
32
+ readonly unit: 'candela' | 'relative';
33
+ /** Measured peak in candela, before optional normalization. */
34
+ readonly peakCandela: number;
35
+ };
36
+
37
+ /** Internal immutable snapshot of the measured distribution. */
38
+ type PreparedPhotometricProfile = {
39
+ /** Measured vertical angles. */
40
+ verticalAngles: Float64Array;
41
+ /** Measured horizontal angles. */
42
+ horizontalAngles: Float64Array;
43
+ /** Scaled candela values. */
44
+ values: Float64Array;
45
+ /** Measured horizontal extent, or zero for rotational symmetry. */
46
+ horizontalSpan: number;
47
+ /** Largest scaled intensity. */
48
+ peak: number;
49
+ };
50
+ const DEGREES_TO_RADIANS = Math.PI / 180;
51
+ const MAX_GRID_SAMPLES = 4_194_304;
52
+
53
+ /** Creates a reusable bilinear sampler; later mutations of the source profile have no effect. */
54
+ export function createPhotometricSampler(profile: PhotometricProfile): PhotometricSampler {
55
+ const prepared = preparePhotometricProfile(profile);
56
+ return (verticalAngle, horizontalAngle) => {
57
+ if (
58
+ !Number.isFinite(verticalAngle) ||
59
+ verticalAngle < 0 ||
60
+ verticalAngle > 180 ||
61
+ !Number.isFinite(horizontalAngle)
62
+ ) {
63
+ throw new Error(
64
+ 'Photometry: sampling requires a vertical angle in [0, 180] and finite horizontal angle'
65
+ );
66
+ }
67
+ return samplePreparedProfile(prepared, verticalAngle, horizontalAngle);
68
+ };
69
+ }
70
+
71
+ /** Integrates the piecewise bilinear angular distribution over solid angle, returning lumens. */
72
+ export function integrateLuminousFlux(profile: PhotometricProfile): number {
73
+ const prepared = preparePhotometricProfile(profile);
74
+ const {verticalAngles, horizontalAngles, values, horizontalSpan} = prepared;
75
+ const rows = new Float64Array(horizontalAngles.length);
76
+ for (let horizontalIndex = 0; horizontalIndex < rows.length; horizontalIndex++) {
77
+ for (let verticalIndex = 0; verticalIndex < verticalAngles.length - 1; verticalIndex++) {
78
+ const lowerAngle = verticalAngles[verticalIndex];
79
+ const upperAngle = verticalAngles[verticalIndex + 1];
80
+ const reflected = lowerAngle + upperAngle > 180;
81
+ const lower = reflected ? 180 - upperAngle : lowerAngle;
82
+ const upper = reflected ? 180 - lowerAngle : upperAngle;
83
+ const midpoint = ((lower + upper) / 2) * DEGREES_TO_RADIANS;
84
+ const halfWidth = ((upper - lower) / 2) * DEGREES_TO_RADIANS;
85
+ // Stable cos(h) - sin(h)/h, including very narrow angular intervals.
86
+ const squaredWidth = halfWidth * halfWidth;
87
+ const difference =
88
+ halfWidth < 0.001
89
+ ? squaredWidth * (-1 / 3 + squaredWidth * (1 / 30 - squaredWidth / 840))
90
+ : Math.cos(halfWidth) - Math.sin(halfWidth) / halfWidth;
91
+ const sharedWeight = Math.sin(midpoint) * Math.sin(halfWidth);
92
+ const offsetWeight = Math.cos(midpoint) * difference;
93
+ const lowerWeight = Math.max(0, sharedWeight + offsetWeight);
94
+ const upperWeight = Math.max(0, sharedWeight - offsetWeight);
95
+ const offset = horizontalIndex * verticalAngles.length + verticalIndex;
96
+ rows[horizontalIndex] +=
97
+ values[offset] * (reflected ? upperWeight : lowerWeight) +
98
+ values[offset + 1] * (reflected ? lowerWeight : upperWeight);
99
+ }
100
+ }
101
+ let flux = 0;
102
+ if (horizontalSpan === 0) flux = rows[0] * 2 * Math.PI;
103
+ else {
104
+ for (let index = 0; index < rows.length - 1; index++) {
105
+ const angularWidth =
106
+ (horizontalAngles[index + 1] - horizontalAngles[index]) * DEGREES_TO_RADIANS;
107
+ flux += (rows[index] / 2 + rows[index + 1] / 2) * angularWidth;
108
+ }
109
+ flux *= 360 / horizontalSpan;
110
+ }
111
+ if (!Number.isFinite(flux)) throw new Error('Photometry: luminous flux overflow');
112
+ return flux;
113
+ }
114
+
115
+ /** Resamples photometry; no image decoding, world-axis conversion or GPU allocation occurs. */
116
+ export function resamplePhotometricProfile(
117
+ profile: PhotometricProfile,
118
+ options: PhotometricResampleOptions = {}
119
+ ): PhotometricGrid {
120
+ const {verticalCount = 181, horizontalCount = 360, normalization = 'none'} = options;
121
+ if (
122
+ !Number.isSafeInteger(verticalCount) ||
123
+ verticalCount < 2 ||
124
+ !Number.isSafeInteger(horizontalCount) ||
125
+ horizontalCount < 1 ||
126
+ verticalCount * horizontalCount > MAX_GRID_SAMPLES ||
127
+ !['none', 'peak'].includes(normalization)
128
+ ) {
129
+ throw new Error('Photometry: invalid resampling dimensions or normalization');
130
+ }
131
+ const prepared = preparePhotometricProfile(profile);
132
+ const verticalAngles = Float64Array.from(
133
+ {length: verticalCount},
134
+ (_, index) => (index * 180) / (verticalCount - 1)
135
+ );
136
+ const horizontalAngles = Float64Array.from(
137
+ {length: horizontalCount},
138
+ (_, index) => (index * 360) / horizontalCount
139
+ );
140
+ const data = new Float64Array(verticalCount * horizontalCount);
141
+ for (let horizontalIndex = 0; horizontalIndex < horizontalCount; horizontalIndex++) {
142
+ for (let verticalIndex = 0; verticalIndex < verticalCount; verticalIndex++) {
143
+ const intensity = samplePreparedProfile(
144
+ prepared,
145
+ verticalAngles[verticalIndex],
146
+ horizontalAngles[horizontalIndex]
147
+ );
148
+ data[horizontalIndex * verticalCount + verticalIndex] =
149
+ normalization === 'peak' ? (prepared.peak > 0 ? intensity / prepared.peak : 0) : intensity;
150
+ }
151
+ }
152
+ return {
153
+ width: verticalCount,
154
+ height: horizontalCount,
155
+ data,
156
+ verticalAngles,
157
+ horizontalAngles,
158
+ unit: normalization === 'peak' ? 'relative' : 'candela',
159
+ peakCandela: prepared.peak
160
+ };
161
+ }
162
+
163
+ /** Validates and snapshots only the angular and intensity fields used by the calculations. */
164
+ function preparePhotometricProfile(profile: PhotometricProfile): PreparedPhotometricProfile {
165
+ const {verticalAngles, horizontalAngles, intensities, intensityScale = 1, symmetry} = profile;
166
+ if (
167
+ verticalAngles.length < 2 ||
168
+ horizontalAngles.length < 1 ||
169
+ intensities.length !== verticalAngles.length * horizontalAngles.length ||
170
+ !Number.isFinite(intensityScale) ||
171
+ intensityScale < 0
172
+ ) {
173
+ throw new Error('Photometry: invalid calculation profile');
174
+ }
175
+ for (const [angles, maximum] of [
176
+ [verticalAngles, 180],
177
+ [horizontalAngles, 360]
178
+ ] as const) {
179
+ for (let index = 0; index < angles.length; index++) {
180
+ if (
181
+ !Number.isFinite(angles[index]) ||
182
+ angles[index] < 0 ||
183
+ angles[index] > maximum ||
184
+ (index > 0 && angles[index] <= angles[index - 1])
185
+ )
186
+ throw new Error('Photometry: invalid calculation angles');
187
+ }
188
+ }
189
+ const first = horizontalAngles[0];
190
+ const last = horizontalAngles[horizontalAngles.length - 1];
191
+ const horizontalSpan = last - first;
192
+ const validSymmetry =
193
+ (symmetry === 'rotational' && horizontalAngles.length === 1) ||
194
+ (symmetry === 'quadrant' && horizontalAngles.length > 1 && first === 0 && last === 90) ||
195
+ (symmetry === 'bilateral' && horizontalAngles.length > 1 && horizontalSpan === 180) ||
196
+ (symmetry === 'none' && horizontalAngles.length > 1 && first === 0 && last === 360);
197
+ if (!validSymmetry) throw new Error('Photometry: symmetry does not match horizontal coverage');
198
+ let peak = 0;
199
+ const values = new Float64Array(intensities.length);
200
+ for (let index = 0; index < values.length; index++) {
201
+ const value = intensities[index];
202
+ const scaled = value * intensityScale;
203
+ if (!Number.isFinite(value) || value < 0 || !Number.isFinite(scaled))
204
+ throw new Error('Photometry: invalid calculation intensity');
205
+ values[index] = scaled;
206
+ peak = Math.max(peak, scaled);
207
+ }
208
+ return {
209
+ verticalAngles: Float64Array.from(verticalAngles),
210
+ horizontalAngles: Float64Array.from(horizontalAngles),
211
+ values,
212
+ horizontalSpan,
213
+ peak
214
+ };
215
+ }
216
+
217
+ /** Samples a validated snapshot, returning zero outside its measured vertical extent. */
218
+ function samplePreparedProfile(
219
+ profile: PreparedPhotometricProfile,
220
+ verticalAngle: number,
221
+ horizontalAngle: number
222
+ ): number {
223
+ const {verticalAngles, horizontalAngles, values, horizontalSpan} = profile;
224
+ if (
225
+ verticalAngle < verticalAngles[0] ||
226
+ verticalAngle > verticalAngles[verticalAngles.length - 1]
227
+ )
228
+ return 0;
229
+ const verticalIndex = findLowerAngle(verticalAngles, verticalAngle);
230
+ const verticalWeight =
231
+ (verticalAngle - verticalAngles[verticalIndex]) /
232
+ (verticalAngles[verticalIndex + 1] - verticalAngles[verticalIndex]);
233
+ let horizontalIndex = 0;
234
+ let horizontalWeight = 0;
235
+ if (horizontalSpan > 0) {
236
+ const period = horizontalSpan === 360 ? 360 : horizontalSpan * 2;
237
+ let folded = (((horizontalAngle - horizontalAngles[0]) % period) + period) % period;
238
+ if (folded > horizontalSpan) folded = period - folded;
239
+ const measuredAngle = horizontalAngles[0] + folded;
240
+ horizontalIndex = findLowerAngle(horizontalAngles, measuredAngle);
241
+ horizontalWeight =
242
+ (measuredAngle - horizontalAngles[horizontalIndex]) /
243
+ (horizontalAngles[horizontalIndex + 1] - horizontalAngles[horizontalIndex]);
244
+ }
245
+ const lowerOffset = horizontalIndex * verticalAngles.length + verticalIndex;
246
+ const upperOffset = horizontalSpan === 0 ? lowerOffset : lowerOffset + verticalAngles.length;
247
+ const lowerValue =
248
+ values[lowerOffset] + (values[lowerOffset + 1] - values[lowerOffset]) * verticalWeight;
249
+ const upperValue =
250
+ values[upperOffset] + (values[upperOffset + 1] - values[upperOffset]) * verticalWeight;
251
+ return lowerValue + (upperValue - lowerValue) * horizontalWeight;
252
+ }
253
+
254
+ /** Finds the lower knot, keeping the final coordinate in the last interval. */
255
+ function findLowerAngle(angles: Float64Array, angle: number): number {
256
+ let lower = 0;
257
+ let upper = angles.length - 1;
258
+ while (upper - lower > 1) {
259
+ const midpoint = Math.floor((lower + upper) / 2);
260
+ if (angle < angles[midpoint]) upper = midpoint;
261
+ else lower = midpoint;
262
+ }
263
+ return Math.min(lower, angles.length - 2);
264
+ }