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

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,12 @@
1
+ # Changelog
2
+
3
+ ## 0.2.1 - 2026-10-21
4
+
5
+ - Put installation and features before the Quick start, and clarify that consumers configure compression decoders themselves when needed.
6
+
7
+ ## 0.2.0 - 2026-10-21
8
+
9
+ - 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.
10
+ - Opt out of specific extensions with the typed `{ disable: [extensionName] }` option. Optional extensions retain their portable fallback; disabled required extensions report an error.
11
+ - 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.
12
+ - 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,27 +1,96 @@
1
1
  Three.js loaders and TSL materials for GLBs exported by [Needle Mesh Baker](https://mesh-baker.needle.tools).
2
2
 
3
+ ## Install
4
+
5
+ ```sh
6
+ npm install @needle-tools/three-mesh-effects three
7
+ ```
8
+
9
+ The package supports Three.js r185 and r186. Its Needle Engine adapter is an
10
+ optional import. The examples use ordinary Three.js and assume an existing
11
+ `renderer`, `scene`, and `camera`.
12
+
3
13
  ## Features
4
14
 
5
- - **Hull effects:** Render effects using an exported hull and its source model.
15
+ - **Hull effects:** Restore the saved effect automatically, optionally binding its source model.
6
16
  - **Octahedral impostors:** Load exported glTF extensions with a Three.js TSL material.
7
17
  - **Deformation rigs:** Run IK and secondary motion alongside standard animation clips.
8
18
  - **Pixel and voxel impostors:** Create the display mode selected in the workbench.
9
19
 
10
- ## Install
20
+ ## Quick start
11
21
 
12
- ```sh
13
- npm install @needle-tools/three-mesh-effects three
22
+ Register once, then load any Mesh Baker glTF without knowing its extensions:
23
+
24
+ ```js
25
+ import { useLoader } from '@needle-tools/three-mesh-effects';
26
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
27
+
28
+ const loader = useLoader(new GLTFLoader(), renderer);
29
+ const { scene: model } = await loader.loadAsync('/model.glb');
30
+ scene.add(model);
14
31
  ```
15
32
 
16
- 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
18
- `renderer`, `scene`, and `camera`.
33
+ This handles hull effects, deformation rigs, octahedral impostors, and pixel impostor atlas
34
+ bindings, including assets combining extensions. It also works with `load`,
35
+ `parse`, and `parseAsync`. Each handler is dynamically imported only for assets
36
+ declaring that extension; bundlers can keep those imports in separate chunks.
37
+ Dynamic imports defer downloads, rather than removing handlers that an asset
38
+ might need. The existing individual registration functions remain available.
39
+
40
+ All extensions are enabled by default. To opt out of specific handlers, pass
41
+ their glTF extension names in the optional third argument:
42
+
43
+ ```js
44
+ useLoader(loader, renderer, { disable: ['NEEDLE_mesh_impostor'] });
45
+ ```
46
+
47
+ Supported keys are `NEEDLE_hull_effect`, `NEEDLE_mesh_impostor`, `NEEDLE_pixel_impostor`, and
48
+ `NEEDLE_deformation_rig`. Disabled optional extensions keep their portable
49
+ fallback without importing the handler. A disabled extension listed in the
50
+ asset's `extensionsRequired` rejects the load with an error. Calling `useLoader`
51
+ again replaces the renderer and disable list for subsequent parses; omitting
52
+ options enables everything again.
53
+
54
+ If a model uses Draco, Meshopt, or KTX2 compression, you must configure the
55
+ corresponding decoder or texture loader on your `GLTFLoader` yourself.
56
+ `useLoader` handles Needle extensions; it does not configure compression decoders.
57
+ Rig animation still needs a per-frame update, pixel display modes remain available
58
+ through `createPixelImpostorDisplay`. Hull effects load alone; optionally use
59
+ `bindHull` to add an original model and animation syncing.
19
60
 
20
61
  ## Hull effects
21
62
 
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.
63
+ When exporting with a hull effect selected, Mesh Baker saves its mode and
64
+ settings in `NEEDLE_hull_effect`. `useLoader` restores it without a second model:
65
+
66
+ ```js
67
+ import { useLoader } from '@needle-tools/three-mesh-effects';
68
+ import { bindHull, getHullEffect } from '@needle-tools/three-mesh-effects/hull-effects';
69
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
70
+
71
+ const loader = useLoader(new GLTFLoader(), renderer);
72
+ const { scene: hull } = await loader.loadAsync('/hull.glb');
73
+ scene.add(hull);
74
+ let effect = getHullEffect(hull);
75
+
76
+ // Optional: show the original inside the hull and follow its animation.
77
+ const { scene: original } = await loader.loadAsync('/original.glb');
78
+ effect = bindHull(hull, original, { animate: true });
79
+ // Each frame: advance your AnimationMixers, then effect.syncAnimation().
80
+ // Call effect.dispose() before removing the hull.
81
+ ```
82
+
83
+ `bindHull` replaces the automatically created effect, preserving its settings.
84
+ It borrows the original and leaves the caller's hierarchy and resources intact.
85
+ Get the current effect again after rebinding; old bindings no longer control it.
86
+ `bindHull(hull, null)` detaches the original and restores the standalone effect.
87
+ `getHullEffect(hull)` returns `undefined` for an ordinary or disposed hull.
88
+ Standalone animated hulls can follow their own animation; call `syncAnimation()`
89
+ after updating their mixers or deformation rig. TSL effects require
90
+ `WebGPURenderer` from `three/webgpu`, using either its WebGPU or WebGL2 backend.
91
+
92
+ The existing manual API remains available for models without the extension.
93
+ Here the hull supplies the effect's surface and the original stays visible inside:
25
94
  Available modes and their defaults are in `HULL_EFFECT_MODES` and
26
95
  `createHullEffectValues()`:
27
96
 
@@ -42,6 +111,22 @@ const effect = createHullEffect(hull, original, createHullEffectValues().flames)
42
111
  // Call effect.dispose() at teardown.
43
112
  ```
44
113
 
114
+ ### Hull extension contract
115
+
116
+ `NEEDLE_hull_effect` version 1 is stored on the glTF scene containing the hull:
117
+
118
+ ```json
119
+ { "version": 1, "mode": "flames", "values": { "height": 0.51, "speed": 1 } }
120
+ ```
121
+
122
+ The name appears in `extensionsUsed`. Exported hull geometry and standard
123
+ materials remain a portable fallback, so it is not marked required. `mode` must
124
+ be a supported `HULL_EFFECT_MODES` value; omitted controls use their documented
125
+ defaults, finite numeric values are clamped to their control ranges. Unknown
126
+ versions, unknown modes, and non-finite or non-numeric control values fail
127
+ explicitly. The extension stores no source URL and triggers no source download.
128
+ Each scene with the extension gets its own runtime; dispose each when unloading.
129
+
45
130
  ## Octahedral impostors
46
131
 
47
132
  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,