@needle-tools/three-mesh-effects 0.1.0-alpha → 0.1.0-alpha.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/LICENSE +21 -21
- package/README.md +94 -88
- package/build/deformation-runtime.js.map +1 -1
- package/build/impostor-runtime-needle-engine.js.map +1 -1
- package/build/impostor-runtime.js.map +1 -1
- package/build/internal/deformation/cloth-surface.js.map +1 -1
- package/build/internal/deformation/fur-surface.js.map +1 -1
- package/build/internal/deformation/ik-constraints.js.map +1 -1
- package/build/internal/deformation/joints-json.js.map +1 -1
- package/build/internal/deformation/limits.js.map +1 -1
- package/build/internal/deformation/motion-settings.js.map +1 -1
- package/build/internal/deformation/pin-cloth.js.map +1 -1
- package/build/internal/deformation/pin-ik.js.map +1 -1
- package/build/internal/deformation/pin-types.js.map +1 -1
- package/build/internal/deformation/pin-wiggle.js.map +1 -1
- package/build/internal/deformation/pose-slots.js.map +1 -1
- package/build/internal/deformation/pose-timeline.js.map +1 -1
- package/build/internal/deformation/rig-drivers.js.map +1 -1
- package/build/internal/deformation/rig-extension.js.map +1 -1
- package/build/internal/deformation/rig-runtime.js.map +1 -1
- package/build/internal/deformation/wind.js.map +1 -1
- package/build/internal/impostor/impostor-metadata.js.map +1 -1
- package/build/internal/impostor/impostor-node-material.js.map +1 -1
- package/build/internal/impostor/impostor-runtime-support.js.map +1 -1
- package/build/internal/impostor/octahedral.js.map +1 -1
- package/build/internal/pixel-impostor/pixel-impostor-display.js.map +1 -1
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +1 -1
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +1 -1
- package/build/internal/rendering/skin-projection.js +52 -52
- package/build/internal/rendering/skin-projection.js.map +2 -2
- package/build/internal/rendering/surface-query.js +52 -52
- package/build/internal/rendering/surface-query.js.map +2 -2
- package/build/internal/rendering/wireframe.js.map +1 -1
- package/build/internal/rendering/wrap-preview-settings.js.map +1 -1
- package/build/internal/rendering/wrap-preview.js +52 -52
- package/build/internal/rendering/wrap-preview.js.map +2 -2
- package/build/internal/rendering/wrap-skin.js +52 -52
- package/build/internal/rendering/wrap-skin.js.map +2 -2
- package/build/pixel-impostor-runtime.js.map +1 -1
- package/build/wrap-effects.js +52 -52
- package/build/wrap-effects.js.map +2 -2
- package/package.json +107 -94
- package/src/deformation/cloth-surface.ts +223 -223
- package/src/deformation/fur-surface.ts +129 -129
- package/src/deformation/ik-constraints.ts +37 -37
- package/src/deformation/joints-json.ts +94 -94
- package/src/deformation/limits.ts +25 -25
- package/src/deformation/motion-settings.ts +9 -9
- package/src/deformation/pin-cloth.ts +149 -149
- package/src/deformation/pin-ik.ts +582 -582
- package/src/deformation/pin-types.ts +22 -22
- package/src/deformation/pin-wiggle.ts +119 -119
- package/src/deformation/pose-slots.ts +106 -106
- package/src/deformation/pose-timeline.ts +242 -242
- package/src/deformation/rig-drivers.ts +32 -32
- package/src/deformation/rig-extension.ts +87 -87
- package/src/deformation/rig-runtime.ts +416 -416
- package/src/deformation/wind.ts +36 -36
- package/src/impostor/impostor-metadata.js +137 -137
- package/src/impostor/impostor-node-material.js +1581 -1581
- package/src/impostor/impostor-runtime-support.js +139 -139
- package/src/impostor/octahedral.js +280 -280
- package/src/pixel-impostor/pixel-impostor-display.js +794 -794
- package/src/pixel-impostor/pixel-impostor-metadata.js +74 -74
- package/src/pixel-impostor/pixel-impostor-runtime.js +78 -78
- package/src/public/deformation-runtime.ts +3 -3
- package/src/public/impostor-runtime-needle-engine.js +56 -56
- package/src/public/impostor-runtime.js +21 -21
- package/src/public/pixel-impostor-runtime.js +5 -5
- package/src/public/wrap-effects.js +21 -21
- package/src/rendering/skin-projection.js +113 -113
- package/src/rendering/surface-query.js +88 -88
- package/src/rendering/wireframe.js +115 -115
- package/src/rendering/wrap-preview-settings.js +123 -123
- package/src/rendering/wrap-preview.js +645 -645
- package/src/rendering/wrap-skin.js +109 -109
- package/build/internal/public/deformation-runtime.js +0 -2143
- package/build/internal/public/deformation-runtime.js.map +0 -7
- package/build/internal/public/impostor-runtime-needle-engine.js +0 -42
- package/build/internal/public/impostor-runtime-needle-engine.js.map +0 -7
- package/build/internal/public/impostor-runtime.js +0 -1333
- package/build/internal/public/impostor-runtime.js.map +0 -7
- package/build/internal/public/pixel-impostor-runtime.js +0 -876
- package/build/internal/public/pixel-impostor-runtime.js.map +0 -7
- package/build/internal/public/wrap-effects.js +0 -5640
- package/build/internal/public/wrap-effects.js.map +0 -7
|
@@ -1,129 +1,129 @@
|
|
|
1
|
-
import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';
|
|
2
|
-
import { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';
|
|
3
|
-
import { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';
|
|
4
|
-
import type { RigDescriptor } from './rig-extension.js';
|
|
5
|
-
|
|
6
|
-
interface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }
|
|
7
|
-
|
|
8
|
-
/** Optional GPU detail for a portable skinned GLB. Nothing is written into its
|
|
9
|
-
* fallback material or geometry, and the variant is absent without Fur pins. */
|
|
10
|
-
export class FurSurface {
|
|
11
|
-
readonly surfaces: Surface[] = [];
|
|
12
|
-
private height: Texture | null = null;
|
|
13
|
-
private clock = uniform(0);
|
|
14
|
-
private wind = uniform(0);
|
|
15
|
-
|
|
16
|
-
constructor(scene: Object3D, descriptor: RigDescriptor, nodes: readonly Object3D[], helpers: readonly Object3D[]) {
|
|
17
|
-
const depth = new Map<Object3D, number>();
|
|
18
|
-
descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? (pin.furDepth ?? .1) : 0));
|
|
19
|
-
descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {
|
|
20
|
-
const index = descriptor.joints.findIndex(joint => joint.node === influence.node);
|
|
21
|
-
const pin = descriptor.pins[index];
|
|
22
|
-
return sum + (pin?.fur ? (pin.furDepth ?? .1) * influence.weight : 0);
|
|
23
|
-
}, 0)));
|
|
24
|
-
scene.traverse(object => {
|
|
25
|
-
if (!(object instanceof SkinnedMesh)) return;
|
|
26
|
-
const geometry = object.geometry, indices = geometry.getAttribute('skinIndex'), weights = geometry.getAttribute('skinWeight');
|
|
27
|
-
if (!indices || !weights || !geometry.getAttribute('uv') || !geometry.getAttribute('normal')) return;
|
|
28
|
-
if ((Array.isArray(object.material) ? object.material : [object.material]).some(material => !(material instanceof MeshStandardMaterial))) return;
|
|
29
|
-
const values = new Float32Array(indices.count);
|
|
30
|
-
for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {
|
|
31
|
-
values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);
|
|
32
|
-
}
|
|
33
|
-
if (!values.some(value => value > 1e-5)) return;
|
|
34
|
-
const modified = geometry.clone();
|
|
35
|
-
modified.setAttribute('furDepth', new BufferAttribute(values, 1));
|
|
36
|
-
const surface: Surface = { mesh: object, geometry, modified, material: object.material, variants: [] };
|
|
37
|
-
object.geometry = modified;
|
|
38
|
-
this.surfaces.push(surface);
|
|
39
|
-
});
|
|
40
|
-
this.rebuild();
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
setHeightMap(height: Texture | null) { if (this.height !== height) { this.height = height; this.rebuild(); } }
|
|
44
|
-
update(seconds: number, windStrength: number) {
|
|
45
|
-
this.clock.value += Math.max(0, Math.min(seconds, .1));
|
|
46
|
-
this.wind.value = windStrength;
|
|
47
|
-
}
|
|
48
|
-
/** GLTFExporter must only see standard portable materials and attributes. */
|
|
49
|
-
setPortable(portable: boolean) {
|
|
50
|
-
for (const surface of this.surfaces) {
|
|
51
|
-
surface.mesh.geometry = portable ? surface.geometry : surface.modified;
|
|
52
|
-
surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
dispose() {
|
|
56
|
-
this.setPortable(true);
|
|
57
|
-
for (const surface of this.surfaces) {
|
|
58
|
-
surface.modified.dispose(); surface.mesh.geometry = surface.geometry;
|
|
59
|
-
for (const variant of surface.variants) variant.dispose();
|
|
60
|
-
}
|
|
61
|
-
this.surfaces.length = 0;
|
|
62
|
-
}
|
|
63
|
-
private rebuild() {
|
|
64
|
-
for (const surface of this.surfaces) {
|
|
65
|
-
const sources = Array.isArray(surface.material) ? surface.material : [surface.material];
|
|
66
|
-
const variants = sources.map(source => this.material(source as MeshStandardMaterial));
|
|
67
|
-
this.setPortable(true);
|
|
68
|
-
for (const old of surface.variants) old.dispose();
|
|
69
|
-
surface.variants = variants;
|
|
70
|
-
}
|
|
71
|
-
this.setPortable(false);
|
|
72
|
-
}
|
|
73
|
-
private material(source: MeshStandardMaterial) {
|
|
74
|
-
const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();
|
|
75
|
-
material.copy(source);
|
|
76
|
-
material.name = `${source.name || 'Material'} · Fur texture motion`;
|
|
77
|
-
const coordinates = uv();
|
|
78
|
-
const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;
|
|
79
|
-
if (!signal) return material;
|
|
80
|
-
const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);
|
|
81
|
-
const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;
|
|
82
|
-
const dimensions = signal.image as { width?: number; height?: number } | undefined;
|
|
83
|
-
const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
|
|
84
|
-
const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));
|
|
85
|
-
const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(.5);
|
|
86
|
-
const raised = mix(.65, 1.35, height);
|
|
87
|
-
const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));
|
|
88
|
-
const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));
|
|
89
|
-
// A shared subpixel-to-two-pixel UV flow keeps color, normal, ORM, AO and
|
|
90
|
-
// opacity aligned. The field follows the skinned surface and can shimmer
|
|
91
|
-
// with wind; height modulates movement rather than drawing synthetic hair.
|
|
92
|
-
const shift = movement.add(gust).mul(depth).mul(raised)
|
|
93
|
-
.clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');
|
|
94
|
-
const sample = (map: Texture) => {
|
|
95
|
-
const node = texture(map, uv(map.channel).add(shift));
|
|
96
|
-
node.updateMatrix = true;
|
|
97
|
-
return node;
|
|
98
|
-
};
|
|
99
|
-
const base = source.map ? sample(source.map) : vec4(1);
|
|
100
|
-
material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));
|
|
101
|
-
if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;
|
|
102
|
-
if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap).xyz,
|
|
103
|
-
vec2(source.normalScale.x, source.normalScale.y));
|
|
104
|
-
material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);
|
|
105
|
-
material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);
|
|
106
|
-
if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));
|
|
107
|
-
if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(
|
|
108
|
-
source.emissive.r * source.emissiveIntensity,
|
|
109
|
-
source.emissive.g * source.emissiveIntensity,
|
|
110
|
-
source.emissive.b * source.emissiveIntensity));
|
|
111
|
-
material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };
|
|
112
|
-
return material;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** Convert the current skin displacement into a local UV offset. The metric
|
|
117
|
-
* inversion avoids assuming that U/V align with world X/Y or have equal scale. */
|
|
118
|
-
function projectMotionToUv(movement: Node<'vec3'>, coordinates: Node<'vec2'>) {
|
|
119
|
-
const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();
|
|
120
|
-
const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();
|
|
121
|
-
const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));
|
|
122
|
-
const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));
|
|
123
|
-
const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);
|
|
124
|
-
const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);
|
|
125
|
-
const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);
|
|
126
|
-
const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);
|
|
127
|
-
const u = movement.dot(dPosDu), v = movement.dot(dPosDv);
|
|
128
|
-
return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));
|
|
129
|
-
}
|
|
1
|
+
import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';
|
|
2
|
+
import { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';
|
|
3
|
+
import { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';
|
|
4
|
+
import type { RigDescriptor } from './rig-extension.js';
|
|
5
|
+
|
|
6
|
+
interface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }
|
|
7
|
+
|
|
8
|
+
/** Optional GPU detail for a portable skinned GLB. Nothing is written into its
|
|
9
|
+
* fallback material or geometry, and the variant is absent without Fur pins. */
|
|
10
|
+
export class FurSurface {
|
|
11
|
+
readonly surfaces: Surface[] = [];
|
|
12
|
+
private height: Texture | null = null;
|
|
13
|
+
private clock = uniform(0);
|
|
14
|
+
private wind = uniform(0);
|
|
15
|
+
|
|
16
|
+
constructor(scene: Object3D, descriptor: RigDescriptor, nodes: readonly Object3D[], helpers: readonly Object3D[]) {
|
|
17
|
+
const depth = new Map<Object3D, number>();
|
|
18
|
+
descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? (pin.furDepth ?? .1) : 0));
|
|
19
|
+
descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {
|
|
20
|
+
const index = descriptor.joints.findIndex(joint => joint.node === influence.node);
|
|
21
|
+
const pin = descriptor.pins[index];
|
|
22
|
+
return sum + (pin?.fur ? (pin.furDepth ?? .1) * influence.weight : 0);
|
|
23
|
+
}, 0)));
|
|
24
|
+
scene.traverse(object => {
|
|
25
|
+
if (!(object instanceof SkinnedMesh)) return;
|
|
26
|
+
const geometry = object.geometry, indices = geometry.getAttribute('skinIndex'), weights = geometry.getAttribute('skinWeight');
|
|
27
|
+
if (!indices || !weights || !geometry.getAttribute('uv') || !geometry.getAttribute('normal')) return;
|
|
28
|
+
if ((Array.isArray(object.material) ? object.material : [object.material]).some(material => !(material instanceof MeshStandardMaterial))) return;
|
|
29
|
+
const values = new Float32Array(indices.count);
|
|
30
|
+
for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {
|
|
31
|
+
values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);
|
|
32
|
+
}
|
|
33
|
+
if (!values.some(value => value > 1e-5)) return;
|
|
34
|
+
const modified = geometry.clone();
|
|
35
|
+
modified.setAttribute('furDepth', new BufferAttribute(values, 1));
|
|
36
|
+
const surface: Surface = { mesh: object, geometry, modified, material: object.material, variants: [] };
|
|
37
|
+
object.geometry = modified;
|
|
38
|
+
this.surfaces.push(surface);
|
|
39
|
+
});
|
|
40
|
+
this.rebuild();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
setHeightMap(height: Texture | null) { if (this.height !== height) { this.height = height; this.rebuild(); } }
|
|
44
|
+
update(seconds: number, windStrength: number) {
|
|
45
|
+
this.clock.value += Math.max(0, Math.min(seconds, .1));
|
|
46
|
+
this.wind.value = windStrength;
|
|
47
|
+
}
|
|
48
|
+
/** GLTFExporter must only see standard portable materials and attributes. */
|
|
49
|
+
setPortable(portable: boolean) {
|
|
50
|
+
for (const surface of this.surfaces) {
|
|
51
|
+
surface.mesh.geometry = portable ? surface.geometry : surface.modified;
|
|
52
|
+
surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
dispose() {
|
|
56
|
+
this.setPortable(true);
|
|
57
|
+
for (const surface of this.surfaces) {
|
|
58
|
+
surface.modified.dispose(); surface.mesh.geometry = surface.geometry;
|
|
59
|
+
for (const variant of surface.variants) variant.dispose();
|
|
60
|
+
}
|
|
61
|
+
this.surfaces.length = 0;
|
|
62
|
+
}
|
|
63
|
+
private rebuild() {
|
|
64
|
+
for (const surface of this.surfaces) {
|
|
65
|
+
const sources = Array.isArray(surface.material) ? surface.material : [surface.material];
|
|
66
|
+
const variants = sources.map(source => this.material(source as MeshStandardMaterial));
|
|
67
|
+
this.setPortable(true);
|
|
68
|
+
for (const old of surface.variants) old.dispose();
|
|
69
|
+
surface.variants = variants;
|
|
70
|
+
}
|
|
71
|
+
this.setPortable(false);
|
|
72
|
+
}
|
|
73
|
+
private material(source: MeshStandardMaterial) {
|
|
74
|
+
const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();
|
|
75
|
+
material.copy(source);
|
|
76
|
+
material.name = `${source.name || 'Material'} · Fur texture motion`;
|
|
77
|
+
const coordinates = uv();
|
|
78
|
+
const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;
|
|
79
|
+
if (!signal) return material;
|
|
80
|
+
const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);
|
|
81
|
+
const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;
|
|
82
|
+
const dimensions = signal.image as { width?: number; height?: number } | undefined;
|
|
83
|
+
const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
|
|
84
|
+
const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));
|
|
85
|
+
const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(.5);
|
|
86
|
+
const raised = mix(.65, 1.35, height);
|
|
87
|
+
const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));
|
|
88
|
+
const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));
|
|
89
|
+
// A shared subpixel-to-two-pixel UV flow keeps color, normal, ORM, AO and
|
|
90
|
+
// opacity aligned. The field follows the skinned surface and can shimmer
|
|
91
|
+
// with wind; height modulates movement rather than drawing synthetic hair.
|
|
92
|
+
const shift = movement.add(gust).mul(depth).mul(raised)
|
|
93
|
+
.clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');
|
|
94
|
+
const sample = (map: Texture) => {
|
|
95
|
+
const node = texture(map, uv(map.channel).add(shift));
|
|
96
|
+
node.updateMatrix = true;
|
|
97
|
+
return node;
|
|
98
|
+
};
|
|
99
|
+
const base = source.map ? sample(source.map) : vec4(1);
|
|
100
|
+
material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));
|
|
101
|
+
if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;
|
|
102
|
+
if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap).xyz,
|
|
103
|
+
vec2(source.normalScale.x, source.normalScale.y));
|
|
104
|
+
material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);
|
|
105
|
+
material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);
|
|
106
|
+
if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));
|
|
107
|
+
if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(
|
|
108
|
+
source.emissive.r * source.emissiveIntensity,
|
|
109
|
+
source.emissive.g * source.emissiveIntensity,
|
|
110
|
+
source.emissive.b * source.emissiveIntensity));
|
|
111
|
+
material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };
|
|
112
|
+
return material;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Convert the current skin displacement into a local UV offset. The metric
|
|
117
|
+
* inversion avoids assuming that U/V align with world X/Y or have equal scale. */
|
|
118
|
+
function projectMotionToUv(movement: Node<'vec3'>, coordinates: Node<'vec2'>) {
|
|
119
|
+
const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();
|
|
120
|
+
const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();
|
|
121
|
+
const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));
|
|
122
|
+
const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));
|
|
123
|
+
const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);
|
|
124
|
+
const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);
|
|
125
|
+
const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);
|
|
126
|
+
const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);
|
|
127
|
+
const u = movement.dot(dPosDu), v = movement.dot(dPosDv);
|
|
128
|
+
return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));
|
|
129
|
+
}
|
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
import { Quaternion, Vector3 } from 'three';
|
|
2
|
-
export type IKConstraint = { mode:'free'|'cone'|'hinge'|'locked'; axis:'auto'|'x'|'y'|'z'; min:number; max:number; orientation?:[number,number,number,number]; maxY?:number };
|
|
3
|
-
export const DEFAULT_IK_CONSTRAINT:Readonly<IKConstraint> = {mode:'free',axis:'auto',min:-120,max:120};
|
|
4
|
-
export function validateIKConstraint(value:IKConstraint) {
|
|
5
|
-
if(value?.maxY!==undefined && (!Number.isFinite(value.maxY)||value.maxY<0||value.maxY>180))throw new Error('Invalid IK cone aperture.');
|
|
6
|
-
if(value?.orientation!==undefined && (!Array.isArray(value.orientation)||value.orientation.length!==4||!value.orientation.every(Number.isFinite)||Math.abs(Math.hypot(...value.orientation)-1)>1e-4))throw new Error('Invalid IK cone orientation.');
|
|
7
|
-
if (!value || !['free','cone','hinge','locked'].includes(value.mode) || !['auto','x','y','z'].includes(value.axis)
|
|
8
|
-
|| !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || (value.mode==='cone' && value.max<0)) throw new Error('Invalid IK joint constraint.');
|
|
9
|
-
}
|
|
10
|
-
/** Stable parent-local cone frame. Z follows the rest bone; X/Y are aperture axes. */
|
|
11
|
-
export function coneFrame(axis:Vector3,constraint:Readonly<IKConstraint>){
|
|
12
|
-
return new Quaternion().fromArray(constraint.orientation??[0,0,0,1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis.clone().normalize()));
|
|
13
|
-
}
|
|
14
|
-
/** Angular ellipse (also valid beyond 90 degrees), rather than a tangent-plane box. */
|
|
15
|
-
export function coneAngle(constraint:Readonly<IKConstraint>,azimuth:number){
|
|
16
|
-
const x=(constraint.mode==='cone'?constraint.max:90)*Math.PI/180,y=(constraint.mode==='cone'?(constraint.maxY??constraint.max):90)*Math.PI/180;
|
|
17
|
-
const c=Math.cos(azimuth),s=Math.sin(azimuth);
|
|
18
|
-
if((x===0&&Math.abs(c)>1e-8)||(y===0&&Math.abs(s)>1e-8))return 0;
|
|
19
|
-
return 1/Math.sqrt((Math.abs(c)<1e-8?0:c/Math.max(x,1e-12))**2+(Math.abs(s)<1e-8?0:s/Math.max(y,1e-12))**2);
|
|
20
|
-
}
|
|
21
|
-
export function constrainCone(rotation:Quaternion,axis:Vector3,constraint:Readonly<IKConstraint>,movingAxis:Vector3=axis){
|
|
22
|
-
const frame=coneFrame(axis,constraint),direction=movingAxis.clone().normalize().applyQuaternion(rotation);
|
|
23
|
-
const local=direction.clone().applyQuaternion(frame.clone().invert()),azimuth=Math.atan2(local.y,local.x);
|
|
24
|
-
const angle=Math.atan2(Math.hypot(local.x,local.y),local.z),limit=coneAngle(constraint,azimuth);
|
|
25
|
-
if(angle<=limit+1e-8)return rotation.clone();
|
|
26
|
-
const target=new Vector3(Math.sin(limit)*Math.cos(azimuth),Math.sin(limit)*Math.sin(azimuth),Math.cos(limit)).applyQuaternion(frame);
|
|
27
|
-
return new Quaternion().setFromUnitVectors(direction,target).multiply(rotation).normalize();
|
|
28
|
-
}
|
|
29
|
-
/** Circular swing cone, not an Euler-angle box. Twist remains free. */
|
|
30
|
-
export function constrainSwing(rotation: Quaternion, axis: Vector3, degrees: number) {
|
|
31
|
-
const direction=axis.clone().normalize(), rotated=direction.clone().applyQuaternion(rotation);
|
|
32
|
-
const angle=direction.angleTo(rotated), limit=degrees*Math.PI/180;
|
|
33
|
-
if(angle<=limit+1e-8)return rotation.clone();
|
|
34
|
-
const normal=new Vector3().crossVectors(direction,rotated);
|
|
35
|
-
if(normal.lengthSq()<1e-12)normal.crossVectors(direction,Math.abs(direction.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0));
|
|
36
|
-
return new Quaternion().setFromAxisAngle(normal.normalize(),limit-angle).multiply(rotation).normalize();
|
|
37
|
-
}
|
|
1
|
+
import { Quaternion, Vector3 } from 'three';
|
|
2
|
+
export type IKConstraint = { mode:'free'|'cone'|'hinge'|'locked'; axis:'auto'|'x'|'y'|'z'; min:number; max:number; orientation?:[number,number,number,number]; maxY?:number };
|
|
3
|
+
export const DEFAULT_IK_CONSTRAINT:Readonly<IKConstraint> = {mode:'free',axis:'auto',min:-120,max:120};
|
|
4
|
+
export function validateIKConstraint(value:IKConstraint) {
|
|
5
|
+
if(value?.maxY!==undefined && (!Number.isFinite(value.maxY)||value.maxY<0||value.maxY>180))throw new Error('Invalid IK cone aperture.');
|
|
6
|
+
if(value?.orientation!==undefined && (!Array.isArray(value.orientation)||value.orientation.length!==4||!value.orientation.every(Number.isFinite)||Math.abs(Math.hypot(...value.orientation)-1)>1e-4))throw new Error('Invalid IK cone orientation.');
|
|
7
|
+
if (!value || !['free','cone','hinge','locked'].includes(value.mode) || !['auto','x','y','z'].includes(value.axis)
|
|
8
|
+
|| !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || (value.mode==='cone' && value.max<0)) throw new Error('Invalid IK joint constraint.');
|
|
9
|
+
}
|
|
10
|
+
/** Stable parent-local cone frame. Z follows the rest bone; X/Y are aperture axes. */
|
|
11
|
+
export function coneFrame(axis:Vector3,constraint:Readonly<IKConstraint>){
|
|
12
|
+
return new Quaternion().fromArray(constraint.orientation??[0,0,0,1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis.clone().normalize()));
|
|
13
|
+
}
|
|
14
|
+
/** Angular ellipse (also valid beyond 90 degrees), rather than a tangent-plane box. */
|
|
15
|
+
export function coneAngle(constraint:Readonly<IKConstraint>,azimuth:number){
|
|
16
|
+
const x=(constraint.mode==='cone'?constraint.max:90)*Math.PI/180,y=(constraint.mode==='cone'?(constraint.maxY??constraint.max):90)*Math.PI/180;
|
|
17
|
+
const c=Math.cos(azimuth),s=Math.sin(azimuth);
|
|
18
|
+
if((x===0&&Math.abs(c)>1e-8)||(y===0&&Math.abs(s)>1e-8))return 0;
|
|
19
|
+
return 1/Math.sqrt((Math.abs(c)<1e-8?0:c/Math.max(x,1e-12))**2+(Math.abs(s)<1e-8?0:s/Math.max(y,1e-12))**2);
|
|
20
|
+
}
|
|
21
|
+
export function constrainCone(rotation:Quaternion,axis:Vector3,constraint:Readonly<IKConstraint>,movingAxis:Vector3=axis){
|
|
22
|
+
const frame=coneFrame(axis,constraint),direction=movingAxis.clone().normalize().applyQuaternion(rotation);
|
|
23
|
+
const local=direction.clone().applyQuaternion(frame.clone().invert()),azimuth=Math.atan2(local.y,local.x);
|
|
24
|
+
const angle=Math.atan2(Math.hypot(local.x,local.y),local.z),limit=coneAngle(constraint,azimuth);
|
|
25
|
+
if(angle<=limit+1e-8)return rotation.clone();
|
|
26
|
+
const target=new Vector3(Math.sin(limit)*Math.cos(azimuth),Math.sin(limit)*Math.sin(azimuth),Math.cos(limit)).applyQuaternion(frame);
|
|
27
|
+
return new Quaternion().setFromUnitVectors(direction,target).multiply(rotation).normalize();
|
|
28
|
+
}
|
|
29
|
+
/** Circular swing cone, not an Euler-angle box. Twist remains free. */
|
|
30
|
+
export function constrainSwing(rotation: Quaternion, axis: Vector3, degrees: number) {
|
|
31
|
+
const direction=axis.clone().normalize(), rotated=direction.clone().applyQuaternion(rotation);
|
|
32
|
+
const angle=direction.angleTo(rotated), limit=degrees*Math.PI/180;
|
|
33
|
+
if(angle<=limit+1e-8)return rotation.clone();
|
|
34
|
+
const normal=new Vector3().crossVectors(direction,rotated);
|
|
35
|
+
if(normal.lengthSq()<1e-12)normal.crossVectors(direction,Math.abs(direction.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0));
|
|
36
|
+
return new Quaternion().setFromAxisAngle(normal.normalize(),limit-angle).multiply(rotation).normalize();
|
|
37
|
+
}
|
|
@@ -1,94 +1,94 @@
|
|
|
1
|
-
import { IK_CHAIN_KINDS, MAX_FUR_DEPTH, type IKChainRole, type PinRecord, type Point, type Rotation } from './pin-types.js';
|
|
2
|
-
import { MAX_DEFORMATION_PINS } from './limits.js';
|
|
3
|
-
import { DEFAULT_MOTION, validateMotionSettings } from './motion-settings.js';
|
|
4
|
-
import { validateIKConstraint, type IKConstraint } from './ik-constraints.js';
|
|
5
|
-
import { capturePose, POSE_SLOTS, resolvePose, type PoseSlot } from './pose-slots.js';
|
|
6
|
-
import type { PinParents } from './pin-types.js';
|
|
7
|
-
import { MAX_POSE_SECONDS, MIN_POSE_SECONDS, type PoseTiming } from './pose-timeline.js';
|
|
8
|
-
import { MAX_WIND_STRENGTH } from './wind.js';
|
|
9
|
-
|
|
10
|
-
function record(value: unknown): Record<string, unknown> {
|
|
11
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid joints JSON object.');
|
|
12
|
-
return value as Record<string, unknown>;
|
|
13
|
-
}
|
|
14
|
-
function numbers(value: unknown, length: number): number[] {
|
|
15
|
-
if (!Array.isArray(value) || value.length !== length || !value.every(v => typeof v === 'number' && Number.isFinite(v))) throw new Error('Invalid joint coordinates.');
|
|
16
|
-
return [...value];
|
|
17
|
-
}
|
|
18
|
-
function point(value: unknown): Point { const v = numbers(value, 3); return [v[0], v[1], v[2]]; }
|
|
19
|
-
function quaternion(value: unknown): Rotation { const v = numbers(value, 4); return [v[0], v[1], v[2], v[3]]; }
|
|
20
|
-
export function validateJoints(value: unknown, maximum = MAX_DEFORMATION_PINS): readonly PinRecord[] {
|
|
21
|
-
if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);
|
|
22
|
-
const ids = new Set<string>();
|
|
23
|
-
const pins = value.map(item => {
|
|
24
|
-
const pin = record(item), pose = record(pin.pose);
|
|
25
|
-
if (typeof pin.id !== 'string' || !pin.id || ids.has(pin.id)) throw new Error('Joint IDs must be unique non-empty strings.');
|
|
26
|
-
ids.add(pin.id);
|
|
27
|
-
if (typeof pin.independent !== 'boolean' || (pin.rigidGroup !== null && (typeof pin.rigidGroup !== 'string' || !pin.rigidGroup))) throw new Error('Invalid joint membership.');
|
|
28
|
-
if (pin.guide !== undefined && typeof pin.guide !== 'boolean') throw new Error('Invalid guide flag.');
|
|
29
|
-
if (pin.authored !== undefined && typeof pin.authored !== 'boolean') throw new Error('Invalid authored flag.');
|
|
30
|
-
if (pin.ik !== undefined && typeof pin.ik !== 'boolean') throw new Error('Invalid IK flag.');
|
|
31
|
-
if (pin.wiggle !== undefined && typeof pin.wiggle !== 'boolean') throw new Error('Invalid Wiggle flag.');
|
|
32
|
-
if (pin.cloth !== undefined && typeof pin.cloth !== 'boolean') throw new Error('Invalid Cloth flag.');
|
|
33
|
-
if (pin.fur !== undefined && typeof pin.fur !== 'boolean') throw new Error('Invalid Fur flag.');
|
|
34
|
-
if (pin.furDepth !== undefined && (typeof pin.furDepth !== 'number' || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error('Invalid Fur depth.');
|
|
35
|
-
const chainRole=pin.chainRole===undefined?undefined:(()=>{
|
|
36
|
-
const value=record(pin.chainRole);
|
|
37
|
-
if(!IK_CHAIN_KINDS.includes(value.kind as IKChainRole['kind'])||!['center','left','right'].includes(value.side as string)||
|
|
38
|
-
(value.position!==undefined&&!['front','hind'].includes(value.position as string)))throw new Error('Invalid IK chain role.');
|
|
39
|
-
return {kind:value.kind as IKChainRole['kind'],side:value.side as IKChainRole['side'],...(value.position?{position:value.position as 'front'|'hind'}:{})};
|
|
40
|
-
})();
|
|
41
|
-
if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error('Choose IK, Wiggle, Cloth or Fur.');
|
|
42
|
-
const motion = pin.motion === undefined ? undefined : (()=>{
|
|
43
|
-
const raw=record(pin.motion), result={reach:Number(raw.reach),frequency:Number(raw.frequency),damping:Number(raw.damping),massInfluence:raw.massInfluence===undefined?DEFAULT_MOTION.massInfluence:Number(raw.massInfluence),strength:raw.strength===undefined?DEFAULT_MOTION.strength:Number(raw.strength)};
|
|
44
|
-
for(const key of ['massInfluence','strength']) if(raw[key]!==undefined && typeof raw[key]!=='number') throw new Error('Invalid motion settings.');
|
|
45
|
-
if (typeof raw.reach!=='number' || typeof raw.frequency!=='number' || typeof raw.damping!=='number') throw new Error('Invalid motion settings.');
|
|
46
|
-
validateMotionSettings(result); return result;
|
|
47
|
-
})();
|
|
48
|
-
const ikConstraint=pin.ikConstraint===undefined?undefined:(()=>{const raw=record(pin.ikConstraint);const value={mode:raw.mode,axis:raw.axis,min:raw.min,max:raw.max,...(raw.orientation!==undefined?{orientation:quaternion(raw.orientation)}:{}),...(raw.maxY!==undefined?{maxY:raw.maxY}:{})} as IKConstraint;validateIKConstraint(value);return value;})();
|
|
49
|
-
const ikTarget=pin.ikTarget === undefined ? undefined : (()=>{
|
|
50
|
-
const raw=record(pin.ikTarget),rotation=quaternion(raw.rotation);
|
|
51
|
-
if (Math.abs(Math.hypot(...rotation)-1)>1e-4) throw new Error('Invalid IK target rotation.');
|
|
52
|
-
return {position:point(raw.position),rotation};
|
|
53
|
-
})();
|
|
54
|
-
if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error('Guides cannot be rigid members or roots.');
|
|
55
|
-
const scale = point(pose.scale), rotation = quaternion(pose.rotation);
|
|
56
|
-
if (scale.some(v => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error('Invalid joint rotation or scale.');
|
|
57
|
-
return { id: pin.id, independent: pin.independent, rigidGroup: pin.rigidGroup, ...(pin.authored === true ? { authored: true } : {}), ...(typeof pin.guide === 'boolean' ? { guide: pin.guide } : {}), ...(typeof pin.ik === 'boolean' ? { ik: pin.ik } : {}),
|
|
58
|
-
...(ikConstraint?{ikConstraint}:{}),...(chainRole?{chainRole}:{}),...(motion ? {motion}:{}),...(ikTarget ? {ikTarget}:{}),...(typeof pin.wiggle === 'boolean' ? {wiggle:pin.wiggle} : {}),...(typeof pin.cloth === 'boolean' ? {cloth:pin.cloth} : {}),...(typeof pin.fur === 'boolean' ? {fur:pin.fur} : {}),...(pin.furDepth !== undefined ? {furDepth:pin.furDepth as number} : {}), rest: point(pin.rest), pose: { position: point(pose.position), rotation, scale } };
|
|
59
|
-
});
|
|
60
|
-
for (const pin of pins) if (pin.rigidGroup) {
|
|
61
|
-
const anchor = pins.find(other => other.rigidGroup === pin.rigidGroup)!;
|
|
62
|
-
const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);
|
|
63
|
-
if (pin.pose.scale.some(v => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error('Rigid joints must share rotation and uniform scale.');
|
|
64
|
-
}
|
|
65
|
-
return pins;
|
|
66
|
-
}
|
|
67
|
-
export interface JointsRig { pins:readonly PinRecord[];activePose:number;poseSlots:readonly PoseSlot[];poseTimes:readonly PoseTiming[];windStrength?:number }
|
|
68
|
-
function validatePoseTimes(value:unknown):readonly PoseTiming[]{
|
|
69
|
-
if(!Array.isArray(value)||value.length>POSE_SLOTS)throw new Error('Invalid pose times.');
|
|
70
|
-
const slots=new Set<number>();
|
|
71
|
-
return value.map(item=>{
|
|
72
|
-
const entry=record(item);
|
|
73
|
-
if(!Number.isInteger(entry.slot)||(entry.slot as number)<0||(entry.slot as number)>POSE_SLOTS||slots.has(entry.slot as number))throw new Error('Invalid pose time slot.');
|
|
74
|
-
slots.add(entry.slot as number);
|
|
75
|
-
if(typeof entry.seconds!=='number'||!Number.isFinite(entry.seconds)||entry.seconds<MIN_POSE_SECONDS||entry.seconds>MAX_POSE_SECONDS)throw new Error('Invalid pose time.');
|
|
76
|
-
return {slot:entry.slot as number,seconds:entry.seconds};
|
|
77
|
-
}).sort((a,b)=>a.slot-b.slot);
|
|
78
|
-
}
|
|
79
|
-
/** Slots are written out in full. A pin the hierarchy places is left unsaid in
|
|
80
|
-
* the editor so it keeps following its parent, but a file has no voxel field to
|
|
81
|
-
* rebuild that hierarchy from and older readers would drop it to rest, so the
|
|
82
|
-
* inherited pose is resolved here and stored. */
|
|
83
|
-
export function validateRig(value:JointsRig, maximum = MAX_DEFORMATION_PINS, parents:PinParents = new Map()):JointsRig{
|
|
84
|
-
const pins=validateJoints(value.pins,maximum);
|
|
85
|
-
if (value.windStrength !== undefined && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error('Invalid wind strength.');
|
|
86
|
-
if(!Number.isInteger(value.activePose)||value.activePose<0||value.activePose>POSE_SLOTS||!Array.isArray(value.poseSlots)||value.poseSlots.length>POSE_SLOTS)throw new Error('Invalid pose slots.');
|
|
87
|
-
const slots=new Set<number>(),ids=new Set(pins.map(p=>p.id));
|
|
88
|
-
const poseSlots=value.poseSlots.map(slot=>{
|
|
89
|
-
if(!slot||!Number.isInteger(slot.slot)||slot.slot<1||slot.slot>POSE_SLOTS||slots.has(slot.slot)||!Array.isArray(slot.poses))throw new Error('Invalid pose slot.');slots.add(slot.slot);
|
|
90
|
-
const pinIds=new Set<string>();for(const p of slot.poses){if(!p||!ids.has(p.id)||pinIds.has(p.id))throw new Error('Invalid pose pin.');pinIds.add(p.id);}
|
|
91
|
-
return {slot:slot.slot,poses:capturePose(validateJoints(resolvePose(pins,slot,parents),maximum))};
|
|
92
|
-
}).filter(slot=>slot.slot!==value.activePose);
|
|
93
|
-
return {pins,activePose:value.activePose,poseSlots,poseTimes:validatePoseTimes(value.poseTimes??[]),...(value.windStrength !== undefined ? {windStrength:value.windStrength} : {})};
|
|
94
|
-
}
|
|
1
|
+
import { IK_CHAIN_KINDS, MAX_FUR_DEPTH, type IKChainRole, type PinRecord, type Point, type Rotation } from './pin-types.js';
|
|
2
|
+
import { MAX_DEFORMATION_PINS } from './limits.js';
|
|
3
|
+
import { DEFAULT_MOTION, validateMotionSettings } from './motion-settings.js';
|
|
4
|
+
import { validateIKConstraint, type IKConstraint } from './ik-constraints.js';
|
|
5
|
+
import { capturePose, POSE_SLOTS, resolvePose, type PoseSlot } from './pose-slots.js';
|
|
6
|
+
import type { PinParents } from './pin-types.js';
|
|
7
|
+
import { MAX_POSE_SECONDS, MIN_POSE_SECONDS, type PoseTiming } from './pose-timeline.js';
|
|
8
|
+
import { MAX_WIND_STRENGTH } from './wind.js';
|
|
9
|
+
|
|
10
|
+
function record(value: unknown): Record<string, unknown> {
|
|
11
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid joints JSON object.');
|
|
12
|
+
return value as Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
function numbers(value: unknown, length: number): number[] {
|
|
15
|
+
if (!Array.isArray(value) || value.length !== length || !value.every(v => typeof v === 'number' && Number.isFinite(v))) throw new Error('Invalid joint coordinates.');
|
|
16
|
+
return [...value];
|
|
17
|
+
}
|
|
18
|
+
function point(value: unknown): Point { const v = numbers(value, 3); return [v[0], v[1], v[2]]; }
|
|
19
|
+
function quaternion(value: unknown): Rotation { const v = numbers(value, 4); return [v[0], v[1], v[2], v[3]]; }
|
|
20
|
+
export function validateJoints(value: unknown, maximum = MAX_DEFORMATION_PINS): readonly PinRecord[] {
|
|
21
|
+
if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);
|
|
22
|
+
const ids = new Set<string>();
|
|
23
|
+
const pins = value.map(item => {
|
|
24
|
+
const pin = record(item), pose = record(pin.pose);
|
|
25
|
+
if (typeof pin.id !== 'string' || !pin.id || ids.has(pin.id)) throw new Error('Joint IDs must be unique non-empty strings.');
|
|
26
|
+
ids.add(pin.id);
|
|
27
|
+
if (typeof pin.independent !== 'boolean' || (pin.rigidGroup !== null && (typeof pin.rigidGroup !== 'string' || !pin.rigidGroup))) throw new Error('Invalid joint membership.');
|
|
28
|
+
if (pin.guide !== undefined && typeof pin.guide !== 'boolean') throw new Error('Invalid guide flag.');
|
|
29
|
+
if (pin.authored !== undefined && typeof pin.authored !== 'boolean') throw new Error('Invalid authored flag.');
|
|
30
|
+
if (pin.ik !== undefined && typeof pin.ik !== 'boolean') throw new Error('Invalid IK flag.');
|
|
31
|
+
if (pin.wiggle !== undefined && typeof pin.wiggle !== 'boolean') throw new Error('Invalid Wiggle flag.');
|
|
32
|
+
if (pin.cloth !== undefined && typeof pin.cloth !== 'boolean') throw new Error('Invalid Cloth flag.');
|
|
33
|
+
if (pin.fur !== undefined && typeof pin.fur !== 'boolean') throw new Error('Invalid Fur flag.');
|
|
34
|
+
if (pin.furDepth !== undefined && (typeof pin.furDepth !== 'number' || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error('Invalid Fur depth.');
|
|
35
|
+
const chainRole=pin.chainRole===undefined?undefined:(()=>{
|
|
36
|
+
const value=record(pin.chainRole);
|
|
37
|
+
if(!IK_CHAIN_KINDS.includes(value.kind as IKChainRole['kind'])||!['center','left','right'].includes(value.side as string)||
|
|
38
|
+
(value.position!==undefined&&!['front','hind'].includes(value.position as string)))throw new Error('Invalid IK chain role.');
|
|
39
|
+
return {kind:value.kind as IKChainRole['kind'],side:value.side as IKChainRole['side'],...(value.position?{position:value.position as 'front'|'hind'}:{})};
|
|
40
|
+
})();
|
|
41
|
+
if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error('Choose IK, Wiggle, Cloth or Fur.');
|
|
42
|
+
const motion = pin.motion === undefined ? undefined : (()=>{
|
|
43
|
+
const raw=record(pin.motion), result={reach:Number(raw.reach),frequency:Number(raw.frequency),damping:Number(raw.damping),massInfluence:raw.massInfluence===undefined?DEFAULT_MOTION.massInfluence:Number(raw.massInfluence),strength:raw.strength===undefined?DEFAULT_MOTION.strength:Number(raw.strength)};
|
|
44
|
+
for(const key of ['massInfluence','strength']) if(raw[key]!==undefined && typeof raw[key]!=='number') throw new Error('Invalid motion settings.');
|
|
45
|
+
if (typeof raw.reach!=='number' || typeof raw.frequency!=='number' || typeof raw.damping!=='number') throw new Error('Invalid motion settings.');
|
|
46
|
+
validateMotionSettings(result); return result;
|
|
47
|
+
})();
|
|
48
|
+
const ikConstraint=pin.ikConstraint===undefined?undefined:(()=>{const raw=record(pin.ikConstraint);const value={mode:raw.mode,axis:raw.axis,min:raw.min,max:raw.max,...(raw.orientation!==undefined?{orientation:quaternion(raw.orientation)}:{}),...(raw.maxY!==undefined?{maxY:raw.maxY}:{})} as IKConstraint;validateIKConstraint(value);return value;})();
|
|
49
|
+
const ikTarget=pin.ikTarget === undefined ? undefined : (()=>{
|
|
50
|
+
const raw=record(pin.ikTarget),rotation=quaternion(raw.rotation);
|
|
51
|
+
if (Math.abs(Math.hypot(...rotation)-1)>1e-4) throw new Error('Invalid IK target rotation.');
|
|
52
|
+
return {position:point(raw.position),rotation};
|
|
53
|
+
})();
|
|
54
|
+
if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error('Guides cannot be rigid members or roots.');
|
|
55
|
+
const scale = point(pose.scale), rotation = quaternion(pose.rotation);
|
|
56
|
+
if (scale.some(v => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error('Invalid joint rotation or scale.');
|
|
57
|
+
return { id: pin.id, independent: pin.independent, rigidGroup: pin.rigidGroup, ...(pin.authored === true ? { authored: true } : {}), ...(typeof pin.guide === 'boolean' ? { guide: pin.guide } : {}), ...(typeof pin.ik === 'boolean' ? { ik: pin.ik } : {}),
|
|
58
|
+
...(ikConstraint?{ikConstraint}:{}),...(chainRole?{chainRole}:{}),...(motion ? {motion}:{}),...(ikTarget ? {ikTarget}:{}),...(typeof pin.wiggle === 'boolean' ? {wiggle:pin.wiggle} : {}),...(typeof pin.cloth === 'boolean' ? {cloth:pin.cloth} : {}),...(typeof pin.fur === 'boolean' ? {fur:pin.fur} : {}),...(pin.furDepth !== undefined ? {furDepth:pin.furDepth as number} : {}), rest: point(pin.rest), pose: { position: point(pose.position), rotation, scale } };
|
|
59
|
+
});
|
|
60
|
+
for (const pin of pins) if (pin.rigidGroup) {
|
|
61
|
+
const anchor = pins.find(other => other.rigidGroup === pin.rigidGroup)!;
|
|
62
|
+
const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);
|
|
63
|
+
if (pin.pose.scale.some(v => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error('Rigid joints must share rotation and uniform scale.');
|
|
64
|
+
}
|
|
65
|
+
return pins;
|
|
66
|
+
}
|
|
67
|
+
export interface JointsRig { pins:readonly PinRecord[];activePose:number;poseSlots:readonly PoseSlot[];poseTimes:readonly PoseTiming[];windStrength?:number }
|
|
68
|
+
function validatePoseTimes(value:unknown):readonly PoseTiming[]{
|
|
69
|
+
if(!Array.isArray(value)||value.length>POSE_SLOTS)throw new Error('Invalid pose times.');
|
|
70
|
+
const slots=new Set<number>();
|
|
71
|
+
return value.map(item=>{
|
|
72
|
+
const entry=record(item);
|
|
73
|
+
if(!Number.isInteger(entry.slot)||(entry.slot as number)<0||(entry.slot as number)>POSE_SLOTS||slots.has(entry.slot as number))throw new Error('Invalid pose time slot.');
|
|
74
|
+
slots.add(entry.slot as number);
|
|
75
|
+
if(typeof entry.seconds!=='number'||!Number.isFinite(entry.seconds)||entry.seconds<MIN_POSE_SECONDS||entry.seconds>MAX_POSE_SECONDS)throw new Error('Invalid pose time.');
|
|
76
|
+
return {slot:entry.slot as number,seconds:entry.seconds};
|
|
77
|
+
}).sort((a,b)=>a.slot-b.slot);
|
|
78
|
+
}
|
|
79
|
+
/** Slots are written out in full. A pin the hierarchy places is left unsaid in
|
|
80
|
+
* the editor so it keeps following its parent, but a file has no voxel field to
|
|
81
|
+
* rebuild that hierarchy from and older readers would drop it to rest, so the
|
|
82
|
+
* inherited pose is resolved here and stored. */
|
|
83
|
+
export function validateRig(value:JointsRig, maximum = MAX_DEFORMATION_PINS, parents:PinParents = new Map()):JointsRig{
|
|
84
|
+
const pins=validateJoints(value.pins,maximum);
|
|
85
|
+
if (value.windStrength !== undefined && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error('Invalid wind strength.');
|
|
86
|
+
if(!Number.isInteger(value.activePose)||value.activePose<0||value.activePose>POSE_SLOTS||!Array.isArray(value.poseSlots)||value.poseSlots.length>POSE_SLOTS)throw new Error('Invalid pose slots.');
|
|
87
|
+
const slots=new Set<number>(),ids=new Set(pins.map(p=>p.id));
|
|
88
|
+
const poseSlots=value.poseSlots.map(slot=>{
|
|
89
|
+
if(!slot||!Number.isInteger(slot.slot)||slot.slot<1||slot.slot>POSE_SLOTS||slots.has(slot.slot)||!Array.isArray(slot.poses))throw new Error('Invalid pose slot.');slots.add(slot.slot);
|
|
90
|
+
const pinIds=new Set<string>();for(const p of slot.poses){if(!p||!ids.has(p.id)||pinIds.has(p.id))throw new Error('Invalid pose pin.');pinIds.add(p.id);}
|
|
91
|
+
return {slot:slot.slot,poses:capturePose(validateJoints(resolvePose(pins,slot,parents),maximum))};
|
|
92
|
+
}).filter(slot=>slot.slot!==value.activePose);
|
|
93
|
+
return {pins,activePose:value.activePose,poseSlots,poseTimes:validatePoseTimes(value.poseTimes??[]),...(value.windStrength !== undefined ? {windStrength:value.windStrength} : {})};
|
|
94
|
+
}
|
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
/** Shared document, import, UI and GPU capacity. Pin records are 64 bytes. */
|
|
2
|
-
export const MAX_DEFORMATION_PINS = 128;
|
|
3
|
-
/** What one sweep of the Suggested pins slider will place. Well short of the
|
|
4
|
-
* document cap: past this the slider stops placing body anchors and starts
|
|
5
|
-
* splitting fine branches, which is hand work rather than a slider's job. */
|
|
6
|
-
export const MAX_SUGGESTED_PINS = 64;
|
|
7
|
-
|
|
8
|
-
/** Cells along the longest axis of the solver lattice.
|
|
9
|
-
*
|
|
10
|
-
* The lattice is N by N by N over the model's bounds, and everything the solver
|
|
11
|
-
* measures — how thick a part is, how far a contact reaches, how much an
|
|
12
|
-
* element is strained — is in units of those cells. What a grid can represent
|
|
13
|
-
* is what it can resolve: on a posed arm a finger is 2.7 cells across at 32 and
|
|
14
|
-
* 3.5 at 40, which is a rod three nodes thick.
|
|
15
|
-
*
|
|
16
|
-
* The ceiling is a memory bound rather than a speed one. Node buffers are 16
|
|
17
|
-
* bytes each and there are about ten of them, so 64 costs roughly 42 MB of
|
|
18
|
-
* those; the harmonic weights are the one that hurts, at four bytes per node
|
|
19
|
-
* per pin slot, which for a full 128 pins is 268 MB at 64 against 67 MB at 40. */
|
|
20
|
-
export const MIN_DEFORMATION_RESOLUTION = 16;
|
|
21
|
-
export const MAX_DEFORMATION_RESOLUTION = 64;
|
|
22
|
-
|
|
23
|
-
/** Bones the skeleton solver turns on its own: every part of the body no pin
|
|
24
|
-
* drives, cut along the curve skeleton. 132 bytes of GPU state each. */
|
|
25
|
-
export const MAX_SKELETON_BONES = 2048;
|
|
1
|
+
/** Shared document, import, UI and GPU capacity. Pin records are 64 bytes. */
|
|
2
|
+
export const MAX_DEFORMATION_PINS = 128;
|
|
3
|
+
/** What one sweep of the Suggested pins slider will place. Well short of the
|
|
4
|
+
* document cap: past this the slider stops placing body anchors and starts
|
|
5
|
+
* splitting fine branches, which is hand work rather than a slider's job. */
|
|
6
|
+
export const MAX_SUGGESTED_PINS = 64;
|
|
7
|
+
|
|
8
|
+
/** Cells along the longest axis of the solver lattice.
|
|
9
|
+
*
|
|
10
|
+
* The lattice is N by N by N over the model's bounds, and everything the solver
|
|
11
|
+
* measures — how thick a part is, how far a contact reaches, how much an
|
|
12
|
+
* element is strained — is in units of those cells. What a grid can represent
|
|
13
|
+
* is what it can resolve: on a posed arm a finger is 2.7 cells across at 32 and
|
|
14
|
+
* 3.5 at 40, which is a rod three nodes thick.
|
|
15
|
+
*
|
|
16
|
+
* The ceiling is a memory bound rather than a speed one. Node buffers are 16
|
|
17
|
+
* bytes each and there are about ten of them, so 64 costs roughly 42 MB of
|
|
18
|
+
* those; the harmonic weights are the one that hurts, at four bytes per node
|
|
19
|
+
* per pin slot, which for a full 128 pins is 268 MB at 64 against 67 MB at 40. */
|
|
20
|
+
export const MIN_DEFORMATION_RESOLUTION = 16;
|
|
21
|
+
export const MAX_DEFORMATION_RESOLUTION = 64;
|
|
22
|
+
|
|
23
|
+
/** Bones the skeleton solver turns on its own: every part of the body no pin
|
|
24
|
+
* drives, cut along the curve skeleton. 132 bytes of GPU state each. */
|
|
25
|
+
export const MAX_SKELETON_BONES = 2048;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };
|
|
2
|
-
export const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };
|
|
3
|
-
export function validateMotionSettings(value: MotionSettings) {
|
|
4
|
-
if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1
|
|
5
|
-
|| !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8
|
|
6
|
-
|| !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1
|
|
7
|
-
|| !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2
|
|
8
|
-
|| !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');
|
|
9
|
-
}
|
|
1
|
+
export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };
|
|
2
|
+
export const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };
|
|
3
|
+
export function validateMotionSettings(value: MotionSettings) {
|
|
4
|
+
if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1
|
|
5
|
+
|| !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8
|
|
6
|
+
|| !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1
|
|
7
|
+
|| !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2
|
|
8
|
+
|| !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');
|
|
9
|
+
}
|