@margoengine/animation 0.0.0-stage → 0.1.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 (67) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1054 -3
  4. package/dist/batch.d.ts +155 -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/deform-readers-DmYAkvBK.js +1 -0
  9. package/dist/deform-readers.d.ts +5 -0
  10. package/dist/deformed-points.d.ts +87 -0
  11. package/dist/deformed-points.js +17 -0
  12. package/dist/discrete-tracks.d.ts +102 -0
  13. package/dist/discrete-tracks.js +1 -0
  14. package/dist/dqs.d.ts +41 -0
  15. package/dist/dqs.js +29 -0
  16. package/dist/errors-t1ewumJS.js +1 -0
  17. package/dist/geometry-cache.d.ts +208 -0
  18. package/dist/geometry-cache.js +4 -0
  19. package/dist/gltf-C2HVNxzB.js +1 -0
  20. package/dist/gltf.d.ts +63 -0
  21. package/dist/group.d.ts +97 -0
  22. package/dist/hdr-format-cmvLFubB.js +1 -0
  23. package/dist/index.d.ts +201 -0
  24. package/dist/index.js +1 -0
  25. package/dist/instanced-morph.d.ts +82 -0
  26. package/dist/instanced-morph.js +13 -0
  27. package/dist/instanced-skin.d.ts +82 -0
  28. package/dist/instanced-skin.js +43 -0
  29. package/dist/interactivity.d.ts +71 -0
  30. package/dist/interactivity.js +4 -0
  31. package/dist/key-cursor.d.ts +23 -0
  32. package/dist/keyframes-BO50xipp.js +4 -0
  33. package/dist/keyframes.d.ts +204 -0
  34. package/dist/lod.d.ts +87 -0
  35. package/dist/lod.js +4 -0
  36. package/dist/material-animation.d.ts +29 -0
  37. package/dist/mixer.d.ts +226 -0
  38. package/dist/mixer.js +4 -0
  39. package/dist/morph-gpu.d.ts +76 -0
  40. package/dist/morph-gpu.js +48 -0
  41. package/dist/playback.d.ts +94 -0
  42. package/dist/playback.js +4 -0
  43. package/dist/point-cache.d.ts +28 -0
  44. package/dist/point-cache.js +1 -0
  45. package/dist/pointer-BOFnz0gk.js +1 -0
  46. package/dist/pointer.d.ts +43 -0
  47. package/dist/pointer.js +1 -0
  48. package/dist/pose-source-MuCl8VDd.js +1 -0
  49. package/dist/pose.d.ts +7 -0
  50. package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
  51. package/dist/retarget.d.ts +107 -0
  52. package/dist/rigid.d.ts +42 -0
  53. package/dist/sampling-DjDWYqt2.js +1 -0
  54. package/dist/sampling.d.ts +112 -0
  55. package/dist/sampling.js +1 -0
  56. package/dist/shader-CgAVFeOl.js +66 -0
  57. package/dist/shader.d.ts +30 -0
  58. package/dist/skeleton-utils.d.ts +2 -0
  59. package/dist/skeleton-utils.js +4 -0
  60. package/dist/skin.d.ts +163 -0
  61. package/dist/src-WGCsukxV.js +4 -0
  62. package/dist/vat-mWaj5B5R.js +50 -0
  63. package/dist/vat.d.ts +178 -0
  64. package/dist/vat.js +1 -0
  65. package/dist/vertex-map-BC_WH7ER.js +1 -0
  66. package/dist/weight-buffer.d.ts +1 -0
  67. package/package.json +133 -6
@@ -0,0 +1,28 @@
1
+ /** Options of {@link parsePointCache}. */
2
+ export interface PointCacheOptions {
3
+ /** Frames per second for a PC2 file, which does not say. Default 24. An MDD file's own times win. */
4
+ fps?: number;
5
+ /** Turn a Z-up file to Y-up, as `(x, z, -y)`. Default false: the file's axes as written. */
6
+ zUp?: boolean;
7
+ /** Refuses a file holding more floats than this. Default 1 GiB of them. */
8
+ maxFloats?: number;
9
+ }
10
+ /** A point cache read whole. `frameCount` and `positions` fit a chunk of `encodeGeometryCache`. */
11
+ export interface PointCache {
12
+ format: 'pc2' | 'mdd';
13
+ /** Frames per second. */
14
+ rate: number;
15
+ frameCount: number;
16
+ vertexCount: number;
17
+ /** Seconds of each frame: the file's for MDD, from its start frame and `fps` for PC2. */
18
+ times: Float32Array;
19
+ /** `frameCount` frames of `vertexCount` vertices, three floats each. */
20
+ positions: Float32Array;
21
+ }
22
+ /**
23
+ * Reads a PC2 (Point Cache 2, little endian) or MDD (big endian) file. To play one, give it the triangles of its mesh:
24
+ * `encodeGeometryCache(cache.rate, [{ frameCount: cache.frameCount, positions: cache.positions, indices }])`.
25
+ *
26
+ * @throws MargoError code `failed` for a cut or empty file or one over `maxFloats`, `unsupported` for another PC2 version.
27
+ */
28
+ export declare function parsePointCache(bytes: Uint8Array, options?: PointCacheOptions): PointCache;
@@ -0,0 +1 @@
1
+ import{MargoError as e}from"@margoengine/math/errors";var t=`POINTCACHE2\0`,n=32,r=8,i=t=>new e(`failed`,`Point cache ${t}; export the file again`);function a(e,t,n,r){let i=new Float32Array(n);for(let a=0;a<n;a++)i[a]=e.getFloat32(t+a*4,r);return i}function o(t,n,r,a){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw i(`has no frames or no vertices`);let o=t*n*3;if(o*4>a)throw i(`is cut off or is not a PC2 or MDD file: its header asks for ${t} frames of ${n} vertices, more than it holds`);if(o>r)throw new e(`failed`,`Point cache holds ${o} floats, over maxFloats ${r}; raise maxFloats or export fewer frames`);return o}function s(t,r,s){if(t.byteLength<n)throw i(`stops inside its header`);let c=t.getInt32(12,!0),l=t.getInt32(16,!0),u=t.getFloat32(20,!0),d=t.getFloat32(24,!0),f=t.getInt32(28,!0);if(c!==1)throw new e(`unsupported`,`PC2 version ${c} is not read; export version 1`);let p=o(f,l,s,t.byteLength-n);if(!(d>0))throw i(`has a sample rate of 0 or less`);let m=new Float32Array(f);for(let e=0;e<f;e++)m[e]=(u+e*d)/r;return{format:`pc2`,rate:r/d,frameCount:f,vertexCount:l,times:m,positions:a(t,n,p,!0)}}function c(e,t,n){if(e.byteLength<r)throw i(`stops inside its header`);let s=e.getInt32(0,!1),c=e.getInt32(4,!1),l=r+s*4,u=o(s,c,n,e.byteLength-l),d=a(e,r,s,!1),f=d[s-1]-d[0];for(let e=1;e<s;e++)if(!(d[e]>d[e-1]))throw i(`has times that do not rise`);return{format:`mdd`,rate:f>0?(s-1)/f:t,frameCount:s,vertexCount:c,times:d,positions:a(e,l,u,!1)}}function l(e,n={}){let{fps:r=24,zUp:i=!1,maxFloats:a=2**28}=n;if(!(r>0&&Number.isFinite(r)))throw RangeError(`Invalid fps; pass a frame rate above 0`);let o=new DataView(e.buffer,e.byteOffset,e.byteLength),l=String.fromCharCode(...e.subarray(0,12))===t?s(o,r,a):c(o,r,a);if(i){let e=l.positions;for(let t=0;t<e.length;t+=3){let n=e[t+1];e[t+1]=e[t+2],e[t+2]=-n}}return l}export{l as parsePointCache};
@@ -0,0 +1 @@
1
+ import{i as e}from"./keyframes-BO50xipp.js";import{a as t,l as n,o as r}from"./gltf-C2HVNxzB.js";import{textureCoordinates as i,textureTransform as a}from"@margoengine/gltf/pbr-model";function o(e,t){return e===1?1:e**t}var s={SCALAR:1,VEC2:2,VEC3:3,VEC4:4},c=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:void 0,l=e=>Array.isArray(e)?e:[],u=(e,t)=>t.split(`/`).reduce((e,t)=>c(e)?.[t],e),d={"pbrMetallicRoughness/baseColorTexture":0,"pbrMetallicRoughness/metallicRoughnessTexture":1,normalTexture:2,occlusionTexture:3,emissiveTexture:4,"extensions/KHR_materials_clearcoat/clearcoatTexture":5,"extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture":6,"extensions/KHR_materials_clearcoat/clearcoatNormalTexture":7,"extensions/KHR_materials_transmission/transmissionTexture":8,"extensions/KHR_materials_sheen/sheenColorTexture":9,"extensions/KHR_materials_sheen/sheenRoughnessTexture":10,"extensions/KHR_materials_specular/specularTexture":11,"extensions/KHR_materials_specular/specularColorTexture":12},f={"pbrMetallicRoughness/baseColorFactor":[`VEC4`,`base`,0],"pbrMetallicRoughness/roughnessFactor":[`SCALAR`,`factors`,0],"pbrMetallicRoughness/metallicFactor":[`SCALAR`,`factors`,1],"normalTexture/scale":[`SCALAR`,`factors`,2,`normalTexture`],"occlusionTexture/strength":[`SCALAR`,`factors`,3,`occlusionTexture`],emissiveFactor:[`VEC3`,`emissive`,0],alphaCutoff:[`SCALAR`,`settings`,1],"extensions/KHR_materials_emissive_strength/emissiveStrength":[`SCALAR`,`strength`,0,`extensions/KHR_materials_emissive_strength`],"extensions/KHR_materials_dispersion/dispersion":[`SCALAR`,`dispersion`,0,`extensions/KHR_materials_dispersion`],"extensions/KHR_materials_clearcoat/clearcoatFactor":[`SCALAR`,`physical`,0],"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":[`SCALAR`,`physical`,1],"extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale":[`SCALAR`,`physical`,2,`extensions/KHR_materials_clearcoat/clearcoatNormalTexture`],"extensions/KHR_materials_transmission/transmissionFactor":[`SCALAR`,`physical`,3],"extensions/KHR_materials_specular/specularColorFactor":[`VEC3`,`physical`,4],"extensions/KHR_materials_specular/specularFactor":[`SCALAR`,`physical`,7],"extensions/KHR_materials_sheen/sheenColorFactor":[`VEC3`,`physical`,8],"extensions/KHR_materials_sheen/sheenRoughnessFactor":[`SCALAR`,`physical`,11],"extensions/KHR_materials_ior/ior":[`SCALAR`,`ext`,1],"extensions/KHR_materials_volume/thicknessFactor":[`SCALAR`,`volume`,0],"extensions/KHR_materials_volume/attenuationColor":[`VEC3`,`volume`,1],"extensions/KHR_materials_volume/attenuationDistance":[`SCALAR`,`volume`,4,`extensions/KHR_materials_volume/attenuationDistance`]},p={color:`VEC3`,intensity:`SCALAR`,range:`SCALAR`,"spot/innerConeAngle":`SCALAR`,"spot/outerConeAngle":`SCALAR`},m={perspective:[`yfov`,`aspectRatio`,`znear`,`zfar`],orthographic:[`xmag`,`ymag`,`znear`,`zfar`]},h=/^\/materials\/\d+\/extensions\/KHR_materials_ior\/ior$/,g=/* @__PURE__ */ new Set([`pbrMetallicRoughness/baseColorFactor`,`emissiveFactor`,`color`]),_=class{constructor(e){this.reason=e}},v=/* @__PURE__ */ new WeakMap,y=e=>{throw new _(e)},b=(i,a,o)=>{let s=i.asset.doc,u=[],d=[],f=[],p=/* @__PURE__ */ new Set,m=[],g=[],y=/* @__PURE__ */ new Set,b=0;a.channels.forEach((e,v)=>{let x=c(e),S=c(x?.target),w=c(S?.extensions),T=c(w?.KHR_animation_pointer)?.pointer;if(S?.path!==`pointer`&&w?.KHR_animation_pointer===void 0){S?.path===`weights`&&typeof S.node==`number`&&p.add(S.node),u.push(e);return}let E=`Animation ${o} channel ${v}`;if(S?.path!==`pointer`||Object.hasOwn(S,`node`)||typeof T!=`string`)throw TypeError(`${E} KHR_animation_pointer needs path 'pointer', no target node and a pointer string; fix the channel target`);if(y.has(T))throw TypeError(`${E} repeats pointer ${T}; use one channel per property`);y.add(T);let D=n(a.samplers[t(x.sampler,a.samplers.length,`sampler`)]),O=r(D.interpolation),k=i.asset.accessor(D.input,`SCALAR`);if(k.some((e,t)=>e<0||t>0&&e<=k[t-1]))throw RangeError(`${E} key times must be nonnegative and strictly increasing; fix the sampler input`);if(b=Math.max(b,k[k.length-1]),h.test(T)){let e=i.asset.accessor(D.output,`SCALAR`),t=O===`CUBICSPLINE`?3:1;for(let n=0;n<k.length;n++)if(e[n*t+(t>>1)]<1)throw RangeError(`${E} pointer ${T} keys an IOR of ${e[n*t+(t>>1)]}; KHR_materials_ior allows animated IORs of 1 or more only`)}let A;try{A=C(i,s,T,E)}catch(e){if(!(e instanceof _))throw e;g.push(`${E}: pointer ${T} ${e.reason}; skipped`);return}if(`path`in A){A.mesh||p.add(A.nodes[0]);for(let e of A.nodes)(A.mesh?f:d).push({node:e,path:A.path,sampler:x.sampler});A.nodes.length||g.push(`${E}: pointer ${T} has no node using the mesh; skipped`);return}let{accessor:j,size:M,bool:N}=A,P=c(l(s.accessors)[D.output]);if(N&&(O!==`STEP`||P?.componentType!==5121||P.normalized))throw TypeError(`${E} pointer ${T} is a boolean; use STEP and an unsigned byte SCALAR accessor`);let F=i.asset.accessor(D.output,j),I=O===`CUBICSPLINE`,L=M*(I?3:1);if(F.length!==k.length*L)throw RangeError(`${E} pointer ${T} has ${F.length/M} output values for ${k.length} keys; key one ${j} per time${I?` with in and out tangents`:``}`);let R=Array.from(k,(e,t)=>{let n=t*L+(I?M:0),r={time:e,value:Array.from(F.subarray(n,n+M)),interpolation:I?`cubicSpline`:O===`STEP`?`discrete`:`linear`};return I&&(r.inTangent=Array.from(F.subarray(n-M,n)),r.outTangent=Array.from(F.subarray(n+M,n+2*M))),r});m.push({target:A,keys:R,pointer:T})});for(let e of f)p.has(e.node)||d.unshift(e);return{ordinary:u,nodes:d,duration:b,warnings:g,...m.length?{bind:()=>{let t=v.get(i);return t||v.set(i,t=/* @__PURE__ */ new Map),e({name:o,tracks:m.map(({target:e,keys:n,pointer:r})=>({target:i,name:r,type:e.type,set:e.make(t),keys:n}))})}}:{}}};function x(e,t){let n=/^\/nodes\/(\d+)\/weights\/(\d+)$/.exec(t);if(n)return t=>{for(let r of e.primitives)r.nodeIndex===+n[1]&&(r.weights[+n[2]]=t[0])};let r;try{r=C(e,e.asset.doc,t,`Behaviour graph`)}catch(e){if(e instanceof _)return;throw e}if(!(`path`in r)){let t=v.get(e);t||v.set(e,t=/* @__PURE__ */ new Map);let n=r.make(t);return e=>n(Float64Array.from(e))}let i=e.nodes[r.nodes[0]],{path:a}=r;if(i&&a!==`weights`)return e=>{a===`rotation`?i.setQuaternion(Array.from(e)):a===`scale`?i.setScale(Array.from(e)):i.setPosition(Array.from(e))}}function S(e,t,n,r,i){if(e===void 0||!/^(0|[1-9]\d*)$/.test(e)||Number(e)>=t)throw TypeError(`${r} pointer ${i} names no ${n} ${e??``}; point at an existing index`);return Number(e)}function C(e,t,n,r){if(!n.startsWith(`/`))throw TypeError(`${r} pointer ${n} is not a JSON pointer; start it with '/'`);let i=n.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),a=()=>{throw TypeError(`${r} pointer ${n} is not an animatable glTF property; point at a property animations may change`)},o=e=>e.split(`/`).some(e=>e===`extras`||e===`extensions`);i.includes(`extras`)&&y(`targets application-defined extras`);let[d,f,...h]=i,_=h.join(`/`);if(d===`nodes`){let i=S(f,l(t.nodes).length,`node`,r,n);if([`translation`,`rotation`,`scale`,`weights`].includes(_))return{nodes:[i],path:_,mesh:!1};if(_===`extensions/KHR_node_visibility/visible`){c(u(l(t.nodes)[i],`extensions/KHR_node_visibility`))||y(`targets a node without KHR_node_visibility`);let n=e.nodes[i];return{accessor:`SCALAR`,size:1,type:`number`,bool:!0,make:()=>e=>{n.visible=e[0]!==0}}}return o(_)&&y(`targets a node extension this player does not drive`),a()}if(d===`meshes`){let e=S(f,l(t.meshes).length,`mesh`,r,n);return _===`weights`?{nodes:l(t.nodes).flatMap((t,n)=>c(t)?.mesh===e?[n]:[]),path:`weights`,mesh:!0}:(o(_)&&y(`targets a mesh extension this player does not drive`),a())}if(d===`materials`)return w(e,t,S(f,l(t.materials).length,`material`,r,n),_,a);if(d===`cameras`){let i=S(f,l(t.cameras).length,`camera`,r,n),o=c(l(t.cameras)[i]),[s,u,d]=h;if(!m[s]?.includes(u)||d!==void 0)return a();(o.type!==s||!c(o[s]))&&y(`targets ${s} values of a ${String(o.type)} camera`),c(o[s])[u]===void 0&&y(`targets ${u}, which the camera does not define`);let p=e.cameras.filter(e=>c(l(t.nodes)[e.nodeIndex])?.camera===i);return p.length||y(`targets a camera no scene node uses`),{accessor:`SCALAR`,size:1,type:`number`,make:e=>{let t=`camera ${i}`,n=e.get(t)??p.map(e=>{let t={...e[s]};return e[s]=t,t});return e.set(t,n),e=>{for(let t of n)t[u]=e[0]}}}}if(d===`extensions`&&f===`KHR_lights_punctual`&&h[0]===`lights`){let i=l(c(c(t.extensions)?.KHR_lights_punctual)?.lights),o=S(h[1],i.length,`light`,r,n),d=h.slice(2).join(`/`),f=c(i[o]),m=p[d];if(!m)return a();d.startsWith(`spot/`)&&f.type!==`spot`&&y(`targets spot cones of a ${String(f.type)} light`),d===`range`&&f.range===void 0&&y(`targets range, which the light does not define`);let _=e.lights.filter(e=>c(u(l(t.nodes)[e.nodeIndex],`extensions/KHR_lights_punctual`))?.light===o);_.length||y(`targets a light no scene node uses`);let v=d.startsWith(`spot/`)?d.slice(5):d;return{accessor:m,size:s[m],type:g.has(d)?`color`:`number`,make:e=>{if(d===`color`){if(!e.has(`light ${o}`))for(let e of _)e.color=e.color.slice();return e.set(`light ${o}`,!0),e=>{for(let t of _)for(let n=0;n<3;n++)t.color[n]=e[n]}}return e=>{for(let t of _)t[v]=e[0]}}}}return d===`extensions`&&y(`targets ${f}, which this player does not drive`),a()}function w(e,t,n,r,i){let o=c(l(t.materials)[n]),p=[...new Set([...e.primitives,...e.pointsAndLines].filter(e=>e.definition.material===n).map(e=>e.material))],m=/^(.+)\/extensions\/KHR_texture_transform\/(offset|scale|rotation|texCoord)$/.exec(r);if(m){let e=d[m[1]],t=m[2];e===void 0&&y(`targets a texture this player does not map to a live UV transform`),t===`texCoord`&&y(`targets texCoord, an integer UV set this player does not switch`),c(u(o,m[1]))||y(`targets a texture the material does not define`),p.length||y(`targets a material no primitive draws`),p.some(t=>t.maps[e])||y(`targets a texture no drawn primitive samples`);let r=t===`rotation`?`SCALAR`:`VEC2`;return{accessor:r,size:s[r],type:t===`rotation`?`number`:`vector`,make:r=>{let i=`texture ${n} ${e}`,o=r.get(i)??T(p,e);return r.set(i,o),n=>{for(let{m:r,own:i,texCoord:s}of o){if(t===`rotation`)i.rotation=n[0];else{let e=i[t];e[0]=n[0],e[1]=n[1]}let o=a(i,s);if(r.uvt&&r.uvt.length>=e*8+8)for(let t=0;t<8;t++)r.uvt[e*8+t]=o[t]}}}}}let h=f[r];if(!h)return(r.startsWith(`extensions/`)||r.includes(`/extensions/`))&&y(`targets a material extension property this player does not drive`),i();let[_,v,b,x]=h,S=r.startsWith(`extensions/`)?r.split(`/`).slice(0,2).join(`/`):void 0;x&&u(o,x)===void 0&&y(`targets ${x.split(`/`).pop()}, which the material does not define`),S&&!c(u(o,S))&&y(`targets ${S.slice(11)}, which the material does not use`),r===`extensions/KHR_materials_ior/ior`&&u(o,r)===0&&y(`targets an IOR of 0, a mode KHR_materials_ior keeps for good (updates are ignored)`),p.length||y(`targets a material no primitive draws`),(v===`physical`||v===`ext`||v===`volume`)&&(p.some(e=>!e.physical)&&y(`targets a physical material factor gltf/pbr did not load (pass decoders.materials)`),(v===`volume`||b===3)&&p.some(e=>!e.tint&&!e.attenuation)&&y(`targets transmission or volume of a material loaded without transmission`));let C=s[_];return{accessor:_,size:C,type:g.has(r)?`color`:C===1?`number`:`vector`,make:e=>{let t=`material ${n}`,r=e.get(t)??E(o,p);if(e.set(t,r),v===`base`)for(let e of p)e.base=e.base.slice();return e=>{if(v===`emissive`||v===`strength`){if(v===`strength`)r.strength=e[0];else for(let t=0;t<3;t++)r.emissive[t]=e[t];for(let e of p)for(let t=0;t<3;t++)e.emission[t]=r.emissive[t]*r.strength}else{if(v===`volume`){if(b===0)r.thickness=e[0];else if(b===4)r.distance=e[0];else for(let t=0;t<3;t++)r.atten[t]=e[t]}else if(v===`dispersion`)for(let t of p)t.dispersion=e[0];else if(v===`ext`&&b===1)for(let t of p)t.ext[1]=Math.max(1,e[0]);else for(let t of p)for(let n=0;n<C;n++)t[v][b+n]=e[n];(v===`base`||v===`volume`||v===`physical`&&b===3)&&D(r)}}}}}function T(e,t){return e.flatMap(e=>{let n=e.maps[t];if(!n)return[];let r=n.extensions?.KHR_texture_transform??{},a=i(n).texCoord,o={...r,offset:[...r.offset??[0,0]],scale:[...r.scale??[1,1]],rotation:r.rotation??0},s=e.maps.slice();return s[t]={...n,texCoord:a,extensions:{...n.extensions,KHR_texture_transform:o}},e.maps=s,[{m:e,own:o,texCoord:a}]})}function E(e,t){let n=c(u(e,`extensions/KHR_materials_volume`)),r=n?.attenuationDistance;return{mats:t,emissive:[...e.emissiveFactor??[0,0,0]],strength:u(e,`extensions/KHR_materials_emissive_strength/emissiveStrength`)??1,atten:[...n?.attenuationColor??[1,1,1]],thickness:n?.thicknessFactor??0,distance:typeof r==`number`?r:1/0}}function D({mats:e,atten:t,thickness:n,distance:r}){let i=n/r;for(let a of e)if((a.tint||a.attenuation)&&a.physical){if(a.physical[3]>0){let e=a.tint??=[0,0,0];for(let n=0;n<3;n++)e[n]=a.base[n]*a.physical[3]*o(t[n],i)}else a.tint=void 0;if(a.attenuation){for(let e=0;e<3;e++)a.attenuation[e]=o(t[e],i);let e=a.opticalDepth??=[0,0,0];for(let n=0;n<3;n++)e[n]=t[n]===1||i===0?0:-Math.log(t[n])*i}if(a.volume){a.volume[0]=n;for(let e=0;e<3;e++)a.volume[1+e]=o(t[e],1/r)}}}export{x as n,b as t};
@@ -0,0 +1,43 @@
1
+ import type { PBRModel } from '@margoengine/gltf/pbr';
2
+ import { type KeyframeClip } from './keyframes.js';
3
+ import { type AnimationDefinition } from './gltf.js';
4
+ import type { AnimationPath } from './gltf.js';
5
+ /** A pointer channel that drives a node's TRS or morph weights: played as an ordinary node track. */
6
+ export interface PointerNodeChannel {
7
+ node: number;
8
+ path: AnimationPath;
9
+ sampler: unknown;
10
+ }
11
+ /** What {@link PointerChannels} found in one glTF clip. */
12
+ export interface PointerPlan {
13
+ /** Channels without KHR_animation_pointer, for the ordinary node track parser. */
14
+ ordinary: unknown[];
15
+ /** Node TRS and weights pointers, mesh weights expanded to every node using the mesh. */
16
+ nodes: PointerNodeChannel[];
17
+ /** Binds the material, light, camera and visibility pointers to live values; undefined when there are none. */
18
+ bind?: () => KeyframeClip;
19
+ /** The last key time of every pointer channel, skipped ones included. */
20
+ duration: number;
21
+ /** One line per skipped pointer channel. */
22
+ warnings: string[];
23
+ }
24
+ /**
25
+ * The shape of {@link pointerChannels}, the opt-in KHR_animation_pointer support `Animation` takes as its `pointers`
26
+ * option: sorts one glTF clip's channels (`def`, labelled `clip` in messages) for `model`.
27
+ */
28
+ export type PointerChannels = (model: PBRModel, def: AnimationDefinition, clip: string) => PointerPlan;
29
+ /**
30
+ * KHR_animation_pointer playback for `Animation`: pass it as the `pointers` option
31
+ * (`Animation.attach(model, {pointers: pointerChannels})`). For each glTF clip it sorts the channels into ordinary
32
+ * channels, pointer channels that drive node TRS and weights (played as node tracks) and property pointers bound on the
33
+ * clip's first playback to the model's live material factors, texture transforms, lights, cameras and node
34
+ * visibility. Malformed pointers, pointers to properties glTF does not let animations change and mismatched accessors
35
+ * throw TypeError or RangeError; valid pointers it cannot drive are skipped and listed in `animation.warnings`.
36
+ * `Animation` calls it; apps only pass it along.
37
+ */
38
+ export declare const pointerChannels: PointerChannels;
39
+ /**
40
+ * A writer of one object model property of the live model, for a value that does not come from a clip: `value` holds its
41
+ * components. Undefined for a property the model has no live value for. Shares its state with playing clips.
42
+ */
43
+ export declare function pointerWriter(model: PBRModel, pointer: string): ((value: ArrayLike<number>) => void) | undefined;
@@ -0,0 +1 @@
1
+ export{t as pointerChannels,n as pointerWriter}from"./pointer-BOFnz0gk.js";
@@ -0,0 +1 @@
1
+ var e=Symbol.for(`margoengine.pose-sources.v1`),t=globalThis[e]??/* @__PURE__ */ new WeakMap;globalThis[e]||Object.defineProperty(globalThis,e,{value:t});function n(e,n){t.set(e,n)}function r(e,n){t.get(e)===n&&t.delete(e)}export{n,r as t};
package/dist/pose.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Writes the pose of `bind` (20 floats per vertex) into `out`. Morph targets are added first: `deltas` holds 12 floats
3
+ * per vertex and target (position at 0, normal at 4) and `weights` one value per target. Then comes the weighted blend
4
+ * of `palette` (16 floats per bone) by `influences`: `words` per vertex, four joint indices then four float weights,
5
+ * twice for eight influences. Everything but position and normal is copied from `bind`.
6
+ */
7
+ export declare function poseVertices(bind: Float32Array, out: Float32Array, deltas: Float32Array, weights: ArrayLike<number>, influences: Uint32Array, words: number, palette: Float32Array): void;
@@ -0,0 +1 @@
1
+ import{MargoError as e}from"@margoengine/math/errors";function t(t,n){if(t.backend===`webgl2`||!t.gpu)throw new e(`unsupported`,`${n} needs WebGPU; see https://margoengine.com/errors#webgpu`)}export{t};
@@ -0,0 +1,107 @@
1
+ import { PBRModel } from '@margoengine/gltf/pbr-model';
2
+ import { type KeyframeClip } from './keyframes.js';
3
+ import { Skeleton } from './skin.js';
4
+ /**
5
+ * A bone hierarchy and its rest pose, as {@link Retarget} reads it. Make one with {@link retargetRig} from a
6
+ * `Skeleton` (bones) or a glTF PBR model (every node, so armature and mesh nodes count toward bone orientations).
7
+ */
8
+ export interface RetargetRig {
9
+ /** Bone names; a bone's index is its position here (a model's node index). */
10
+ readonly names: readonly string[];
11
+ /** Parent bone per bone, -1 at the top. */
12
+ readonly parents: readonly number[];
13
+ /** Rest local pose, 10 numbers per bone: translation xyz, rotation quaternion xyzw, scale xyz. */
14
+ readonly rest: Float64Array;
15
+ }
16
+ /** Options for {@link Retarget}. */
17
+ export interface RetargetOptions {
18
+ /**
19
+ * Target bone name to source bone name. A target bone that is not listed follows the source bone of the same name,
20
+ * when there is one. Map a target bone to `''` to leave it at rest.
21
+ */
22
+ names?: Readonly<Record<string, string>>;
23
+ /** The target bone whose position follows the source's (the hips). Default: none, every bone keeps its rest position. */
24
+ hip?: string;
25
+ /**
26
+ * Scale on the hip's movement from rest. Default: the target hip's rest height (y in model or skeleton space) over
27
+ * the source hip's, or 1 when either is not above 0.
28
+ */
29
+ hipScale?: number;
30
+ }
31
+ /** A glTF PBR model's player, such as an `Animation`, whose clip {@link Retarget.clip} can sample. */
32
+ export interface RetargetPlayer {
33
+ readonly model: PBRModel;
34
+ readonly clips: readonly {
35
+ readonly name: string;
36
+ readonly duration: number;
37
+ }[];
38
+ clip: number;
39
+ time: number;
40
+ playing: boolean;
41
+ play(clip: number): unknown;
42
+ seek(time: number): unknown;
43
+ }
44
+ /**
45
+ * The bones and current local pose of a `Skeleton`, or of every node of a glTF PBR model (names, parents and the
46
+ * nodes' local transforms), as a {@link RetargetRig}. The current pose becomes the rig's rest pose, the reference both
47
+ * rigs are compared in, so pose both characters the same way (both in T-pose, say) before making their rigs.
48
+ */
49
+ export declare function retargetRig(from: Skeleton | PBRModel): RetargetRig;
50
+ /**
51
+ * Retargeting: moves one skeleton the way another moves, bone by bone. Each
52
+ * mapped target bone turns in model space by the same rotation its source bone has turned from rest, which absorbs
53
+ * different bone axes and rest orientations: target world rotation = source world rotation x inverse(source rest
54
+ * world rotation) x target rest world rotation. Unmapped target bones keep their rest local rotation, every bone keeps
55
+ * its rest length and scale, and the `hip` bone's position follows the source hip's movement from rest times
56
+ * `hipScale`. Both rigs' model spaces are assumed to face the same way.
57
+ */
58
+ export declare class Retarget {
59
+ readonly source: RetargetRig;
60
+ readonly target: RetargetRig;
61
+ /** Source bone per target bone, -1 where the target bone is not mapped. */
62
+ readonly map: Int32Array;
63
+ /** Target hip bone index, or -1. */
64
+ readonly hip: number;
65
+ /** Source bone the hip follows, or -1. */
66
+ readonly sourceHip: number;
67
+ /** Scale applied to the hip's movement. */
68
+ readonly hipScale: number;
69
+ private readonly sourceOrder;
70
+ private readonly targetOrder;
71
+ private readonly sourceRest;
72
+ private readonly targetRest;
73
+ private readonly sourceNow;
74
+ private readonly targetNow;
75
+ private readonly delta;
76
+ private readonly input;
77
+ private readonly output;
78
+ private readonly poses;
79
+ private readonly quaternion;
80
+ private readonly vector;
81
+ constructor(source: RetargetRig, target: RetargetRig, options?: RetargetOptions);
82
+ /**
83
+ * The target's local pose (10 numbers per target bone, as in {@link RetargetRig.rest}) for a source local pose
84
+ * (10 per source bone). Unmapped target bones get their rest pose.
85
+ */
86
+ pose(source: Float64Array, out?: Float64Array): Float64Array;
87
+ /**
88
+ * Poses `target` the way `source` is posed now: each must be the Skeleton or model its rig was made from. Writes
89
+ * only the mapped bones' rotations and the hip's position; other target bones keep what they have (the retarget
90
+ * assumes them at rest).
91
+ */
92
+ apply(source: Skeleton | PBRModel, target: Skeleton | PBRModel): void;
93
+ /**
94
+ * A code-authored clip for the target rig from a source clip, sampled at `fps` (default 30) from 0 to the clip's
95
+ * duration: a rotation track per mapped target bone and a translation track for the hip, linear keys. The source
96
+ * is a `KeyframeClip` whose tracks name source bones (sampled over the source rig's rest pose; weights tracks are
97
+ * not carried over), or a glTF clip played by the source model's `Animation` (`{animation, clip}`; its clip, time and
98
+ * playing state are restored afterwards). Play the result with `applyKeyframeClip` or an `AnimationGroup`.
99
+ */
100
+ clip(source: KeyframeClip | {
101
+ readonly animation: RetargetPlayer;
102
+ readonly clip: string | number;
103
+ }, { fps, name }?: {
104
+ fps?: number;
105
+ name?: string;
106
+ }): KeyframeClip;
107
+ }
@@ -0,0 +1,42 @@
1
+ import { type KeyframeClip } from './keyframes.js';
2
+ /** A bone of a rigid rig: its id (the track target) and its rest translation. */
3
+ export interface RigidBone {
4
+ id: string;
5
+ translation: readonly [number, number, number];
6
+ }
7
+ /** A mesh rigidly bound to a bone, with the rest pose its keys are measured from. */
8
+ export interface RigidBinding {
9
+ /** The mesh's id, as named by its keys. */
10
+ object: string;
11
+ /** The bone that carries it. One bone may carry several meshes. */
12
+ bone: string;
13
+ /** Rest position. */
14
+ position: readonly [number, number, number];
15
+ /** Rest rotation as a quaternion `[x, y, z, w]`. */
16
+ rotation: readonly [number, number, number, number];
17
+ }
18
+ /** A keyed pose of a bound mesh. */
19
+ export interface RigidKey {
20
+ object: string;
21
+ /** Seconds, >= 0. Keys need not be sorted; among equal times the later key wins. */
22
+ time: number;
23
+ position: readonly [number, number, number];
24
+ rotation: readonly [number, number, number, number];
25
+ }
26
+ /** Options for {@link compileRigidClip}. */
27
+ export interface RigidClipOptions {
28
+ /** Clip name. */
29
+ name?: string;
30
+ /** Seconds; when past the last key, the last pose is held until then. */
31
+ duration?: number;
32
+ }
33
+ /**
34
+ * Compiles keys of rigidly bound meshes into stepped bone translation and rotation tracks. Each bone follows one of
35
+ * its meshes: the first in binding order that has been keyed so far. A key moves the bone by the mesh's offset from
36
+ * its rest position (`bone.translation + key.position - rest.position`) and rotates it by
37
+ * `key.rotation * inverse(rest.rotation)`. A bone whose first key is after 0 starts at rest; bones without keyed
38
+ * meshes get no tracks. Keys of unbound meshes are ignored.
39
+ * @throws TypeError for malformed bones, bindings or keys, or a binding to an unknown bone or a mesh bound twice;
40
+ * RangeError for a non-finite or negative time or value.
41
+ */
42
+ export declare function compileRigidClip(bones: readonly RigidBone[], bindings: readonly RigidBinding[], keys: readonly RigidKey[], options?: RigidClipOptions): KeyframeClip;
@@ -0,0 +1 @@
1
+ import{normalizeQuaternion as e}from"@margoengine/math/quat";function t(t,n,r,i,a,o,s,c,l,u){let d=c===`CUBICSPLINE`?3:1,f=o-a,p=f?Math.max(0,Math.min(1,(s-a)/f)):0,m=(r*d+ +(d===3))*n,h=(i*d+ +(d===3))*n;if(c===`STEP`||r===i)for(let e=0;e<n;e++)u[e]=t[m+e];else if(c===`CUBICSPLINE`){let e=p*p,a=e*p;for(let o=0;o<n;o++)u[o]=(2*a-3*e+1)*t[m+o]+(a-2*e+p)*f*t[(r*3+2)*n+o]+(-2*a+3*e)*t[h+o]+(a-e)*f*t[i*3*n+o]}else if(l){let e=0;for(let n=0;n<4;n++)e+=t[m+n]*t[h+n];let n=e<0?-1:1;e=Math.abs(e);let r=1-p,i=p;if(e<.9995){let t=Math.acos(Math.min(1,e)),n=Math.sin(t);r=Math.sin((1-p)*t)/n,i=Math.sin(p*t)/n}for(let e=0;e<4;e++)u[e]=t[m+e]*r+t[h+e]*i*n}else for(let e=0;e<n;e++)u[e]=t[m+e]*(1-p)+t[h+e]*p;if(l){if(!(u[0]||u[1]||u[2]||u[3]))throw RangeError(`Zero animation quaternion; rotation keys must be non-zero quaternions`);e(u,u)}for(let e=0;e<n;e++)if(!Number.isFinite(u[e]))throw RangeError(`Animation sample overflow; use finite keyframe values`);return u}var n=()=>/* @__PURE__ */ TypeError(`Invalid animation track; pass times and values arrays, an integer width >= 1, a finite time and STEP, LINEAR or CUBICSPLINE`);function r(e,r,i,a){let o=e.times,s=o.length;if(!s||!Number.isFinite(r))throw n();let c=e.cursor<s?e.cursor:0,l=o[c],u=c,d=l;if(c===0||l<=r){for(;c+1<s;){let e=o[c+1];if(e<=r)c++,l=e;else{u=c+1,d=e;break}}u<c&&(u=c,d=l)}else{let e=0,t=s-1;for(;e<t;){let n=Math.ceil((e+t)/2);o[n]<=r?e=n:t=n-1}c=e,u=Math.min(c+1,s-1),l=o[c],d=o[u]}return e.cursor=c,t(e.values,e.width,c,u,l,d,r,e.interpolation,i,a)}function i(e,t,n,r,i,o=!1,s){if(s!==void 0&&(!(s instanceof Float32Array)||s.length!==n||s.buffer===e.buffer||s.buffer===t.buffer))throw TypeError(`Invalid animation sample target; pass a Float32Array of the track width that does not share the times or values buffer`);return a(e,t,n,r,i,o,s)}function a(e,r,i,a,o,s=!1,c){if(!e.length||!Number.isInteger(i)||i<1||!Number.isFinite(a)||o!==`STEP`&&o!==`LINEAR`&&o!==`CUBICSPLINE`)throw n();let l=o===`CUBICSPLINE`?3:1;if(r.length!==e.length*i*l)throw RangeError(`Animation output count mismatch; values needs times.length * width numbers (three times that for CUBICSPLINE)`);let u=0,d=e.length-1;for(;u<d;){let t=Math.ceil((u+d)/2);e[t]<=a?u=t:d=t-1}let f=u,p=Math.min(f+1,e.length-1);return c=c?.length===i&&(!s||i===4)?c:new Float32Array(i),t(r,i,f,p,e[f],e[p],a,o,s,c)}function o(e){if(!Array.isArray(e))throw TypeError(`Clip markers must be an array of {time, name}`);for(let t of e){if(typeof t?.name!=`string`||!t.name)throw TypeError(`Clip marker needs a nonempty string name`);if(!Number.isFinite(t.time)||t.time<0)throw RangeError(`Clip marker time must be a finite number >= 0`)}return Object.freeze(e.map(e=>Object.freeze({...e})).sort((e,t)=>e.time-t.time))}var s=class{constructor(e,t,n=!0){if(this.at=0,this.fresh=!0,!(t>0)||!Number.isFinite(t))throw RangeError(`Clip duration must be a finite number > 0 seconds`);if(this.markers=o(e),this.duration=t,this.loop=n,this.markers.some(e=>e.time>t))throw RangeError(`Clip marker time is past the clip duration; move it inside the clip`)}get time(){return this.loop?this.at%this.duration:this.at}advance(e,t=[]){if(!Number.isFinite(e))throw RangeError(`Clip advance needs a finite delta in seconds`);return this.move(this.at+e,t)}seek(e,t=!1,n=[]){if(!Number.isFinite(e)||e<0)throw RangeError(`Clip seek needs a finite time >= 0 seconds`);let r=this.move(e,n);return t||(r.length=0),r}move(e,t){let{duration:n,loop:r}=this;t.length=0,e=r?Math.max(e,0):Math.min(Math.max(e,0),n);let i=this.at,a=e>=i,o=a?i:e,s=a?e:i,c=r?Math.floor(o/n):0,l=r?Math.floor(s/n):0,u=[];if((l-c+1)*this.markers.length>65536)throw RangeError(`Clip step spans too many laps; use smaller deltas`);for(let e=c;e<=l;e++)for(let t of this.markers){let r=t.time+e*n;r<=s&&(r>o||this.fresh&&a&&r===o)&&u.push([r,t])}u.sort((e,t)=>a?e[0]-t[0]:t[0]-e[0]);for(let e of u)t.push(e[1]);return this.at=e,this.fresh=!1,t}},c=(e,t,n)=>{let r=0,i=0;if(n)for(let n=0;n<4;n++)r+=e[n]*t[n];let a=r<0?-1:1;for(let n=0;n<e.length;n++)i=Math.max(i,Math.abs(e[n]-a*t[n]));return i},l=(t,n,r)=>{for(let e=0;e<t.width;e++)r[e]=t.values[n*t.width+e];return t.quaternion?e(r,r):r};function u(e,t){let{times:n,values:r,width:i,interpolation:o,quaternion:s}=e,u=n.length;if(!(t>=0)||!Number.isFinite(t))throw RangeError(`Compression tolerance must be a finite number >= 0`);if(o!==`LINEAR`&&o!==`STEP`)throw TypeError(`Only LINEAR and STEP tracks compress; pass interpolation LINEAR or STEP`);if(u<1||r.length!==u*i)throw RangeError(`Track needs times and width numbers per key; values.length must be times.length * width`);let d=new Uint8Array(u),f=new Float32Array(i),p=new Float32Array(i),m={times:/* @__PURE__ */ new Float32Array(2),values:new Float32Array(2*i),width:i,interpolation:o,quaternion:s};if(d[0]=d[u-1]=1,o===`STEP`)for(let n=1,r=0;n<u-1;n++)c(l(e,n,f),l(e,r,p),s)>t&&(d[r=n]=1);else{let o=[0,u-1];for(;o.length;){let u=o.pop(),h=o.pop(),g=-1,_=t;m.times[0]=n[h],m.times[1]=n[u],m.values.set(r.subarray(h*i,h*i+i),0),m.values.set(r.subarray(u*i,u*i+i),i);for(let t=h+1;t<u;t++){let r=c(a(m.times,m.values,i,n[t],`LINEAR`,s,f),l(e,t,p),s);r>_&&(_=r,g=t)}g>=0&&(d[g]=1,o.push(h,g,g,u))}}let h=d.reduce((e,t)=>e+t,0),g={times:new Float32Array(h),values:new Float32Array(h*i),width:i,interpolation:o,...s?{quaternion:s}:{},error:0};for(let e=0,t=0;e<u;e++)d[e]&&(g.times[t]=n[e],g.values.set(r.subarray(e*i,e*i+i),t++*i));for(let t=0;t<u;t++)g.error=Math.max(g.error,c(a(g.times,g.values,i,n[t],o,s,f),l(e,t,p),s));return g}function d(e){let{values:t,width:n}=e,r=new Float32Array(n).fill(1/0),i=new Float32Array(n).fill(-1/0),a=new Float32Array(n),o=new Uint16Array(t.length);if(!t.length||t.length!==e.times.length*n)throw RangeError(`Track needs times and width numbers per key; values.length must be times.length * width`);for(let e=0;e<t.length;e++){let a=t[e],o=e%n;if(!Number.isFinite(a))throw RangeError(`Track values must be finite to quantise`);a<r[o]&&(r[o]=a),a>i[o]&&(i[o]=a)}for(let e=0;e<n;e++)a[e]=(i[e]-r[e])/65535;for(let e=0;e<t.length;e++){let i=e%n;o[e]=a[i]?Math.round((t[e]-r[i])/a[i]):0}let{values:s,...c}=e;return{...c,data:o,min:r,step:a}}function f(e){let{data:t,min:n,step:r,...i}=e,a=new Float32Array(t.length);for(let i=0;i<t.length;i++)a[i]=n[i%e.width]+t[i]*r[i%e.width];return{...i,values:a}}export{i as a,r as c,d as i,u as n,a as o,f as r,o as s,s as t};
@@ -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;
@@ -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,66 @@
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)}){return`
38
+ struct Vertex {position:vec4f,normal:vec4f,tangent:vec4f,uv:vec4f,color:vec4f}
39
+ struct Morph {position:vec4f,normal:vec4f,tangent:vec4f}
40
+ struct Slot {source:u32,output:u32,count:u32,targets:u32,morphs:u32,weights:u32,bones:u32,joints:u32,influences:u32,pad0:u32,pad1:u32,pad2:u32}
41
+ @group(0) @binding(0) var<storage,read> source:array<Vertex>;
42
+ @group(0) @binding(1) var<storage,read_write> output:array<Vertex>;
43
+ @group(0) @binding(2) var<storage,read> morphs:array<Morph>;
44
+ @group(0) @binding(3) var<storage,read> weights:array<f32>;
45
+ @group(0) @binding(4) var<storage,read> boneMatrices:array<mat4x4f>;
46
+ @group(0) @binding(5) var<storage,read> influences:array<vec4u>;
47
+ @group(0) @binding(6) var<storage,read> slots:array<Slot>;
48
+ @group(0) @binding(7) var<storage,read> work:array<vec2u>;
49
+ ${t.functions}
50
+ @compute @workgroup_size(64) fn main(@builtin(workgroup_id) group:vec3u,@builtin(num_workgroups) groups:vec3u,@builtin(local_invocation_index) lane:u32) {
51
+ let item=group.y*groups.x+group.x;
52
+ if(item>=work[0].x){return;}
53
+ let entry=work[item+1u];let s=slots[entry.x];let i=entry.y+lane;
54
+ if(i>=s.count){return;}
55
+ var v=source[s.source+i];
56
+ for(var morphIndex=0u;morphIndex<s.targets;morphIndex++) {
57
+ let m=morphs[s.morphs+morphIndex*s.count+i];let w=weights[s.weights+morphIndex];
58
+ v.position+=vec4f(m.position.xyz*w,0);v.normal+=vec4f(m.normal.xyz*w,0);v.tangent+=vec4f(m.tangent.xyz*w,0);
59
+ }
60
+ if(s.joints>0u) {
61
+ let at=s.influences+i*${e?4:2}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]);`:``}
62
+ ${t.blend}
63
+ }
64
+ v.normal=vec4f(normalize(v.normal.xyz),0);output[s.output+i]=v;
65
+ }
66
+ `}export{e as n,a as t};
@@ -0,0 +1,30 @@
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
+ /** Text a skinning mode puts into the batched shader: module-scope `functions`, and the `blend` that moves `v`. */
19
+ export interface SkinningShader {
20
+ functions: string;
21
+ blend: string;
22
+ }
23
+ /**
24
+ * Batched deformation (batch.ts): many primitives in one dispatch. Each workgroup deforms 64 vertices of one slot,
25
+ * named by the work list (`work[0].x` workgroups, then a slot index and first vertex per workgroup); each slot record
26
+ * gives where its vertices, deltas, weights, bones and influences start in the shared buffers. The per-vertex
27
+ * arithmetic is the per-primitive shader's, term for term, so the output is the same bits. `extra`: eight influences.
28
+ * `skin` replaces that arithmetic for a skinning mode.
29
+ */
30
+ export declare function batchedDeformationShader(extra: boolean, skin?: SkinningShader): string;
@@ -0,0 +1,2 @@
1
+ export { cloneModel } from './clone.js';
2
+ export { Retarget, retargetRig, type RetargetOptions, type RetargetPlayer, type RetargetRig, } from './retarget.js';
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.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-BO50xipp.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("0.1.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)))}return l(i,i.sceneOf(e)).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}})}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`);this.sourceNow=p(e),this.targetNow=p(t);let a=this.sourceRest=p(e),o=this.targetRest=p(t);if(v(this.sourceOrder,e.parents,e.rest,a.rotation,a.position,a.scale),v(this.targetOrder,t.parents,t.rest,o.rotation,o.position,o.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 s=this.sourceHip<0?0:a.position[this.sourceHip*3+1],c=this.hip<0?0:o.position[this.hip*3+1],l=n.hipScale??(s>0&&c>0?c/s:1);if(typeof l!=`number`||!Number.isFinite(l)||l<=0)throw RangeError(`Retarget hipScale ${l} is invalid; pass a finite number > 0`);this.hipScale=l,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||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){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),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};