@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.
Files changed (70) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1172 -2
  4. package/dist/batch.d.ts +162 -0
  5. package/dist/clip-utils.d.ts +50 -0
  6. package/dist/clip-utils.js +1 -0
  7. package/dist/clone.d.ts +15 -0
  8. package/dist/cor.d.ts +52 -0
  9. package/dist/cor.js +17 -0
  10. package/dist/deform-readers-DmYAkvBK.js +1 -0
  11. package/dist/deform-readers.d.ts +5 -0
  12. package/dist/deformed-points.d.ts +87 -0
  13. package/dist/deformed-points.js +17 -0
  14. package/dist/discrete-tracks.d.ts +102 -0
  15. package/dist/discrete-tracks.js +1 -0
  16. package/dist/dqs.d.ts +42 -0
  17. package/dist/dqs.js +29 -0
  18. package/dist/errors-t1ewumJS.js +1 -0
  19. package/dist/geometry-cache.d.ts +208 -0
  20. package/dist/geometry-cache.js +4 -0
  21. package/dist/gltf-C2HVNxzB.js +1 -0
  22. package/dist/gltf.d.ts +63 -0
  23. package/dist/group.d.ts +97 -0
  24. package/dist/hdr-format-cmvLFubB.js +1 -0
  25. package/dist/index.d.ts +203 -0
  26. package/dist/index.js +1 -0
  27. package/dist/instanced-morph.d.ts +82 -0
  28. package/dist/instanced-morph.js +13 -0
  29. package/dist/instanced-skin.d.ts +82 -0
  30. package/dist/instanced-skin.js +43 -0
  31. package/dist/interactivity.d.ts +71 -0
  32. package/dist/interactivity.js +4 -0
  33. package/dist/key-cursor.d.ts +23 -0
  34. package/dist/keyframes-YpidiYS4.js +4 -0
  35. package/dist/keyframes.d.ts +204 -0
  36. package/dist/lod.d.ts +87 -0
  37. package/dist/lod.js +4 -0
  38. package/dist/material-animation.d.ts +29 -0
  39. package/dist/mixer.d.ts +226 -0
  40. package/dist/mixer.js +4 -0
  41. package/dist/morph-gpu.d.ts +94 -0
  42. package/dist/morph-gpu.js +50 -0
  43. package/dist/morph-table.d.ts +29 -0
  44. package/dist/playback.d.ts +94 -0
  45. package/dist/playback.js +4 -0
  46. package/dist/point-cache.d.ts +28 -0
  47. package/dist/point-cache.js +1 -0
  48. package/dist/pointer-DyWpFsQi.js +1 -0
  49. package/dist/pointer.d.ts +43 -0
  50. package/dist/pointer.js +1 -0
  51. package/dist/pose-source-MuCl8VDd.js +1 -0
  52. package/dist/pose.d.ts +12 -0
  53. package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
  54. package/dist/retarget.d.ts +115 -0
  55. package/dist/rigid.d.ts +42 -0
  56. package/dist/sampling-DjDWYqt2.js +1 -0
  57. package/dist/sampling.d.ts +112 -0
  58. package/dist/sampling.js +1 -0
  59. package/dist/shader-DuGkHFKx.js +73 -0
  60. package/dist/shader.d.ts +62 -0
  61. package/dist/skeleton-utils.d.ts +2 -0
  62. package/dist/skeleton-utils.js +4 -0
  63. package/dist/skin.d.ts +163 -0
  64. package/dist/src-fuuIJ3rU.js +4 -0
  65. package/dist/vat-SpfL7y9U.js +53 -0
  66. package/dist/vat.d.ts +194 -0
  67. package/dist/vat.js +1 -0
  68. package/dist/vertex-map-BC_WH7ER.js +1 -0
  69. package/dist/weight-buffer.d.ts +1 -0
  70. package/package.json +139 -4
package/dist/dqs.js ADDED
@@ -0,0 +1,29 @@
1
+ import{t as e}from"./shader-DuGkHFKx.js";var t=16;function n(e,t){t.fill(0),t[0]=t[4]=t[8]=1;for(let n=0;n<12;n++){if(e[1]*e[1]+e[2]*e[2]+e[5]*e[5]<=1e-32*(e[0]*e[0]+e[4]*e[4]+e[8]*e[8]))return;for(let n=0;n<2;n++)for(let r=n+1;r<3;r++){let i=e[n*3+r];if(!i)continue;let a=(e[r*3+r]-e[n*3+n])/(2*i),o=Math.sign(a||1)/(Math.abs(a)+Math.sqrt(a*a+1)),s=1/Math.sqrt(o*o+1),c=o*s;for(let t=0;t<3;t++){let i=e[t*3+n],a=e[t*3+r];e[t*3+n]=s*i-c*a,e[t*3+r]=c*i+s*a}for(let t=0;t<3;t++){let i=e[n*3+t],a=e[r*3+t];e[n*3+t]=s*i-c*a,e[r*3+t]=c*i+s*a}for(let e=0;e<3;e++){let i=t[e*3+n],a=t[e*3+r];t[e*3+n]=s*i-c*a,t[e*3+r]=c*i+s*a}}}}var r=/* @__PURE__ */ new Float64Array(9),i=/* @__PURE__ */ new Float64Array(9),a=/* @__PURE__ */ new Float64Array(9),o=/* @__PURE__ */ new Float64Array(9),s=[0,1,2],c=e=>e[0]*(e[4]*e[8]-e[5]*e[7])-e[1]*(e[3]*e[8]-e[5]*e[6])+e[2]*(e[3]*e[7]-e[4]*e[6]);function l(e,t,l,u){for(let n=0;n<3;n++)for(let i=0;i<3;i++)r[n*3+i]=e[t+n*4]*e[t+i*4]+e[t+n*4+1]*e[t+i*4+1]+e[t+n*4+2]*e[t+i*4+2];n(r,i),s.sort((e,t)=>r[t*4]-r[e*4]);let d=s.map(e=>Math.sqrt(Math.max(r[e*4],0))),f=d[0]*1e-7,p=0;for(let n=0;n<3;n++){let r=s[n];if(!(d[n]<=f||!d[n])){p++;for(let o=0;o<3;o++)a[o*3+n]=(e[t+o]*i[r]+e[t+4+o]*i[3+r]+e[t+8+o]*i[6+r])/d[n]}}if(p===0)for(let e=0;e<3;e++)for(let t=0;t<3;t++)a[t*3+e]=i[t*3+s[e]];else if(p===1){let e=a[0],t=a[3],n=a[6],r=+(Math.abs(e)<.6),i=+!r,o=r*e+i*t,s=r-o*e,c=i-o*t,l=-o*n,u=Math.hypot(s,c,l);a[1]=s/u,a[4]=c/u,a[7]=l/u}p&&p<3&&(a[2]=a[3]*a[7]-a[6]*a[4],a[5]=a[6]*a[1]-a[0]*a[7],a[8]=a[0]*a[4]-a[3]*a[1]);for(let e=0;e<3;e++)for(let t=0;t<3;t++){let n=0;for(let r=0;r<3;r++)n+=a[e*3+r]*i[t*3+s[r]];o[e*3+t]=n}let m=1;if(c(o)<0){if(p===3){m=-1;for(let e=0;e<9;e++)o[e]=-o[e]}else for(let e=0;e<3;e++){let t=s[2];for(let n=0;n<3;n++)o[e*3+n]-=2*a[e*3+2]*i[n*3+t]}}let h=(e,t)=>{let n=0;for(let r=0;r<3;r++)n+=d[r]*i[e*3+s[r]]*i[t*3+s[r]];return m*n};l[u]=h(0,0),l[u+1]=h(1,1),l[u+2]=h(2,2),l[u+3]=h(0,1),l[u+4]=h(0,2),l[u+5]=h(1,2),l[u+6]=l[u+7]=0}function u(e){let t=o,n=t[0]+t[4]+t[8],r,i,a,s;if(n>0){let e=2*Math.sqrt(n+1);s=e/4,r=(t[7]-t[5])/e,i=(t[2]-t[6])/e,a=(t[3]-t[1])/e}else if(t[0]>=t[4]&&t[0]>=t[8]){let e=2*Math.sqrt(Math.max(1+t[0]-t[4]-t[8],0));s=(t[7]-t[5])/e,r=e/4,i=(t[1]+t[3])/e,a=(t[2]+t[6])/e}else if(t[4]>=t[8]){let e=2*Math.sqrt(Math.max(1+t[4]-t[0]-t[8],0));s=(t[2]-t[6])/e,r=(t[1]+t[3])/e,i=e/4,a=(t[5]+t[7])/e}else{let e=2*Math.sqrt(Math.max(1+t[8]-t[0]-t[4],0));s=(t[3]-t[1])/e,r=(t[2]+t[6])/e,i=(t[5]+t[7])/e,a=e/4}let c=Math.hypot(r,i,a,s);e[0]=r/c,e[1]=i/c,e[2]=a/c,e[3]=s/c}var d=/* @__PURE__ */ new Float64Array(4);function f(e,n=e){if(e.length%t||n.length<e.length)throw RangeError(`Invalid bone palette; pass 16 floats per bone and an output at least as long`);for(let r=0;r<e.length;r+=t){let t=e[r+12],i=e[r+13],a=e[r+14];l(e,r,n,r+8),u(d);let[o,s,c,f]=d;n[r]=o,n[r+1]=s,n[r+2]=c,n[r+3]=f,n[r+4]=.5*(t*f+i*c-a*s),n[r+5]=.5*(-t*c+i*f+a*o),n[r+6]=.5*(t*s-i*o+a*f),n[r+7]=-.5*(t*o+i*s+a*c)}return n}var p=(e,t=!1)=>{let n=[`x`,`y`,`z`,`w`].map(e=>[t?`ids.${e}`:`joints.${e}`,`jointWeights.${e}`]);if(e)for(let e of[`x`,`y`,`z`,`w`])n.push([`jointsExtra.${e}`,`weightsExtra.${e}`]);return`var pivot=${n[0][0]};var heaviest=${n[0][1]};
2
+ ${n.slice(1).map(([e,t])=>`if(${t}>heaviest){heaviest=${t};pivot=${e};}`).join(``)}
3
+ let near=boneMatrices[s.bones+pivot][0];
4
+ var real=vec4f(0);var dual=vec4f(0);var stretchA=vec4f(0);var stretchB=vec4f(0);
5
+ ${n.map(([e,t])=>`{let b=boneMatrices[s.bones+${e}];let k=select(${t},-${t},dot(b[0],near)<0);real+=b[0]*k;dual+=b[1]*k;stretchA+=b[2]*${t};stretchB+=b[3]*${t};}`).join(`
6
+ `)}
7
+ let size=length(real);let turn=real/size;let moved=dual/size;
8
+ let shift=2*(turn.w*moved.xyz-moved.w*turn.xyz+cross(turn.xyz,moved.xyz));
9
+ let stretch=mat3x3f(stretchA.x,stretchA.w,stretchB.x,stretchA.w,stretchA.y,stretchB.y,stretchB.x,stretchB.y,stretchA.z);
10
+ v.position=vec4f(rotated(turn,stretch*v.position.xyz)+shift,1);
11
+ let normalMatrix=mat3x3f(cross(stretch[1],stretch[2]),cross(stretch[2],stretch[0]),cross(stretch[0],stretch[1]));
12
+ let handedness=select(-1.0,1.0,dot(stretch[0],cross(stretch[1],stretch[2]))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;
13
+ v.normal=vec4f(rotated(turn,select(vec3f(0,1,0),bent,dot(bent,bent)>0.0)),0);
14
+ v.tangent=vec4f(rotated(turn,stretch*v.tangent.xyz),v.tangent.w*handedness);`},m={name:`dual-quaternion`,shader:t=>e(t,{functions:`fn rotated(q:vec4f,x:vec3f)->vec3f {return x+2*cross(q.xyz,cross(q.xyz,x)+q.w*x);}`,blend:p(t)}),encode:e=>{f(e)},blend:(e,t,n,r,i)=>y(e,t,n,r,i)},h=`fn boneMatrix(b:mat4x4f)->mat4x4f {
15
+ let st=mat3x3f(b[2].x,b[2].w,b[3].x,b[2].w,b[2].y,b[3].y,b[3].x,b[3].y,b[2].z);
16
+ let shift=2*(b[0].w*b[1].xyz-b[1].w*b[0].xyz+cross(b[0].xyz,b[1].xyz));
17
+ return mat4x4f(vec4f(rotated(b[0],st[0]),0),vec4f(rotated(b[0],st[1]),0),vec4f(rotated(b[0],st[2]),0),vec4f(shift,1));
18
+ }`,g=e=>{let t=[`x`,`y`,`z`,`w`].map(e=>`boneMatrix(boneMatrices[s.bones+ids.${e}])*jointWeights.${e}`);if(e)for(let e of[`x`,`y`,`z`,`w`])t.push(`boneMatrix(boneMatrices[s.bones+jointsExtra.${e}])*weightsExtra.${e}`);return`
19
+ {let lin=${t.join(`+`)};
20
+ let lp=lin*vec4f(p0.xyz,1);
21
+ let nm=mat3x3f(cross(lin[1].xyz,lin[2].xyz),cross(lin[2].xyz,lin[0].xyz),cross(lin[0].xyz,lin[1].xyz));
22
+ let hd=select(-1.0,1.0,dot(lin[0].xyz,cross(lin[1].xyz,lin[2].xyz))>=0.0);let bn=nm*n0.xyz*hd;
23
+ let ln=select(vec3f(0,1,0),normalize(bn),dot(bn,bn)>0.0);let dn=v.normal.xyz;let dnu=select(dn,normalize(dn),dot(dn,dn)>0.0);
24
+ let lt=(lin*vec4f(t0.xyz,0)).xyz;
25
+ v.position=vec4f(mix(lp.xyz,v.position.xyz,share),1);
26
+ v.normal=vec4f(mix(ln,dnu,share),0);
27
+ v.tangent=vec4f(mix(lt,v.tangent.xyz,share),select(t0.w*hd,v.tangent.w,share>=0.5));}`},_={name:`dual-quaternion-blend`,shader:t=>e(t,{functions:`fn rotated(q:vec4f,x:vec3f)->vec3f {return x+2*cross(q.xyz,cross(q.xyz,x)+q.w*x);}\n${h}`,blend:`let ids=vec4u(joints.x&65535u,joints.y,joints.z,joints.w);let share=f32(joints.x>>16u)/65535.0;
28
+ let p0=v.position;let n0=v.normal;let t0=v.tangent;
29
+ ${p(t,!0)}${g(t)}`}),encode:m.encode,blend:(e,t,n,r,i,a)=>y(e,t,n,r,i,a),share:e=>{let t=e?.fbxSkinning?.blendWeights;return Array.isArray(t)||ArrayBuffer.isView(t)?t:void 0}},v=(e,t,n,r)=>{let i=e[1]*r-e[2]*n+e[3]*t,a=e[2]*t-e[0]*r+e[3]*n,o=e[0]*n-e[1]*t+e[3]*r;return[t+2*(e[1]*o-e[2]*a),n+2*(e[2]*i-e[0]*o),r+2*(e[0]*a-e[1]*i)]};function y(e,n,r,i,a=[0,0,1],o=1){if(n.length!==r.length||!n.length)throw RangeError(`Invalid influences; pass as many joints as weights, at least one`);let s=n[0],c=r[0];for(let e=1;e<n.length;e++)r[e]>c&&(c=r[e],s=n[e]);let l=s*t,u=[0,0,0,0],d=[0,0,0,0],f=[0,0,0,0,0,0];for(let i=0;i<n.length;i++){let a=n[i]*t,o=r[i],s=0;for(let t=0;t<4;t++)s+=e[a+t]*e[l+t];let c=s<0?-o:o;for(let t=0;t<4;t++)u[t]+=e[a+t]*c,d[t]+=e[a+4+t]*c;for(let t=0;t<6;t++)f[t]+=e[a+8+t]*o}let p=Math.hypot(...u),m=u.map(e=>e/p),h=d.map(e=>e/p),g=i[0],_=i[1],y=i[2],x=v(m,f[0]*g+f[3]*_+f[4]*y,f[3]*g+f[1]*_+f[5]*y,f[4]*g+f[5]*_+f[2]*y),S=[2*(m[3]*h[0]-h[3]*m[0]+m[1]*h[2]-m[2]*h[1]),2*(m[3]*h[1]-h[3]*m[1]+m[2]*h[0]-m[0]*h[2]),2*(m[3]*h[2]-h[3]*m[2]+m[0]*h[1]-m[1]*h[0])],C=f[1]*f[2]-f[5]*f[5],w=f[4]*f[5]-f[3]*f[2],T=f[3]*f[5]-f[4]*f[1],E=f[0]*f[2]-f[4]*f[4],D=f[3]*f[4]-f[0]*f[5],O=f[0]*f[1]-f[3]*f[3],k=Math.sign(f[0]*C+f[3]*w+f[4]*T),A=v(m,k*(C*a[0]+w*a[1]+T*a[2]),k*(w*a[0]+E*a[1]+D*a[2]),k*(T*a[0]+D*a[1]+O*a[2])),j=Math.hypot(A[0],A[1],A[2])||1,M={position:[x[0]+S[0],x[1]+S[1],x[2]+S[2]],normal:[A[0]/j,A[1]/j,A[2]/j]};return o>=1?M:b(e,n,r,i,a,o,M)}function b(e,n,r,i,a,o,s){let c=[0,0,0,0,0,0,0,0,0],l=[0,0,0];for(let i=0;i<n.length;i++){let a=n[i]*t,o=r[i],s=[e[a],e[a+1],e[a+2],e[a+3]],u=[e[a+4],e[a+5],e[a+6],e[a+7]],d=[[e[a+8],e[a+11],e[a+12]],[e[a+11],e[a+9],e[a+13]],[e[a+12],e[a+13],e[a+10]]];for(let e=0;e<3;e++){let t=v(s,d[e][0],d[e][1],d[e][2]);for(let n=0;n<3;n++)c[e*3+n]+=t[n]*o}l[0]+=o*2*(s[3]*u[0]-u[3]*s[0]+s[1]*u[2]-s[2]*u[1]),l[1]+=o*2*(s[3]*u[1]-u[3]*s[1]+s[2]*u[0]-s[0]*u[2]),l[2]+=o*2*(s[3]*u[2]-u[3]*s[2]+s[0]*u[1]-s[1]*u[0])}let[u,d,f]=[c.slice(0,3),c.slice(3,6),c.slice(6,9)],p=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],m=[p(d,f),p(f,u),p(u,d)],h=Math.sign(u[0]*m[0][0]+u[1]*m[0][1]+u[2]*m[0][2])||1,g=(e,t)=>[e[0][0]*t[0]+e[1][0]*t[1]+e[2][0]*t[2],e[0][1]*t[0]+e[1][1]*t[1]+e[2][1]*t[2],e[0][2]*t[0]+e[1][2]*t[1]+e[2][2]*t[2]],_=g([u,d,f],i).map((e,t)=>e+l[t]),y=g(m,a).map(e=>e*h),b=Math.hypot(y[0],y[1],y[2]),x=b>0?y.map(e=>e/b):[0,1,0],S=(e,t)=>e+(t-e)*o,C=[S(x[0],s.normal[0]),S(x[1],s.normal[1]),S(x[2],s.normal[2])],w=Math.hypot(C[0],C[1],C[2])||1;return{position:[S(_[0],s.position[0]),S(_[1],s.position[1]),S(_[2],s.position[2])],normal:[C[0]/w,C[1]/w,C[2]/w]}}export{_ as blendSkinning,m as dualQuaternionSkinning,f as encodeDualQuaternions,y as skinDualQuaternion};
@@ -0,0 +1 @@
1
+ var e=(e,t)=>Object.assign(Error(t),{name:`MargoError`,code:e}),t=(e,t)=>`${e}; see https://margoengine.com/errors#${t}`,n=(e,n)=>RangeError(t(e,n));export{n,e as t};
@@ -0,0 +1,208 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin } from '@margoengine/core/extension';
4
+ import { PBRModel, type GLTFDocument } from '@margoengine/gltf/pbr-model';
5
+ /** One run of frames sharing a topology. Positions and normals hold `frameCount` frames of `vertexCount` vertices. */
6
+ export interface GeometryChunk {
7
+ /** Frames per second of the cache. */
8
+ rate: number;
9
+ /** Frames in the whole cache, or 0 when the file does not say. */
10
+ totalFrames: number;
11
+ firstFrame: number;
12
+ frameCount: number;
13
+ vertexCount: number;
14
+ indices: Uint32Array;
15
+ /** Two floats per vertex; zero when the cache has none. */
16
+ uvs: Float32Array;
17
+ positions: Float32Array;
18
+ normals: Float32Array;
19
+ /** Min xyz then max xyz over every frame of the chunk. */
20
+ bounds: Float32Array;
21
+ }
22
+ /** Bytes as they arrive: a `fetch` body, any async iterable, or one array. */
23
+ export type GeometryCacheBytes = AsyncIterable<Uint8Array> | ReadableStream<Uint8Array> | Uint8Array;
24
+ /** Options for {@link readGeometryCache}. */
25
+ export interface GeometryCacheReadOptions {
26
+ /** Stops the read: the iterator rejects with the signal's reason. */
27
+ signal?: AbortSignal;
28
+ /** Refuses a chunk larger than this, before allocating it. Default 1 GiB. */
29
+ maxChunkBytes?: number;
30
+ }
31
+ /**
32
+ * Reads a geometry cache as it arrives, one chunk per step, holding no more than the chunk being read. A chunk with no
33
+ * indices or UVs repeats the previous chunk's. Rejects with a `failed` MargoError on a damaged or cut off file.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * const response = await fetch('/flag.mgc');
38
+ * for await (const chunk of readGeometryCache(response.body!)) console.log(chunk.firstFrame, chunk.vertexCount);
39
+ * ```
40
+ */
41
+ export declare function readGeometryCache(source: GeometryCacheBytes, { signal, maxChunkBytes }?: GeometryCacheReadOptions): AsyncGenerator<GeometryChunk, void, undefined>;
42
+ /** One chunk to write: frames of positions, with normals and UVs when the file should carry them. */
43
+ export interface GeometryChunkInput {
44
+ frameCount: number;
45
+ /** `frameCount` frames of three floats per vertex. */
46
+ positions: Float32Array;
47
+ /** Leave out to repeat the last chunk's topology. */
48
+ indices?: Uint32Array;
49
+ /** Same shape as `positions`. Default: computed when read. */
50
+ normals?: Float32Array;
51
+ /** Two floats per vertex. Default: the last chunk's if it has as many vertices, else zero. */
52
+ uvs?: Float32Array;
53
+ }
54
+ /** Writes a geometry cache (format in the package README). Chunks of about a second stream well. */
55
+ export declare function encodeGeometryCache(rate: number, chunks: readonly GeometryChunkInput[]): Uint8Array;
56
+ /** One frame of a mesh sequence, as a fluid or destruction bake writes one mesh a frame. */
57
+ export interface MeshSequenceFrame {
58
+ /** Three floats per vertex. */
59
+ positions: Float32Array;
60
+ /** Whole triangles into this frame's vertices. */
61
+ indices: Uint32Array;
62
+ /** Three floats per vertex. Default: computed when read. */
63
+ normals?: Float32Array;
64
+ /** Two floats per vertex. */
65
+ uvs?: Float32Array;
66
+ }
67
+ /** Options for {@link encodeMeshSequence} and {@link streamMeshSequence}. */
68
+ export interface MeshSequenceOptions {
69
+ /** Most frames in one chunk, 1..65,536. Default the frame rate rounded (about a second, which streams well). */
70
+ maxChunkFrames?: number;
71
+ }
72
+ /**
73
+ * Streams a mesh sequence (one whole mesh a frame, the topology free to change: a meshed fluid, a fracture) as
74
+ * geometry-cache bytes, chunk by chunk, for {@link GeometryCachePlayer}. Frames may arrive from any iterable or async
75
+ * iterable (files read one at a time), so a long bake is never in memory whole.
76
+ * @throws RangeError for a rate not above 0, a bad `maxChunkFrames`, an empty sequence or a malformed frame (named).
77
+ * @example
78
+ * ```ts
79
+ * const parts: Uint8Array[] = [];
80
+ * const tri = (x: number) => ({positions: new Float32Array([x, 0, 0, 1, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2])});
81
+ * for await (const part of streamMeshSequence(24, [tri(0), tri(0.1)])) parts.push(part);
82
+ * ```
83
+ */
84
+ export declare function streamMeshSequence(rate: number, frames: Iterable<MeshSequenceFrame> | AsyncIterable<MeshSequenceFrame>, options?: MeshSequenceOptions): AsyncGenerator<Uint8Array, void, undefined>;
85
+ /**
86
+ * A mesh sequence (one whole mesh a frame) as one geometry-cache file, its total frame count filled in.
87
+ * @throws RangeError as {@link streamMeshSequence}.
88
+ */
89
+ export declare function encodeMeshSequence(rate: number, frames: Iterable<MeshSequenceFrame> | AsyncIterable<MeshSequenceFrame>, options?: MeshSequenceOptions): Promise<Uint8Array>;
90
+ /** Where a cache comes from. A URL, an array or a function can start again; a stream cannot, so it keeps what it read. */
91
+ export type GeometryCacheSource = string | URL | GeometryCacheBytes | ((signal: AbortSignal) => GeometryCacheBytes);
92
+ /** Options for {@link GeometryCachePlayer.attach}. */
93
+ export interface GeometryCachePlayerOptions {
94
+ /** Start over at the end. Default true. */
95
+ loop?: boolean;
96
+ /** Playback rate multiplier, finite and >= 0. Default 1. */
97
+ speed?: number;
98
+ /** Chunks to read ahead of the one playing, at least 1. Default 2. */
99
+ ahead?: number;
100
+ /** Stops the stream; the player keeps the frame it has. */
101
+ signal?: AbortSignal;
102
+ /** A glTF material for the mesh. Default: plain white. */
103
+ material?: NonNullable<GLTFDocument['materials']>[number];
104
+ /** See {@link GeometryCacheReadOptions.maxChunkBytes}. */
105
+ maxChunkBytes?: number;
106
+ }
107
+ /** What the player has done so far. */
108
+ export interface GeometryCacheStats {
109
+ /** Frames written to the GPU. */
110
+ uploads: number;
111
+ /** Frames the clock waited because the chunk had not arrived. */
112
+ stalls: number;
113
+ /** Chunks read, restarts included. */
114
+ chunks: number;
115
+ /** Times the mesh changed topology. */
116
+ swaps: number;
117
+ }
118
+ /**
119
+ * Plays a geometry cache on a mesh of its own (`player.model`), reading chunks only as far ahead as `ahead`. The clock
120
+ * waits when the stream falls behind, so playback never jumps. Between two frames of one topology the vertices
121
+ * interpolate; a chunk with another topology swaps the mesh at its first frame.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * const flag = await GeometryCachePlayer.attach(stage.engine, '/flag.mgc');
126
+ * flag.model.root.setPosition([0, 2, 0]);
127
+ * ```
128
+ */
129
+ export declare class GeometryCachePlayer implements EnginePlugin {
130
+ private readonly open;
131
+ private readonly abort;
132
+ private readonly rewinds;
133
+ private readonly unlisten;
134
+ readonly name: string;
135
+ /** Seconds played. Set it, or call {@link seek}, to move. */
136
+ time: number;
137
+ playing: boolean;
138
+ speed: number;
139
+ loop: boolean;
140
+ /** The mesh being played. The player owns it: dispose the player, not the model. */
141
+ readonly model: PBRModel;
142
+ readonly stats: GeometryCacheStats;
143
+ /** Settles when the stream has been read to its end, which follows the clock by `ahead` chunks; rejects if reading fails. */
144
+ readonly done: Promise<void>;
145
+ /** Why reading stopped early, if it did. */
146
+ failure?: unknown;
147
+ disposed: boolean;
148
+ private engine?;
149
+ private buffer?;
150
+ private capacity;
151
+ private scratch;
152
+ private installed;
153
+ private chunks;
154
+ /** The frame the reader delivers next. */
155
+ private readTo;
156
+ /** Frames in the whole cache, once the end has been read. */
157
+ private frames;
158
+ private shown;
159
+ /** Ends a reader when a seek restarts it. */
160
+ private reader;
161
+ private wake?;
162
+ private settle;
163
+ private readonly ahead;
164
+ /** Reads the first chunk, then adds the mesh and the player to the engine. */
165
+ static attach(engine: EngineKernel, source: GeometryCacheSource, options?: GeometryCachePlayerOptions): Promise<GeometryCachePlayer>;
166
+ private constructor();
167
+ setup(engine: Engine): void;
168
+ /** Seconds in the whole cache, or Infinity until the stream has ended. */
169
+ get duration(): number;
170
+ /** Min xyz then max xyz of the chunk playing, over all its frames. */
171
+ get bounds(): Float32Array;
172
+ /**
173
+ * Moves the clock by `delta` seconds times `speed`, wrapping or stopping at the last frame as `loop` says: the CPU
174
+ * part of the frame update, which a seek from `@margoengine/cutscene/seek` replays. It reads and shows no frame, so a
175
+ * replayed step never waits for the stream; the next update shows the frame reached, or waits there for its data.
176
+ */
177
+ advanceTime(delta: number): void;
178
+ /** The frame place and lap of the last `advanceTime`, read by the frame update that follows it. */
179
+ private at;
180
+ private wrapped;
181
+ /** Moves the clock. A place the player no longer holds starts the stream again, if it can. */
182
+ seek(seconds: number): this;
183
+ onPreUpdate(delta: number): void;
184
+ onDeviceRestored(engine: Engine): void;
185
+ dispose(): void;
186
+ [Symbol.dispose]: () => void;
187
+ private find;
188
+ private holdsAll;
189
+ /** The chunk that opens the next lap stays, so that a wrap can show it at once. */
190
+ private pinned;
191
+ /** Lets go of chunks already played, when they can be read again. */
192
+ private drop;
193
+ /** Chunks held unbroken after the one playing. One held further on, past a gap, does not stop the reader. */
194
+ private behind;
195
+ private pump;
196
+ private restart;
197
+ private packs;
198
+ /**
199
+ * The CPU pose synchronous scene queries test (shared/pose-source.js): `scratch`, the very floats the frame uploads.
200
+ */
201
+ private readonly pose;
202
+ /** Writes the frame's vertices into `scratch`. Position and normal only: the rest is the chunk's. */
203
+ private pack;
204
+ private show;
205
+ /** Another topology: the mesh takes this chunk's vertices and triangles, and the output buffer grows if it must. */
206
+ private swap;
207
+ private bind;
208
+ }
@@ -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"./pose-source-MuCl8VDd.js";import{MargoError as t}from"@margoengine/math/errors";import{GLTFAsset as n,PBRModel as r}from"@margoengine/gltf/pbr-model";var i=16,a=64,o=1212368717,s=1263421507,c=1,l=1,u=2,d=20,f=e=>new t(`failed`,`Geometry cache ${e}; export the file again`);async function*p(e,t){if(e instanceof Uint8Array)yield e;else{if(`getReader`in e){let n=e.getReader(),r=()=>void n.cancel(t?.reason).catch(()=>{});t?.addEventListener(`abort`,r,{once:!0});try{for(;;){let{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t?.removeEventListener(`abort`,r),n.cancel().catch(()=>{}),n.releaseLock()}}yield*e}}var m=class{constructor(){this.parts=[],this.head=0,this.size=0}push(e){this.parts.push(e),this.size+=e.length}take(e){let t=new Uint8Array(e);for(let n=0;n<e;){let r=this.parts[0],i=Math.min(r.length-this.head,e-n);t.set(r.subarray(this.head,this.head+i),n),n+=i,this.head+=i,this.head===r.length&&(this.parts.shift(),this.head=0)}return this.size-=e,t}};function h(e){let{positions:t,indices:n,vertexCount:r,frameCount:i}=e,a=new Float32Array(t.length);for(let e=0;e<i;e++){let i=e*r*3;for(let e=0;e+2<n.length;e+=3){let r=i+n[e]*3,o=i+n[e+1]*3,s=i+n[e+2]*3,c=t[o]-t[r],l=t[o+1]-t[r+1],u=t[o+2]-t[r+2],d=t[s]-t[r],f=t[s+1]-t[r+1],p=t[s+2]-t[r+2],m=l*p-u*f,h=u*d-c*p,g=c*f-l*d;for(let e of[r,o,s])a[e]+=m,a[e+1]+=h,a[e+2]+=g}}for(let e=0;e<a.length;e+=3){let t=Math.hypot(a[e],a[e+1],a[e+2]);t>0?(a[e]/=t,a[e+1]/=t,a[e+2]/=t):a[e+2]=1}return a}async function*g(e,{signal:t,maxChunkBytes:n=2**30}={}){let r=new m,d=0,g=0,_=0,v,y,b=(e,t)=>{let n=t.getUint32(12,!0),r=t.getUint32(16,!0),i=t.getUint32(20,!0),a=t.getUint32(24,!0),o=e.buffer,s=0,c=e=>{let t=new Float32Array(o,s,e);return s+=e*4,t},p=i?new Uint32Array(o,0,i):y?.indices;if(s=i*4,!p)throw f(`starts with a chunk that has no indices`);for(let e=0;e<p.length;e++)if(p[e]>=r)throw f(`has an index past its vertices`);let m=a&u?c(r*2):y?.uvs.length===r*2?y.uvs:new Float32Array(r*2),_=c(n*r*3),v={rate:d,totalFrames:g,firstFrame:t.getUint32(8,!0),frameCount:n,vertexCount:r,indices:p,uvs:m,positions:_,normals:_,bounds:/* @__PURE__ */ new Float32Array(6)};for(let e=0;e<6;e++)v.bounds[e]=t.getFloat32(32+e*4,!0);v.normals=a&l?c(n*r*3):h(v);for(let e of[_,v.normals])for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw f(`holds a non-finite vertex`);return v};for await(let m of p(e,t))for(t?.throwIfAborted(),r.push(m);;){if(!d){if(r.size<i)break;let e=r.take(i),t=new DataView(e.buffer);if(t.getUint32(0,!0)!==o)throw f(`has the wrong magic number`);if(t.getUint32(4,!0)!==c)throw f(`has unknown version ${t.getUint32(4,!0)}`);if(d=t.getFloat32(8,!0),g=t.getUint32(12,!0),!(d>0&&Number.isFinite(d)))throw f(`has no frame rate`)}if(!v){if(r.size<a)break;let e=new DataView(r.take(a).buffer),t=e.getUint32(12,!0),i=e.getUint32(16,!0),o=e.getUint32(20,!0),c=e.getUint32(24,!0),d=o*4+(c&u?i*8:0)+t*i*(c&l?24:12);if(e.getUint32(0,!0)!==s)throw f(`has a damaged chunk header`);if(!t||i<3||i>1e6||o%3)throw f(`has a chunk with no frames, a broken triangle list, or not 3 to 1,000,000 vertices`);if(e.getUint32(8,!0)!==_)throw f(`skips from frame ${_} to ${e.getUint32(8,!0)}`);if(e.getUint32(4,!0)!==d)throw f(`has a chunk of the wrong size`);if(d>n)throw RangeError(`Geometry chunk of ${d} bytes is over maxChunkBytes; raise it or export smaller chunks`);v=e}let e=v.getUint32(4,!0);if(r.size<e)break;let p=b(r.take(e),v);v=void 0,y=p,_+=p.frameCount,yield p,t?.throwIfAborted()}if(!d||v||r.size)throw f(`ends inside a chunk`);if(g&&_!==g)throw f(`ends at frame ${_} of ${g}`)}function _(e,t){if(!(e>0&&Number.isFinite(e))||!t.length)throw RangeError(`Invalid geometry cache; pass a frame rate above 0 and at least one chunk`);let n=[],r=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i)),d=0;r.setUint32(0,o,!0),r.setUint32(4,c,!0),r.setFloat32(8,e,!0),n.push(new Uint8Array(r.buffer));for(let{frameCount:e,positions:r,indices:i,normals:o,uvs:c}of t){let t=r.length/3/e;if(!Number.isInteger(e)||e<1||!Number.isInteger(t)||t<1||o&&o.length!==r.length||c&&c.length!==t*2||i&&i.length%3)throw RangeError(`Invalid geometry chunk; give positions and normals frameCount frames of 3 floats per vertex, 2 UV floats per vertex and whole triangles`);let f=[i,c,r,o].filter(e=>e!==void 0),p=f.reduce((e,t)=>e+t.byteLength,0),m=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(a)),h=[1/0,1/0,1/0],g=[-1/0,-1/0,-1/0];for(let e=0;e<r.length;e++)h[e%3]=Math.min(h[e%3],r[e]),g[e%3]=Math.max(g[e%3],r[e]);m.setUint32(0,s,!0),m.setUint32(4,p,!0),m.setUint32(8,d,!0),m.setUint32(12,e,!0),m.setUint32(16,t,!0),m.setUint32(20,i?.length??0,!0),m.setUint32(24,(o?l:0)|(c?u:0),!0),[...h,...g].forEach((e,t)=>m.setFloat32(32+t*4,e,!0)),n.push(new Uint8Array(m.buffer));for(let e of f)n.push(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));d+=e}r.setUint32(12,d,!0);let f=new Uint8Array(n.reduce((e,t)=>e+t.length,0)),p=0;for(let e of n)f.set(e,p),p+=e.length;return f}var v=(e,t)=>e===t||!!e&&!!t&&e.length===t.length&&e.every((e,n)=>Object.is(e,t[n]));async function*y(e,t,n){if(!(e>0&&Number.isFinite(e)))throw RangeError(`Invalid mesh sequence rate; pass frames a second above 0`);let r=n?.maxChunkFrames??Math.max(1,Math.round(e));if(!Number.isInteger(r)||r<1||r>65536)throw RangeError(`Invalid maxChunkFrames; pass a whole number from 1 to 65536`);let a=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i));a.setUint32(0,o,!0),a.setUint32(4,c,!0),a.setFloat32(8,e,!0),yield new Uint8Array(a.buffer);let s=[],l=0,u,d,f=()=>{let t=s[0],n=t.positions.length,r=e=>{let t=new Float32Array(n*s.length);return s.forEach((r,i)=>t.set(e(r),i*n)),t},a=_(e,[{frameCount:s.length,positions:r(e=>e.positions),normals:t.normals?r(e=>e.normals):void 0,indices:u&&C(u,t.indices)?void 0:t.indices,uvs:t.uvs&&!v(d,t.uvs)?t.uvs:void 0}]).subarray(i);return new DataView(a.buffer,a.byteOffset).setUint32(8,l,!0),l+=s.length,u=t.indices,t.uvs&&(d=t.uvs),s=[],a},p=0;for await(let e of t){let{positions:t,indices:n,normals:i,uvs:a}=e??{},o=t?.length/3;if(!(t instanceof Float32Array)||!(n instanceof Uint32Array)||!Number.isInteger(o)||o<3||o>1e6||n.length%3||n.some(e=>e>=o)||i!==void 0&&(!(i instanceof Float32Array)||i.length!==t.length)||a!==void 0&&(!(a instanceof Float32Array)||a.length!==o*2)||!t.every(Number.isFinite))throw RangeError(`Invalid mesh sequence frame ${p}; pass 3 to 1,000,000 finite vertices, whole triangles into them, and normals and UVs sized to the vertices`);let c=s[0];c&&(s.length>=r||c.positions.length!==t.length||!C(c.indices,n)||!c.normals!=!i||!v(c.uvs,a))&&(yield f()),s.push(e),p++}if(!s.length)throw RangeError(`Empty mesh sequence; pass at least one frame`);return yield f(),l}async function*b(e,t,n={}){yield*y(e,t,n)}async function x(e,t,n={}){let r=[],i=y(e,t,n),a=await i.next();for(;!a.done;)r.push(a.value),a=await i.next();let o=new Uint8Array(r.reduce((e,t)=>e+t.length,0)),s=0;for(let e of r)o.set(e,s),s+=e.length;return new DataView(o.buffer).setUint32(12,a.value,!0),o}var S=0,C=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]),w=class i{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static async attach(e,n,r={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let{ahead:a=2,speed:o=1,signal:s,maxChunkBytes:c}=r;if(!Number.isInteger(a)||a<1||!Number.isFinite(o)||o<0)throw RangeError(`Invalid geometry cache options; ahead must be a whole number >= 1 and speed a finite number >= 0`);if(!e.gpu)throw new t(`unsupported`,`GeometryCachePlayer needs WebGPU; create the engine with the webgpu backend`);let l=new AbortController,u=()=>l.abort(s.reason),d=e,p,m={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:`geometry-cache:load:`+S++,setup(){p=d.sceneOf(m)}};for(;d.plugins.has(m.name);)m.name+=`:`;d.use(m),p.removePlugin(m.name);let h=()=>s?.removeEventListener(`abort`,u);s?.aborted?u():s?.addEventListener(`abort`,u,{once:!0});let _=()=>g(T(n,l.signal),{signal:l.signal,maxChunkBytes:c}),v=_();try{let e=await v.next();if(e.done)throw f(`holds no chunks`);let t=typeof n==`string`||typeof n==`function`||n instanceof URL||n instanceof Uint8Array,a,o={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:m.name,setup(){a=new i(d,e.value,v,_,l,r,t,h)}};try{p.use(o)}finally{p.plugins.get(o.name)===o&&p.removePlugin(o.name)}return a}catch(e){throw h(),l.abort(e),await v.return(),e}}constructor(e,t,i,a,o,{ahead:s=2,speed:c=1,loop:l=!0,material:u},f,p){this.open=a,this.abort=o,this.rewinds=f,this.unlisten=p,this.name=`geometry-cache:`+S++,this.time=0,this.playing=!0,this.stats={uploads:0,stalls:0,chunks:0,swaps:0},this.disposed=!1,this.capacity=0,this.readTo=0,this.frames=1/0,this.shown=``,this.reader=0,this.at=0,this.wrapped=!1,this.packs=0,this.pose=()=>this.buffer&&this.model.primitives[0].deformed===this.buffer?{vertices:this.scratch,revision:this.packs}:void 0,this.ahead=s,this.speed=c,this.loop=l,this.chunks=[t],this.installed=t,this.stats.chunks=1,this.readTo=t.frameCount,t.totalFrames&&(this.frames=t.totalFrames),this.scratch=new Float32Array(t.vertexCount*d),this.pack(t),this.model=new r(e,new n({asset:{version:`2.0`},materials:[u??{}],meshes:[{primitives:[{attributes:{POSITION:0},material:0}]}],nodes:[{mesh:0}]},[]),[],[[{vertices:this.scratch.slice(),indices:t.indices}]]),this.done=new Promise((e,t)=>{this.settle=n=>n===void 0?e():t(n)}),this.done.catch(()=>{});try{e.use(this.model),e.use(this),this.pump(i,this.reader)}catch(e){throw this.dispose(),e}}setup(e){this.engine=e,this.bind(e.gpu)}get duration(){return this.frames/this.installed.rate}get bounds(){return this.installed.bounds}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache delta; pass finite seconds >= 0`);let t=this.installed.rate;this.playing&&(this.time+=e*this.speed);let n=this.time*t,r=!1;n>=this.frames&&(this.loop?(n%=this.frames,this.time=n/t,r=!0):(n=this.frames-1,this.time=this.frames/t,this.playing=!1)),this.at=n,this.wrapped=r}seek(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache time; pass finite seconds >= 0`);return this.time=e,this}onPreUpdate(e){if(this.disposed)return;let t=this.time;this.advanceTime(e);let n=this.at,r=this.wrapped,i=Math.floor(n),a=this.find(i);r&&this.failure===void 0&&this.rewinds&&!this.holdsAll()&&this.restart(),a?(this.show(a,i,n-i),this.drop(i),this.wake?.()):(this.time=t,this.failure===void 0&&(this.stats.stalls++,this.rewinds&&i<this.readTo&&this.restart()),this.wake?.())}onDeviceRestored(e){this.buffer=void 0,this.capacity=0,this.shown=``,this.bind(e.gpu)}dispose(){this.disposed||(this.disposed=!0,this.unlisten(),this.reader++,this.abort.abort(new t(`disposed`,`GeometryCachePlayer is disposed; attach the cache again`)),this.wake?.(),this.settle(),this.engine?.sceneOf(this)?.removePlugin(this.name),this.model.primitives[0].deformed=void 0,this.buffer?.destroy(),this.buffer=void 0,this.model.dispose(),this.chunks=[])}[Symbol.dispose??Symbol()](){this.dispose()}find(e){return this.chunks.find(t=>e>=t.firstFrame&&e<t.firstFrame+t.frameCount)}holdsAll(){return this.chunks.reduce((e,t)=>e+t.frameCount,0)>=this.frames}pinned(e){return this.loop&&e.firstFrame===0}drop(e){this.rewinds&&(this.chunks=this.chunks.filter(t=>t.firstFrame+t.frameCount>e||t===this.installed||this.pinned(t)))}behind(){let e=Math.floor(this.time*this.installed.rate),t=-1;this.find(e)||(t=0);for(let n=this.find(e);n;n=this.find(e))e=n.firstFrame+n.frameCount,t++;return t}async pump(e,t){try{for(;;){for(;t===this.reader&&this.behind()>=this.ahead;)await new Promise(e=>this.wake=e);if(t!==this.reader)break;let{done:n,value:r}=await e.next();if(t!==this.reader)break;if(n){this.frames=this.readTo,this.settle();return}this.stats.chunks++,this.readTo=r.firstFrame+r.frameCount,(!this.rewinds||r.firstFrame+r.frameCount>Math.floor(this.time*this.installed.rate))&&!this.chunks.some(e=>e.firstFrame===r.firstFrame)&&(this.chunks.push(r),this.chunks.sort((e,t)=>e.firstFrame-t.firstFrame))}e.return()}catch(e){if(t!==this.reader)return;this.failure=e,this.settle(e)}}restart(){this.reader++,this.readTo=0,this.wake?.(),this.chunks=this.chunks.filter(e=>this.pinned(e)),this.pump(this.open(),this.reader)}pack(e,t=0,n=e,r=0,i=0){this.packs++;let a=this.scratch,o=e.vertexCount,s=t*o*3,c=r*o*3,l=e.positions,u=n.positions,f=e.normals,p=n.normals;for(let t=0;t<o;t++){let n=t*d,r=s+t*3,o=c+t*3,m=f[r]+(p[o]-f[r])*i,h=f[r+1]+(p[o+1]-f[r+1])*i,g=f[r+2]+(p[o+2]-f[r+2])*i,_=Math.hypot(m,h,g);_>0?(m/=_,h/=_,g/=_):g=1,a[n]=l[r]+(u[o]-l[r])*i,a[n+1]=l[r+1]+(u[o+1]-l[r+1])*i,a[n+2]=l[r+2]+(u[o+2]-l[r+2])*i,a[n+3]=1,a[n+4]=m,a[n+5]=h,a[n+6]=g,a[n+12]=e.uvs[t*2],a[n+13]=e.uvs[t*2+1],a[n+16]=a[n+17]=a[n+18]=a[n+19]=1}}show(e,t,n){let r=t-e.firstFrame,i=e.firstFrame+`:`+r+`:`+n;if(i===this.shown)return;let a=e,o=r+1;if(o===e.frameCount){let t=this.find(e.firstFrame+e.frameCount);t&&t.vertexCount===e.vertexCount&&C(t.indices,e.indices)?(a=t,o=0):o=r}(this.installed.vertexCount!==e.vertexCount||!C(this.installed.indices,e.indices))&&this.swap(e),this.installed=e,this.pack(e,r,a,o,n),this.engine.gpu.queue.writeBuffer(this.buffer,0,this.scratch),this.shown=i,this.stats.uploads++}swap(e){let t=this.model.primitives[0];this.scratch=new Float32Array(e.vertexCount*d),this.pack(e),t.deformed=void 0,this.model.writeGeometry([{vertices:this.scratch.slice(),indices:e.indices}]),this.bind(this.engine.gpu),this.stats.swaps++}bind(t){let n=this.model.primitives[0];this.scratch.byteLength>this.capacity&&(this.buffer?.destroy(),this.capacity=this.scratch.byteLength,this.buffer=t.createBuffer({size:this.capacity,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})),n.deformed=this.buffer,n.deformedOffset=0,e(n,this.pose),t.queue.writeBuffer(this.buffer,0,this.scratch)}};function T(e,n){return typeof e==`function`?e(n):typeof e!=`string`&&!(e instanceof URL)?e:(async function*(){let r=await fetch(e,{signal:n});if(!r.ok||!r.body)throw new t(`failed`,`Geometry cache request failed with status ${r.status}; check the URL`);yield*p(r.body,n)})()}export{w as GeometryCachePlayer,_ as encodeGeometryCache,x as encodeMeshSequence,g as readGeometryCache,b as streamMeshSequence};
@@ -0,0 +1 @@
1
+ function e(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(t);return e}function t(e,t){if(!Array.isArray(e))throw TypeError(t);return e}function n(n){let r=e(n,`Invalid glTF animation`);return{nodes:t(r.nodes,`Invalid glTF nodes`),accessors:t(r.accessors??[],`Invalid glTF accessors`),animations:t(r.animations??[],`Invalid glTF animations`),skins:t(r.skins??[],`Invalid glTF skins`)}}function r(n){let r=e(n,`Invalid glTF animation`);if(r.name!==void 0&&typeof r.name!=`string`)throw TypeError(`Invalid glTF animation; name must be a string when present`);return{name:r.name,channels:t(r.channels,`Invalid glTF animation`),samplers:t(r.samplers,`Invalid glTF animation`)}}function i(t){let n=e(t,`Invalid glTF animation`),r=n.target&&typeof n.target==`object`&&!Array.isArray(n.target)?n.target:{};return{sampler:n.sampler,target:{node:r.node,path:r.path}}}function a(t){let n=e(t,`Invalid glTF animation`);return{input:n.input,output:n.output,interpolation:n.interpolation}}function o(t){let n=e(t,`Invalid animation target`);return{matrix:n.matrix,skin:n.skin}}function s(e,t){let n=typeof t==`number`?e.accessors[t]:void 0;if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;return{componentType:r.componentType,normalized:r.normalized}}function c(e,t,n){if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>=t)throw TypeError(`Invalid animation ${n}; use an integer index inside the array it refers to`);return e}function l(e){if(e!==`translation`&&e!==`rotation`&&e!==`scale`&&e!==`weights`)throw TypeError(`Invalid animation target; path must be translation, rotation, scale or weights`);return e}function u(e){if(e===void 0)return`LINEAR`;if(e!==`STEP`&&e!==`LINEAR`&&e!==`CUBICSPLINE`)throw RangeError(`Invalid animation time/interpolation; interpolation must be STEP, LINEAR or CUBICSPLINE`);return e}function d(n,r){let i=e(n,`Invalid skin joints`),a=t(i.joints,`Invalid skin joints`);if(!a.length||new Set(a).size!==a.length||!a.every(e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<r))throw TypeError(`Invalid skin joints; use integer node indices inside the glTF nodes array`);return{joints:a,inverseBindMatrices:i.inverseBindMatrices}}function f(n){let r=e(n,`Invalid glTF morph target`);return{targets:t(r.targets??[],`Invalid glTF morph target`).map(t=>{let n=e(t,`Invalid glTF morph target`);return{POSITION:n.POSITION,NORMAL:n.NORMAL,TANGENT:n.TANGENT}}),attributes:e(r.attributes??{},`Invalid skin attributes`)}}export{c as a,l as c,d,n as i,a as l,i as n,u as o,r,o as s,s as t,f as u};
package/dist/gltf.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { Interpolation } from './sampling.js';
2
+ export type AnimationPath = 'translation' | 'rotation' | 'scale' | 'weights';
3
+ export interface AnimationDocument {
4
+ nodes: unknown[];
5
+ accessors: unknown[];
6
+ animations: unknown[];
7
+ skins: unknown[];
8
+ }
9
+ export interface AnimationChannel {
10
+ sampler: unknown;
11
+ target: {
12
+ node: unknown;
13
+ path: unknown;
14
+ };
15
+ }
16
+ export interface AnimationSampler {
17
+ input: unknown;
18
+ output: unknown;
19
+ interpolation: unknown;
20
+ }
21
+ export interface AnimationDefinition {
22
+ name?: string;
23
+ channels: unknown[];
24
+ samplers: unknown[];
25
+ }
26
+ export interface AnimationNode {
27
+ matrix: unknown;
28
+ skin: unknown;
29
+ }
30
+ export interface AnimationAccessor {
31
+ componentType: unknown;
32
+ normalized: unknown;
33
+ }
34
+ export interface Skin {
35
+ joints: number[];
36
+ inverseBindMatrices: unknown;
37
+ }
38
+ export interface MorphTarget {
39
+ POSITION?: unknown;
40
+ NORMAL?: unknown;
41
+ TANGENT?: unknown;
42
+ }
43
+ export interface SkinAttributes extends Record<string, unknown> {
44
+ JOINTS_0?: unknown;
45
+ WEIGHTS_0?: unknown;
46
+ JOINTS_1?: unknown;
47
+ WEIGHTS_1?: unknown;
48
+ }
49
+ export interface MorphDefinition {
50
+ targets: MorphTarget[];
51
+ attributes: SkinAttributes;
52
+ }
53
+ export declare function animationDocument(value: unknown): AnimationDocument;
54
+ export declare function animationDefinition(value: unknown): AnimationDefinition;
55
+ export declare function animationChannel(value: unknown): AnimationChannel;
56
+ export declare function animationSampler(value: unknown): AnimationSampler;
57
+ export declare function animationNode(value: unknown): AnimationNode;
58
+ export declare function animationAccessor(doc: AnimationDocument, id: unknown): AnimationAccessor | undefined;
59
+ export declare function animationIndex(value: unknown, length: number, label: string): number;
60
+ export declare function animationPath(value: unknown): AnimationPath;
61
+ export declare function animationInterpolation(value: unknown): Interpolation;
62
+ export declare function skinDefinition(value: unknown, nodeCount: number): Skin;
63
+ export declare function morphDefinition(value: unknown): MorphDefinition;
@@ -0,0 +1,97 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Engine, EnginePlugin } from '@margoengine/core/extension';
3
+ import type { PBRModel } from '@margoengine/gltf/pbr';
4
+ import { type KeyframeClip } from './keyframes.js';
5
+ import { Skeleton } from './skin.js';
6
+ /**
7
+ * A glTF PBR model's player that an {@link AnimationGroup} drives: an `Animation` from this package fits. Its own
8
+ * playback is paused while it is a member; the group seeks it instead.
9
+ */
10
+ export interface AnimationGroupPlayer {
11
+ readonly model: PBRModel;
12
+ readonly clips: readonly {
13
+ readonly name: string;
14
+ readonly duration: number;
15
+ }[];
16
+ readonly options: {
17
+ readonly loop?: boolean;
18
+ };
19
+ clip: number;
20
+ playing: boolean;
21
+ seek(time: number): unknown;
22
+ setMorph(node: number, target: number, weight: number): void;
23
+ }
24
+ /** A member of an {@link AnimationGroup}: a model's `Animation`, or (for a code-authored clip) a `Skeleton`. */
25
+ export type AnimationGroupMember = AnimationGroupPlayer | Skeleton;
26
+ /** Options for {@link AnimationGroup}. */
27
+ export interface AnimationGroupOptions {
28
+ /**
29
+ * For a code-authored clip: wrap at its end (default true), else hold its first and last frames. A glTF clip loops
30
+ * as each member Animation's own `loop` option says.
31
+ */
32
+ loop?: boolean;
33
+ /** Clip seconds per second, finite and >= 0. Default 1. */
34
+ speed?: number;
35
+ }
36
+ /**
37
+ * One clip and one clock driving many models, for crowds of clones. Members are
38
+ * glTF PBR models' `Animation`s playing a clip they all have (by name or index), or, for a code-authored
39
+ * `KeyframeClip`, `Skeleton`s and `Animation`s whose bones or nodes the tracks name. Each member may run `offset`
40
+ * seconds ahead (negative: behind) of the group. A glTF clip plays through each member's own sampling path
41
+ * (`animation.seek`), and a code clip through bindings resolved once in `add`, so a frame allocates nothing in the group
42
+ * itself. Use it as an engine plugin (`engine.use(group)`; it advances in `onPreUpdate`) or call `update(delta)`.
43
+ * A member whose model is disposed leaves the group at the next `update` or `seek`; remove a member before disposing
44
+ * only its Animation.
45
+ */
46
+ export declare class AnimationGroup implements EnginePlugin {
47
+ readonly clip: string | number | KeyframeClip;
48
+ readonly options: AnimationGroupOptions;
49
+ readonly name: string;
50
+ /** Group time in seconds; a member plays `time + offset`. */
51
+ time: number;
52
+ /** False stops `update` (and the plugin) from advancing `time`. */
53
+ playing: boolean;
54
+ private readonly members;
55
+ private engine?;
56
+ private disposed;
57
+ /** Creates a group and adds it to `engine` as a plugin, so it advances every frame. */
58
+ static attach(engine: Engine, clip: string | number | KeyframeClip, options?: AnimationGroupOptions): AnimationGroup;
59
+ /**
60
+ * @param clip A glTF clip name or index that every member Animation has, or a code-authored `KeyframeClip`.
61
+ * @param options `loop` (code clips) and `speed`.
62
+ */
63
+ constructor(clip: string | number | KeyframeClip, options?: AnimationGroupOptions);
64
+ /** Number of members. */
65
+ get size(): number;
66
+ /** True when `target` is a member. */
67
+ has(target: AnimationGroupMember): boolean;
68
+ /**
69
+ * Adds a member that plays `offset` seconds ahead of the group (adding it again only changes its offset) and poses it
70
+ * at the current time. An Animation member's own playback is paused (`playing = false`).
71
+ */
72
+ add(target: AnimationGroupMember, offset?: number): this;
73
+ /** Removes a member; it keeps its last pose (an Animation stays paused). */
74
+ remove(target: AnimationGroupMember): this;
75
+ /** Changes a member's time offset in seconds and poses it. */
76
+ setOffset(target: AnimationGroupMember, offset: number): this;
77
+ /** Sets the group time and poses every member. */
78
+ seek(time: number): this;
79
+ /** Advances the group by `delta` seconds times `speed` (when playing) and poses every member. */
80
+ update(delta: number): this;
81
+ /**
82
+ * Moves the group clock by `delta` seconds times `speed` when playing, posing nothing: the CPU part of `update`,
83
+ * which a seek from `@margoengine/cutscene/seek` replays; the next update poses every member at the time reached.
84
+ */
85
+ advanceTime(delta: number): void;
86
+ /** Engine plugin hook; the group needs no GPU resources. */
87
+ setup(engine: Engine): void;
88
+ /** Engine plugin hook: `update(delta)` before the engine updates world matrices. */
89
+ onPreUpdate(delta: number): void;
90
+ /** Drops every member (they keep their last pose) and detaches from the engine. */
91
+ dispose(): void;
92
+ [Symbol.dispose]: () => void;
93
+ /** Poses every member; a member whose model was disposed leaves the group. */
94
+ private poseAll;
95
+ private pose;
96
+ private bind;
97
+ }
@@ -0,0 +1 @@
1
+ function e(e){return e?.view?.viewport}function t(t){let n=e(t);return n?[n[2],n[3]]:[t.width,t.height]}function n(t,n){let r=e(n);if(!r)return;t.setViewport(r[0],r[1],r[2],r[3],0,1);let i=n.view.scissor??r;t.setScissorRect(i[0],i[1],i[2],i[3])}var r=e=>typeof e==`string`&&e.endsWith(`float`);export{n,t as r,r as t};