@needle-tools/three-mesh-effects 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 - 2026-10-21
4
+
5
+ - Register `useLoader(loader, renderer)` once to load any combination of Needle glTF runtime extensions without inspecting an asset beforehand. Extension handlers load dynamically as needed.
6
+ - Opt out of specific extensions with the typed `{ disable: [extensionName] }` option. Optional extensions retain their portable fallback; disabled required extensions report an error.
7
+ - Automatically restore saved hull effects and settings from the versioned `NEEDLE_hull_effect` extension. Hull effects work without an original model and can follow their own skin animation.
8
+ - Use `bindHull(hull, original)` to attach an original model and animation syncing later, or pass `null` to detach it. Existing manual registration functions and `createHullEffect` remain supported.
package/README.md CHANGED
@@ -1,11 +1,43 @@
1
1
  Three.js loaders and TSL materials for GLBs exported by [Needle Mesh Baker](https://mesh-baker.needle.tools).
2
2
 
3
- ## Features
3
+ ## Automatic glTF loading
4
4
 
5
- - **Hull effects:** Render effects using an exported hull and its source model.
6
- - **Octahedral impostors:** Load exported glTF extensions with a Three.js TSL material.
7
- - **Deformation rigs:** Run IK and secondary motion alongside standard animation clips.
8
- - **Pixel and voxel impostors:** Create the display mode selected in the workbench.
5
+ Register once, then load any Mesh Baker glTF without knowing its extensions:
6
+
7
+ ```js
8
+ import { useLoader } from '@needle-tools/three-mesh-effects';
9
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
10
+
11
+ const loader = useLoader(new GLTFLoader(), renderer);
12
+ const { scene: model } = await loader.loadAsync('/model.glb');
13
+ scene.add(model);
14
+ ```
15
+
16
+ This handles hull effects, deformation rigs, octahedral impostors, and pixel impostor atlas
17
+ bindings, including assets combining extensions. It also works with `load`,
18
+ `parse`, and `parseAsync`. Each handler is dynamically imported only for assets
19
+ declaring that extension; bundlers can keep those imports in separate chunks.
20
+ Dynamic imports defer downloads, rather than removing handlers that an asset
21
+ might need. The existing individual registration functions remain available.
22
+
23
+ All extensions are enabled by default. To opt out of specific handlers, pass
24
+ their glTF extension names in the optional third argument:
25
+
26
+ ```js
27
+ useLoader(loader, renderer, { disable: ['NEEDLE_mesh_impostor'] });
28
+ ```
29
+
30
+ Supported keys are `NEEDLE_hull_effect`, `NEEDLE_mesh_impostor`, `NEEDLE_pixel_impostor`, and
31
+ `NEEDLE_deformation_rig`. Disabled optional extensions keep their portable
32
+ fallback without importing the handler. A disabled extension listed in the
33
+ asset's `extensionsRequired` rejects the load with an error. Calling `useLoader`
34
+ again replaces the renderer and disable list for subsequent parses; omitting
35
+ options enables everything again.
36
+
37
+ Configure Draco, Meshopt and KTX2 decoders on the loader as usual when needed.
38
+ Rig animation still needs a per-frame update, pixel display modes remain available
39
+ through `createPixelImpostorDisplay`. Hull effects load alone; optionally use
40
+ `bindHull` to add an original model and animation syncing.
9
41
 
10
42
  ## Install
11
43
 
@@ -14,14 +46,49 @@ npm install @needle-tools/three-mesh-effects three
14
46
  ```
15
47
 
16
48
  The package supports Three.js r185 and r186. Its Needle Engine adapter is an
17
- optional import. The examples below use ordinary Three.js and assume an existing
49
+ optional import. The examples use ordinary Three.js and assume an existing
18
50
  `renderer`, `scene`, and `camera`.
19
51
 
52
+ ## Features
53
+
54
+ - **Hull effects:** Restore the saved effect automatically, optionally binding its source model.
55
+ - **Octahedral impostors:** Load exported glTF extensions with a Three.js TSL material.
56
+ - **Deformation rigs:** Run IK and secondary motion alongside standard animation clips.
57
+ - **Pixel and voxel impostors:** Create the display mode selected in the workbench.
58
+
20
59
  ## Hull effects
21
60
 
22
- Hull effects need two models: the hull GLB exported by Mesh Baker, and the
23
- original source model you uploaded. The hull supplies the effect's surface;
24
- the source remains visible inside it and supplies its appearance and animation.
61
+ When exporting with a hull effect selected, Mesh Baker saves its mode and
62
+ settings in `NEEDLE_hull_effect`. `useLoader` restores it without a second model:
63
+
64
+ ```js
65
+ import { useLoader } from '@needle-tools/three-mesh-effects';
66
+ import { bindHull, getHullEffect } from '@needle-tools/three-mesh-effects/hull-effects';
67
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
68
+
69
+ const loader = useLoader(new GLTFLoader(), renderer);
70
+ const { scene: hull } = await loader.loadAsync('/hull.glb');
71
+ scene.add(hull);
72
+ let effect = getHullEffect(hull);
73
+
74
+ // Optional: show the original inside the hull and follow its animation.
75
+ const { scene: original } = await loader.loadAsync('/original.glb');
76
+ effect = bindHull(hull, original, { animate: true });
77
+ // Each frame: advance your AnimationMixers, then effect.syncAnimation().
78
+ // Call effect.dispose() before removing the hull.
79
+ ```
80
+
81
+ `bindHull` replaces the automatically created effect, preserving its settings.
82
+ It borrows the original and leaves the caller's hierarchy and resources intact.
83
+ Get the current effect again after rebinding; old bindings no longer control it.
84
+ `bindHull(hull, null)` detaches the original and restores the standalone effect.
85
+ `getHullEffect(hull)` returns `undefined` for an ordinary or disposed hull.
86
+ Standalone animated hulls can follow their own animation; call `syncAnimation()`
87
+ after updating their mixers or deformation rig. TSL effects require
88
+ `WebGPURenderer` from `three/webgpu`, using either its WebGPU or WebGL2 backend.
89
+
90
+ The existing manual API remains available for models without the extension.
91
+ Here the hull supplies the effect's surface and the original stays visible inside:
25
92
  Available modes and their defaults are in `HULL_EFFECT_MODES` and
26
93
  `createHullEffectValues()`:
27
94
 
@@ -42,6 +109,22 @@ const effect = createHullEffect(hull, original, createHullEffectValues().flames)
42
109
  // Call effect.dispose() at teardown.
43
110
  ```
44
111
 
112
+ ### Hull extension contract
113
+
114
+ `NEEDLE_hull_effect` version 1 is stored on the glTF scene containing the hull:
115
+
116
+ ```json
117
+ { "version": 1, "mode": "flames", "values": { "height": 0.51, "speed": 1 } }
118
+ ```
119
+
120
+ The name appears in `extensionsUsed`. Exported hull geometry and standard
121
+ materials remain a portable fallback, so it is not marked required. `mode` must
122
+ be a supported `HULL_EFFECT_MODES` value; omitted controls use their documented
123
+ defaults, finite numeric values are clamped to their control ranges. Unknown
124
+ versions, unknown modes, and non-finite or non-numeric control values fail
125
+ explicitly. The extension stores no source URL and triggers no source download.
126
+ Each scene with the extension gets its own runtime; dispose each when unloading.
127
+
45
128
  ## Octahedral impostors
46
129
 
47
130
  An 800,000-triangle source represented by a two-triangle impostor:
@@ -5109,7 +5109,7 @@ function createHullEffect(asset, original, effect, options = {}) {
5109
5109
  const hazeNoiseEnabled = mode === "heat-haze" && values.strength > 0;
5110
5110
  const shroudCurlEnabled = mode === "shroud" && values.amplitude > 0;
5111
5111
  asset.updateWorldMatrix(true, true);
5112
- original.updateWorldMatrix(true, true);
5112
+ original?.updateWorldMatrix(true, true);
5113
5113
  const inverse = asset.matrixWorld.clone().invert();
5114
5114
  const shells = [];
5115
5115
  asset.traverse((object) => {
@@ -5127,12 +5127,14 @@ function createHullEffect(asset, original, effect, options = {}) {
5127
5127
  const center = uniform2(bounds.getCenter(new THREE3.Vector3()));
5128
5128
  const size = Math.max(bounds.getSize(new THREE3.Vector3()).length(), 1e-5);
5129
5129
  const normalized = positionLocal.sub(center).div(size);
5130
- const sourceCopy = cloneSkeleton(original);
5131
- sourceCopy.name = "Original inside wrap";
5132
- if (mode === "control") sourceCopy.visible = false;
5133
- sourceCopy.matrix.copy(inverse.clone().multiply(original.matrixWorld));
5130
+ const animationSource = original ?? asset;
5131
+ const sourceCopy = cloneSkeleton(animationSource);
5132
+ sourceCopy.name = original ? "Original inside wrap" : "Hull animation driver";
5133
+ if (!original || mode === "control") sourceCopy.visible = false;
5134
+ if (original) sourceCopy.matrix.copy(inverse.clone().multiply(original.matrixWorld));
5135
+ else sourceCopy.matrix.identity();
5134
5136
  sourceCopy.matrixAutoUpdate = false;
5135
- const skin = createWrapSkin(original, sourceCopy, asset, options.animate);
5137
+ const skin = createWrapSkin(animationSource, sourceCopy, asset, options.animate);
5136
5138
  const helpers = [];
5137
5139
  sourceCopy.traverse((object) => {
5138
5140
  if (object.userData.previewWireframeOverlay || object.userData.previewGaussianSplat || object.userData.wrapPreview) helpers.push(object);
@@ -5149,7 +5151,7 @@ function createHullEffect(asset, original, effect, options = {}) {
5149
5151
  };
5150
5152
  object.material = Array.isArray(object.material) ? object.material.map(cloneMaterial) : cloneMaterial(object.material);
5151
5153
  });
5152
- group.add(sourceCopy);
5154
+ if (original || skin) group.add(sourceCopy);
5153
5155
  const clock = time.mul(uniforms.speed ?? 1);
5154
5156
  const curl = (p) => {
5155
5157
  const q = p.sub(center).div(size).mul(mode === "force-field" || mode === "shroud" ? uniforms.detail : 4).add(vec32(0, clock.mul(0.3), clock.mul(0.2)));
@@ -5627,16 +5629,116 @@ function createHullEffect(asset, original, effect, options = {}) {
5627
5629
  }
5628
5630
  };
5629
5631
  }
5632
+
5633
+ // src/rendering/hull-effect-metadata.js
5634
+ var NEEDLE_HULL_EFFECT = "NEEDLE_hull_effect";
5635
+ function parseHullEffectDescriptor(raw) {
5636
+ if (!raw || typeof raw !== "object") throw new Error("Invalid NEEDLE_hull_effect descriptor.");
5637
+ const record = (
5638
+ /** @type {Record<string, unknown>} */
5639
+ raw
5640
+ );
5641
+ if (record.version !== 1) throw new Error("Unsupported NEEDLE_hull_effect version.");
5642
+ if (typeof record.mode !== "string" || !Object.hasOwn(HULL_EFFECT_CONTROLS, record.mode)) throw new Error("Unknown NEEDLE_hull_effect mode.");
5643
+ if (!record.values || typeof record.values !== "object" || Array.isArray(record.values)) throw new Error("Invalid NEEDLE_hull_effect values.");
5644
+ const input = (
5645
+ /** @type {Record<string, unknown>} */
5646
+ record.values
5647
+ );
5648
+ const values = {};
5649
+ for (const control of HULL_EFFECT_CONTROLS[record.mode]) {
5650
+ const value = Object.hasOwn(input, control.key) ? input[control.key] : control.value;
5651
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`Invalid NEEDLE_hull_effect value: ${control.key}.`);
5652
+ values[control.key] = Math.max(control.min, Math.min(control.max, value));
5653
+ }
5654
+ return { version: 1, mode: record.mode, values };
5655
+ }
5656
+
5657
+ // src/rendering/hull-effect-runtime.js
5658
+ var hulls = /* @__PURE__ */ new WeakMap();
5659
+ function getHullEffect(hull) {
5660
+ return hulls.get(hull)?.effect;
5661
+ }
5662
+ function bindHull(hull, original, options = {}) {
5663
+ const state = hulls.get(hull);
5664
+ if (!state || state.disposed) throw new Error("Load this hull with useLoader before calling bindHull.");
5665
+ if (original && (original === hull || isAncestor(hull, original) || isAncestor(original, hull))) throw new Error("Hull and original must have separate hierarchies.");
5666
+ state.effect.dispose();
5667
+ const effect = createHullEffect(hull, original, { ...state.descriptor.values, mode: state.descriptor.mode }, options);
5668
+ state.effect = manageEffect(hull, state, effect);
5669
+ state.disposed = false;
5670
+ hulls.set(hull, state);
5671
+ return state.effect;
5672
+ }
5673
+ function isAncestor(ancestor, object) {
5674
+ for (let parent = object.parent; parent; parent = parent.parent) if (parent === ancestor) return true;
5675
+ return false;
5676
+ }
5677
+ function manageEffect(hull, state, effect) {
5678
+ const update = effect.update.bind(effect), dispose = effect.dispose.bind(effect);
5679
+ let disposed = false;
5680
+ effect.update = (next) => {
5681
+ if (disposed || !update(next)) return false;
5682
+ state.descriptor = parseHullEffectDescriptor({ ...state.descriptor, values: next });
5683
+ return true;
5684
+ };
5685
+ effect.dispose = () => {
5686
+ if (disposed) return;
5687
+ disposed = true;
5688
+ dispose();
5689
+ if (state.effect === effect) {
5690
+ state.disposed = true;
5691
+ hulls.delete(hull);
5692
+ }
5693
+ };
5694
+ return effect;
5695
+ }
5696
+ var NeedleHullEffectLoaderPlugin = class {
5697
+ name = NEEDLE_HULL_EFFECT;
5698
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTFParser} parser */
5699
+ constructor(parser) {
5700
+ this.parser = parser;
5701
+ }
5702
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
5703
+ async afterRoot(result) {
5704
+ const json = (
5705
+ /** @type {{scenes?: {extensions?: Record<string, unknown>}[]}} */
5706
+ this.parser.json
5707
+ );
5708
+ const pending = result.scenes.flatMap((scene, index) => {
5709
+ const raw = json.scenes?.[index]?.extensions?.[this.name];
5710
+ return raw === void 0 ? [] : [{ scene, descriptor: parseHullEffectDescriptor(raw) }];
5711
+ });
5712
+ const created = [];
5713
+ try {
5714
+ for (const { scene, descriptor } of pending) {
5715
+ const effect = createHullEffect(scene, null, { ...descriptor.values, mode: descriptor.mode }, { animate: result.animations.length ? true : void 0 });
5716
+ const state = { descriptor, effect, disposed: false };
5717
+ state.effect = manageEffect(scene, state, effect);
5718
+ hulls.set(scene, state);
5719
+ created.push(state.effect);
5720
+ }
5721
+ } catch (error) {
5722
+ for (const effect of created) effect.dispose();
5723
+ throw error;
5724
+ }
5725
+ }
5726
+ };
5630
5727
  export {
5631
5728
  HULL_EFFECT_CONTROLS,
5632
5729
  HULL_EFFECT_MODES,
5730
+ NEEDLE_HULL_EFFECT,
5731
+ NeedleHullEffectLoaderPlugin,
5633
5732
  applyPreviewWireframeBlendMode,
5733
+ bindHull,
5634
5734
  captureWrapSkinPose,
5635
5735
  createBarycentricWireframeGeometry,
5636
5736
  createHullEffect,
5637
5737
  createHullEffectValues,
5638
5738
  createPreviewWireframeMaterial,
5739
+ getHullEffect,
5639
5740
  isWrapTopology,
5741
+ parseHullEffectDescriptor,
5640
5742
  parseWireframeBlendMode,
5641
5743
  prepareAuraGeometry,
5642
5744
  prepareIceNormalAttributes,