@margoengine/animation 0.0.0-stage → 1.0.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 +201 -0
- package/NOTICE +4 -0
- package/README.md +1172 -2
- package/dist/batch.d.ts +162 -0
- package/dist/clip-utils.d.ts +50 -0
- package/dist/clip-utils.js +1 -0
- package/dist/clone.d.ts +15 -0
- package/dist/cor.d.ts +52 -0
- package/dist/cor.js +17 -0
- package/dist/deform-readers-DmYAkvBK.js +1 -0
- package/dist/deform-readers.d.ts +5 -0
- package/dist/deformed-points.d.ts +87 -0
- package/dist/deformed-points.js +17 -0
- package/dist/discrete-tracks.d.ts +102 -0
- package/dist/discrete-tracks.js +1 -0
- package/dist/dqs.d.ts +42 -0
- package/dist/dqs.js +29 -0
- package/dist/errors-t1ewumJS.js +1 -0
- package/dist/geometry-cache.d.ts +208 -0
- package/dist/geometry-cache.js +4 -0
- package/dist/gltf-C2HVNxzB.js +1 -0
- package/dist/gltf.d.ts +63 -0
- package/dist/group.d.ts +97 -0
- package/dist/hdr-format-cmvLFubB.js +1 -0
- package/dist/index.d.ts +203 -0
- package/dist/index.js +1 -0
- package/dist/instanced-morph.d.ts +82 -0
- package/dist/instanced-morph.js +13 -0
- package/dist/instanced-skin.d.ts +82 -0
- package/dist/instanced-skin.js +43 -0
- package/dist/interactivity.d.ts +71 -0
- package/dist/interactivity.js +4 -0
- package/dist/key-cursor.d.ts +23 -0
- package/dist/keyframes-YpidiYS4.js +4 -0
- package/dist/keyframes.d.ts +204 -0
- package/dist/lod.d.ts +87 -0
- package/dist/lod.js +4 -0
- package/dist/material-animation.d.ts +29 -0
- package/dist/mixer.d.ts +226 -0
- package/dist/mixer.js +4 -0
- package/dist/morph-gpu.d.ts +94 -0
- package/dist/morph-gpu.js +50 -0
- package/dist/morph-table.d.ts +29 -0
- package/dist/playback.d.ts +94 -0
- package/dist/playback.js +4 -0
- package/dist/point-cache.d.ts +28 -0
- package/dist/point-cache.js +1 -0
- package/dist/pointer-DyWpFsQi.js +1 -0
- package/dist/pointer.d.ts +43 -0
- package/dist/pointer.js +1 -0
- package/dist/pose-source-MuCl8VDd.js +1 -0
- package/dist/pose.d.ts +12 -0
- package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
- package/dist/retarget.d.ts +115 -0
- package/dist/rigid.d.ts +42 -0
- package/dist/sampling-DjDWYqt2.js +1 -0
- package/dist/sampling.d.ts +112 -0
- package/dist/sampling.js +1 -0
- package/dist/shader-DuGkHFKx.js +73 -0
- package/dist/shader.d.ts +62 -0
- package/dist/skeleton-utils.d.ts +2 -0
- package/dist/skeleton-utils.js +4 -0
- package/dist/skin.d.ts +163 -0
- package/dist/src-fuuIJ3rU.js +4 -0
- package/dist/vat-SpfL7y9U.js +53 -0
- package/dist/vat.d.ts +194 -0
- package/dist/vat.js +1 -0
- package/dist/vertex-map-BC_WH7ER.js +1 -0
- package/dist/weight-buffer.d.ts +1 -0
- package/package.json +139 -4
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** How a keyframe track blends between keys, as in glTF 2.0: `STEP` holds the previous key, `LINEAR` interpolates (slerp for rotations), `CUBICSPLINE` uses in/out tangents (three values per key). */
|
|
2
|
+
export type Interpolation = 'STEP' | 'LINEAR' | 'CUBICSPLINE';
|
|
3
|
+
/**
|
|
4
|
+
* Samples one keyframe track at `time` and returns the result (allocating `width` numbers unless `target` is given). Checks its arguments and throws on bad ones; use {@link sampleTrackInto} in a hot loop.
|
|
5
|
+
*
|
|
6
|
+
* `times` is increasing seconds; `values` holds `width` numbers per key (three times that for `CUBICSPLINE`). Set `quaternion` for rotation tracks so the result is normalised. Time outside the track clamps to the first or last key.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* const times = new Float32Array([0, 1]);
|
|
11
|
+
* const values = new Float32Array([0, 0, 0, 10, 0, 0]);
|
|
12
|
+
* sampleTrack(times, values, 3, 0.5, 'LINEAR'); // Float32Array [5, 0, 0]
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export declare function sampleTrack(times: Float32Array, values: Float32Array, width: number, time: number, interpolation: Interpolation, quaternion?: boolean, target?: Float32Array): Float32Array;
|
|
16
|
+
/** Same as {@link sampleTrack} without the argument checks on `times`, `values` and `target`: pass a preallocated `out` of `width` numbers to avoid allocating. Defaults: `quaternion` false. */
|
|
17
|
+
export declare function sampleTrackInto(times: Float32Array, values: Float32Array, width: number, time: number, interpolation: Interpolation, quaternion?: boolean, out?: Float32Array): Float32Array;
|
|
18
|
+
/** A named moment in a clip, in seconds from its start. */
|
|
19
|
+
export interface ClipMarker {
|
|
20
|
+
/** Seconds, finite and >= 0. */
|
|
21
|
+
time: number;
|
|
22
|
+
/** What happened, for example `'footstep'`; nonempty. */
|
|
23
|
+
name: string;
|
|
24
|
+
/** Anything the caller wants handed back with the marker. */
|
|
25
|
+
data?: unknown;
|
|
26
|
+
}
|
|
27
|
+
/** Checks markers and returns a frozen copy sorted by time (stable for equal times). Throws TypeError or RangeError naming the fix. */
|
|
28
|
+
export declare function validateMarkers(markers: readonly ClipMarker[]): readonly ClipMarker[];
|
|
29
|
+
/**
|
|
30
|
+
* Tracks a play position through a clip and reports the markers it passes. A marker at time m is passed once the
|
|
31
|
+
* position is at or beyond m, so moving forward from a to b reports markers in (a, b], moving back reports (b, a], and
|
|
32
|
+
* going forward then back over the same stretch reports each marker once each way. The first forward move also reports
|
|
33
|
+
* markers at the start position. With `loop`, markers repeat every `duration` seconds, a step longer than the clip
|
|
34
|
+
* reports every lap, and `time` wraps; without it, the position clamps to 0 and `duration`.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* const steps = new ClipMarkers([{time: 0.25, name: 'footstep'}, {time: 0.75, name: 'footstep'}], 1);
|
|
39
|
+
* steps.advance(0.5).map((m) => m.time); // [0.25]
|
|
40
|
+
* steps.advance(0.5).map((m) => m.time); // [0.75]
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export declare class ClipMarkers {
|
|
44
|
+
readonly markers: readonly ClipMarker[];
|
|
45
|
+
/** Clip length in seconds. */
|
|
46
|
+
readonly duration: number;
|
|
47
|
+
private readonly loop;
|
|
48
|
+
private at;
|
|
49
|
+
private fresh;
|
|
50
|
+
/** `markers` are checked and sorted (see {@link validateMarkers}); `duration` is seconds > 0; `loop` defaults to true. */
|
|
51
|
+
constructor(markers: readonly ClipMarker[], duration: number, loop?: boolean);
|
|
52
|
+
/** Position in seconds inside the clip (wrapped when looping). */
|
|
53
|
+
get time(): number;
|
|
54
|
+
/** Moves by `delta` seconds (negative plays backward) and returns the markers passed, in order of travel. `out` is cleared and reused when given. */
|
|
55
|
+
advance(delta: number, out?: ClipMarker[]): ClipMarker[];
|
|
56
|
+
/** Jumps to `time` seconds (finite, >= 0). Returns the markers between the old and new position when `fire` is true, none by default. */
|
|
57
|
+
seek(time: number, fire?: boolean, out?: ClipMarker[]): ClipMarker[];
|
|
58
|
+
private move;
|
|
59
|
+
}
|
|
60
|
+
/** One keyframe track as plain arrays, the shape {@link sampleTrack} takes. */
|
|
61
|
+
export interface TrackData {
|
|
62
|
+
times: Float32Array;
|
|
63
|
+
/** `width` numbers per key. */
|
|
64
|
+
values: Float32Array;
|
|
65
|
+
width: number;
|
|
66
|
+
/** `'LINEAR'` or `'STEP'`; CUBICSPLINE tracks are not compressed. */
|
|
67
|
+
interpolation: 'STEP' | 'LINEAR';
|
|
68
|
+
/** Set for rotation tracks (width 4): both sides are normalised and compared along the shortest path. */
|
|
69
|
+
quaternion?: boolean;
|
|
70
|
+
}
|
|
71
|
+
/** What {@link compressTrack} returns. */
|
|
72
|
+
export interface CompressedTrack extends TrackData {
|
|
73
|
+
/** The largest component difference, over every original key time, between the original and the reduced track's sample. Never above `tolerance`. */
|
|
74
|
+
error: number;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Removes keys a track does not need. Every original key time still samples to within `tolerance` (value units, per
|
|
78
|
+
* component; rotations compare normalised quaternion components) of the original, and `error` reports the real maximum.
|
|
79
|
+
* The first and last keys stay. Linear tracks keep the keys that bend the curve (Douglas-Peucker on the sampled values);
|
|
80
|
+
* step tracks drop keys within `tolerance` of the key held before them. Sampling the result is the same call as before.
|
|
81
|
+
* Use 0 to remove only exact repeats.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```ts
|
|
85
|
+
* const times = new Float32Array([0, 1, 2]), values = new Float32Array([0, 5, 10]);
|
|
86
|
+
* compressTrack({times, values, width: 1, interpolation: 'LINEAR'}, 0.001).times; // Float32Array [0, 2]
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export declare function compressTrack(track: TrackData, tolerance: number): CompressedTrack;
|
|
90
|
+
/** A track with its values as 16-bit integers: component c of a key is `min[c] + data[i] * step[c]`. */
|
|
91
|
+
export interface QuantizedTrack extends Omit<TrackData, 'values'> {
|
|
92
|
+
data: Uint16Array;
|
|
93
|
+
/** Per component: the smallest value in the track. */
|
|
94
|
+
min: Float32Array;
|
|
95
|
+
/** Per component: (largest - smallest) / 65535, 0 for a constant component. */
|
|
96
|
+
step: Float32Array;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Stores a track's values as 16-bit integers between each component's smallest and largest value: half the bytes of
|
|
100
|
+
* Float32 values, and no component is off by more than half a `step` (range / 131070) plus Float32 rounding. Times stay
|
|
101
|
+
* Float32. Undo with {@link dequantizeTrack}.
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```ts
|
|
105
|
+
* const times = new Float32Array([0, 1]), values = new Float32Array([-1, 3]);
|
|
106
|
+
* const q = quantizeTrack({times, values, width: 1, interpolation: 'LINEAR'}); // q.data Uint16Array [0, 65535]
|
|
107
|
+
* dequantizeTrack(q).values; // Float32Array [-1, 3]
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export declare function quantizeTrack(track: TrackData): QuantizedTrack;
|
|
111
|
+
/** Rebuilds the Float32 track from a {@link QuantizedTrack}. */
|
|
112
|
+
export declare function dequantizeTrack(q: QuantizedTrack): TrackData;
|
package/dist/sampling.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{t as ClipMarkers,n as compressTrack,r as dequantizeTrack,i as quantizeTrack,a as sampleTrack,o as sampleTrackInto,s as validateMarkers}from"./sampling-DjDWYqt2.js";
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
var e=`
|
|
2
|
+
struct Vertex {position:vec4f,normal:vec4f,tangent:vec4f,uv:vec4f,color:vec4f}
|
|
3
|
+
struct Morph {position:vec4f,normal:vec4f,tangent:vec4f}
|
|
4
|
+
struct Influence {joints:vec4u,weights:vec4f}
|
|
5
|
+
@group(0) @binding(0) var<storage,read> source:array<Vertex>;
|
|
6
|
+
@group(0) @binding(1) var<storage,read_write> output:array<Vertex>;
|
|
7
|
+
@group(0) @binding(2) var<storage,read> morphs:array<Morph>;
|
|
8
|
+
@group(0) @binding(3) var<storage,read> weights:array<f32>;
|
|
9
|
+
@group(0) @binding(4) var<storage,read> boneMatrices:array<mat4x4f>;
|
|
10
|
+
@group(0) @binding(5) var<storage,read> influences:array<Influence>;
|
|
11
|
+
@group(0) @binding(6) var<uniform> counts:vec4u;
|
|
12
|
+
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
13
|
+
if(id.x>=counts.x){return;}
|
|
14
|
+
var v=source[id.x];
|
|
15
|
+
for(var morphIndex=0u;morphIndex<counts.y;morphIndex++) {
|
|
16
|
+
let m=morphs[morphIndex*counts.x+id.x];let w=weights[morphIndex];
|
|
17
|
+
v.position+=vec4f(m.position.xyz*w,0);v.normal+=vec4f(m.normal.xyz*w,0);v.tangent+=vec4f(m.tangent.xyz*w,0);
|
|
18
|
+
}
|
|
19
|
+
if(counts.z>0u) {
|
|
20
|
+
let inf=influences[id.x];
|
|
21
|
+
let skin=boneMatrices[inf.joints.x]*inf.weights.x+boneMatrices[inf.joints.y]*inf.weights.y+boneMatrices[inf.joints.z]*inf.weights.z+boneMatrices[inf.joints.w]*inf.weights.w;
|
|
22
|
+
v.position=skin*vec4f(v.position.xyz,1);
|
|
23
|
+
let normalMatrix=mat3x3f(cross(skin[1].xyz,skin[2].xyz),cross(skin[2].xyz,skin[0].xyz),cross(skin[0].xyz,skin[1].xyz));
|
|
24
|
+
let handedness=select(-1.0,1.0,dot(skin[0].xyz,cross(skin[1].xyz,skin[2].xyz))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;
|
|
25
|
+
v.normal=vec4f(select(vec3f(0,1,0),bent,dot(bent,bent)>0.0),0);
|
|
26
|
+
v.tangent=vec4f((skin*vec4f(v.tangent.xyz,0)).xyz,v.tangent.w*handedness);
|
|
27
|
+
}
|
|
28
|
+
v.normal=vec4f(normalize(v.normal.xyz),0);output[id.x]=v;
|
|
29
|
+
}
|
|
30
|
+
`,t=e.slice(e.indexOf(` let skin=`),e.indexOf(`
|
|
31
|
+
}
|
|
32
|
+
v.normal=vec4f(normalize`)),n=(e,t,n)=>`if(all(${e}==vec4f(0))){\n${t}\n }else{\n${n}\n }`;e.replace(`struct Influence {joints:vec4u,weights:vec4f}`,`struct Influence {joints:vec4u,weights:vec4f,jointsExtra:vec4u,weightsExtra:vec4f}`).replace(t,n(`inf.weightsExtra`,t,t.replace(`boneMatrices[inf.joints.w]*inf.weights.w;`,`boneMatrices[inf.joints.w]*inf.weights.w+boneMatrices[inf.jointsExtra.x]*inf.weightsExtra.x+boneMatrices[inf.jointsExtra.y]*inf.weightsExtra.y+boneMatrices[inf.jointsExtra.z]*inf.weightsExtra.z+boneMatrices[inf.jointsExtra.w]*inf.weightsExtra.w;`)));var r=e=>`let skin=boneMatrices[s.bones+joints.x]*jointWeights.x+boneMatrices[s.bones+joints.y]*jointWeights.y+boneMatrices[s.bones+joints.z]*jointWeights.z+boneMatrices[s.bones+joints.w]*jointWeights.w${e?`+boneMatrices[s.bones+jointsExtra.x]*weightsExtra.x+boneMatrices[s.bones+jointsExtra.y]*weightsExtra.y+boneMatrices[s.bones+jointsExtra.z]*weightsExtra.z+boneMatrices[s.bones+jointsExtra.w]*weightsExtra.w`:``};
|
|
33
|
+
v.position=skin*vec4f(v.position.xyz,1);
|
|
34
|
+
let normalMatrix=mat3x3f(cross(skin[1].xyz,skin[2].xyz),cross(skin[2].xyz,skin[0].xyz),cross(skin[0].xyz,skin[1].xyz));
|
|
35
|
+
let handedness=select(-1.0,1.0,dot(skin[0].xyz,cross(skin[1].xyz,skin[2].xyz))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;
|
|
36
|
+
v.normal=vec4f(select(vec3f(0,1,0),bent,dot(bent,bent)>0.0),0);
|
|
37
|
+
v.tangent=vec4f((skin*vec4f(v.tangent.xyz,0)).xyz,v.tangent.w*handedness);`,i=e=>e?n(`weightsExtra`,r(!1),r(!0)):r(!1);function a(e,t={functions:``,blend:i(e)},n=!1){return`
|
|
38
|
+
struct Vertex {position:vec4f,normal:vec4f,tangent:vec4f,uv:vec4f,color:vec4f}
|
|
39
|
+
struct Slot {source:u32,output:u32,count:u32,targets:u32,morphs:u32,weights:u32,bones:u32,joints:u32,influences:u32,entry:u32,pad1:u32,pad2:u32}
|
|
40
|
+
@group(0) @binding(0) var<storage,read> source:array<Vertex>;
|
|
41
|
+
@group(0) @binding(1) var<storage,read_write> output:array<Vertex>;
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@group(0) @binding(2) var<storage,read> morphs:array<vec4u>;
|
|
45
|
+
@group(0) @binding(3) var<storage,read> weights:array<f32>;
|
|
46
|
+
@group(0) @binding(4) var<storage,read> boneMatrices:array<mat4x4f>;
|
|
47
|
+
@group(0) @binding(5) var<storage,read> influences:array<vec4u>;
|
|
48
|
+
@group(0) @binding(6) var<storage,read> slots:array<Slot>;
|
|
49
|
+
@group(0) @binding(7) var<storage,read> work:array<vec2u>;
|
|
50
|
+
${t.functions}
|
|
51
|
+
@compute @workgroup_size(64) fn main(@builtin(workgroup_id) group:vec3u,@builtin(num_workgroups) groups:vec3u,@builtin(local_invocation_index) lane:u32) {
|
|
52
|
+
let item=group.y*groups.x+group.x;
|
|
53
|
+
if(item>=work[0].x){return;}
|
|
54
|
+
let entry=work[item+1u];let s=slots[entry.x];let i=entry.y+lane;
|
|
55
|
+
if(i>=s.count){return;}
|
|
56
|
+
var v=source[s.source+i];
|
|
57
|
+
if(s.targets>0u) {
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
let entries=s.morphs+(s.count+4u)/4u;let first=morphs[s.morphs+i/4u][i%4u];let end=morphs[s.morphs+(i+1u)/4u][(i+1u)%4u];
|
|
61
|
+
for(var e=first;e<end;e++) {
|
|
62
|
+
let at=entries+e*s.entry;let p=morphs[at];let w=weights[s.weights+p.w];
|
|
63
|
+
v.position+=vec4f(bitcast<vec3f>(p.xyz)*w,0);v.normal+=vec4f(bitcast<vec3f>(morphs[at+1u].xyz)*w,0);
|
|
64
|
+
if(s.entry>2u){v.tangent+=vec4f(bitcast<vec3f>(morphs[at+2u].xyz)*w,0);}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if(s.joints>0u) {
|
|
68
|
+
let at=s.influences+i*${(e?4:2)+ +!!n}u;let joints=influences[at];let jointWeights=bitcast<vec4f>(influences[at+1u]);${e?`let jointsExtra=influences[at+2u];let weightsExtra=bitcast<vec4f>(influences[at+3u]);`:``}${n?`let vertexData=bitcast<vec4f>(influences[at+${e?4:2}u]);`:``}
|
|
69
|
+
${t.blend}
|
|
70
|
+
}
|
|
71
|
+
v.normal=vec4f(normalize(v.normal.xyz),0);output[s.output+i]=v;
|
|
72
|
+
}
|
|
73
|
+
`}export{e as n,a as t};
|
package/dist/shader.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
export declare const deformationShader = "\nstruct Vertex {position:vec4f,normal:vec4f,tangent:vec4f,uv:vec4f,color:vec4f}\nstruct Morph {position:vec4f,normal:vec4f,tangent:vec4f}\nstruct Influence {joints:vec4u,weights:vec4f}\n@group(0) @binding(0) var<storage,read> source:array<Vertex>;\n@group(0) @binding(1) var<storage,read_write> output:array<Vertex>;\n@group(0) @binding(2) var<storage,read> morphs:array<Morph>;\n@group(0) @binding(3) var<storage,read> weights:array<f32>;\n@group(0) @binding(4) var<storage,read> boneMatrices:array<mat4x4f>;\n@group(0) @binding(5) var<storage,read> influences:array<Influence>;\n@group(0) @binding(6) var<uniform> counts:vec4u;\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u) {\n if(id.x>=counts.x){return;}\n var v=source[id.x];\n for(var morphIndex=0u;morphIndex<counts.y;morphIndex++) {\n let m=morphs[morphIndex*counts.x+id.x];let w=weights[morphIndex];\n v.position+=vec4f(m.position.xyz*w,0);v.normal+=vec4f(m.normal.xyz*w,0);v.tangent+=vec4f(m.tangent.xyz*w,0);\n }\n if(counts.z>0u) {\n let inf=influences[id.x];\n let skin=boneMatrices[inf.joints.x]*inf.weights.x+boneMatrices[inf.joints.y]*inf.weights.y+boneMatrices[inf.joints.z]*inf.weights.z+boneMatrices[inf.joints.w]*inf.weights.w;\n v.position=skin*vec4f(v.position.xyz,1);\n let normalMatrix=mat3x3f(cross(skin[1].xyz,skin[2].xyz),cross(skin[2].xyz,skin[0].xyz),cross(skin[0].xyz,skin[1].xyz));\n let handedness=select(-1.0,1.0,dot(skin[0].xyz,cross(skin[1].xyz,skin[2].xyz))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;\n v.normal=vec4f(select(vec3f(0,1,0),bent,dot(bent,bent)>0.0),0);\n v.tangent=vec4f((skin*vec4f(v.tangent.xyz,0)).xyz,v.tangent.w*handedness);\n }\n v.normal=vec4f(normalize(v.normal.xyz),0);output[id.x]=v;\n}\n";
|
|
2
|
+
/** The four-influence shader and its 32-byte storage stride remain unchanged. */
|
|
3
|
+
export declare const deformationShader8: string;
|
|
4
|
+
/** Another way to blend bones: `Animation`'s `skinning` option. `@margoengine/animation/dqs` holds the one Margo ships. */
|
|
5
|
+
export interface SkinningMode {
|
|
6
|
+
/** Names the mode in the arena's pipeline table and in errors. */
|
|
7
|
+
readonly name: string;
|
|
8
|
+
/** The batched compute shader, four influences or (`extra`) eight. */
|
|
9
|
+
shader(extra: boolean): string;
|
|
10
|
+
/** Rewrites a bone palette in place, 16 floats per bone, into what the shader reads. Runs after the palette is checked. */
|
|
11
|
+
encode(palette: Float32Array): void;
|
|
12
|
+
/**
|
|
13
|
+
* A share in [0, 1] for each vertex of a node's file primitive, read from the node's glTF `extras`. `Animation`
|
|
14
|
+
* packs it into the upper 16 bits of each vertex's first joint index, so only a mode that masks the index reads it.
|
|
15
|
+
*/
|
|
16
|
+
share?(extras: unknown): ArrayLike<number> | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* The mode's blend on the CPU: where one vertex goes, the shader's steps in double precision. `palette` is the
|
|
19
|
+
* encoded palette (after `encode`), `joints` and `weights` the vertex's influences in the shader's order (weights
|
|
20
|
+
* summing to 1), `position` and `normal` its bind values after the morph targets, and `share` its share from
|
|
21
|
+
* {@link SkinningMode.share} (1 for a mode without one, or a node without shares). Returns the position and the unit
|
|
22
|
+
* normal. `Animation` poses synchronous queries (`@margoengine/bvh` raycasts) with it; a mode without it has no CPU
|
|
23
|
+
* pose, so those queries throw MargoError `unsupported` rather than test the bind pose.
|
|
24
|
+
*/
|
|
25
|
+
blend?(palette: Float32Array, joints: ArrayLike<number>, weights: ArrayLike<number>, position: ArrayLike<number>, normal: ArrayLike<number>, share: number, data?: ArrayLike<number>): {
|
|
26
|
+
position: ArrayLike<number>;
|
|
27
|
+
normal: ArrayLike<number>;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Four numbers per vertex the mode's shader reads as `vertexData` (and `blend` as `data`), made once per skinned mesh
|
|
31
|
+
* from all of its primitives in the file's bind pose: one array of `4 * vertices` numbers per part, in order.
|
|
32
|
+
* `Animation` keeps them per mode, asset and mesh, so copies and clones of a model make them once.
|
|
33
|
+
*/
|
|
34
|
+
vertexData?(parts: readonly SkinMeshPart[]): Float32Array[];
|
|
35
|
+
}
|
|
36
|
+
/** One primitive of a skinned mesh as the file has it, for {@link SkinningMode.vertexData}. */
|
|
37
|
+
export interface SkinMeshPart {
|
|
38
|
+
/** Bind-pose positions, three numbers per vertex. */
|
|
39
|
+
readonly positions: ArrayLike<number>;
|
|
40
|
+
/** Triangle corners (three per triangle), or null for a primitive that draws no triangles. */
|
|
41
|
+
readonly triangles: ArrayLike<number> | null;
|
|
42
|
+
/** Joint indices into the skin's joints, `influences` per vertex. */
|
|
43
|
+
readonly joints: ArrayLike<number>;
|
|
44
|
+
/** Weights parallel to `joints`. */
|
|
45
|
+
readonly weights: ArrayLike<number>;
|
|
46
|
+
/** Influences per vertex: 4, or 8 with JOINTS_1. */
|
|
47
|
+
readonly influences: number;
|
|
48
|
+
}
|
|
49
|
+
/** Text a skinning mode puts into the batched shader: module-scope `functions`, and the `blend` that moves `v`. */
|
|
50
|
+
export interface SkinningShader {
|
|
51
|
+
functions: string;
|
|
52
|
+
blend: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Batched deformation (batch.ts): many primitives in one dispatch. Each workgroup deforms 64 vertices of one slot,
|
|
56
|
+
* named by the work list (`work[0].x` workgroups, then a slot index and first vertex per workgroup); each slot record
|
|
57
|
+
* gives where its vertices, deltas, weights, bones and influences start in the shared buffers. The per-vertex
|
|
58
|
+
* arithmetic is the per-primitive shader's, term for term, so the output is the same bits. `extra`: eight influences.
|
|
59
|
+
* `skin` replaces that arithmetic for a skinning mode. `data`: each vertex's influences end with one more vec4, the
|
|
60
|
+
* mode's `vertexData`, which the blend reads as `vertexData`.
|
|
61
|
+
*/
|
|
62
|
+
export declare function batchedDeformationShader(extra: boolean, skin?: SkinningShader, data?: boolean): string;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{a as e,i as t,s as n}from"./keyframes-YpidiYS4.js";import{MargoError as r}from"@margoengine/math/errors";import{normalizeQuaternion as i}from"@margoengine/math/quat";import{PBRModel as a,closeImages as o}from"@margoengine/gltf/pbr-model";var s=0,c=(e,t)=>{let n=t+s++;for(;e.plugins?.has(n);)n+=`:`;return n};function l(e,t){return{scene:t,run(n){if(!t)return n();let r,i={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:c(e,`scene-scope:`),setup(){r=n()}};return t.use(i),t.removePlugin(i.name),r}}}var u=[0,0,0,1];async function d(e){if(!(e instanceof a))throw TypeError(`cloneModel needs a glTF PBR PBRModel; pass a loaded model`);if(e.disposed)throw new r(`disposed`,`cloneModel source is disposed; clone a live model`);let t=e.shareImages(),n=e.asset.doc,i=e.root.engine,s;if(!n.buffers?.length){let t=/* @__PURE__ */ new Map;for(let n of[...e.primitives,...e.pointsAndLines])t.set(n.definition,n.topology?{vertices:n.vertices,indices:n.indices,topology:n.topology}:n);s=(n.meshes??[]).map(e=>(e.primitives??[]).map(e=>t.get(e)))}let c=l(i,i.sceneOf(e)),d=c.run(()=>{let n;try{n=new a(i,e.asset,t,s);let r=i.store.transforms,o=(e,t)=>{let n=e.id,i=r.x[n],a=r.y[n],o=r.z[n],s=r.sx[n],c=r.sy[n],l=r.sz[n];Number.isFinite(i+a+o)?t.position.set(i,a,o):t.setPosition([i,a,o]),Number.isFinite(s+c+l)?t.scale.set(s,c,l):t.setScale([s,c,l]),u[0]=r.qx[n],u[1]=r.qy[n],u[2]=r.qz[n],u[3]=r.qw[n],t.setQuaternion(u),t.visible=e.visible};return o(e.root,n.root),e.nodes.forEach((e,t)=>o(e,n.nodes[t])),e.primitives.forEach((e,t)=>n.primitives[t]?.weights.set(e.weights)),n.adoptStaticBatches(e),i.plugins.get(e.name)===e&&i.use(n),n}catch(e){throw n?n.dispose():o(t),e}});try{await c.run(()=>d.attachStrokes())}catch(e){throw d.dispose(),e}return d}var f=[0,0,0,0],p=e=>({rotation:new Float64Array(e.names.length*4),position:new Float64Array(e.names.length*3),scale:new Float64Array(e.names.length*3)});function m(e,t){let{names:n,parents:r,rest:i}=e??{},a=n?.length;if(!Array.isArray(n)||!Array.isArray(r)||r.length!==a||!(i instanceof Float64Array))throw TypeError(`Retarget ${t} needs a rig with names, parents and rest; make it with retargetRig`);if(i.length!==a*10||!i.every(Number.isFinite))throw RangeError(`Retarget ${t} rest pose needs 10 finite numbers per bone`);let o=r.map(()=>[]),s=[];r.forEach((e,n)=>{if(!Number.isInteger(e)||e<-1||e>=a||e===n)throw RangeError(`Retarget ${t} bone ${n} parent ${e} is invalid; use -1 or another bone's index`);e>=0&&o[e].push(n)});for(let e=r.flatMap((e,t)=>e<0?[t]:[]);e.length;){let t=e.pop();s.push(t),e.push(...o[t])}if(s.length!==a)throw RangeError(`Retarget ${t} parents form a cycle; every chain must reach a top bone`);return s}function h(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];e[t]=l*u+o*p+s*f-c*d,e[t+1]=l*d-o*f+s*p+c*u,e[t+2]=l*f+o*d-s*u+c*p,e[t+3]=l*p-o*u-s*d-c*f}function g(e,t,n,r,i,a){let o=-n[r],s=-n[r+1],c=-n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];e[t]=l*u+o*p+s*f-c*d,e[t+1]=l*d-o*f+s*p+c*u,e[t+2]=l*f+o*d-s*u+c*p,e[t+3]=l*p-o*u-s*d-c*f}function _(e,t,n,r,i,a,o,s=!1){let c=s?-1:1,l=n[r]*c,u=n[r+1]*c,d=n[r+2]*c,f=n[r+3],p=2*(u*o-d*a),m=2*(d*i-l*o),h=2*(l*a-u*i);e[t]=i+f*p+u*h-d*m,e[t+1]=a+f*m+d*p-l*h,e[t+2]=o+f*h+l*m-u*p}function v(e,t,n,r,i,a){for(let o=0;o<e.length;o++){let s=e[o],c=t[s],l=s*10;if(c<0){for(let e=0;e<3;e++)i[s*3+e]=n[l+e],a[s*3+e]=n[l+7+e];for(let e=0;e<4;e++)r[s*4+e]=n[l+3+e]}else{h(r,s*4,r,c*4,n,l+3),_(i,s*3,r,c*4,a[c*3]*n[l],a[c*3+1]*n[l+1],a[c*3+2]*n[l+2]);for(let e=0;e<3;e++)i[s*3+e]+=i[c*3+e],a[s*3+e]=a[c*3+e]*n[l+7+e]}}}function y(e,t,r,i){if(e instanceof n){if(e.count!==t)throw RangeError(`Retarget ${r} has ${e.count} bones but its rig has ${t}; use a source with the rig's bone count`);for(let n=0;n<t;n++){let{translation:t,rotation:r,scale:a}=e.getPose(n);i.set(t,n*10),i.set(r,n*10+3),i.set(a,n*10+7)}return}if(!(e instanceof a))throw TypeError(`Retarget ${r} must be a Skeleton or a glTF PBR model`);if(e.nodes.length!==t)throw RangeError(`Retarget ${r} has ${e.nodes.length} nodes but its rig ${t}; use its own rig`);let o=e.root.engine.store.transforms;for(let n=0;n<t;n++){let t=e.nodes[n].id,r=n*10;i[r]=o.x[t],i[r+1]=o.y[t],i[r+2]=o.z[t],i[r+3]=o.qx[t],i[r+4]=o.qy[t],i[r+5]=o.qz[t],i[r+6]=o.qw[t],i[r+7]=o.sx[t],i[r+8]=o.sy[t],i[r+9]=o.sz[t]}}function b(e){if(e instanceof n){let t=new Float64Array(e.count*10);return y(e,e.count,`skeleton`,t),{names:e.names,parents:e.parents,rest:t}}if(!(e instanceof a))throw TypeError(`retargetRig needs a Skeleton or a glTF PBR model`);let t=new Map(e.nodes.map((e,t)=>[e.id,t])),r=e.root.engine.store.parents,i=new Float64Array(e.nodes.length*10);return y(e,e.nodes.length,`model`,i),{names:e.nodes.map(e=>e.name),parents:e.nodes.map(e=>t.get(r[e.id])??-1),rest:i}}var x=class{constructor(e,t,n={}){this.source=e,this.target=t,this.delta=/* @__PURE__ */ new Float64Array(4),this.quaternion=[0,0,0,1],this.vector=[0,0,0],this.sourceOrder=m(e,`source`),this.targetOrder=m(t,`target`);let r=n.names??{};if(typeof r!=`object`)throw TypeError(`Retarget names must map target bone names to source bone names`);for(let[t,n]of Object.entries(r))if(typeof n!=`string`||n&&!e.names.includes(n))throw RangeError(`Retarget maps ${t} to ${n}, which the source does not have; fix the names map`);let i=e=>Object.hasOwn(r,e)?r[e]:e;if(this.map=Int32Array.from(t.names,t=>i(t)?e.names.indexOf(i(t)):-1),!this.map.some(e=>e>=0))throw RangeError(`Retarget maps no bones; pass a names map or use rigs with matching bone names`);let a=n.hold??[];if(!Array.isArray(a))throw TypeError(`Retarget hold must be an array of target bone names`);this.held=new Uint8Array(t.names.length);for(let e of a){let n=typeof e==`string`?t.names.indexOf(e):-1;if(n<0)throw RangeError(`Retarget holds ${String(e)}, which the target does not have; fix the hold list`);this.map[n]<0&&(this.held[n]=1)}this.sourceNow=p(e),this.targetNow=p(t);let o=this.sourceRest=p(e),s=this.targetRest=p(t);if(v(this.sourceOrder,e.parents,e.rest,o.rotation,o.position,o.scale),v(this.targetOrder,t.parents,t.rest,s.rotation,s.position,s.scale),this.hip=n.hip===void 0?-1:t.names.indexOf(n.hip),n.hip!==void 0&&this.hip<0)throw RangeError(`Retarget hip ${n.hip} is not a target bone; pass the target's hip bone name`);if(this.sourceHip=this.hip<0?-1:this.map[this.hip],this.hip>=0&&this.sourceHip<0)throw RangeError(`Retarget hip ${n.hip} has no source bone; map it in names`);let c=this.sourceHip<0?0:o.position[this.sourceHip*3+1],l=this.hip<0?0:s.position[this.hip*3+1],u=n.hipScale??(c>0&&l>0?l/c:1);if(typeof u!=`number`||!Number.isFinite(u)||u<=0)throw RangeError(`Retarget hipScale ${u} is invalid; pass a finite number > 0`);this.hipScale=u,this.input=new Float64Array(e.names.length*10),this.output=new Float64Array(t.names.length*10),this.poses=t.names.map((e,t)=>({rotation:this.output.subarray(t*10+3,t*10+7),...t===this.hip?{translation:this.output.subarray(t*10,t*10+3)}:{}}))}pose(e,t=new Float64Array(this.target.names.length*10)){if(!(e instanceof Float64Array)||e.length!==this.source.names.length*10)throw TypeError(`Retarget pose needs a Float64Array of ${this.source.names.length*10} numbers`);if(!(t instanceof Float64Array)||t.length!==this.target.names.length*10)throw TypeError(`Retarget output needs a Float64Array of ${this.target.names.length*10} numbers`);let n=this.sourceNow,r=this.targetNow,{parents:a,rest:o}=this.target,s=this.delta;v(this.sourceOrder,this.source.parents,e,n.rotation,n.position,n.scale),t.set(o);for(let e=0;e<this.targetOrder.length;e++){let o=this.targetOrder[e],c=a[o],l=this.map[o],u=o*10;if(l>=0){if(g(s,0,this.sourceRest.rotation,l*4,this.targetRest.rotation,o*4),h(r.rotation,o*4,n.rotation,l*4,s,0),c<0)for(let e=0;e<4;e++)t[u+3+e]=r.rotation[o*4+e];else g(t,u+3,r.rotation,c*4,r.rotation,o*4);for(let e=0;e<4;e++)f[e]=t[u+3+e];t.set(i(f,f),u+3)}if(o===this.hip){let e=this.hipScale,i=this.sourceHip*3,a=this.targetRest.position[o*3]+e*(n.position[i]-this.sourceRest.position[i]),s=this.targetRest.position[o*3+1]+e*(n.position[i+1]-this.sourceRest.position[i+1]),l=this.targetRest.position[o*3+2]+e*(n.position[i+2]-this.sourceRest.position[i+2]);if(c<0)t[u]=a,t[u+1]=s,t[u+2]=l;else{_(t,u,r.rotation,c*4,a-r.position[c*3],s-r.position[c*3+1],l-r.position[c*3+2],!0);for(let e=0;e<3;e++)t[u+e]/=r.scale[c*3+e]}}if(c<0){for(let e=0;e<3;e++)r.position[o*3+e]=t[u+e],r.scale[o*3+e]=t[u+7+e];for(let e=0;e<4;e++)r.rotation[o*4+e]=t[u+3+e]}else{h(r.rotation,o*4,r.rotation,c*4,t,u+3),_(r.position,o*3,r.rotation,c*4,r.scale[c*3]*t[u],r.scale[c*3+1]*t[u+1],r.scale[c*3+2]*t[u+2]);for(let e=0;e<3;e++)r.position[o*3+e]+=r.position[c*3+e],r.scale[o*3+e]=r.scale[c*3+e]*t[u+7+e]}}return t}apply(e,t){y(e,this.source.names.length,`source`,this.input);let r=this.pose(this.input,this.output);if(t instanceof n){if(t.count!==this.target.names.length)throw RangeError(`Retarget target has ${t.count} bones but its rig has ${this.target.names.length}; pass a target with the rig's bone count`);for(let e=0;e<this.map.length;e++)(this.map[e]>=0||this.held[e]||e===this.hip)&&t.setPose(e,this.poses[e]);return}if(!(t instanceof a))throw TypeError(`Retarget target must be a Skeleton or a glTF PBR model`);if(t.nodes.length!==this.target.names.length)throw RangeError(`Retarget target has ${t.nodes.length} nodes but its rig has ${this.target.names.length}; pass a model with the rig's node count`);let i=this.quaternion,o=this.vector;for(let e=0;e<this.map.length;e++){if(this.map[e]>=0||this.held[e]){for(let t=0;t<4;t++)i[t]=r[e*10+3+t];t.nodes[e].setQuaternion(i)}if(e===this.hip){for(let t=0;t<3;t++)o[t]=r[e*10+t];t.nodes[e].setPosition(o)}}}clip(n,{fps:r=30,name:i}={}){if(typeof r!=`number`||!Number.isFinite(r)||r<=0||r>1e3)throw RangeError(`Retarget clip fps ${r} is invalid; pass frames per second from 0 to 1000`);let o=this.input,s=this.source.names.length,c,l,u,d=()=>{};if(`tracks`in n&&Array.isArray(n.tracks)){let t=n,r=t.tracks.filter(e=>e.path!==`weights`&&this.source.names.includes(e.target)),i=r.map(e=>this.source.names.indexOf(e.target)*10),a=/* @__PURE__ */ new Float64Array(4);c=t.duration,l=t.name,u=t=>{o.set(this.source.rest),r.forEach((n,r)=>{let s=e(n,t,a),c=i[r]+(n.path===`translation`?0:n.path===`rotation`?3:7);for(let e=0;e<(n.path===`rotation`?4:3);e++)o[c+e]=s[e]})}}else{let{animation:e,clip:t}=n,r=e?.model;if(!(r instanceof a)||!Array.isArray(e.clips)||typeof e.seek!=`function`)throw TypeError(`Retarget clip needs a KeyframeClip or {animation, clip} with an Animation`);let i=typeof t==`string`?e.clips.findIndex(e=>e.name===t):t;if(!Number.isInteger(i)||i<0||i>=e.clips.length)throw RangeError(`Retarget clip ${t} is not one of the source model's clips; pass a name or index it has`);let f={clip:e.clip,time:e.time,playing:e.playing};c=e.clips[i].duration,l=e.clips[i].name,e.play(i),u=t=>{e.seek(t),y(r,s,`source`,o)},d=()=>{e.play(f.clip),e.seek(f.time),e.playing=f.playing}}let f=Math.max(1,Math.ceil(c*r)),p=Array.from(this.map.keys()).filter(e=>this.map[e]>=0||this.held[e]),m=p.map(()=>[]),h=[],g=this.output;try{for(let e=0;e<=f;e++){let t=c*e/f;if(u(t),this.pose(o,g),p.forEach((e,n)=>m[n].push({time:t,value:Array.from(g.subarray(e*10+3,e*10+7))})),this.hip>=0&&h.push({time:t,value:Array.from(g.subarray(this.hip*10,this.hip*10+3))}),c===0)break}}finally{d()}let _=p.map((e,t)=>({target:this.target.names[e],path:`rotation`,keys:m[t]}));this.hip>=0&&_.push({target:this.target.names[this.hip],path:`translation`,keys:h});let v=/* @__PURE__ */ new Set;for(let e of _)if(v.has(e.target+e.path))throw RangeError(`Retarget target rig repeats bone name ${e.target}; give target bones unique names`);else v.add(e.target+e.path);return t({name:i??l,tracks:_})}};export{x as Retarget,d as cloneModel,b as retargetRig};
|
package/dist/skin.d.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
3
|
+
import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
|
|
4
|
+
import type { Mat4, MutableVec3, Quat, Vec3 } from '@margoengine/math';
|
|
5
|
+
/** A bone's transform local to its parent bone; omitted parts keep their value (or the default, for a new bone). */
|
|
6
|
+
export interface BonePose {
|
|
7
|
+
/** Default [0, 0, 0]. */
|
|
8
|
+
translation?: Vec3;
|
|
9
|
+
/** Unit quaternion [x, y, z, w], normalised on input. Default [0, 0, 0, 1]. */
|
|
10
|
+
rotation?: Quat;
|
|
11
|
+
/** Default [1, 1, 1]. */
|
|
12
|
+
scale?: Vec3;
|
|
13
|
+
}
|
|
14
|
+
/** One bone of a {@link Skeleton}. Its translation, rotation and scale are the base (bind) pose. */
|
|
15
|
+
export interface BoneData extends BonePose {
|
|
16
|
+
/** Stable id that keyframe tracks target; unique in the skeleton. */
|
|
17
|
+
name: string;
|
|
18
|
+
/** Index of the parent bone, or -1 for the one root bone. */
|
|
19
|
+
parent: number;
|
|
20
|
+
}
|
|
21
|
+
/** @internal Checks `width` finite numbers (TypeError for the shape, RangeError for the values). */
|
|
22
|
+
export declare function finite(value: unknown, width: number, label: string): ArrayLike<number>;
|
|
23
|
+
/**
|
|
24
|
+
* A bone hierarchy authored from raw data: a base (bind) pose, a current pose set bone by bone, and the matrices a
|
|
25
|
+
* {@link Skin} deforms with. Matrices are in skeleton space, the local space of the skinned mesh the bones live under;
|
|
26
|
+
* they are recomputed lazily after a pose change. Bone length and thickness are display concerns and not stored.
|
|
27
|
+
*/
|
|
28
|
+
export declare class Skeleton {
|
|
29
|
+
/** Bone names in input order; a bone's index is its position here. */
|
|
30
|
+
readonly names: readonly string[];
|
|
31
|
+
/** Parent bone index per bone, -1 for the root. */
|
|
32
|
+
readonly parents: readonly number[];
|
|
33
|
+
/** Index of the root bone; vertices whose weights sum to zero follow it. */
|
|
34
|
+
readonly root: number;
|
|
35
|
+
/** Increments on every pose or bind-pose change, so consumers can skip unchanged uploads. */
|
|
36
|
+
revision: number;
|
|
37
|
+
private readonly pose;
|
|
38
|
+
private readonly base;
|
|
39
|
+
private readonly inverse;
|
|
40
|
+
private readonly world;
|
|
41
|
+
private readonly skin;
|
|
42
|
+
private readonly order;
|
|
43
|
+
private readonly byName;
|
|
44
|
+
private readonly local;
|
|
45
|
+
private readonly workspace;
|
|
46
|
+
private dirty;
|
|
47
|
+
/**
|
|
48
|
+
* @param bones The hierarchy and base pose; exactly one bone has parent -1.
|
|
49
|
+
* @param inverseBindMatrices Optional 16 column-major numbers per bone; computed from the base pose when omitted.
|
|
50
|
+
*/
|
|
51
|
+
constructor(bones: readonly BoneData[], inverseBindMatrices?: ArrayLike<number>);
|
|
52
|
+
/** Number of bones. */
|
|
53
|
+
get count(): number;
|
|
54
|
+
/** Index of the bone with this name, or -1. */
|
|
55
|
+
index(name: string): number;
|
|
56
|
+
private bone;
|
|
57
|
+
/** Sets any of a bone's local translation, rotation and scale in the current pose. */
|
|
58
|
+
setPose(bone: number, pose: BonePose): this;
|
|
59
|
+
/** A copy of a bone's current local transform. */
|
|
60
|
+
getPose(bone: number): {
|
|
61
|
+
translation: MutableVec3;
|
|
62
|
+
rotation: [number, number, number, number];
|
|
63
|
+
scale: MutableVec3;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Returns bones to the base pose: every bone when `bone` is omitted, else that bone alone (Restore Pose) or, with
|
|
67
|
+
* `nested`, that bone and all bones under it (Restore Pose All).
|
|
68
|
+
*/
|
|
69
|
+
restorePose(bone?: number, nested?: boolean): this;
|
|
70
|
+
/** Makes the current pose the base pose and recomputes every inverse bind matrix from it (the mesh stays put). */
|
|
71
|
+
setBindPose(): this;
|
|
72
|
+
private bind;
|
|
73
|
+
private changed;
|
|
74
|
+
private update;
|
|
75
|
+
/** Each bone's current skeleton-space matrix, 16 column-major numbers per bone. Read-only; refreshed on access. */
|
|
76
|
+
get matrices(): Float64Array;
|
|
77
|
+
/** Inverse bind matrices, 16 column-major numbers per bone (for export). Read-only. */
|
|
78
|
+
get inverseBindMatrices(): Float64Array;
|
|
79
|
+
/** `matrices` times `inverseBindMatrices` per bone: what moves a bind-pose vertex. Read-only; refreshed on access. */
|
|
80
|
+
get skinMatrices(): Float64Array;
|
|
81
|
+
/** `parent` (e.g. the skinned mesh's `primitives[0].node.matrix`) times the bone's matrix: its world matrix. */
|
|
82
|
+
worldMatrix(bone: number, parent?: Mat4, out?: Float32Array<ArrayBuffer>): Float32Array;
|
|
83
|
+
}
|
|
84
|
+
interface PosedSnapshot {
|
|
85
|
+
readonly node: PBRModel['root'];
|
|
86
|
+
readonly vertices: Float32Array;
|
|
87
|
+
readonly indices: Uint32Array;
|
|
88
|
+
readonly doubleSided: boolean;
|
|
89
|
+
readonly side: 'front' | 'back' | 'double';
|
|
90
|
+
readonly matrix: Float32Array;
|
|
91
|
+
readonly primitiveIndex: number;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Up to four bone influences per vertex over a {@link Skeleton}, deforming a `createMesh` mesh (or any gltf/pbr model
|
|
95
|
+
* whose primitives share one vertex array) on the GPU once attached. Weights are normalised to sum 1 as they are set;
|
|
96
|
+
* a vertex whose weights sum to zero follows the root bone.
|
|
97
|
+
*/
|
|
98
|
+
export declare class Skin implements EnginePlugin {
|
|
99
|
+
readonly skeleton: Skeleton;
|
|
100
|
+
readonly name: string;
|
|
101
|
+
/** Vertex count. */
|
|
102
|
+
readonly count: number;
|
|
103
|
+
/** The mesh it deforms, when made by `Skin.attach`. */
|
|
104
|
+
mesh?: PBRModel;
|
|
105
|
+
private readonly ids;
|
|
106
|
+
private readonly weights;
|
|
107
|
+
private edits;
|
|
108
|
+
private pickingSource?;
|
|
109
|
+
private posed?;
|
|
110
|
+
private dirtyFrom;
|
|
111
|
+
private dirtyTo;
|
|
112
|
+
private uploaded;
|
|
113
|
+
private disposed;
|
|
114
|
+
private gpu?;
|
|
115
|
+
private unsubscribe?;
|
|
116
|
+
private readonly prepare;
|
|
117
|
+
/** @param joints Four bone indices per vertex. @param weights Four weights per vertex, each finite and >= 0. */
|
|
118
|
+
constructor(skeleton: Skeleton, joints: ArrayLike<number>, weights: ArrayLike<number>);
|
|
119
|
+
/**
|
|
120
|
+
* Replaces the influences of vertices `first` onward (four joints and four weights each), for weight painting. Costs
|
|
121
|
+
* O(changed vertices) here; the next frame uploads 32 bytes per vertex from the lowest to the highest changed one.
|
|
122
|
+
*/
|
|
123
|
+
setInfluences(first: number, joints: ArrayLike<number>, weights: ArrayLike<number>): this;
|
|
124
|
+
/**
|
|
125
|
+
* CPU skinning at the skeleton's current pose, with the GPU pass's maths: bind-pose `positions` (and `normals`), xyz
|
|
126
|
+
* per vertex in skeleton space, to posed copies. For picking a posed mesh and for exporting a static pose.
|
|
127
|
+
*/
|
|
128
|
+
pose(positions: ArrayLike<number>, normals?: ArrayLike<number>): {
|
|
129
|
+
positions: Float32Array;
|
|
130
|
+
normals?: Float32Array;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* A synchronous picking source for `Raycaster.intersectPosed` (`@margoengine/bvh`): hits on the mesh at the skeleton's
|
|
134
|
+
* current pose, skinned on the CPU with {@link Skin.pose}. The posed vertices are cached per skeleton `revision` and
|
|
135
|
+
* influence edit, so many rays in one frame skin once. Needs a skin made by `Skin.attach`.
|
|
136
|
+
*/
|
|
137
|
+
get picking(): {
|
|
138
|
+
readonly root: PBRModel['root'];
|
|
139
|
+
readonly disposed: boolean;
|
|
140
|
+
posePickingGeometry(): readonly PosedSnapshot[];
|
|
141
|
+
};
|
|
142
|
+
private requireMesh;
|
|
143
|
+
/**
|
|
144
|
+
* A skin that deforms `mesh` on the GPU from now on, as a plugin of the mesh's engine. `mesh` is a `createMesh` mesh
|
|
145
|
+
* (or any gltf/pbr model whose primitives share one vertex array) with one vertex per four influences.
|
|
146
|
+
*/
|
|
147
|
+
static attach(mesh: PBRModel, skeleton: Skeleton, joints: ArrayLike<number>, weights: ArrayLike<number>): Skin;
|
|
148
|
+
setup(engine: Engine): void;
|
|
149
|
+
private scenePosed?;
|
|
150
|
+
/**
|
|
151
|
+
* The CPU pose synchronous scene queries test while the GPU pass deforms the mesh (shared/pose-source.js): the
|
|
152
|
+
* vertices `picking` caches per pose, copied into one array so a tree over it is refitted, not rebuilt.
|
|
153
|
+
*/
|
|
154
|
+
private readonly scenePose;
|
|
155
|
+
registerPasses(graph: FrameGraph): void;
|
|
156
|
+
private deform;
|
|
157
|
+
private release;
|
|
158
|
+
onDeviceRestored(engine: Engine): void;
|
|
159
|
+
/** Stops deforming the mesh and frees the GPU buffers. CPU posing keeps working. */
|
|
160
|
+
dispose(): void;
|
|
161
|
+
[Symbol.dispose]: () => void;
|
|
162
|
+
}
|
|
163
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{n as e}from"./errors-t1ewumJS.js";import{t}from"./vertex-map-BC_WH7ER.js";import{n,t as r}from"./pose-source-MuCl8VDd.js";import{t as i}from"./deform-readers-DmYAkvBK.js";import{c as a,o}from"./sampling-DjDWYqt2.js";import{t as s}from"./shader-DuGkHFKx.js";import{a as c,i as l,s as u,t as d}from"./keyframes-YpidiYS4.js";import{a as f,c as p,d as m,i as h,l as g,n as _,o as v,r as y,s as b,t as x,u as S}from"./gltf-C2HVNxzB.js";import{MargoError as C}from"@margoengine/math/errors";import{invertMatrixStable as w,multiplyMatrices as T}from"@margoengine/math/mat4";import{conjugateQuaternion as E,multiplyQuaternions as D,normalizeQuaternion as O}from"@margoengine/math/quat";import{PBRModel as k,textureCoordinates as A,textureTransform as j}from"@margoengine/gltf/pbr-model";import{MargoError as M}from"@margoengine/math";function ee(e,t){for(let n=t;n>=0;n=e.parents?.[n]??-1)if(e.hidden[n])return!0;return!1}function te(e,t,n,r,i,a,o,s){let c=s?.blend,l=!!s?.share,u=[],d=[],f=e.length/20,{words:p,floats:m,header:h,stride:g}=n,_=n.count===f,v=new Float32Array(i.buffer,i.byteOffset,i.length),y=s?.vertexData?4:0,b=a-y,x=/* @__PURE__ */ new Float64Array(16);t.set(e);for(let n=0,s=0;n<f;n++,s+=20){let f=e[s],S=e[s+1],C=e[s+2],w=e[s+4],T=e[s+5],E=e[s+6];for(let e=_?p[n]:0,t=_?p[n+1]:0;e<t;e++){let t=h+e*g,n=r[p[t+3]];f+=m[t]*n,S+=m[t+1]*n,C+=m[t+2]*n,w+=m[t+4]*n,T+=m[t+5]*n,E+=m[t+6]*n}if(i.length&&c){u.length=d.length=0;for(let e=n*a,t=e+b;e<t;e+=8)for(let t=0;t<4;t++)u.push(i[e+t]),d.push(v[e+4+t]);let e=1;l&&(e=(u[0]>>>16)/65535,u[0]&=65535);let t=y?v.subarray(n*a+b,n*a+a):void 0,r=c(o,u,d,[f,S,C],[w,T,E],e,t);f=r.position[0],S=r.position[1],C=r.position[2],w=r.normal[0],T=r.normal[1],E=r.normal[2]}else if(i.length){x.fill(0);for(let e=n*a,t=e+b;e<t;e+=8)for(let t=0;t<4;t++){let n=v[e+4+t],r=i[e+t]*16;if(n)for(let e=0;e<16;e++)x[e]+=n*o[r+e]}let e=x[0]*f+x[4]*S+x[8]*C+x[12],t=x[1]*f+x[5]*S+x[9]*C+x[13];C=x[2]*f+x[6]*S+x[10]*C+x[14],f=e,S=t;let r=x[5]*x[10]-x[6]*x[9],s=x[6]*x[8]-x[4]*x[10],c=x[4]*x[9]-x[5]*x[8],l=x[9]*x[2]-x[10]*x[1],u=x[10]*x[0]-x[8]*x[2],d=x[8]*x[1]-x[9]*x[0],p=x[1]*x[6]-x[2]*x[5],m=x[2]*x[4]-x[0]*x[6],h=x[0]*x[5]-x[1]*x[4],g=x[0]*r+x[1]*s+x[2]*c>=0?1:-1,_=(r*w+l*T+p*E)*g,y=(s*w+u*T+m*E)*g,D=(c*w+d*T+h*E)*g,O=_*_+y*y+D*D>0;w=O?_:0,T=O?y:1,E=O?D:0}let D=Math.hypot(w,T,E)||1;t[s]=f,t[s+1]=S,t[s+2]=C,t[s+4]=w/D,t[s+5]=T/D,t[s+6]=E/D}}var N=e=>Math.ceil((e+1)/4)*4;function ne(e,t,n,r,i){let a=e.length,o=new Uint32Array(n+1),s=new Int32Array(n).fill(-1);e.forEach((e,t)=>{for(let n of e)if(n)for(let e of n.rows)s[e]!==t&&(s[e]=t,o[e+1]++)});for(let e=0;e<n;e++)o[e+1]+=o[e];let c=o[n],l=new Uint32Array(c*r),u=new Float32Array(l.buffer),d=o.slice(0,n),f=new Uint32Array(n);s.fill(-1),e.forEach((e,t)=>e.forEach((e,n)=>{if(!e)return;let{rows:i,values:a}=e;for(let e=0;e<i.length;e++){let o=i[e];s[o]!==t&&(s[o]=t,f[o]=d[o]++,l[f[o]*r+3]=t);let c=f[o]*r+n*4;u[c]=a[e*3],u[c+1]=a[e*3+1],u[c+2]=a[e*3+2]}}));let p=N(t);if(!i){let e=new Uint32Array(p+l.length);return e.set(o),e.set(l,p),{count:t,targets:a,stride:r,header:p,words:e,floats:new Float32Array(e.buffer)}}let m=0;for(let e=0;e<t;e++)m+=o[i[e]+1]-o[i[e]];let h=new Uint32Array(p+m*r),g=0;for(let e=0;e<t;e++){let t=i[e],n=o[t],a=o[t+1];h[e]=g,h.set(l.subarray(n*r,a*r),p+g*r),g+=a-n}return h[t]=g,{count:t,targets:a,stride:r,header:p,words:h,floats:new Float32Array(h.buffer)}}var re=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Float32Array.prototype),`buffer`).get,ie=Reflect.apply,ae=[];function oe(e){return ie(re,e,ae)instanceof ArrayBuffer}var P=80,F=16,I=16,se=4,ce=64,le=48,ue=64,L=class{constructor(e,t,n=1){this.bytes=e,this.usage=t,this.align=n,this.capacity=0,this.top=0,this.ranges=/* @__PURE__ */ new Set}get live(){let e=0;for(let t of this.ranges)e+=t.size;return e}},de=class{constructor(e){this.source=new L(P,GPUBufferUsage.STORAGE),this.morphs=new L(F,GPUBufferUsage.STORAGE),this.influences=new L(I,GPUBufferUsage.STORAGE),this.weights=new L(se,GPUBufferUsage.STORAGE),this.bones=new L(ce,GPUBufferUsage.STORAGE),this.slots=/* @__PURE__ */ new Set,this.blocks=/* @__PURE__ */ new Map,this.version=0;let t=1;for(;t*P%e;)t++;this.output=new L(P,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC,t)}get pools(){return[this.source,this.output,this.morphs,this.influences,this.weights,this.bones]}},R=/* @__PURE__ */ new WeakMap,z=(e,t)=>Math.ceil(e/t)*t,B=(e,t)=>t+`:`+e.count+`:`+(t===`i`?(e.skin??``)+`:`+(e.mode?.name??``):``),V=e=>e.joints?e.count*((e.extra?4:2)+ +!!e.mode?.vertexData):0,H=(e,t)=>t===`s`?e.primitive.vertices:e.primitive.part?.vertexMap??e.definition,U=(e,t,n)=>e.asset===t.asset&&H(e,n)===H(t,n)&&B(e,n)===B(t,n),W=e=>Math.max(4,e),fe=class e{constructor(e){this.device=e,this.pages=[],this.version=0,this.pipelines=[],this.modes=[void 0];let t=e.limits;this.limit=Math.min(t.maxStorageBufferBindingSize,t.maxBufferSize),this.alignment=t.minStorageBufferOffsetAlignment??256}static of(t){let n=R.get(t);return n||R.set(t,n=new e(t)),n}variant(e,t){let n=this.modes.indexOf(t);return n<0&&(n=this.modes.push(t)-1),n*2+ +e}pipeline(e,t){return this.pipelines[this.variant(e,t)]??=this.device.createComputePipeline({layout:`auto`,compute:{module:this.device.createShaderModule({code:t?.shader(e)??s(e)}),entryPoint:`main`}})}add(e){if(!e.length)return[];let t=/* @__PURE__ */ new Map,n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;for(let o of e){let e=this.needs(o);if(e.some((e,t)=>e*[P,P,F,I,se,ce][t]>this.limit))throw RangeError(`Animation buffer exceeds device limit; load the model with a smaller maxPartVertices so the mesh splits, or reduce vertices, joints and morph targets`);let s=o.joints?o.primitive.node:void 0,c=s&&i.get(s)?.get(o.skin),l;if(c&&c.spec.joints===o.joints&&c.spec.mode===o.mode){let t=e[5];e[5]=0,this.fits(c.page,r.get(c.page),e)?(l=c.page,a.set(o,c.spec)):e[5]=t}if(l??=[...this.pages,...n].find(t=>this.fits(t,r.get(t),e)),l||n.push(l=new de(this.alignment)),s&&!c){let e=i.get(s);e||i.set(s,e=/* @__PURE__ */ new Map),e.set(o.skin,{spec:o,page:l})}let u=t.get(l)??[];(this.block(l,o,`s`)||u.some(e=>U(e,o,`s`)))&&(e[0]=0),(this.block(l,o,`m`)||u.some(e=>U(e,o,`m`)))&&(e[2]=0),(this.block(l,o,`i`)||u.some(e=>U(e,o,`i`)))&&(e[3]=0);let d=r.get(l)??[0,0,0,0,0,0];e.forEach((e,t)=>d[t]+=e),r.set(l,d);let f=t.get(l);f||t.set(l,f=[]),f.push(o)}this.pages.push(...n);for(let[e,n]of t)this.reserve(e,r.get(e),n);let o=/* @__PURE__ */ new Map,s=e.map(e=>{let n=[...t].find(([,t])=>t.includes(e))[0],r=this.place(n,e,o.get(a.get(e))?.bones);return o.set(e,r),r}),c=this.device.createCommandEncoder();for(let e of s)c.copyBufferToBuffer(e.page.source.buffer,e.source.range.offset*P,e.page.output.buffer,e.output.offset*P,e.count*P);return this.device.queue.submit([c.finish()]),this.version++,s}remove(e){let t=e.page;if(!t.slots.delete(e))return;let n=e.primitive;this.published(e)&&(n.deformed=n.deformedOffset=void 0),t.output.ranges.delete(e.output),t.weights.ranges.delete(e.weights),(e.bones.refs=(e.bones.refs??1)-1)<=0&&t.bones.ranges.delete(e.bones);for(let[n,r]of[[e.source,t.source],[e.morphs,t.morphs],[e.influences,t.influences]])if(n&&--n.refs===0){r.ranges.delete(n.range),n.owner.delete(n.key);let e=t.blocks.get(n.asset);n.owner.size||e.delete(n.holder),e.size||t.blocks.delete(n.asset)}if(t.version++,this.version++,!t.slots.size){for(let e of t.pools)e.buffer?.destroy();t.info?.buffer.destroy(),this.pages.splice(this.pages.indexOf(t),1)}}dispatches(e,t,n){if(n.version===this.version&&n.owners.length===e.length&&n.owners.every((t,n)=>t===e[n]))return n.dispatches;let r=[],i=/* @__PURE__ */ new Map;for(let n of e)for(let e of t(n)){let t=e.page;if(!t.slots.has(e))continue;this.records(t);let n=i.get(t);n||i.set(t,n=[]);let r=n[this.variant(e.extra,e.mode)]??=[];for(let t=0;t<e.count;t+=ue)r.push(e.index,t)}let a=this.device.limits.maxComputeWorkgroupsPerDimension??65535;try{for(let[e,t]of i)for(let n=0;n<t.length;n++){let i=t[n];if(!i?.length)continue;let o=i.length/2,s=this.pipeline(!!(n&1),this.modes[n>>1]),c=new Uint32Array(i.length+2);c[0]=o,c.set(i,2);let l=this.mapped(c),u=Math.min(o,a);r.push({pipeline:s,table:l,x:u,y:Math.ceil(o/u),group:void 0}),r[r.length-1].group=this.device.createBindGroup({layout:s.getBindGroupLayout(0),entries:[e.source.buffer,e.output.buffer,e.morphs.buffer,e.weights.buffer,e.bones.buffer,e.influences.buffer,e.info.buffer,l].map((e,t)=>({binding:t,resource:{buffer:e}}))})}}catch(e){for(let e of r)e.table.destroy();throw e}return this.retire(n.dispatches.map(e=>e.table)),n.owners=e.slice(),n.version=this.version,n.dispatches=r,r}drop(e){for(let t of e.dispatches)t.table.destroy();e.dispatches=[],e.owners=[],e.version=-1}block(e,t,n){return e.blocks.get(t.asset)?.get(H(t,n))?.get(B(t,n))}needs(e){return[e.count,e.count,e.morphWords/4,V(e),W(e.targets),e.joints]}fits(e,t,n){return e.pools.every((r,i)=>{let a=i===1?r.align*(e.slots.size+1):0;return(r.live+(t?.[i]??0)+n[i]+a)*r.bytes<=this.limit})}reserve(e,t,n){let r=e.pools,i=(e,i)=>e===1?n.reduce((e,t)=>z(e,r[1].align)+t.count,i):i+t[e];if(r.every((e,t)=>e.buffer&&i(t,e.top)<=e.capacity))return;let a=r.some(e=>e.ranges.size)?this.device.createCommandEncoder():void 0,o=[],s=[...e.slots].filter(e=>this.published(e));r.forEach((e,t)=>{let n=[...e.ranges].sort((e,t)=>e.offset-t.offset),r=0;for(let t of n)r=z(r,e.align)+t.size;let s=i(t,r),c=Math.floor(this.limit/e.bytes),l=Math.max(s,Math.min(c,e.capacity*2),1),u=this.device.createBuffer({size:Math.max(16,l*e.bytes),usage:e.usage|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),d=0;for(let t of n)d=z(d,e.align),t.size&&a.copyBufferToBuffer(e.buffer,t.offset*e.bytes,u,d*e.bytes,t.size*e.bytes),t.offset=d,d+=t.size;e.buffer&&o.push(e.buffer),e.buffer=u,e.capacity=Math.floor(u.size/e.bytes),e.top=d}),a&&this.device.queue.submit([a.finish()]),this.retire(o);for(let e of s)this.publish(e);e.version++,this.version++}place(e,t,n){let r=(e,t)=>{let n=z(e.top,e.align),r={offset:n,size:t};return e.top=n+t,e.ranges.add(r),r},i=(n,i,a,o)=>{if(!a&&i!==`s`)return;let s=e.blocks.get(t.asset);s||e.blocks.set(t.asset,s=/* @__PURE__ */ new Map);let c=H(t,i),l=s.get(c);l||s.set(c,l=/* @__PURE__ */ new Map);let u=B(t,i),d=l.get(u);return d||(d={range:r(n,a),refs:0,key:u,owner:l,asset:t.asset,holder:c},l.set(u,d),this.write(n,d.range,o())),d.refs++,d},a={page:e,primitive:t.primitive,count:t.count,targets:t.targets,morphStride:t.morphStride,joints:t.joints,extra:t.extra,mode:t.mode,source:i(e.source,`s`,t.count,()=>t.primitive.vertices),output:r(e.output,t.count),weights:r(e.weights,W(t.targets)),bones:n?(n.refs++,n):Object.assign(r(e.bones,t.joints),{refs:1}),morphs:i(e.morphs,`m`,t.morphWords/4,t.deltas),influences:i(e.influences,`i`,V(t),t.influences),index:-1};return e.slots.add(a),e.version++,this.publish(a),a}published(e){let t=e.primitive;return t.deformed===e.page.output.buffer&&(t.deformedOffset??0)===e.output.offset*P}publish(e){let t=e.primitive;t.deformed=e.page.output.buffer,t.deformedOffset=e.output.offset*P}write(e,t,n){t.size&&this.device.queue.writeBuffer(e.buffer,t.offset*e.bytes,n)}records(e){if(e.info?.version===e.version)return;let t=new Uint32Array(Math.max(1,e.slots.size)*(le/4)),n=0;for(let r of e.slots)r.index=n,t.set([r.source.range.offset,r.output.offset,r.count,r.targets,r.morphs?.range.offset??0,r.weights.offset,r.bones.offset,r.joints,r.influences?.range.offset??0,r.morphStride/4],n++*(le/4));e.info&&this.retire([e.info.buffer]),e.info={buffer:this.mapped(t),version:e.version}}mapped(e){let t=this.device.createBuffer({size:Math.max(16,e.byteLength),usage:GPUBufferUsage.STORAGE,mappedAtCreation:!0});return new Uint32Array(t.getMappedRange()).set(e),t.unmap(),t}retire(e){e.length&&this.device.queue.onSubmittedWorkDone().then(()=>{for(let t of e)t.destroy()})}},G=/* @__PURE__ */ new WeakMap;function K(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(t+` must be an object`);return e}function pe(e,t){if(!Array.isArray(e)||e.length!==2||e.some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e))))throw TypeError(t+` needs two finite Float32 values`)}function me(e,t,n){let r=e.asset.doc.accessors??[],i=f(t,r.length,`material accessor`),a=r[i];if(a.componentType!==5126||a.type!==n||a.normalized!==void 0&&a.normalized!==!1)throw TypeError(`Material animation accessors must be unnormalized Float32 `+n);if(!Number.isSafeInteger(a.count)||a.count<1)throw RangeError(`Material animation accessor count must be positive`);let o=e.asset.accessor(i,n);if(o.length!==a.count*(n===`SCALAR`?1:2)||o.some(e=>!Number.isFinite(e)))throw RangeError(`Material animation accessor length/values must match its definition`);return new Float32Array(o)}function he(e,t,n){let r=me(e,g(t.samplers[f(n,t.samplers.length,`material sampler`)]).input,`SCALAR`);if(r.some((e,t)=>e<0||t>0&&e<=r[t-1]))throw RangeError(`Material animation times must be nonnegative and strictly increasing`);return r}function ge(e,t){let n=[],r=[],i=/* @__PURE__ */ new Set,a=0;for(let o of t.channels){let s=K(o,`Animation channel`),c=K(s.target,`Animation target`),l=c.extensions===void 0?void 0:K(c.extensions,`Animation target extensions`);if(c.path!==`pointer`&&l?.KHR_animation_pointer===void 0){r.push(o);continue}if(c.path!==`pointer`||Object.hasOwn(c,`node`))throw TypeError(`Material animation pointer requires path pointer and an absent target node`);let u=K(l?.KHR_animation_pointer,`KHR_animation_pointer`).pointer,d=typeof u==`string`&&/^\/materials\/(0|[1-9]\d*)\/pbrMetallicRoughness\/baseColorTexture\/extensions\/KHR_texture_transform\/(offset|scale)$/.exec(u);if(!d)throw TypeError(`Unsupported material animation pointer; use baseColorTexture offset or scale`);let p=f(Number(d[1]),e.asset.doc.materials?.length??0,`material`),m=d[2],h=e.asset.doc.materials[p].pbrMetallicRoughness?.baseColorTexture;if(!h||!Number.isInteger(h.index)||h.index<0||h.index>=(e.asset.doc.textures?.length??0))throw TypeError(`Material animation target needs a real baseColorTexture`);if(pe(K(h.extensions?.KHR_texture_transform,`Material animation initial transform`)[m],`Material animation initial `+m),A(h),!e.primitives.some(e=>e.definition.material===p))throw TypeError(`Material animation target must have a current model primitive`);let _=p+`:`+m;if(i.has(_))throw TypeError(`Duplicate material animation target; use one channel per property`);i.add(_);let v=g(t.samplers[f(s.sampler,t.samplers.length,`material sampler`)]);if(v.interpolation!==`STEP`)throw TypeError(`Material animation requires explicit STEP interpolation`);let y=he(e,t,s.sampler),b=me(e,v.output,`VEC2`);if(b.length!==y.length*2)throw RangeError(`Material animation output count must match its keys`);a=Math.max(a,y[y.length-1]),n.push({material:p,property:m,times:y,values:b})}return{tracks:n,nodeChannels:r,duration:a}}function _e(e){if(!(e instanceof k))throw TypeError(`Material animation needs a PBRModel`);let t=e.root,n=t.engine;if(e.disposed||n.disposed)throw new M(`disposed`,`Material animation model is disposed; load a new model`);if(n.meshes.get(t.id)!==t)throw new M(`state`,`Material animation model root is stale; load a new model`)}function q(e){let t=e.material.maps?.[0];if(!t||t.index!==e.texture||!Array.isArray(e.material.uvt)||e.material.uvt.length<8)throw new M(`state`,`Material animation binding changed; recreate the player for the current material`);let n=K(t.extensions?.KHR_texture_transform,`Material animation map transform`);for(let t of e.tracks.keys())pe(n[t],`Material animation map `+t);return A(t),t}function ve(e,t={}){if(_e(e),K(t,`Material animation options`),t.loop!==void 0&&typeof t.loop!=`boolean`)throw TypeError(`Material animation loop must be boolean`);let n=e.asset.doc.animations??[],r=f(t.clip===void 0?0:t.clip,n.length,`material clip`),i=y(n[r]),a=ge(e,i);if(!a.tracks.length)throw TypeError(`Selected clip needs supported material animation tracks`);let s=a.duration;for(let t of a.nodeChannels){let n=he(e,i,K(t,`Animation channel`).sampler);s=Math.max(s,n[n.length-1])}let c=e.asset,l=c.doc,u=/* @__PURE__ */ new Map,d=new Set(a.tracks.map(e=>e.material));for(let t of a.tracks)for(let n of e.primitives)if(n.definition.material===t.material){let e=u.get(n.material);e||(e={material:n.material,texture:l.materials[t.material].pbrMetallicRoughness.baseColorTexture.index,primitives:/* @__PURE__ */ new Map,tracks:/* @__PURE__ */ new Map},u.set(n.material,e));let r=e.tracks.get(t.property);if(r&&r!==t)throw TypeError(`Aliased material animation targets overlap; use one track per actual material property`);e.tracks.set(t.property,t),e.primitives.set(n,t.material)}let p=()=>{if(_e(e),e.asset!==c||e.asset.doc!==l)throw new M(`state`,`Material animation asset changed; recreate the player`);let t=0,n=0;for(let t of u.values()){n+=t.primitives.size;for(let[n,r]of t.primitives)if(!e.primitives.includes(n)||n.material!==t.material||n.definition.material!==r||n.node.engine!==e.root.engine||n.node.engine.meshes.get(n.node.id)!==n.node)throw new M(`state`,`Material animation primitive binding changed; recreate the player`);q(t)}for(let n of e.primitives)d.has(n.definition.material)&&t++;if(t!==n)throw new M(`state`,`Material animation primitive bindings changed; recreate the player`)};p();for(let e of u.values())for(let t of e.tracks.keys())if(G.get(e.material)?.has(t))throw new M(`attached`,`Material animation property is already owned by an active player; dispose that player first`);for(let e of u.values()){let t=G.get(e.material);t||G.set(e.material,t=/* @__PURE__ */ new Set);for(let n of e.tracks.keys())t.add(n)}let m=!1,h,g=()=>{if(!m){m=!0,h?.(),h=void 0;for(let e of u.values()){let t=G.get(e.material);for(let n of e.tracks.keys())t.delete(n);t.size||G.delete(e.material)}}};try{h=e.onDispose(g)}catch(e){throw g(),e}let _=t.loop??!1;return{dispose:g,seek(e){if(m)throw new M(`disposed`,`Material animation player is disposed; create a new player`);if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw RangeError(`Material animation seconds must be finite and nonnegative`);p();let t=_&&s>0?e%s:Math.min(e,s),n=/* @__PURE__ */ new Map;for(let e of a.tracks){let r=o(e.times,e.values,2,t,`STEP`);n.set(e,[r[0],r[1]])}let r=Array.from(u.values(),e=>{let t=q(e),r=t.extensions.KHR_texture_transform,i={...r};for(let[t,r]of e.tracks)i[t]=n.get(r);i.offset&&=[...i.offset],i.scale&&=[...i.scale];let a=A(t).texCoord,o=j({...i,texCoord:a},a),s=e.material.uvt;return{binding:e,changed:[...e.tracks.keys()].some(e=>{let t=r[e],n=i[e];return!Object.is(t[0],n[0])||!Object.is(t[1],n[1])})||o.some((e,t)=>!Object.is(e,s[t])),map:{...t,extensions:{...t.extensions,KHR_texture_transform:i}},rows:o}});for(let{binding:e,changed:t,map:n,rows:i}of r)if(t){let t=e.material.maps.slice();t[0]=n,e.material.maps=t;for(let t=0;t<8;t++)e.material.uvt[t]=i[t]}}}}function ye(e,t,n,r={}){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))throw TypeError(`compileRigidClip needs arrays of bones, bindings and keys`);let i=(e,t,n)=>{let r=e;if(typeof r!=`object`||!r||r.length!==t)throw TypeError(`${n} needs ${t} numbers`);if(!Array.from(r).every(e=>typeof e==`number`&&Number.isFinite(e)))throw RangeError(`${n} must be finite numbers`);return Array.from(r)},a=/* @__PURE__ */ new Set;for(let t of e){if(typeof t?.id!=`string`||!t.id)throw TypeError(`Every rigid bone needs a nonempty string id`);i(t.translation,3,`Bone ${t.id} translation`),a.add(t.id)}let o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map;for(let e of t){if(typeof e?.object!=`string`||o.has(e.object))throw TypeError(`Binding for ${String(e?.object)} is missing or repeated; bind each mesh once`);if(!a.has(e.bone))throw TypeError(`Binding for ${e.object} names unknown bone ${e.bone}; bind it to a listed bone`);i(e.position,3,`Binding ${e.object} position`),i(e.rotation,4,`Binding ${e.object} rotation`),o.set(e.object,e),s.set(e.bone,[...s.get(e.bone)??[],e.object])}let c=/* @__PURE__ */ new Map;for(let e of n){if(typeof e?.object!=`string`)throw TypeError(`Every rigid key needs a string object`);if(typeof e.time!=`number`||!Number.isFinite(e.time)||e.time<0)throw RangeError(`Key of ${e.object} needs a finite time of 0 or more`);i(e.position,3,`Key of ${e.object} position`),i(e.rotation,4,`Key of ${e.object} rotation`);let t=o.get(e.object);t&&c.set(t.bone,[...c.get(t.bone)??[],e])}let{name:u,duration:d}=r;if(d!==void 0&&(typeof d!=`number`||!Number.isFinite(d)||d<0))throw RangeError(`duration must be a finite number of seconds, 0 or more`);let f=[];for(let t of e){let e=[...c.get(t.id)??[]].sort((e,t)=>e.time-t.time);if(!e.length)continue;let n=new Map((s.get(t.id)??[]).map((e,t)=>[e,t])),r=s.get(t.id),i=/* @__PURE__ */ new Map,a=[],l=[];e[0].time>0&&(a.push({time:0,value:t.translation,interpolation:`discrete`}),l.push({time:0,value:[0,0,0,1],interpolation:`discrete`}));let u=1/0;for(let s=0;s<e.length;){let c=e[s].time;for(;s<e.length&&e[s].time===c;){let t=e[s++];i.set(t.object,t),u=Math.min(u,n.get(t.object))}let d=o.get(r[u]),f=i.get(d.object);a.push({time:c,value:[0,1,2].map(e=>t.translation[e]+(f.position[e]-d.position[e])),interpolation:`discrete`}),l.push({time:c,value:D(O(f.rotation),E(O(d.rotation))),interpolation:`discrete`})}d!==void 0&&d>e[e.length-1].time&&(a.push({...a[a.length-1],time:d}),l.push({...l[l.length-1],time:d})),f.push({target:t.id,path:`translation`,keys:a},{target:t.id,path:`rotation`,keys:l})}return l(u===void 0?{tracks:f}:{name:u,tracks:f})}var J=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e))throw RangeError(`AnimationGroup ${t} ${e} is invalid; pass finite seconds`);return e},be=0,xe=class e{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let i=new e(n,r);return t.use(i),i}constructor(e,t={}){if(this.clip=e,this.options=t,this.name=`animation-group:`+be++,this.time=0,this.playing=!0,this.members=[],this.disposed=!1,typeof e!=`string`&&typeof e!=`number`&&!Array.isArray(e?.tracks))throw TypeError(`AnimationGroup clip must be a glTF clip name or index, or a KeyframeClip`);if(t.loop!==void 0&&typeof t.loop!=`boolean`)throw TypeError(`AnimationGroup loop must be a boolean`);let n=t.speed??1;if(typeof n!=`number`||!Number.isFinite(n)||n<0)throw RangeError(`AnimationGroup speed ${n} is invalid; pass a finite number >= 0`)}get size(){return this.members.length}has(e){return this.members.some(t=>t.target===e)}add(e,t=0){if(this.disposed)throw new C(`disposed`,`AnimationGroup is disposed; create a new group`);J(t,`offset`);let n=this.members.find(t=>t.target===e);if(n)return n.offset=t,this.pose(n),this;let r=this.clip,i=typeof r==`object`,a=-1;if(!i){let t=e;if(e instanceof u||!Array.isArray(t?.clips)||typeof t.seek!=`function`)throw TypeError(`AnimationGroup with a glTF clip needs Animation members; pass Animation.attach(model)`);if(a=typeof r==`string`?t.clips.findIndex(e=>e.name===r):r,!Number.isInteger(a)||a<0||a>=t.clips.length)throw RangeError(`AnimationGroup clip ${r} is not one of this model's clips; pass a name or index it has`);t.playing=!1}let o={target:e,offset:t,clip:a,bindings:i?this.bind(r,e):[]};return this.members.push(o),this.pose(o),this}remove(e){let t=this.members.findIndex(t=>t.target===e);return t>=0&&this.members.splice(t,1),this}setOffset(e,t){let n=this.members.find(t=>t.target===e);if(!n)throw RangeError(`AnimationGroup member not found; add it first`);return n.offset=J(t,`offset`),this.pose(n),this}seek(e){if(J(e,`time`)<0)throw RangeError(`AnimationGroup time ${e} is invalid; pass seconds >= 0`);return this.time=e,this.poseAll(),this}update(e){return this.advanceTime(e),this.poseAll(),this}advanceTime(e){if(J(e,`delta`)<0)throw RangeError(`AnimationGroup delta ${e} is invalid; pass >= 0`);this.playing&&!this.disposed&&(this.time+=e*(this.options.speed??1))}setup(e){if(this.disposed)throw new C(`disposed`,`AnimationGroup is disposed; create a new group`);this.engine=e}onPreUpdate(e){this.update(e)}dispose(){this.disposed||(this.disposed=!0,this.members.length=0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.engine=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}poseAll(){for(let e=this.members.length-1;e>=0;e--){let t=this.members[e].target;!(t instanceof u)&&t.model.disposed?this.members.splice(e,1):this.pose(this.members[e])}}pose(e){let t=this.time+e.offset;if(e.clip>=0){let n=e.target,r=n.clips[e.clip].duration;n.clip=e.clip,n.seek(t>=0?t:(n.options.loop??!0)&&r>0?t%r+r:0);return}let n=this.clip.duration,r=(this.options.loop??!0)&&n>0?(t%n+n)%n:Math.min(Math.max(t,0),n);for(let t=0;t<e.bindings.length;t++)e.bindings[t](r)}bind(e,t){let n=[];if(t instanceof u){for(let r of e.tracks){let e=r.path===`weights`?-1:t.index(r.target);if(e<0)continue;let i=new Float64Array(r.path===`rotation`?4:3),a={[r.path]:i};n.push(n=>{c(r,n,i),t.setPose(e,a)})}return n}let r=t,i=r?.model?.nodes;if(!Array.isArray(i)||typeof r.setMorph!=`function`)throw TypeError(`AnimationGroup members must be Skeletons or Animations; pass Animation.attach(model)`);for(let t of e.tracks){let e=i.findIndex(e=>e.name===t.target);if(e<0)continue;let a=i[e],o=t.values.length/t.times.length,s=new Float64Array(o),l=[0,0,0,1];if(t.path===`weights`){let n=r.model.primitives.find(t=>t.nodeIndex===e)?.weights.length??0;if(n!==o)throw RangeError(`Keyframe track ${t.target} weights has ${o} values but the node has ${n} morph targets; key one weight per target`)}n.push(n=>{if(c(t,n,s),t.path===`weights`)for(let t=0;t<o;t++)r.setMorph(e,t,s[t]);else if(t.path===`translation`)a.setPosition(s);else if(t.path===`scale`)a.setScale(s);else{for(let e=0;e<4;e++)l[e]=s[e];a.setQuaternion(l)}})}return n}};function Se(e,t,n){let r=[],i=[],a=0;return t.channels.forEach((o,s)=>{let c=o,l=c?.target?.extensions?.KHR_animation_pointer;if(c?.target?.path!==`pointer`&&l===void 0){r.push(o);return}let u=g(t.samplers[f(c.sampler,t.samplers.length,`sampler`)]);a=Math.max(a,e.asset.accessor(u.input,`SCALAR`).at(-1)??0),i.push(`Animation ${n} channel ${s}: pointer ${String(l?.pointer)} is not played; pass pointers from @margoengine/animation/pointer (Animation.attach(model, {pointers: pointerChannels}))`)}),{ordinary:r,nodes:[],duration:a,warnings:i}}var Ce=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function we(e){let t=new Float32Array(e*16);for(let e=0;e<t.length;e+=16)t[e]=t[e+5]=t[e+10]=t[e+15]=1;return t}var Y=/* @__PURE__ */ new Float32Array,Te=/* @__PURE__ */ new WeakMap;function Ee(e,t,n,r,i){let a=n.nodes[r]?.mesh,o=t.doc?.meshes,s=(typeof a==`number`?o?.[a]:void 0)?.primitives??[],c=s.indexOf(i),l=c<0?[i]:s,u=Te.get(e);u||Te.set(e,u=/* @__PURE__ */ new WeakMap);let d=u.get(t);d||u.set(t,d=/* @__PURE__ */ new Map);let f=c<0?-1-r:a,p=c<0?void 0:d.get(f);if(!p){let n=l.map(e=>{let n=e,r=n.attributes??{},i=t.accessor(r.POSITION,`VEC3`),a=i.length/3,o=r.JOINTS_1!==void 0&&r.WEIGHTS_1!==void 0?8:4,s=new Float32Array(a*o),c=new Float32Array(a*o);for(let e=0;e<o/4;e++){let n=r[`JOINTS_`+e],i=r[`WEIGHTS_`+e];if(n===void 0||i===void 0)continue;let l=t.accessor(n,`VEC4`),u=t.accessor(i,`VEC4`);for(let t=0;t<a;t++)for(let n=0;n<4;n++)s[t*o+e*4+n]=l[t*4+n],c[t*o+e*4+n]=u[t*4+n]}return{positions:i,triangles:n.mode!==void 0&&n.mode!==4?null:n.indices===void 0?Uint32Array.from({length:a-a%3},(e,t)=>t):t.accessor(n.indices,`SCALAR`),joints:s,weights:c,influences:o}});if(p=e.vertexData(n),p.length!==n.length||p.some((e,t)=>e.length!==n[t].positions.length/3*4))throw RangeError(`Invalid skinning vertexData; the mode must return four numbers per vertex of each part`);c>=0&&d.set(f,p)}return p[Math.max(c,0)]}var De=()=>/* @__PURE__ */ new Uint32Array,Oe={count:0,targets:0,stride:8,header:N(0),words:new Uint32Array(N(0)),floats:new Float32Array(N(0))},ke=()=>Oe;function Ae(e,t,n,r){for(let i=0;i<4;i++)for(let a=0;a<4;a++)r[i*4+a]=e[a]*t[n+i*4]+e[4+a]*t[n+i*4+1]+e[8+a]*t[n+i*4+2]+e[12+a]*t[n+i*4+3]}function je(){try{let e=globalThis.GPUQueue,t=typeof e==`function`?e.prototype:void 0,n=t&&Object.getOwnPropertyDescriptor(t,`writeBuffer`)?.value;if(t&&typeof n==`function`&&/^function writeBuffer\(\)\s*\{\s*\[native code\]\s*\}$/.test(Function.prototype.toString.call(n)))return{prototype:t,writer:n}}catch{}}var X=/* @__PURE__ */ je(),Me=Reflect.get(Object.prototype,`__lookupGetter__`),Ne=Symbol.for(`margoengine.writeBuffer.copiesInput`);function Z(e,t){if(Object.hasOwn(e,`writeBuffer`)||typeof Me!=`function`||Me.call(e,`writeBuffer`)!==void 0)return!1;let n=Object.getPrototypeOf(e);return X&&t===X.writer&&n===X.prototype?!0:!!n&&Object.getOwnPropertyDescriptor(n,`writeBuffer`)?.value===t&&t[Ne]===!0}function Q(e,t,n,r,i,a){let o=n.uploadArgs;o[0]=r,o[1]=i,o[2]=a;try{Reflect.apply(t,e,o)}finally{o[2]=void 0}}var Pe=()=>({owners:[],version:-1,dispatches:[]}),Fe=e=>e.slots,Ie=/* @__PURE__ */ new WeakMap,Le=[`POSITION`,`NORMAL`,`TANGENT`];function Re(e,t,n,r,i,a){return ne(t.map(t=>Le.map(n=>t[n]===void 0?void 0:e.sparseAccessor(t[n],`VEC3`))),n,r,i,a)}var $=/* @__PURE__ */ new WeakMap;function ze(e){return{primitive:e,slot:void 0,get output(){return this.slot.page.output.buffer},get weights(){return this.slot.page.weights.buffer},get bones(){return this.slot.page.bones.buffer},palette:/* @__PURE__ */ new Float32Array,paletteBits:/* @__PURE__ */ new Uint32Array,spare:/* @__PURE__ */ new Float32Array,spareBits:/* @__PURE__ */ new Uint32Array,next:/* @__PURE__ */ new Float32Array,bonesChanged:!1,uploadedWeights:new Float32Array(e.weights.length),bonesUploaded:!1,weightsUploaded:!1,uploadArgs:[void 0,0,void 0],joints:[],inverseBind:Y,influences:De,deltas:ke}}function Be(e,n,r,i,a,o,s,c){let l=new ArrayBuffer(Math.max(32,i*o*4)),u=new Uint32Array(l),d=new Float32Array(l),f=o>=16;for(let e of Object.keys(r))if(/^(JOINTS|WEIGHTS)_/.test(e)&&!/^(JOINTS|WEIGHTS)_[01]$/.test(e))throw RangeError(`More than eight joint influences are unsupported; limit each vertex to JOINTS_0 and JOINTS_1`);let p=[];for(let i=0;i<(f?2:1);i++){let o=r[`JOINTS_`+i],s=r[`WEIGHTS_`+i];if(o===void 0||s===void 0)throw TypeError(`Skin attributes require paired JOINTS_`+i+` and WEIGHTS_`+i);let l=e.accessor(o,`VEC4`),u=e.accessor(s,`VEC4`),d=x(n,o);if(l.length!==a*4||u.length!==a*4||d?.componentType!==5121&&d?.componentType!==5123||d?.normalized)throw TypeError(`Invalid skin attributes; JOINTS_n must be unsigned byte or short VEC4, WEIGHTS_n VEC4, one per vertex`);let f=x(n,s);if(!f||f.componentType!==5126&&f.componentType!==5121&&f.componentType!==5123||f.componentType!==5126&&!f.normalized)throw TypeError(`Invalid skin weight component type; use float, or normalized unsigned byte or short weights`);p.push({ids:t(l,4,c),weights:t(u,4,c)})}for(let e=0;e<i;e++){let t=p[0].weights,n=t[e*4]+t[e*4+1]+t[e*4+2]+t[e*4+3];if(f){let t=p[1].weights;n+=t[e*4]+t[e*4+1]+t[e*4+2]+t[e*4+3]}if(n<=0)throw RangeError(`Skin weights must have a positive sum`);for(let t=0;t<p.length;t++)for(let r=0;r<4;r++){let{ids:i,weights:a}=p[t],c=e*4+r,l=e*o+t*8;if(!Number.isInteger(i[c])||i[c]<0||i[c]>=s||a[c]<0)throw RangeError(`Invalid skin joint/weight; joint indices must address the skin joints and weights must be >= 0`);u[l+r]=i[c],d[l+4+r]=a[c]/n}}return u}function Ve(e,t){e.setPipeline(t.pipeline),e.setBindGroup(0,t.group),e.dispatchWorkgroups(t.x,t.y)}var He=class o{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(e,t={}){this.model=e,this.options=t,this.playing=!0,this.time=0,this.clip=0,this.due=!1,this.resources=[],this.leaders=[],this.wholes=[/* @__PURE__ */ new Float32Array,/* @__PURE__ */ new Float32Array],this.deformedNodes=[],this.slots=[],this.cache=Pe(),this.inverse=/* @__PURE__ */ new Float32Array(16),this.joint=/* @__PURE__ */ new Float32Array(16),this.product=/* @__PURE__ */ new Float32Array(16),this.workspace=/* @__PURE__ */ new Float64Array(52),this.quaternion=[0,0,0,1],this.disposed=!1,this.groupStart=/* @__PURE__ */ new Int32Array(1),this.groupItems=/* @__PURE__ */ new Int32Array,this.prepareDeformation=e=>this.deform(e),this.createDeformationRenderer=(e,t)=>{let n=new o(e,this.options);n.playing=!1;try{return n.setup(e.root.engine,t),{prepare:n.prepareDeformation,dispose:()=>n.dispose()}}catch(e){throw n.dispose(),e}},this.name=`animation:`+e.name,this.validate(),this.joints=t.skeleton??e,this.rest=e.nodes.map(e=>{let t=e.engine.store.transforms,n=e.id;return{position:[t.x[n],t.y[n],t.z[n]],scale:[t.sx[n],t.sy[n],t.sz[n]],rotation:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]]}});let n=h(e.asset.doc),r=[];this.clips=(t.skeleton?[]:n.animations).map((i,a)=>{let o=y(i),s=o.name??String(a),c=t.pointers?t.pointers(e,o,s):Se(e,o,s);r.push(...c.warnings);let l=/* @__PURE__ */ new Set,u=(t,r,i)=>{if(b(n.nodes[t]).matrix)throw TypeError(`Invalid animation target; glTF animations cannot drive a node that has a matrix, give it translation/rotation/scale`);let a=t+`:`+r;if(l.has(a))throw RangeError(`Duplicate animation target; give each node and path (translation, rotation, scale, weights) one channel per animation`);l.add(a);let s=g(o.samplers[f(i,o.samplers.length,`sampler`)]),c=e.asset.accessor(s.input,`SCALAR`),u=v(s.interpolation),d=!0;for(let e=0;e<c.length&&d;e++)d=!(c[e]<0||e>0&&c[e]<=c[e-1]);if(!d)throw RangeError(`Invalid animation time/interpolation; keyframe times must be >= 0 and strictly increasing`);if(x(n,s.input)?.componentType!==5126||x(n,s.output)?.componentType!==5126)throw TypeError(`Animation accessors must be Float32; re-export the glTF without quantised animation data`);let p=this.groupStart[t]<this.groupStart[t+1]?this.groupItems[this.groupStart[t]]:-1,m=p<0?void 0:e.primitives[p].weights.length,h=r===`rotation`?4:r===`weights`?m??0:3;if(!h)throw TypeError(`Animation target has no morph weights; animate weights only on a node whose mesh has morph targets`);let _=e.asset.accessor(s.output,r===`weights`?`SCALAR`:r===`rotation`?`VEC4`:`VEC3`),y=u===`CUBICSPLINE`?3:1;if(_.length!==c.length*h*y)throw RangeError(`Animation output count mismatch; the output accessor needs one value per key (three per key for CUBICSPLINE)`);return{node:t,path:r,times:c,values:_,width:h,interpolation:u,sample:new Float32Array(h),...r===`rotation`?{rotation:[0,0,0,1]}:{},cursor:0}},d=c.ordinary.map(t=>{let n=_(t);return u(f(n.target.node,e.nodes.length,`node`),p(n.target.path),n.sampler)});for(let e of c.nodes)d.push(u(e.node,e.path,e.sampler));return{name:o.name??`Animation `+a,duration:Math.max(c.duration,...d.map(e=>e.times.at(-1))),tracks:d,...c.bind?{bind:c.bind}:{}}}),this.warnings=r}static attach(e,t={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new o(e,t),r=e.root.engine;return r.use(n,r.sceneOf(e)??e.root.scene),n}validate(){this.groupPrimitives(),this.checkWidths(),this.checkOptions()}groupPrimitives(){let e=this.model.primitives,t=new Int32Array(this.model.nodes.length+1),n=new Int32Array(e.length);for(let n of e)t[n.nodeIndex+1]++;for(let e=0;e<t.length-1;e++)t[e+1]+=t[e];let r=t.slice(0,-1);e.forEach((e,t)=>n[r[e.nodeIndex]++]=t),this.groupStart=t,this.groupItems=n}grouped(){let e=this.model.primitives,t=this.groupStart,n=this.groupItems;if(e.length!==n.length||t.length!==this.model.nodes.length+1)return!1;for(let r=0;r+1<t.length;r++)for(let i=t[r];i<t[r+1];i++)if(e[n[i]]?.nodeIndex!==r)return!1;return!0}checkWidths(){let e=this.model.primitives,t=this.groupStart,n=this.groupItems;for(let r=0;r+1<t.length;r++)for(let i=t[r]+1;i<t[r+1];i++)if(e[n[i]].weights.length!==e[n[t[r]]].weights.length)throw RangeError(`Morph target counts must match across a node's primitives; give every primitive of the mesh the same targets`)}checkFrame(){this.grouped()||this.groupPrimitives(),this.checkWidths(),this.checkOptions()}checkOptions(){if(this.options.loop!==void 0&&typeof this.options.loop!=`boolean`||!Number.isFinite(this.options.speed??1)||(this.options.speed??1)<0)throw RangeError(`Invalid animation options; loop must be a boolean and speed a finite number >= 0`);let e=this.options.skeleton;if(e!==void 0&&e.nodes?.length!==this.model.nodes.length)throw TypeError(`Invalid skeleton option; pass a model of the same file, with the same nodes`);let t=this.options.skinning;if(t!==void 0&&(typeof t?.shader!=`function`||typeof t.encode!=`function`||t.blend!==void 0&&typeof t.blend!=`function`||t.vertexData!==void 0&&typeof t.vertexData!=`function`))throw TypeError(`Invalid skinning option; pass dualQuaternionSkinning from @margoengine/animation/dqs`);if(this.options.pointers!==void 0&&typeof this.options.pointers!=`function`)throw TypeError(`Animation pointers option must be pointerChannels; import it from @margoengine/animation/pointer`)}play(e=0){if(this.disposed)throw new C(`disposed`,`Animation is disposed; create a new Animation`);let t=typeof e==`string`?this.clips.findIndex(t=>t.name===e):e;if(!Number.isInteger(t)||t<0||t>=this.clips.length)throw RangeError(`Unknown animation clip; pass a clip name or an index from animation.clips`);for(let[e,t]of this.rest.entries())this.model.nodes[e].setPosition(t.position).setScale(t.scale).setQuaternion(t.rotation);return this.clip=t,this.time=0,this.playing=!0,this.apply(0),this}captureState(){if(this.disposed)throw new C(`disposed`,`Cannot capture a disposed Animation; use a live player`);return{version:1,clip:this.clip,time:this.time,playing:this.playing,loop:this.options.loop??!0,speed:this.options.speed??1}}restoreState(e){if(this.disposed||!e||e.version!==1||!Number.isInteger(e.clip)||e.clip<0||e.clip>=Math.max(1,this.clips.length)||!Number.isFinite(e.time)||e.time<0||typeof e.playing!=`boolean`||typeof e.loop!=`boolean`||!Number.isFinite(e.speed)||e.speed<0)throw new C(`state`,`Invalid Animation state; restore a snapshot of this model`);return this.clip=e.clip,this.options.loop=e.loop,this.options.speed=e.speed,this.seek(e.time),this.playing=e.playing,this}seek(e){if(!Number.isFinite(e)||e<0||this.disposed)throw RangeError(`Invalid animation time; seek to a finite time >= 0 on a live Animation`);return this.time=e,this.apply(e),this}setMorph(e,t,n=NaN){if(typeof e==`string`){let n=[];for(let t of this.model.primitives)for(let r=0;r<t.targetNames.length;r++)t.targetNames[r]===e&&r<t.weights.length&&n.push([t,r]);if(!n.length||!Number.isFinite(Math.fround(t))||this.disposed)throw this.morphError(`name ${JSON.stringify(e)}`);for(let[e,r]of n)e.weights[r]=t;return}let r=this.model.primitives,i=!1,a=Number.isInteger(t)&&t>=0;for(let n=0;n<r.length;n++)r[n].nodeIndex===e&&(i=!0,t>=r[n].weights.length&&(a=!1));if(!i||!a||!Number.isFinite(Math.fround(n))||this.disposed)throw this.morphError(`node ${e}, target ${t}`);for(let i=0;i<r.length;i++)r[i].nodeIndex===e&&(r[i].weights[t]=n)}morphError(t){let n=/* @__PURE__ */ new Map;for(let e of this.model.primitives)e.weights.length&&n.set(e.nodeIndex,e.weights.length);return e(`Invalid morph target/weight; pass a morph target index the node has and a finite weight, on a live Animation; requested ${t}; available `+([...n].map(([e,t])=>`node ${e}: ${t} targets`).join(`, `)||`no morphed nodes`),`geometry`)}apply(e){this.due=!1;let t=this.clips[this.clip];if(!t)return;let n=(this.options.loop??!0)&&t.duration>0?e%t.duration:Math.min(e,t.duration);this.grouped()||this.groupPrimitives();for(let e=0;e<t.tracks.length;e++){let r=t.tracks[e],i=a(r,n,r.path===`rotation`,r.sample),o=this.model.nodes[r.node];if(r.path===`translation`)o.position.set(i[0],i[1],i[2]);else if(r.path===`scale`)o.scale.set(i[0],i[1],i[2]);else if(r.path===`rotation`){if(i.length!==4)o.setQuaternion(Array.from(i));else{for(let e=0;e<4;e++)this.quaternion[e]=i[e];o.setQuaternion(this.quaternion)}}else{o.check();let e=this.model.primitives,t=this.groupItems;for(let n=this.groupStart[r.node];n<this.groupStart[r.node+1];n++)e[t[n]].weights.set(i)}}t.bind&&d(t.bound??=t.bind(),n)}setup(e,r=e.gpu){if(e!==this.model.root.engine||this.model.disposed||this.disposed)throw new C(`attached`,`Animation model is disposed or belongs to another engine; attach the Animation to the engine that loaded the model`);if(!r)throw new C(`unsupported`,`Animation requires WebGPU; use a browser with WebGPU or leave skinning and morphing out; see https://margoengine.com/errors#webgpu`);this.device=r,this.unsubscribe?.(),this.unsubscribe=this.model.onDispose(()=>this.destroy());let i=this.arena=fe.of(r),a=[],o=[],s=h(this.model.asset.doc);for(let e of this.model.primitives){let n=S(e.definition),r=n.targets,i=b(s.nodes[e.nodeIndex]).skin,c=typeof i==`number`?s.skins[i]:void 0;if(i!==void 0&&(typeof i!=`number`||!Number.isInteger(i)||i<0||!c))throw TypeError(`Missing glTF skin; the node must reference a skin index that exists in the glTF skins array`);if(!r.length&&i===void 0)continue;let l=e.vertices.length/20,u=ze(e),d=this.model.asset,f=e.part?.vertexMap,p=f?d.accessor(n.attributes.POSITION,`VEC3`).length/3:l;for(let e of r)for(let t of Le){let n=e[t],r=n===void 0?void 0:d.doc.accessors?.[n];if(n!==void 0&&(r?.type!==`VEC3`||r.count!==p))throw RangeError(`Morph target count mismatch; every morph attribute needs one VEC3 per vertex`)}let h=Y,g=[],_=n.attributes,v=i!==void 0&&(_.JOINTS_1!==void 0||_.WEIGHTS_1!==void 0),y=i!==void 0&&this.options.skinning?.vertexData?this.options.skinning:void 0,C=v?16:8,w=C+(y?4:0),T=/* @__PURE__ */ new Uint32Array(8);if(i!==void 0){let n=m(c,this.model.nodes.length);if(g=n.joints,h=n.inverseBindMatrices===void 0?we(g.length):this.model.asset.accessor(n.inverseBindMatrices,`MAT4`),n.inverseBindMatrices!==void 0&&x(s,n.inverseBindMatrices)?.componentType!==5126)throw TypeError(`Inverse bind matrices must be Float32; re-export the glTF without quantised matrices`);if(h.length!==g.length*16)throw RangeError(`Inverse bind matrix count mismatch; the skin needs one 4x4 matrix per joint`);let r=g.length,i=e.nodeIndex,a=e.definition;u.influences=()=>{let e=Be(d,s,_,l,p,w,r,f);if(y){let n=t(Ee(y,d,s,i,a),4,f),r=new Float32Array(e.buffer,e.byteOffset,e.length);for(let e=0;e<l;e++)for(let t=0;t<4;t++){let i=n[e*4+t];if(!Number.isFinite(i))throw RangeError(`Invalid skinning vertexData; every number must be finite`);r[e*w+C+t]=i}}return e},T=u.influences()}let E=this.options.skinning,D=g.length?E?.share?.(s.nodes[e.nodeIndex]?.extras):void 0;if(g.length&&E?.share){let e;if(D){if(D.length!==p)throw RangeError(`Invalid skin share count; the node needs one share per vertex of its primitive`);e=t(D,1,f);for(let t=0;t<l;t++)if(!(e[t]>=0&&e[t]<=1))throw RangeError(`Invalid skin share; each vertex needs a finite share between 0 and 1`)}let n=t=>{for(let n=0;n<l;n++)t[n*w]=t[n*w]&65535|(e?Math.round(e[n]*65535):65535)<<16;return t};n(T);let r=u.influences;u.influences=()=>n(r())}u.joints=g,u.inverseBind=h;let O=r.some(e=>e.TANGENT!==void 0)?12:8,k=f??e.definition,A;r.length&&(u.deltas=()=>Re(d,r,l,p,O,f),$.has(k)||(A=u.deltas(),$.set(k,A.words.length)));let j=r.length?$.get(k):0;g.length||(u.palette=Float32Array.from(Ce),u.paletteBits=new Uint32Array(u.palette.buffer)),a.push(u),o.push({primitive:e,count:l,targets:r.length,joints:g.length,extra:v,mode:g.length?this.options.skinning:void 0,asset:this.model.asset,definition:e.definition,skin:i,morphWords:j,morphStride:O,deltas:()=>{let e=A??u.deltas();return A=void 0,e.words},influences:()=>T.subarray(0,g.length?l*w:0)})}let c=i.add(o);this.slots.push(...c);for(let e of c)i.pipeline(e.extra,e.mode);a.forEach((e,t)=>{e.slot=c[t],e.leader=a.slice(0,t).find(e=>e.slot.bones===c[t].bones&&!e.leader)});let l=a.filter(e=>e.joints.length&&!e.leader).sort((e,t)=>e.slot.bones.offset-t.slot.bones.offset),u=l.reduce((e,t)=>e+t.joints.length*16,0),d=new Float32Array(u),f=new Float32Array(u),p=0;for(let e of l){let t=e.joints.length*16;e.palette=d.subarray(p,p+t),e.spare=f.subarray(p,p+t);for(let n=0;n<t;n+=16)e.palette.set(Ce,n);e.paletteBits=new Uint32Array(d.buffer,p*4,t),e.spareBits=new Uint32Array(f.buffer,p*4,t),p+=t}if(this.leaders.push(...l),this.wholes=[d,f],this.followLeaders(a),a.forEach((e,t)=>{let n=e.primitive.weights;n.length&&n.byteLength<=W(c[t].targets)*4&&r.queue.writeBuffer(e.weights,c[t].weights.offset*4,n)}),this.resources.push(...a),!this.options.skinning||this.options.skinning.blend)for(let e of a)n(e.primitive,e.pose=()=>this.cpuPose(e));for(let e of a)this.deformedNodes.includes(e.primitive.node)||this.deformedNodes.push(e.primitive.node);this.model.prepareDeformation=this.prepareDeformation,this.model.createDeformationRenderer=this.createDeformationRenderer}onPreUpdate(e){this.model.disposed?this.model.root.engine.sceneOf(this)?.removePlugin(this.name):(this.checkFrame(),this.advanceTime(e),this.due&&this.apply(this.time))}advanceTime(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);if(!this.playing||this.disposed)return;this.time+=e*(this.options.speed??1);let t=this.clips[this.clip]?.duration??0;(this.options.loop??!0)&&t>0&&(this.time%=t),this.due=!0,this.options.loop===!1&&this.time>=(this.clips[this.clip]?.duration??1/0)&&(this.playing=!1)}registerPasses(e){let t=Ie.get(e);t||Ie.set(e,t={members:/* @__PURE__ */ new Set,ran:0,cache:Pe()}),t.members.add(this),this.group=t,e.add({name:this.name,order:-10,execute:e=>this.deformAll(e)})}deformAll(e){let t=this.group;if(!t||e.backend!==`webgpu`)return this.deform(e);let n=t.ran===0;if(t.ran=t.ran+1>=t.members.size?0:t.ran+1,n)try{let n=[];for(let r of t.members)r.upload(e)&&n.push(r);if(!n.length)return;let r=e.encoder.beginComputePass();try{n[0].arena.dispatches(n,Fe,t.cache).forEach(e=>Ve(r,e))}finally{r.end()}}catch(e){throw t.ran=0,e}}deform(e){if(!this.upload(e))return;let t=e.encoder.beginComputePass();try{this.arena.dispatches([this],Fe,this.cache).forEach(e=>Ve(t,e))}finally{t.end()}}upload(e){if(e.backend!==`webgpu`||this.model.disposed)return!1;let{store:t}=this.model.root.engine,n=i.has(this.model);for(let e=0;!n&&e<this.deformedNodes.length;e++)ee(t,this.deformedNodes[e].id)||(n=!0);if(!n)return!1;let r=this.contiguous();for(let t of this.resources){let n=t.primitive.weights;for(let e=0;e<n.length;e++)if(!Number.isFinite(n[e]))throw RangeError(`Invalid morph weights; set finite weights on the primitive`);if(t.joints.length&&!t.leader){let n=e.device.queue,i=n.writeBuffer,a=Z(n,i),o=a&&t.bonesUploaded&&t.bonesQueue===n,s=t.next=o?t.spare:t.palette;if(!w(t.primitive.node.matrix,this.inverse,this.workspace))throw RangeError(`Singular skinned mesh transform; give the skinned node a non-zero scale`);for(let e=0;e<t.joints.length;e++)Ae(this.joints.nodes[t.joints[e]].matrix,t.inverseBind,e*16,this.joint),T(this.inverse,this.joint,this.product),s.set(this.product,e*16);for(let e=0;e<s.length;e++)if(!Number.isFinite(s[e]))throw RangeError(`Skin matrix overflow; use finite joint transforms and inverse bind matrices`);this.options.skinning?.encode(s);let c=!o;for(let e=0;!c&&e<t.spareBits.length;e++)t.spareBits[e]!==t.paletteBits[e]&&(c=!0);t.bonesChanged=c,c&&!r&&this.uploadBones(n,i,a,t,s,t.slot.bones.offset)}if(t.primitive.weights.length){let n=t.primitive.weights,r=e.device.queue,i=r.writeBuffer,a=Z(r,i),o=t.slot.weights.offset*4;if(n.byteLength>W(t.slot.targets)*4)throw RangeError(`Morph weights longer than the primitive has morph targets; give primitive.weights one value per target`);if(!a||!(n instanceof Float32Array)||!oe(n)||n.length!==t.uploadedWeights.length){t.weightsUploaded=!1;try{Q(r,i,t,t.weights,o,n)}finally{t.weightsUploaded=!1}}else{let e=!t.weightsUploaded||t.weightsQueue!==r;for(let r=0;!e&&r<n.length;r++)Object.is(n[r],t.uploadedWeights[r])||(e=!0);e&&(t.weightsUploaded=!1,Q(r,i,t,t.weights,o,n),t.uploadedWeights.set(n),t.weightsQueue=r,t.weightsUploaded=!0)}}}if(r){let t=this.leaders,n=e.device.queue,r=t[0].next.buffer,i=t[0].next.byteOffset===0;for(let e=0;i&&e<t.length;e++)i=t[e].bonesChanged&&t[e].next.buffer===r;if(i){let e=n.writeBuffer,i=t[0];this.uploadBones(n,e,Z(n,e),i,this.wholes[0].buffer===r?this.wholes[0]:this.wholes[1],i.slot.bones.offset,t)}else for(let e of t)if(e.bonesChanged){let t=n.writeBuffer;this.uploadBones(n,t,Z(n,t),e,e.next,e.slot.bones.offset)}}for(let e of this.leaders)!e.bonesChanged&&e.next===e.spare&&this.swap(e);return this.resources.length>0}cpuPose(e){let t=e.primitive;if(!t.deformed||t.deformed!==e.slot.page.output.buffer||(t.deformedOffset??0)!==e.slot.output.offset*80)return;let n=e.posed??={vertices:Y,revision:0,bind:Y,influences:e.influences(),deltas:e.deltas(),palette:new Float32Array(e.joints.length*16),encoded:this.options.skinning?new Float32Array(e.joints.length*16):Y,weights:new Float32Array(t.weights.length),sampled:new Float32Array(t.weights.length)},r=t.weights;this.weightSource&&r.length&&(n.sampled.set(t.weights),this.weightSource.weightsInto(this,t,n.sampled),r=n.sampled);let i=n.bind!==t.vertices;if(i&&(n.bind=t.vertices,n.vertices=new Float32Array(t.vertices.length)),e.joints.length&&!w(t.node.matrix,this.inverse,this.workspace))throw RangeError(`Singular skinned mesh transform; give the skinned node a non-zero scale`);for(let t=0;t<e.joints.length;t++){Ae(this.joints.nodes[e.joints[t]].matrix,e.inverseBind,t*16,this.joint),T(this.inverse,this.joint,this.product);for(let e=0;e<16;e++)Object.is(n.palette[t*16+e],this.product[e])||(n.palette[t*16+e]=this.product[e],i=!0)}for(let e=0;e<n.weights.length;e++)Object.is(n.weights[e],Math.fround(r[e]))||(n.weights[e]=r[e],i=!0);if(i){let t=this.options.skinning;t&&e.joints.length&&(n.encoded.set(n.palette),t.encode(n.encoded)),te(n.bind,n.vertices,n.deltas,n.weights,n.influences,(e.slot.extra?16:8)+(e.slot.mode?.vertexData?4:0),t?n.encoded:n.palette,t),n.revision++}return n}contiguous(){let e=this.leaders;if(e.length<2)return!1;let t=e[0],n=t.slot.page,r=t.slot.bones.offset+t.joints.length;for(let t=1;t<e.length;t++){let i=e[t];if(i.slot.page!==n||i.slot.bones.offset!==r)return!1;r+=i.joints.length}return(r-t.slot.bones.offset)*64===this.wholes[0].byteLength}swap(e){let t=e.palette,n=e.paletteBits;e.palette=e.spare,e.spare=t,e.paletteBits=e.spareBits,e.spareBits=n,this.followLeaders(this.resources)}uploadBones(e,t,n,r,i,a,o=[r]){let s=!1;for(let e of o)e.bonesUploaded=!1;try{if(Q(e,t,r,r.bones,a*64,i),n){for(let t of o)t.next===t.spare&&this.swap(t),t.bonesQueue=e;s=!0}}finally{for(let e of o)e.bonesUploaded=s}}followLeaders(e){for(let t of e)t.leader&&(t.palette=t.leader.palette,t.paletteBits=t.leader.paletteBits,t.spare=t.leader.spare,t.spareBits=t.leader.spareBits)}release(){if(this.model.createDeformationRenderer===this.createDeformationRenderer&&(this.model.createDeformationRenderer=void 0),this.model.prepareDeformation===this.prepareDeformation&&(this.model.prepareDeformation=void 0),this.arena){this.arena.drop(this.cache),this.group&&this.arena.drop(this.group.cache);for(let e of this.slots)this.arena.remove(e)}for(let e of this.resources)e.pose&&r(e.primitive,e.pose);this.resources=[],this.leaders=[],this.deformedNodes=[],this.slots=[],this.arena=void 0}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.model.root.engine.sceneOf(this)?.removePlugin(this.name),this.unsubscribe?.(),this.unsubscribe=void 0,this.release(),this.group?.members.delete(this),this.group=void 0,this.device=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}destroy(){this.dispose()}};export{ve as i,xe as n,ye as r,He as t};
|