@threenative/core 0.3.3 → 0.3.5

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 (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { createHash } from "node:crypto";
2
3
  import { existsSync } from "node:fs";
3
4
  import { readFile, writeFile } from "node:fs/promises";
4
5
  import { createRequire } from "node:module";
@@ -7,6 +8,7 @@ import { fileURLToPath } from "node:url";
7
8
 
8
9
  const THREE_VERSION = "0.185.1";
9
10
  const PATCH_NAME = `three@${THREE_VERSION}.patch`;
11
+ const UPGRADE_PATCH_NAME = `three@${THREE_VERSION}-prd269-upgrade.patch`;
10
12
 
11
13
  /** Apply the package-owned Three.js patch to the dependency resolved for the consumer. */
12
14
  export async function applyThreePatch(options = {}) {
@@ -29,15 +31,18 @@ export async function applyThreePatch(options = {}) {
29
31
 
30
32
  const patchPath = path.join(packageRoot, "patches", PATCH_NAME);
31
33
  const patch = parsePatch(await readFile(patchPath, "utf8"), patchPath);
32
- const plans = await planPatch(threeRoot, patch);
34
+ const upgradePath = path.join(packageRoot, "patches", UPGRADE_PATCH_NAME);
35
+ const upgrades = existsSync(upgradePath)
36
+ ? parsePatch(await readFile(upgradePath, "utf8"), upgradePath)
37
+ : [];
38
+ const plans = await planPatch(threeRoot, patch, upgrades);
39
+ // `planPatch` refuses any file it does not fully recognise, so every plan that is not already
40
+ // `patched` is safe to write — including the files an older release of this patch already
41
+ // touched, which is the state a project upgrading from the previous `latest` is in.
33
42
  if (plans.every((plan) => plan.status === "patched")) return "unchanged";
34
- if (plans.some((plan) => plan.status !== "stock")) {
35
- throw new Error(
36
- `TN_THREE_PATCH_PARTIAL: ${manifestPath} is neither stock nor fully patched; refusing to modify a partial installation.`,
37
- );
38
- }
39
43
 
40
- for (const plan of plans) await writeFile(plan.file, plan.contents, "utf8");
44
+ for (const plan of plans)
45
+ if (plan.status !== "patched") await writeFile(plan.file, plan.contents, "utf8");
41
46
  return "patched";
42
47
  }
43
48
 
@@ -140,6 +145,12 @@ function parsePatchFiles(text, patchPath) {
140
145
  }
141
146
 
142
147
  function parsePatchLine(line, current, hunk, patchPath) {
148
+ const blobs = /^index ([a-f0-9]{40})\.\.([a-f0-9]{40}) /u.exec(line);
149
+ if (blobs !== null) {
150
+ current.oldBlob = blobs[1];
151
+ current.newBlob = blobs[2];
152
+ return hunk;
153
+ }
143
154
  if (line.startsWith("--- ")) {
144
155
  current.oldPath = patchPathFromHeader(line.slice(4), patchPath);
145
156
  return hunk;
@@ -206,7 +217,7 @@ function patchPathFromHeader(header, patchPath) {
206
217
  return relative;
207
218
  }
208
219
 
209
- async function planPatch(threeRoot, files) {
220
+ async function planPatch(threeRoot, files, upgrades) {
210
221
  const plans = [];
211
222
  for (const file of files) {
212
223
  const target = path.resolve(threeRoot, file.oldPath);
@@ -216,57 +227,128 @@ async function planPatch(threeRoot, files) {
216
227
  );
217
228
  }
218
229
  const original = await readFile(target, "utf8");
219
- const lines = original.replaceAll("\r\n", "\n").split("\n");
220
- const status = classifyFile(lines, file.hunks);
221
- if (status === "patched") {
222
- plans.push({ contents: original, file: target, status });
223
- continue;
224
- }
225
- if (status !== "stock") {
230
+ const recognised = upgradeKnownFile(original, file.oldPath, upgrades);
231
+ const lines = recognised.replaceAll("\r\n", "\n").split("\n");
232
+ const states = classifyFile(lines, file.hunks);
233
+ const unknown = states.findIndex((state) => state === "unknown");
234
+ if (unknown !== -1) {
226
235
  throw new Error(
227
- `TN_THREE_PATCH_PARTIAL: hunk state is mixed in ${target}; refusing to modify a partial installation.`,
236
+ `TN_THREE_PATCH_PARTIAL: hunk ${String(unknown + 1)} of ${file.oldPath} matches neither the stock nor the patched text in ${target}; refusing to modify an installation this package does not recognise.`,
228
237
  );
229
238
  }
230
- plans.push({ contents: applyFile(lines, file.hunks, target).join("\n"), file: target, status });
239
+ const status = states.every((state) => state === "patched")
240
+ ? "patched"
241
+ : states.some((state) => state === "patched")
242
+ ? "extended"
243
+ : "stock";
244
+ assertKnownExtension(status, recognised === original, file.oldPath, upgrades);
245
+ if (status === "patched") {
246
+ plans.push({
247
+ contents: recognised,
248
+ file: target,
249
+ status: recognised === original ? status : "extended",
250
+ });
251
+ continue;
252
+ }
253
+ plans.push({
254
+ contents: applyFile(lines, file.hunks, states, target).join("\n"),
255
+ file: target,
256
+ status,
257
+ });
231
258
  }
232
259
  return plans;
233
260
  }
234
261
 
262
+ /** Registered migration files must not fall through to permissive hunk-only upgrades. */
263
+ function assertKnownExtension(status, unchanged, file, upgrades) {
264
+ if (
265
+ status === "extended" &&
266
+ unchanged &&
267
+ upgrades.some((candidate) => candidate.oldPath === file)
268
+ ) {
269
+ throw new Error(
270
+ `TN_THREE_PATCH_PARTIAL: ${file} is partly patched but does not match an exact supported predecessor; refusing an unrecognised installation.`,
271
+ );
272
+ }
273
+ }
274
+
275
+ /** Upgrade only exact known prior blobs; a custom edit never enters this migration. */
276
+ function upgradeKnownFile(original, file, upgrades, seen = new Set()) {
277
+ const normalized = original.replaceAll("\r\n", "\n");
278
+ const upgrade = upgrades.find(
279
+ (candidate) => candidate.oldPath === file && candidate.oldBlob === blobHash(normalized),
280
+ );
281
+ if (upgrade === undefined) return original;
282
+ if (seen.has(upgrade.oldBlob))
283
+ throw new Error(`TN_THREE_PATCH_INVALID: cyclic known upgrade for ${file}.`);
284
+ seen.add(upgrade.oldBlob);
285
+ const lines = normalized.split("\n");
286
+ const states = classifyFile(lines, upgrade.hunks);
287
+ if (states.some((state) => state !== "stock"))
288
+ throw new Error(`TN_THREE_PATCH_INVALID: known upgrade hunks do not match ${file}.`);
289
+ const contents = applyFile(lines, upgrade.hunks, states, file).join("\n");
290
+ if (blobHash(contents) !== upgrade.newBlob)
291
+ throw new Error(`TN_THREE_PATCH_INVALID: known upgrade output does not match ${file}.`);
292
+ return upgradeKnownFile(contents, file, upgrades, seen);
293
+ }
294
+
295
+ function blobHash(contents) {
296
+ return createHash("sha1")
297
+ .update(`blob ${Buffer.byteLength(contents)}\0`)
298
+ .update(contents)
299
+ .digest("hex");
300
+ }
301
+
302
+ /**
303
+ * Every hunk's state in this file, in patch order: `"stock"`, `"patched"` or `"unknown"`.
304
+ *
305
+ * Per hunk rather than per file, because an upgrade lands on a file an *older release of this same
306
+ * package's patch* already modified. The consumer declares the patch in its own manifest, so the
307
+ * package manager applies it at install time — meaning a project scaffolded from the previous
308
+ * `latest` carries the previous patch's text, and only this release's new hunks are still stock.
309
+ * Both states are repairable by applying the stock remainder, and the old hunks are not re-derived
310
+ * from a different patch: they are this patch's own hunks, already at their patched text.
311
+ *
312
+ * A hunk in neither state is a file this package does not recognise — hand-edited, or owned by a
313
+ * different patch — and stays the refusal it always was.
314
+ */
235
315
  function classifyFile(lines, hunks) {
236
- let stock = true;
237
- let patched = true;
316
+ const states = [];
238
317
  let offset = 0;
239
318
  for (const hunk of hunks) {
240
- const oldLines = hunk.lines
241
- .filter((line) => line[0] === " " || line[0] === "-")
242
- .map((line) => line.slice(1));
243
- const newLines = hunk.lines
244
- .filter((line) => line[0] === " " || line[0] === "+")
245
- .map((line) => line.slice(1));
246
- if (locate(lines, oldLines, hunk.oldStart - 1 + offset) === undefined) stock = false;
247
- if (locate(lines, newLines, hunk.newStart - 1) === undefined) patched = false;
319
+ const oldLines = hunkLines(hunk, "old");
320
+ const newLines = hunkLines(hunk, "new");
321
+ if (locate(lines, newLines, hunk.newStart - 1) !== undefined) states.push("patched");
322
+ else if (locate(lines, oldLines, hunk.oldStart - 1 + offset) !== undefined)
323
+ states.push("stock");
324
+ else states.push("unknown");
248
325
  offset += newLines.length - oldLines.length;
249
326
  }
250
- if (stock) return "stock";
251
- if (patched) return "patched";
252
- return "mixed";
327
+ return states;
253
328
  }
254
329
 
255
- function applyFile(lines, hunks, file) {
330
+ function hunkLines(hunk, side) {
331
+ return hunk.lines
332
+ .filter((line) =>
333
+ side === "old" ? line[0] === " " || line[0] === "-" : line[0] === " " || line[0] === "+",
334
+ )
335
+ .map((line) => line.slice(1));
336
+ }
337
+
338
+ function applyFile(lines, hunks, states, file) {
256
339
  const result = [...lines];
257
340
  let offset = 0;
258
- for (const hunk of hunks) {
259
- const oldLines = hunk.lines
260
- .filter((line) => line[0] === " " || line[0] === "-")
261
- .map((line) => line.slice(1));
262
- const newLines = hunk.lines
263
- .filter((line) => line[0] === " " || line[0] === "+")
264
- .map((line) => line.slice(1));
341
+ for (const [number, hunk] of hunks.entries()) {
342
+ const oldLines = hunkLines(hunk, "old");
343
+ const newLines = hunkLines(hunk, "new");
265
344
  const index = locate(result, oldLines, hunk.oldStart - 1 + offset);
266
- if (index === undefined) {
267
- throw new Error(`TN_THREE_PATCH_INVALID: stock hunk no longer matches ${file}.`);
345
+ if (states[number] === "stock") {
346
+ if (index === undefined)
347
+ throw new Error(`TN_THREE_PATCH_INVALID: stock hunk no longer matches ${file}.`);
348
+ result.splice(index, oldLines.length, ...newLines);
268
349
  }
269
- result.splice(index, oldLines.length, ...newLines);
350
+ // Already-patched hunks are left alone. Their line-count change is already in the file, so
351
+ // the offset still moves to keep later stock hunks near their expected location.
270
352
  offset += newLines.length - oldLines.length;
271
353
  }
272
354
  return result;
@@ -0,0 +1,264 @@
1
+ /*!
2
+ * Selectively adapted from GGEZ packages/anim-runtime/src/runtime/helpers.ts
3
+ * (findBlend1DChildren, computeTriangleBarycentricWeights, findBlend2DEdgeWeights)
4
+ * at 45ed541cb163ef98694467758f60d5533373ac60. Replaced graph children with
5
+ * validated fixed sample indices, initialization-only sorting and reusable output.
6
+ * MIT License
7
+ * Copyright (c) 2026 @alightinastorm (x.com/alightinastorm)
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ * The above copyright notice and this permission notice shall be included in all
15
+ * copies or substantial portions of the Software.
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ interface IBlendThreshold {
26
+ readonly value: number;
27
+ readonly index: number;
28
+ }
29
+
30
+ type Point = readonly [number, number];
31
+ type Triangle = readonly [number, number, number];
32
+ const EPSILON = 1e-10;
33
+
34
+ export function animationFinite(value: number, name: string): number {
35
+ if (!Number.isFinite(value)) throw new Error(`AnimationComposer: ${name} must be finite.`);
36
+ return value;
37
+ }
38
+
39
+ export class BlendSpace1D {
40
+ readonly weights: Float64Array;
41
+ readonly #samples: readonly IBlendThreshold[];
42
+
43
+ constructor(thresholds: readonly number[]) {
44
+ if (thresholds.length === 0) throw new Error("BlendSpace1D requires samples.");
45
+ this.#samples = thresholds
46
+ .map((value, index) => ({ value: animationFinite(value, `threshold[${index}]`), index }))
47
+ .sort((a, b) => a.value - b.value);
48
+ for (let i = 1; i < this.#samples.length; i += 1) {
49
+ const distance =
50
+ (this.#samples[i] as IBlendThreshold).value -
51
+ (this.#samples[i - 1] as IBlendThreshold).value;
52
+ if (distance === 0) throw new Error("BlendSpace1D: duplicate threshold.");
53
+ animationFinite(distance, "threshold interval");
54
+ }
55
+ this.weights = new Float64Array(thresholds.length);
56
+ }
57
+
58
+ sample(value: number): Float64Array {
59
+ animationFinite(value, "1D query");
60
+ const weights = this.weights;
61
+ weights.fill(0);
62
+ const first = this.#samples[0] as IBlendThreshold;
63
+ const last = this.#samples[this.#samples.length - 1] as IBlendThreshold;
64
+ if (value <= first.value) weights[first.index] = 1;
65
+ else if (value >= last.value) weights[last.index] = 1;
66
+ else {
67
+ for (let i = 1; i < this.#samples.length; i += 1) {
68
+ const b = this.#samples[i] as IBlendThreshold;
69
+ if (value > b.value) continue;
70
+ const a = this.#samples[i - 1] as IBlendThreshold;
71
+ const t = (value - a.value) / (b.value - a.value);
72
+ weights[a.index] = 1 - t;
73
+ weights[b.index] = t;
74
+ break;
75
+ }
76
+ }
77
+ return weights;
78
+ }
79
+ }
80
+
81
+ function cross(a: Point, b: Point, c: Point): number {
82
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
83
+ }
84
+
85
+ function hull(points: readonly Point[]): number[] {
86
+ const sorted = points
87
+ .map((_, i) => i)
88
+ .sort(
89
+ (a, b) =>
90
+ (points[a] as Point)[0] - (points[b] as Point)[0] ||
91
+ (points[a] as Point)[1] - (points[b] as Point)[1],
92
+ );
93
+ const half = (indices: number[]) => {
94
+ const result: number[] = [];
95
+ for (const i of indices) {
96
+ while (
97
+ result.length > 1 &&
98
+ cross(
99
+ points[result[result.length - 2] as number] as Point,
100
+ points[result[result.length - 1] as number] as Point,
101
+ points[i] as Point,
102
+ ) <= 0
103
+ )
104
+ result.pop();
105
+ result.push(i);
106
+ }
107
+ return result.slice(0, -1);
108
+ };
109
+ return [...half(sorted), ...half([...sorted].reverse())];
110
+ }
111
+
112
+ /** Fixed complete convex-hull triangulation. Collinear triangles and overlapping tiles fail at load. */
113
+ export class BlendSpace2D {
114
+ readonly weights: Float64Array;
115
+ readonly #points: readonly Point[];
116
+ readonly #triangles: readonly Triangle[];
117
+ readonly #hull: readonly number[];
118
+ readonly #boundary: readonly (readonly [number, number])[];
119
+
120
+ constructor(points: readonly Point[], triangles: readonly Triangle[]) {
121
+ if (points.length < 3 || triangles.length === 0)
122
+ throw new Error("BlendSpace2D requires a triangulation of at least three samples.");
123
+ this.#points = points.map((p, i) => {
124
+ if (p.length !== 2) throw new Error(`BlendSpace2D: sample[${i}] must have two coordinates.`);
125
+ return [animationFinite(p[0], `sample[${i}].x`), animationFinite(p[1], `sample[${i}].y`)];
126
+ });
127
+ for (let a = 0; a < points.length; a += 1)
128
+ for (let b = a + 1; b < points.length; b += 1)
129
+ if (
130
+ (points[a] as Point)[0] === (points[b] as Point)[0] &&
131
+ (points[a] as Point)[1] === (points[b] as Point)[1]
132
+ )
133
+ throw new Error("BlendSpace2D: duplicate sample.");
134
+ this.#hull = hull(this.#points);
135
+ this.weights = new Float64Array(points.length);
136
+ const used = new Set<number>();
137
+ const seen = new Set<string>();
138
+ const edges = new Map<string, { a: number; b: number; count: number }>();
139
+ let area = 0;
140
+ this.#triangles = triangles.map((triangle) => {
141
+ if (
142
+ triangle.length !== 3 ||
143
+ triangle.some((i) => !Number.isInteger(i) || i < 0 || i >= points.length)
144
+ )
145
+ throw new Error("BlendSpace2D: invalid triangle index.");
146
+ const key = [...triangle].sort((a, b) => a - b).join(",");
147
+ if (seen.has(key)) throw new Error("BlendSpace2D: duplicate triangle.");
148
+ seen.add(key);
149
+ let [a, b, c] = triangle;
150
+ const signed = animationFinite(
151
+ cross(points[a] as Point, points[b] as Point, points[c] as Point),
152
+ "triangle area",
153
+ );
154
+ if (signed === 0) throw new Error("BlendSpace2D: collinear triangle.");
155
+ if (signed < 0) [b, c] = [c, b];
156
+ area += Math.abs(signed);
157
+ for (const index of triangle) used.add(index);
158
+ for (const [u, v] of [
159
+ [a, b],
160
+ [b, c],
161
+ [c, a],
162
+ ]) {
163
+ const key = [u, v].sort((a, b) => (a as number) - (b as number)).join(",");
164
+ const edge = edges.get(key);
165
+ if (edge !== undefined) {
166
+ if (edge.count !== 1 || edge.a !== v)
167
+ throw new Error("BlendSpace2D: overlapping/nonmanifold triangulation.");
168
+ edge.count += 1;
169
+ } else edges.set(key, { a: u as number, b: v as number, count: 1 });
170
+ }
171
+ return [a, b, c];
172
+ });
173
+ if (used.size !== points.length) throw new Error("BlendSpace2D: unused sample.");
174
+ const origin = points[this.#hull[0] as number] as Point;
175
+ let hullArea = 0;
176
+ for (let i = 1; i + 1 < this.#hull.length; i += 1)
177
+ hullArea += cross(
178
+ origin,
179
+ points[this.#hull[i] as number] as Point,
180
+ points[this.#hull[i + 1] as number] as Point,
181
+ );
182
+ if (!Number.isFinite(area) || Math.abs(area - hullArea) > EPSILON * hullArea)
183
+ throw new Error("BlendSpace2D: triangulation must cover the convex hull exactly.");
184
+ for (const edge of edges.values()) {
185
+ if (edge.count !== 1) continue;
186
+ const onHull = this.#hull.some((a, i) => {
187
+ const b = this.#hull[(i + 1) % this.#hull.length] as number;
188
+ return (
189
+ cross(points[a] as Point, points[b] as Point, points[edge.a] as Point) === 0 &&
190
+ cross(points[a] as Point, points[b] as Point, points[edge.b] as Point) === 0
191
+ );
192
+ });
193
+ if (!onHull) throw new Error("BlendSpace2D: triangulation has an interior boundary.");
194
+ }
195
+ this.#boundary = [...edges.values()]
196
+ .filter((edge) => edge.count === 1)
197
+ .map((edge) => [edge.a, edge.b]);
198
+ for (let i = 0; i < this.#triangles.length; i += 1) {
199
+ const a = this.#triangles[i] as Triangle;
200
+ for (let j = i + 1; j < this.#triangles.length; j += 1) {
201
+ const b = this.#triangles[j] as Triangle;
202
+ for (let u = 0; u < 3; u += 1)
203
+ for (let v = 0; v < 3; v += 1) {
204
+ const p = points[a[u] as number] as Point;
205
+ const q = points[a[(u + 1) % 3] as number] as Point;
206
+ const r = points[b[v] as number] as Point;
207
+ const s = points[b[(v + 1) % 3] as number] as Point;
208
+ if (cross(p, q, r) * cross(p, q, s) < 0 && cross(r, s, p) * cross(r, s, q) < 0)
209
+ throw new Error("BlendSpace2D: crossing triangle edges.");
210
+ }
211
+ }
212
+ }
213
+ }
214
+
215
+ sample(x: number, y: number): Float64Array {
216
+ animationFinite(x, "2D query.x");
217
+ animationFinite(y, "2D query.y");
218
+ this.weights.fill(0);
219
+ for (const [a, b, c] of this.#triangles) {
220
+ const p = this.#points[a] as Point;
221
+ const q = this.#points[b] as Point;
222
+ const r = this.#points[c] as Point;
223
+ const denominator = cross(p, q, r);
224
+ const wa = ((q[1] - r[1]) * (x - r[0]) + (r[0] - q[0]) * (y - r[1])) / denominator;
225
+ const wb = ((r[1] - p[1]) * (x - r[0]) + (p[0] - r[0]) * (y - r[1])) / denominator;
226
+ const wc = 1 - wa - wb;
227
+ if (Math.min(wa, wb, wc) < -EPSILON) continue;
228
+ animationFinite(wa + wb + wc, "barycentric query");
229
+ this.weights[a] = Math.max(0, wa);
230
+ this.weights[b] = Math.max(0, wb);
231
+ this.weights[c] = Math.max(0, wc);
232
+ const sum =
233
+ (this.weights[a] as number) + (this.weights[b] as number) + (this.weights[c] as number);
234
+ this.weights[a] = (this.weights[a] as number) / sum;
235
+ this.weights[b] = (this.weights[b] as number) / sum;
236
+ this.weights[c] = (this.weights[c] as number) / sum;
237
+ return this.weights;
238
+ }
239
+ let best = Number.POSITIVE_INFINITY;
240
+ let bestA = 0;
241
+ let bestB = 0;
242
+ let bestT = 0;
243
+ for (const [a, b] of this.#boundary) {
244
+ const p = this.#points[a] as Point;
245
+ const q = this.#points[b] as Point;
246
+ const dx = q[0] - p[0];
247
+ const dy = q[1] - p[1];
248
+ const t = Math.max(0, Math.min(1, ((x - p[0]) * dx + (y - p[1]) * dy) / (dx * dx + dy * dy)));
249
+ const distance = animationFinite(
250
+ (x - p[0] - dx * t) ** 2 + (y - p[1] - dy * t) ** 2,
251
+ "hull projection",
252
+ );
253
+ if (distance < best) {
254
+ best = distance;
255
+ bestA = a;
256
+ bestB = b;
257
+ bestT = t;
258
+ }
259
+ }
260
+ this.weights[bestA] = 1 - bestT;
261
+ this.weights[bestB] = bestT;
262
+ return this.weights;
263
+ }
264
+ }