@layoutit/polycss-morph 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var ve="polycss-morph.model@1",pe="polycss-morph.catalog@1",ye="polycss-morph.package@1";var co=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Do=/^[a-z0-9][a-z0-9._-]*$/,lo=/^\d+\.\d+\.\d+$/,No=/^[a-f0-9]{64}$/,_o=new Set(["joint-skin","morph-regions","prepared-playback","static-prepared"]),Ho=new Set(["animation","joint-skinning","morph-targets","prepared-playback","retained-render","semantic-controls","sparse-updates","springs"]),Fo=new Set(["atlas-slice","direct-image","solid-quad","solid-triangle"]),qo=new Set(["control-value","joint-rotation","joint-scale","joint-translation","morph-weight","shape-matrix"]),Oe=class extends TypeError{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphContractError",this.code=e,this.path=t}};function h(o,e,t){throw new Oe(o,e,t)}function O(o,e,t){(!o||typeof o!="object"||Array.isArray(o))&&h("invalid-type",e,"expected an object");let n=Object.keys(o).sort(),r=[...t].sort();return(n.length!==r.length||n.some((a,i)=>a!==r[i]))&&h("invalid-keys",e,`expected exactly ${r.join(", ")}`),o}function A(o,e){return Array.isArray(o)||h("invalid-type",e,"expected an array"),o}function Z(o,e){return(typeof o!="string"||o.length===0)&&h("invalid-string",e,"expected a non-empty string"),o}function J(o,e){return(typeof o!="number"||!Number.isFinite(o))&&h("invalid-number",e,"expected a finite number"),o}function K(o,e,t=0){let n=J(o,e);return(!Number.isSafeInteger(n)||n<t)&&h("invalid-integer",e,`expected an integer >= ${t}`),n}function Ue(o,e){return typeof o!="boolean"&&h("invalid-boolean",e,"expected a boolean"),o}function H(o,e){let t=Z(o,e);return co.test(t)||h("invalid-id",e,"expected a normalized kebab-case id"),t}function G(o,e){let t=new Set;for(let n of o)t.has(n)&&h("duplicate-id",e,`duplicate id ${n}`),t.add(n)}function Me(o,e){let t=A(o,e);return t.length!==3&&h("invalid-vector",e,"expected three components"),t.map((n,r)=>J(n,`${e}[${r}]`))}function ie(o,e){let t=A(o,e);return t.length!==16&&h("invalid-matrix",e,"expected sixteen components"),t.map((n,r)=>J(n,`${e}[${r}]`))}function po(o,e){let t=Z(o,e);return t.split("/").some(n=>!Do.test(n))&&h("invalid-path",e,"expected lowercase URL-safe package path segments"),t}function Ae(o,e,t){let n=K(o,e);return n>=t&&h("out-of-range",e,`expected an index below ${t}`),n}function Jo(o,e){let t=O(o,e,["normals","polygons","vertices"]),n=A(t.vertices,`${e}.vertices`).map((i,s)=>Me(i,`${e}.vertices[${s}]`)),r=A(t.normals,`${e}.normals`).map((i,s)=>Me(i,`${e}.normals[${s}]`));n.length===0&&h("missing-topology",`${e}.vertices`,"expected at least one vertex"),r.length===0&&h("missing-topology",`${e}.normals`,"expected at least one normal");let a=A(t.polygons,`${e}.polygons`).map((i,s)=>{let d=`${e}.polygons[${s}]`,l=O(i,d,["id","normalIndices","vertexIndices"]),c=A(l.vertexIndices,`${d}.vertexIndices`).map((y,b)=>Ae(y,`${d}.vertexIndices[${b}]`,n.length)),p=A(l.normalIndices,`${d}.normalIndices`).map((y,b)=>Ae(y,`${d}.normalIndices[${b}]`,r.length));return c.length<3&&h("invalid-polygon",d,"expected at least three vertices"),p.length!==c.length&&h("invalid-polygon",d,"normal and vertex index counts must match"),new Set(c).size!==c.length&&h("invalid-polygon",d,"vertex indices must be unique"),{id:H(l.id,`${d}.id`),vertexIndices:c,normalIndices:p}});return a.length===0&&h("missing-topology",`${e}.polygons`,"expected at least one polygon"),G(a.map(i=>i.id),`${e}.polygons`),{vertices:n,normals:r,polygons:a}}function Wo(o,e,t){let n=O(o,e,["atlas","fallback","height","id","materialId","matrix","polygonId","shapeId","strategy","width"]),r=Z(n.strategy,`${e}.strategy`);Fo.has(r)||h("invalid-strategy",`${e}.strategy`,"unknown render strategy");let a=H(n.polygonId,`${e}.polygonId`),i=H(n.shapeId,`${e}.shapeId`),s=H(n.materialId,`${e}.materialId`);t.polygonIds.has(a)||h("unknown-reference",`${e}.polygonId`,a),t.shapeIds.has(i)||h("unknown-reference",`${e}.shapeId`,i),t.materialIds.has(s)||h("unknown-reference",`${e}.materialId`,s);let d=J(n.width,`${e}.width`),l=J(n.height,`${e}.height`);(d<=0||l<=0)&&h("invalid-size",e,"leaf dimensions must be positive");let c=r==="atlas-slice"||r==="direct-image",p=n.atlas===null?null:yo(n.atlas,`${e}.atlas`);c!==(p!==null)&&h("invalid-strategy",`${e}.atlas`,c?"image strategies require an atlas/source slice":"solid strategies cannot declare an atlas/source slice");let y=n.fallback===null?null:Yo(n.fallback,`${e}.fallback`);return y!==null&&r!=="solid-triangle"&&h("invalid-strategy",`${e}.fallback`,"only solid-triangle leaves may declare a prepared fallback"),{id:H(n.id,`${e}.id`),polygonId:a,shapeId:i,materialId:s,strategy:r,width:d,height:l,matrix:ie(n.matrix,`${e}.matrix`),atlas:p,fallback:y}}function Yo(o,e){let t=O(o,e,["atlas","height","matrixFromLeaf","width"]),n=K(t.width,`${e}.width`,1),r=K(t.height,`${e}.height`,1),a=yo(t.atlas,`${e}.atlas`);return(a.width!==n||a.height!==r)&&h("invalid-size",e,"fallback dimensions must match its per-polygon atlas slice"),{width:n,height:r,matrixFromLeaf:ie(t.matrixFromLeaf,`${e}.matrixFromLeaf`),atlas:a}}function yo(o,e){let t=O(o,e,["height","pageHeight","pageWidth","resourcePath","width","x","y"]),n={resourcePath:po(t.resourcePath,`${e}.resourcePath`),x:K(t.x,`${e}.x`),y:K(t.y,`${e}.y`),width:K(t.width,`${e}.width`,1),height:K(t.height,`${e}.height`,1),pageWidth:K(t.pageWidth,`${e}.pageWidth`,1),pageHeight:K(t.pageHeight,`${e}.pageHeight`,1)};return(n.x+n.width>n.pageWidth||n.y+n.height>n.pageHeight)&&h("out-of-range",e,"slice must fit inside its page"),n}function Go(o,e,t){(!o||typeof o!="object"||Array.isArray(o))&&h("invalid-type",e,"expected a deformation object");let n=Z(o.kind,`${e}.kind`);if(n==="none")return O(o,e,["kind"]),{kind:n};if(n==="morph-regions"){let r=O(o,e,["kind","targets"]),a=A(r.targets,`${e}.targets`).map((i,s)=>{let d=`${e}.targets[${s}]`,l=O(i,d,["deltas","id"]),c=A(l.deltas,`${d}.deltas`).map((y,b)=>{let m=`${d}.deltas[${b}]`,u=O(y,m,["normal","position","vertexIndex"]),x=u.position===null?null:Me(u.position,`${m}.position`),g=u.normal===null?null:Me(u.normal,`${m}.normal`);return x===null&&g===null&&h("empty-delta",m,"expected a position or normal delta"),{vertexIndex:Ae(u.vertexIndex,`${m}.vertexIndex`,t.vertices.length),position:x,normal:g}});c.length===0&&h("missing-deltas",`${d}.deltas`,"expected at least one delta");let p=c.map(y=>String(y.vertexIndex));return G(p,`${d}.deltas`),{id:H(l.id,`${d}.id`),deltas:c}});return a.length===0&&h("missing-targets",`${e}.targets`,"expected at least one target"),G(a.map(i=>i.id),`${e}.targets`),{kind:n,targets:a}}if(n==="joint-skin"){let r=O(o,e,["joints","kind","vertices"]),a=A(r.joints,`${e}.joints`).map((l,c)=>{let p=`${e}.joints[${c}]`,y=O(l,p,["id","inverseBindMatrix","parentId","restMatrix"]);return{id:H(y.id,`${p}.id`),parentId:y.parentId===null?null:H(y.parentId,`${p}.parentId`),restMatrix:ie(y.restMatrix,`${p}.restMatrix`),inverseBindMatrix:ie(y.inverseBindMatrix,`${p}.inverseBindMatrix`)}});a.length===0&&h("missing-joints",`${e}.joints`,"expected at least one joint"),G(a.map(l=>l.id),`${e}.joints`),Qo(a,`${e}.joints`);let i=new Set(a.map(l=>l.id)),s=A(r.vertices,`${e}.vertices`).map((l,c)=>{let p=`${e}.vertices[${c}]`,y=O(l,p,["influences","vertexIndex"]),b=Ae(y.vertexIndex,`${p}.vertexIndex`,t.vertices.length),m=A(y.influences,`${p}.influences`).map((x,g)=>{let v=`${p}.influences[${g}]`,I=O(x,v,["jointId","weight"]),E=H(I.jointId,`${v}.jointId`);i.has(E)||h("unknown-reference",`${v}.jointId`,E);let $=J(I.weight,`${v}.weight`);return($<=0||$>1)&&h("invalid-weight",`${v}.weight`,"expected 0 < weight <= 1"),{jointId:E,weight:$}});m.length===0&&h("missing-influences",`${p}.influences`,"expected at least one influence"),G(m.map(x=>x.jointId),`${p}.influences`);let u=m.reduce((x,g)=>x+g.weight,0);return Math.abs(u-1)>1e-6&&h("invalid-weight",`${p}.influences`,"weights must sum to 1"),{vertexIndex:b,influences:m}});s.length!==t.vertices.length&&h("missing-skin-vertex",`${e}.vertices`,"every topology vertex must have one skin record");let d=s.map(l=>String(l.vertexIndex));return G(d,`${e}.vertices`),{kind:n,joints:a,vertices:s}}h("invalid-deformation",`${e}.kind`,`unknown deformation kind ${n}`)}function Qo(o,e){let t=new Map(o.map(r=>[r.id,r]));o.filter(r=>r.parentId===null).length!==1&&h("invalid-hierarchy",e,"expected exactly one root joint");for(let r of o){r.parentId!==null&&!t.has(r.parentId)&&h("unknown-reference",e,`joint ${r.id} references ${r.parentId}`);let a=new Set,i=r;for(;i;)a.has(i.id)&&h("invalid-hierarchy",e,`cycle at joint ${i.id}`),a.add(i.id),i=i.parentId===null?void 0:t.get(i.parentId)}}function Ko(o){return o==="control-value"||o==="morph-weight"?1:o==="joint-rotation"?4:o==="shape-matrix"?16:3}function Xo(o,e,t,n){let r=O(o,e,["interpolation","target","targetId","timesMs","values"]),a=Z(r.target,`${e}.target`);qo.has(a)||h("invalid-animation-target",`${e}.target`,a);let i=H(r.targetId,`${e}.targetId`);(a==="control-value"?t.controlIds:a==="morph-weight"?t.targetIds:a==="shape-matrix"?t.shapeIds:t.jointIds).has(i)||h("unknown-reference",`${e}.targetId`,i);let d=Z(r.interpolation,`${e}.interpolation`);d!=="linear"&&d!=="step"&&h("invalid-interpolation",`${e}.interpolation`,d),a==="shape-matrix"&&d!=="step"&&h("invalid-interpolation",`${e}.interpolation`,"shape matrices require step interpolation");let l=A(r.timesMs,`${e}.timesMs`).map((p,y)=>J(p,`${e}.timesMs[${y}]`)),c=A(r.values,`${e}.values`).map((p,y)=>{let b=A(p,`${e}.values[${y}]`),m=Ko(a);b.length!==m&&h("invalid-animation-value",`${e}.values[${y}]`,`expected ${m} components`);let u=b.map((x,g)=>J(x,`${e}.values[${y}][${g}]`));return a==="joint-rotation"&&Math.hypot(...u)<=1e-12&&h("invalid-animation-value",`${e}.values[${y}]`,"quaternion must be non-zero"),u});return(l.length===0||l.length!==c.length)&&h("invalid-animation-samples",e,"times and values must have the same non-zero length"),(l[0]!==0||l.some((p,y)=>p<0||p>n||y>0&&p<=l[y-1]))&&h("invalid-animation-time",`${e}.timesMs`,"times must start at zero and increase within the clip"),{target:a,targetId:i,interpolation:d,timesMs:l,values:c}}function Zo(o,e,t,n){let r=O(o,e,["durationMs","frames","loop"]),a=J(r.durationMs,`${e}.durationMs`);a<=0&&h("invalid-duration",`${e}.durationMs`,"expected a positive duration");let i=A(r.frames,`${e}.frames`).map((s,d)=>{let l=`${e}.frames[${d}]`,c=O(s,l,["leaves","modelMatrix","shapes","timeMs"]),p=J(c.timeMs,`${l}.timeMs`),y=A(c.shapes,`${l}.shapes`).map((m,u)=>{let x=`${l}.shapes[${u}]`,g=O(m,x,["matrix","shapeId"]),v=H(g.shapeId,`${x}.shapeId`);return n.has(v)||h("unknown-reference",`${x}.shapeId`,v),{shapeId:v,matrix:ie(g.matrix,`${x}.matrix`)}});G(y.map(m=>m.shapeId),`${l}.shapes`);let b=A(c.leaves,`${l}.leaves`).map((m,u)=>{let x=`${l}.leaves[${u}]`,g=O(m,x,["atlasRow","leafId","matrix","opacity","visible"]),v=H(g.leafId,`${x}.leafId`);t.has(v)||h("unknown-reference",`${x}.leafId`,v);let I=g.opacity===null?null:J(g.opacity,`${x}.opacity`);return I!==null&&(I<0||I>1)&&h("out-of-range",`${x}.opacity`,"expected 0 <= opacity <= 1"),{leafId:v,matrix:g.matrix===null?null:ie(g.matrix,`${x}.matrix`),visible:g.visible===null?null:Ue(g.visible,`${x}.visible`),opacity:I,atlasRow:g.atlasRow===null?null:K(g.atlasRow,`${x}.atlasRow`)}});return G(b.map(m=>m.leafId),`${l}.leaves`),{timeMs:p,modelMatrix:c.modelMatrix===null?null:ie(c.modelMatrix,`${l}.modelMatrix`),shapes:y,leaves:b}});return i.length===0&&h("missing-frames",`${e}.frames`,"expected at least one frame"),(i[0].timeMs!==0||i.some((s,d)=>s.timeMs<0||s.timeMs>a||d>0&&s.timeMs<=i[d-1].timeMs))&&h("invalid-frame-time",`${e}.frames`,"frames must start at zero and increase within the timeline"),{durationMs:a,loop:Ue(r.loop,`${e}.loop`),frames:i}}function et(o,e){let t=["retained-render"];return o==="morph-regions"&&t.push("morph-targets","sparse-updates"),o==="joint-skin"&&t.push("joint-skinning","sparse-updates"),o==="prepared-playback"&&t.push("prepared-playback","sparse-updates"),e.controls.length>0&&t.push("semantic-controls"),e.springs.length>0&&t.push("springs"),e.animations.length>0&&t.push("animation"),t}function F(o){let t=O(o,"$",["animations","budgets","capabilities","controls","deformation","identity","materials","playback","profile","provenance","render","schema","springs","topology"]);t.schema!==ve&&h("invalid-schema","$.schema",`expected ${ve}`);let n=O(t.identity,"$.identity",["id","name","revision"]),r={id:H(n.id,"$.identity.id"),name:Z(n.name,"$.identity.name"),revision:Z(n.revision,"$.identity.revision")};lo.test(r.revision)||h("invalid-revision","$.identity.revision","expected x.y.z");let a=Z(t.profile,"$.profile");_o.has(a)||h("invalid-profile","$.profile",a);let i=A(t.capabilities,"$.capabilities").map((P,C)=>{let f=Z(P,`$.capabilities[${C}]`);return Ho.has(f)||h("invalid-capability",`$.capabilities[${C}]`,f),f});G(i,"$.capabilities"),i.some((P,C)=>C>0&&P<=i[C-1])&&h("non-canonical-order","$.capabilities","capabilities must be sorted");let s=O(t.budgets,"$.budgets",["maxBytes","maxFrames","maxJoints","maxLeaves","maxPolygons","maxResources","maxVertices"]),d={maxVertices:K(s.maxVertices,"$.budgets.maxVertices"),maxPolygons:K(s.maxPolygons,"$.budgets.maxPolygons"),maxLeaves:K(s.maxLeaves,"$.budgets.maxLeaves"),maxFrames:K(s.maxFrames,"$.budgets.maxFrames"),maxJoints:K(s.maxJoints,"$.budgets.maxJoints"),maxResources:K(s.maxResources,"$.budgets.maxResources"),maxBytes:K(s.maxBytes,"$.budgets.maxBytes")},l=Jo(t.topology,"$.topology"),c=A(t.materials,"$.materials").map((P,C)=>{let f=`$.materials[${C}]`,S=O(P,f,["color","id"]),M=A(S.color,`${f}.color`);M.length!==4&&h("invalid-color",`${f}.color`,"expected four components");let R=M.map((z,q)=>{let ee=J(z,`${f}.color[${q}]`);return(ee<0||ee>1)&&h("out-of-range",`${f}.color[${q}]`,"expected 0 <= component <= 1"),ee});return{id:H(S.id,`${f}.id`),color:R}});c.length===0&&h("missing-materials","$.materials","expected at least one material"),G(c.map(P=>P.id),"$.materials");let p=O(t.render,"$.render",["leaves","modelMatrix","shapes"]),y=A(p.shapes,"$.render.shapes").map((P,C)=>{let f=`$.render.shapes[${C}]`,S=O(P,f,["id","matrix"]);return{id:H(S.id,`${f}.id`),matrix:ie(S.matrix,`${f}.matrix`)}});y.length===0&&h("missing-shapes","$.render.shapes","expected at least one shape"),G(y.map(P=>P.id),"$.render.shapes");let b=A(p.leaves,"$.render.leaves").map((P,C)=>Wo(P,`$.render.leaves[${C}]`,{polygonIds:new Set(l.polygons.map(f=>f.id)),shapeIds:new Set(y.map(f=>f.id)),materialIds:new Set(c.map(f=>f.id))}));G(b.map(P=>P.id),"$.render.leaves"),G(b.map(P=>P.polygonId),"$.render.leaves[*].polygonId"),b.length!==l.polygons.length&&h("unstable-topology","$.render.leaves","every polygon must bind exactly one retained leaf");let m={modelMatrix:ie(p.modelMatrix,"$.render.modelMatrix"),shapes:y,leaves:b},u=Go(t.deformation,"$.deformation",l);(a==="static-prepared"||a==="prepared-playback"?u.kind!=="none":u.kind!==a)&&h("profile-mismatch","$.deformation.kind",`does not match profile ${a}`);let x=new Set(u.kind==="morph-regions"?u.targets.map(P=>P.id):[]),g=new Set(u.kind==="joint-skin"?u.joints.map(P=>P.id):[]),v=A(t.controls,"$.controls").map((P,C)=>{let f=`$.controls[${C}]`,S=O(P,f,["anchor","axis","id","initial","maximum","minimum","radius","targets"]),M=J(S.minimum,`${f}.minimum`),R=J(S.maximum,`${f}.maximum`),z=J(S.initial,`${f}.initial`);(M>R||z<M||z>R)&&h("invalid-control-bounds",f,"expected minimum <= initial <= maximum");let q=Me(S.anchor,`${f}.anchor`),ee=Me(S.axis,`${f}.axis`);Math.hypot(...ee)<1e-9&&h("invalid-control-axis",`${f}.axis`,"axis must be non-zero");let he=J(S.radius,`${f}.radius`);he<=0&&h("invalid-control-radius",`${f}.radius`,"radius must be positive");let ge=A(S.targets,`${f}.targets`).map((ce,$e)=>{let j=`${f}.targets[${$e}]`,Q=O(ce,j,["scale","targetId"]),Y=H(Q.targetId,`${j}.targetId`);return x.has(Y)||h("unknown-reference",`${j}.targetId`,Y),{targetId:Y,scale:J(Q.scale,`${j}.scale`)}});return G(ge.map(ce=>ce.targetId),`${f}.targets`),{id:H(S.id,`${f}.id`),anchor:q,axis:ee,radius:he,minimum:M,maximum:R,initial:z,targets:ge}});G(v.map(P=>P.id),"$.controls");let I=new Set(v.map(P=>P.id)),E=A(t.springs,"$.springs").map((P,C)=>{let f=`$.springs[${C}]`,S=O(P,f,["controlId","damping","id","stiffness"]),M=H(S.controlId,`${f}.controlId`);I.has(M)||h("unknown-reference",`${f}.controlId`,M);let R=J(S.stiffness,`${f}.stiffness`),z=J(S.damping,`${f}.damping`);return(R<=0||z<0)&&h("invalid-spring",f,"expected stiffness > 0 and damping >= 0"),{id:H(S.id,`${f}.id`),controlId:M,stiffness:R,damping:z}});G(E.map(P=>P.id),"$.springs");let $=new Set(y.map(P=>P.id)),w=A(t.animations,"$.animations").map((P,C)=>{let f=`$.animations[${C}]`,S=O(P,f,["channels","durationMs","id","loop"]),M=J(S.durationMs,`${f}.durationMs`);M<=0&&h("invalid-duration",`${f}.durationMs`,"expected a positive duration");let R=A(S.channels,`${f}.channels`).map((q,ee)=>Xo(q,`${f}.channels[${ee}]`,{controlIds:I,jointIds:g,shapeIds:$,targetIds:x},M));R.length===0&&h("missing-channels",`${f}.channels`,"expected at least one channel");let z=R.map(q=>`${q.target}:${q.targetId}`);return G(z,`${f}.channels`),{id:H(S.id,`${f}.id`),durationMs:M,loop:Ue(S.loop,`${f}.loop`),channels:R}});G(w.map(P=>P.id),"$.animations");let W=t.playback===null?null:Zo(t.playback,"$.playback",new Set(b.map(P=>P.id)),$);a==="prepared-playback"!=(W!==null)&&h("profile-mismatch","$.playback","playback is required only by the prepared-playback profile");let V=O(t.provenance,"$.provenance",["generator","generatorVersion","sources"]),B=A(V.sources,"$.provenance.sources").map((P,C)=>{let f=`$.provenance.sources[${C}]`,S=O(P,f,["id","kind","license","sha256","uri"]),M=Z(S.kind,`${f}.kind`);M!=="authored"&&M!=="generated"&&M!=="open-data"&&h("invalid-source-kind",`${f}.kind`,M);let R=Z(S.uri,`${f}.uri`);(R.startsWith("/")||R.startsWith("file:")||R.includes("\\"))&&h("invalid-source-uri",`${f}.uri`,"local filesystem paths are forbidden");let z=S.sha256===null?null:Z(S.sha256,`${f}.sha256`);return z!==null&&!No.test(z)&&h("invalid-hash",`${f}.sha256`,"expected lowercase SHA-256"),{id:H(S.id,`${f}.id`),kind:M,uri:R,sha256:z,license:Z(S.license,`${f}.license`)}});B.length===0&&h("missing-provenance","$.provenance.sources","expected at least one source"),G(B.map(P=>P.id),"$.provenance.sources");let te={generator:H(V.generator,"$.provenance.generator"),generatorVersion:Z(V.generatorVersion,"$.provenance.generatorVersion"),sources:B};lo.test(te.generatorVersion)||h("invalid-revision","$.provenance.generatorVersion","expected x.y.z");let T=et(a,{controls:v,springs:E,animations:w});for(let P of T)i.includes(P)||h("missing-capability","$.capabilities",`profile requires ${P}`);let L=u.kind==="joint-skin"?u.joints.length:0,D=W?.frames.length??0,_=[["maxVertices",l.vertices.length,d.maxVertices],["maxPolygons",l.polygons.length,d.maxPolygons],["maxLeaves",b.length,d.maxLeaves],["maxFrames",D,d.maxFrames],["maxJoints",L,d.maxJoints]];for(let[P,C,f]of _)C>f&&h("budget-exceeded",`$.budgets.${P}`,`${C} exceeds ${f}`);return{schema:ve,identity:r,profile:a,capabilities:i,budgets:d,topology:l,materials:c,render:m,deformation:u,controls:v,springs:E,animations:w,playback:W,provenance:te}}function Be(o){return co.test(o)}function De(o){try{return po(o,"$"),!0}catch{return!1}}var k=class extends Error{constructor(e,t,n,r={}){super(`${t}: ${n}`),this.name="PolyMorphPackageError",this.code=e,this.path=t,"cause"in r&&(this.cause=r.cause)}};function Ne(o,e,t){if(o===null)return"null";if(typeof o=="string"||typeof o=="boolean")return JSON.stringify(o);if(typeof o=="number"){if(!Number.isFinite(o))throw new k("invalid-json",e,"numbers must be finite");return JSON.stringify(Object.is(o,-0)?0:o)}if(Array.isArray(o)){if(t.has(o))throw new k("invalid-json",e,"cycles are forbidden");t.add(o);let n=`[${o.map((r,a)=>Ne(r,`${e}[${a}]`,t)).join(",")}]`;return t.delete(o),n}if(typeof o=="object"&&o){if(t.has(o))throw new k("invalid-json",e,"cycles are forbidden");let n=Object.getPrototypeOf(o);if(n!==Object.prototype&&n!==null)throw new k("invalid-json",e,"expected a plain object");t.add(o);let r=o,a=`{${Object.keys(r).sort().map(i=>{let s=r[i];if(s===void 0||typeof s=="function"||typeof s=="symbol")throw new k("invalid-json",`${e}.${i}`,"value is not JSON");return`${JSON.stringify(i)}:${Ne(s,`${e}.${i}`,t)}`}).join(",")}}`;return t.delete(o),a}throw new k("invalid-json",e,"value is not JSON")}function mo(o){return Ne(o,"$",new WeakSet)}function we(o){return new TextEncoder().encode(mo(o))}function ke(o,e="$"){let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new k("invalid-utf8",e,"expected UTF-8 bytes")}try{return JSON.parse(t)}catch{throw new k("invalid-json",e,"expected valid JSON")}}async function se(o){if(!globalThis.crypto?.subtle)throw new k("missing-crypto","$","Web Crypto is required");let e=Uint8Array.from(o),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var ot=/^[a-f0-9]{64}$/,tt=/^\d+\.\d+\.\d+$/,nt=/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/,rt=new Set(["joint-skin","morph-regions","prepared-playback","static-prepared"]),at=new Set(["data","image","model"]);function N(o,e,t){throw new k(o,e,t)}function Ie(o,e,t){(!o||typeof o!="object"||Array.isArray(o))&&N("invalid-type",e,"expected an object");let n=Object.keys(o).sort(),r=[...t].sort();return(n.length!==r.length||n.some((a,i)=>a!==r[i]))&&N("invalid-keys",e,`expected exactly ${r.join(", ")}`),o}function fo(o,e){return Array.isArray(o)||N("invalid-type",e,"expected an array"),o}function le(o,e){return(typeof o!="string"||o.length===0)&&N("invalid-string",e,"expected a non-empty string"),o}function He(o,e){let t=le(o,e);return Be(t)||N("invalid-id",e,"expected a normalized kebab-case id"),t}function Fe(o,e){let t=le(o,e);return De(t)||N("invalid-path",e,"expected a normalized package-relative path"),t}function uo(o,e){let t=le(o,e);return tt.test(t)||N("invalid-revision",e,"expected x.y.z"),t}function ho(o,e){let t=le(o,e);return rt.has(t)||N("invalid-profile",e,t),t}function go(o,e){let t=le(o,e);return ot.test(t)||N("invalid-hash",e,"expected lowercase SHA-256"),t}function it(o,e){return(typeof o!="number"||!Number.isSafeInteger(o)||o<0)&&N("invalid-bytes",e,"expected a non-negative safe integer"),o}function st(o,e){let t=Ie(o,e,["bytes","mediaType","path","role","sha256"]),n=le(t.role,`${e}.role`);at.has(n)||N("invalid-role",`${e}.role`,n);let r=le(t.mediaType,`${e}.mediaType`).toLowerCase();return(!nt.test(r)||r!==t.mediaType)&&N("invalid-media-type",`${e}.mediaType`,"expected a normalized type/subtype"),n==="image"&&!r.startsWith("image/")&&N("invalid-media-type",`${e}.mediaType`,"image resources require an image media type"),{path:Fe(t.path,`${e}.path`),role:n,mediaType:r,bytes:it(t.bytes,`${e}.bytes`),sha256:go(t.sha256,`${e}.sha256`)}}function _e(o,e){let t=new Set;for(let n of o)t.has(n)&&N("duplicate",e,n),t.add(n)}function Mo(o,e){o.some((t,n)=>n>0&&t<=o[n-1])&&N("non-canonical-order",e,"entries must be unique and sorted")}function Re(o){let e=Ie(o,"$",["identity","modelPath","profile","resources","schema"]);e.schema!==ye&&N("invalid-schema","$.schema",`expected ${ye}`);let t=Ie(e.identity,"$.identity",["id","name","revision"]),n={id:He(t.id,"$.identity.id"),name:le(t.name,"$.identity.name"),revision:uo(t.revision,"$.identity.revision")},r=fo(e.resources,"$.resources").map((d,l)=>st(d,`$.resources[${l}]`));r.length===0&&N("missing-resource","$.resources","expected at least the model resource");let a=r.map(d=>d.path);_e(a,"$.resources"),Mo(a,"$.resources");let i=Fe(e.modelPath,"$.modelPath"),s=r.filter(d=>d.role==="model");return(s.length!==1||s[0].path!==i)&&N("invalid-model-resource","$.resources","expected exactly one model resource matching modelPath"),s[0].mediaType!=="application/json"&&N("invalid-model-resource","$.resources","model resource must be application/json"),{schema:ye,identity:n,profile:ho(e.profile,"$.profile"),modelPath:i,resources:r}}function lt(o,e){let t=Ie(o,e,["id","manifestPath","manifestSha256","name","profile","revision"]),n=Fe(t.manifestPath,`${e}.manifestPath`);return n.endsWith("/manifest.json")||N("invalid-manifest-path",`${e}.manifestPath`,"expected a package manifest.json path"),{id:He(t.id,`${e}.id`),name:le(t.name,`${e}.name`),revision:uo(t.revision,`${e}.revision`),profile:ho(t.profile,`${e}.profile`),manifestPath:n,manifestSha256:go(t.manifestSha256,`${e}.manifestSha256`)}}function Se(o){let e=Ie(o,"$",["defaultId","packages","schema"]);e.schema!==pe&&N("invalid-schema","$.schema",`expected ${pe}`);let t=fo(e.packages,"$.packages").map((a,i)=>lt(a,`$.packages[${i}]`));t.length===0&&N("missing-package","$.packages","expected at least one package");let n=t.map(a=>a.id);_e(n,"$.packages"),Mo(n,"$.packages"),_e(t.map(a=>a.manifestPath),"$.packages[*].manifestPath");let r=He(e.defaultId,"$.defaultId");return n.includes(r)||N("unknown-default","$.defaultId",r),{schema:pe,defaultId:r,packages:t}}var qe="model.json";function dt(o){return[...new Set(o.render.leaves.flatMap(e=>[...e.atlas?[e.atlas.resourcePath]:[],...e.fallback?[e.fallback.atlas.resourcePath]:[]]))].sort()}async function ct(o,e=[]){let t=F(o),n=we(t),r=new Map([[qe,n]]),a=[{path:qe,role:"model",mediaType:"application/json",bytes:n.byteLength,sha256:await se(n)}];for(let l of e){if(r.has(l.path))throw new k("duplicate",l.path,"resource path is already present");let c=Uint8Array.from(l.bytes);r.set(l.path,c),a.push({path:l.path,role:l.role,mediaType:l.mediaType,bytes:c.byteLength,sha256:await se(c)})}for(let l of dt(t)){let c=a.find(p=>p.path===l);if(!c)throw new k("missing-resource",l,"model image is not included in the package");if(c.role!=="image")throw new k("invalid-role",l,"model image resource must use the image role")}a.sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0);let i=Re({schema:ye,identity:t.identity,profile:t.profile,modelPath:qe,resources:a}),s=a.reduce((l,c)=>l+c.bytes,0);if(a.length>t.budgets.maxResources)throw new k("budget-exceeded","$.budgets.maxResources",`${a.length} resources exceed ${t.budgets.maxResources}`);if(s>t.budgets.maxBytes)throw new k("budget-exceeded","$.budgets.maxBytes",`${s} bytes exceed ${t.budgets.maxBytes}`);let d=we(i);return{manifest:i,manifestBytes:d,manifestSha256:await se(d),files:r}}async function pt(o,e){let t=e.map(a=>({id:a.manifest.identity.id,name:a.manifest.identity.name,revision:a.manifest.identity.revision,profile:a.manifest.profile,manifestPath:a.manifestPath,manifestSha256:a.manifestSha256}));t.sort((a,i)=>a.id<i.id?-1:a.id>i.id?1:0);let n=Se({schema:pe,defaultId:o,packages:t}),r=we(n);return{catalog:n,bytes:r,sha256:await se(r)}}function Je(o,e){if(e.identity.id!==o.identity.id||e.identity.name!==o.identity.name||e.identity.revision!==o.identity.revision||e.profile!==o.profile)throw new k("profile-mismatch","$.model","model identity or profile does not match its manifest")}var bo=64*1024*1024,yt=1024,mt=128*1024*1024,xo=3e4;function Pe(o,e,t){let n=o??e;if(!Number.isSafeInteger(n)||n<=0)throw new k("invalid-limit",t,"expected a positive safe integer");return n}function $o(o){if(typeof o!="string"||o.length===0||o.includes("\\")||o.includes("#")||o.includes("?"))throw new k("invalid-base-url","$.baseUrl","expected a clean HTTP(S) base URL");let e;try{e=new URL(o,globalThis.location?.href??"https://polycss.invalid/")}catch{throw new k("invalid-base-url","$.baseUrl","expected a valid URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new k("invalid-base-url","$.baseUrl","expected HTTP or HTTPS");return e.pathname.endsWith("/")||(e.pathname+="/"),e}async function ft(o,e,t){let n=o.headers.get("content-length");if(n!==null){let a=Number(n);if(!Number.isSafeInteger(a)||a<0||a>t)throw new k("resource-too-large",e,`declared bytes exceed ${t}`)}if(o.body?.getReader){let a=o.body.getReader(),i=[],s=0;for(;;){let c=await a.read();if(c.done)break;if(s+=c.value.byteLength,s>t)throw await a.cancel(),new k("resource-too-large",e,`bytes exceed ${t}`);i.push(c.value)}let d=new Uint8Array(s),l=0;for(let c of i)d.set(c,l),l+=c.byteLength;return d}if(n===null)throw new k("resource-too-large",e,"content-length is required without a readable body");let r=new Uint8Array(await o.arrayBuffer());if(r.byteLength>t)throw new k("resource-too-large",e,`bytes exceed ${t}`);return r}async function We(o,e,t,n,r){let a=n??AbortSignal.timeout(r),i;try{i=await o(e,{cache:"no-store",signal:a})}catch(s){throw a.aborted?s:new k("request-failed",e.pathname,"request failed",{cause:s})}if(!i.ok)throw new k("request-failed",e.pathname,`HTTP ${i.status}`);return ft(i,e.pathname,t)}async function Po(o,e,t){let n=await se(o);if(n!==e)throw new k("stale-hash",t,`expected ${e}, received ${n}`)}function ut(o,e){let t=e.lastIndexOf("/");return Le(o,e.slice(0,t+1))}function Le(o,e){let t=new URL(e,o);if(t.origin!==o.origin||!t.href.startsWith(o.href))throw new k("invalid-path",e,"package path escapes its base URL");return t}async function vo(o,e={}){let t=$o(o),n=Pe(e.maxResourceBytes,bo,"$.maxResourceBytes"),r=e.fetchImpl??globalThis.fetch;if(typeof r!="function")throw new k("missing-fetch","$.fetchImpl","a fetch implementation is required");let a=Pe(e.requestTimeoutMs,xo,"$.requestTimeoutMs"),i=await We(r,Le(t,"catalog.json"),n,e.signal,a);return{catalog:Se(ke(i,"$.catalog")),bytes:i,sha256:await se(i)}}async function ht(o,e={}){let t=$o(o),n=Pe(e.maxResourceBytes,bo,"$.maxResourceBytes"),r=Pe(e.maxResources,yt,"$.maxResources"),a=Pe(e.maxTotalBytes,mt,"$.maxTotalBytes"),i=Pe(e.requestTimeoutMs,xo,"$.requestTimeoutMs"),s=e.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new k("missing-fetch","$.fetchImpl","a fetch implementation is required");let d=await vo(t.href,{fetchImpl:s,maxResourceBytes:n,requestTimeoutMs:i,signal:e.signal}),l=e.modelId??d.catalog.defaultId,c=d.catalog.packages.find($=>$.id===l);if(!c)throw new k("unknown-package","$.modelId",l);let p=await We(s,Le(t,c.manifestPath),n,e.signal,i);await Po(p,c.manifestSha256,c.manifestPath);let y=Re(ke(p,"$.manifest"));if(y.identity.id!==c.id||y.identity.name!==c.name||y.identity.revision!==c.revision||y.profile!==c.profile)throw new k("profile-mismatch","$.manifest","catalog row does not match its manifest");let b=ut(t,c.manifestPath);if(y.resources.length>r)throw new k("package-too-large","$.manifest.resources",`${y.resources.length} resources exceed ${r}`);let m=0;for(let $ of y.resources){if($.bytes>n)throw new k("resource-too-large",$.path,`declared bytes exceed ${n}`);if(m+=$.bytes,m>a)throw new k("package-too-large",$.path,`declared package bytes exceed ${a}`)}let u=new Map,x=async $=>{let w=await We(s,Le(b,$.path),Math.min(n,$.bytes),e.signal,i);if(w.byteLength!==$.bytes)throw new k("stale-size",$.path,`expected ${$.bytes}, received ${w.byteLength}`);return await Po(w,$.sha256,$.path),{descriptor:$,bytes:w}},g=y.resources.find($=>$.path===y.modelPath),v=await x(g);u.set(g.path,v);let I=F(ke(v.bytes,"$.model"));if(Je(y,I),y.resources.length>I.budgets.maxResources)throw new k("budget-exceeded","$.budgets.maxResources",`${y.resources.length} resources exceed ${I.budgets.maxResources}`);if(m>I.budgets.maxBytes)throw new k("budget-exceeded","$.budgets.maxBytes",`${m} bytes exceed ${I.budgets.maxBytes}`);for(let $ of y.resources)$!==g&&u.set($.path,await x($));let E=new Set(I.render.leaves.flatMap($=>[...$.atlas?[$.atlas.resourcePath]:[],...$.fallback?[$.fallback.atlas.resourcePath]:[]]));for(let $ of E){let w=u.get($);if(!w)throw new k("missing-resource",$,"model image is not declared by the package");if(w.descriptor.role!=="image")throw new k("invalid-role",$,"model image resource must use the image role")}return{catalog:d.catalog,catalogSha256:d.sha256,catalogRow:c,manifest:y,manifestSha256:c.manifestSha256,model:I,resources:u}}import{buildPolyCameraSceneTransform as wo,capturePolyCameraSnapshot as ko,createPolyCamera as gt,formatMatrix3dValues as Mt,injectPolyBaseStyles as Pt,isSolidTriangleSupported as bt}from"@layoutit/polycss";var me=class extends Error{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphRenderError",this.code=e,this.path=t}};var xt={"atlas-slice":"s","direct-image":"s","solid-quad":"b","solid-triangle":"u"};function U(o,e,t){throw new me(o,e,t)}function Ge(o,e){return(!Array.isArray(o)||o.length!==16||o.some(t=>typeof t!="number"||!Number.isFinite(t)))&&U("invalid-matrix",e,"expected sixteen finite components"),o}function fe(o){return`matrix3d(${Mt(o)})`}function $t(o,e){let t=new Array(16).fill(0);for(let n=0;n<4;n+=1)for(let r=0;r<4;r+=1){let a=0;for(let i=0;i<4;i+=1)a+=o[i*4+r]*e[n*4+i];t[n*4+r]=Object.is(a,-0)?0:a}return t}function Ye(o,e,t){return t&&o.fallback?$t(e,o.fallback.matrixFromLeaf):e}function vt(o){let[e,t,n,r]=o;return`rgba(${Math.round(e*255)}, ${Math.round(t*255)}, ${Math.round(n*255)}, ${r})`}function Qe(o,e,t,n=[]){(!o||typeof o!="object"||Array.isArray(o))&&U("invalid-update",e,"expected an object");let r=new Set([...t,...n]),a=Object.keys(o);return(t.some(i=>!a.includes(i))||a.some(i=>!r.has(i)))&&U("invalid-update",e,`allowed keys are ${[...r].sort().join(", ")}`),o}function Io(o,e){let t=new Set;for(let n of o)t.has(n)&&U("duplicate-update",e,n),t.add(n)}function wt(o,e){let t=Qe(o,e,["matrix","shapeId"]);return typeof t.shapeId!="string"&&U("invalid-update",`${e}.shapeId`,"expected a string"),{shapeId:t.shapeId,matrix:Ge(t.matrix,`${e}.matrix`)}}function kt(o,e){let t=Qe(o,e,["leafId"],["atlasRow","matrix","opacity","visible"]);typeof t.leafId!="string"&&U("invalid-update",`${e}.leafId`,"expected a string");let n={leafId:t.leafId};return t.matrix!==void 0&&(n.matrix=Ge(t.matrix,`${e}.matrix`)),t.visible!==void 0&&(typeof t.visible!="boolean"&&U("invalid-update",`${e}.visible`,"expected a boolean"),n.visible=t.visible),t.opacity!==void 0&&((typeof t.opacity!="number"||!Number.isFinite(t.opacity)||t.opacity<0||t.opacity>1)&&U("invalid-update",`${e}.opacity`,"expected 0 <= opacity <= 1"),n.opacity=t.opacity),t.atlasRow!==void 0&&((!Number.isSafeInteger(t.atlasRow)||t.atlasRow<0)&&U("invalid-update",`${e}.atlasRow`,"expected a non-negative integer"),n.atlasRow=t.atlasRow),n}function It(o){let e=Qe(o,"$",[],["leaves","modelMatrix","shapes"]),t=e.shapes===void 0?void 0:(()=>{Array.isArray(e.shapes)||U("invalid-update","$.shapes","expected an array");let r=e.shapes.map((a,i)=>wt(a,`$.shapes[${i}]`));return Io(r.map(a=>a.shapeId),"$.shapes"),r})(),n=e.leaves===void 0?void 0:(()=>{Array.isArray(e.leaves)||U("invalid-update","$.leaves","expected an array");let r=e.leaves.map((a,i)=>kt(a,`$.leaves[${i}]`));return Io(r.map(a=>a.leafId),"$.leaves"),r})();return{...e.modelMatrix===void 0?{}:{modelMatrix:Ge(e.modelMatrix,"$.modelMatrix")},...t===void 0?{}:{shapes:t},...n===void 0?{}:{leaves:n}}}function Rt(o,e,t,n){o.style.setProperty("--polycss-atlas-width",`${e.width}px`),o.style.setProperty("--polycss-atlas-height",`${e.height}px`),o.style.backgroundImage=`url("${n.replace(/"/gu,"%22")}")`,o.style.backgroundPosition=`${-t.x}px ${-t.y}px`,o.style.backgroundSize=`${t.pageWidth}px ${t.pageHeight}px`}function St(o,e,t,n,r){let a=`url("${r.replace(/"/gu,"%22")}")`,i=`${-e.x}px ${-e.y}px`,s=`${e.pageWidth}px ${e.pageHeight}px`;o.style.width=`${t}px`,o.style.height=`${n}px`,o.style.backgroundColor="currentColor",o.style.setProperty("mask-image",a),o.style.setProperty("mask-mode","alpha"),o.style.setProperty("mask-position",i),o.style.setProperty("mask-repeat","no-repeat"),o.style.setProperty("mask-size",s),o.style.setProperty("-webkit-mask-image",a),o.style.setProperty("-webkit-mask-position",i),o.style.setProperty("-webkit-mask-repeat","no-repeat"),o.style.setProperty("-webkit-mask-size",s)}function jt(o,e,t,n,r){let a=r?e.fallback:null,i=o.createElement(a?"s":xt[e.strategy]);return i.className="polycss-morph-leaf",i.dataset.polyMorphLeaf=e.id,i.dataset.polyMorphStrategy=e.strategy,i.dataset.polyMorphResolvedStrategy=a?"atlas-slice":e.strategy,i.style.transform=fe(Ye(e,e.matrix,a!==null)),i.style.color=vt(t),i.style.backfaceVisibility="visible",i.style.backgroundRepeat="no-repeat",i.style.opacity="1",i.style.transformOrigin="0 0",i.style.visibility="visible",e.atlas?(i.style.width=`${e.width}px`,i.style.height=`${e.height}px`,Rt(i,e,e.atlas,n(e.atlas.resourcePath,e.id))):a?St(i,a.atlas,a.width,a.height,n(a.atlas.resourcePath,e.id)):e.strategy==="solid-quad"&&(i.style.width=`${e.width}px`,i.style.height=`${e.height}px`),i}function Ct(o,e,t={}){(!o||typeof o.appendChild!="function"||!o.ownerDocument)&&U("invalid-host","$.host","expected an HTMLElement");let n=F(e),r=o.ownerDocument,a=n.render.leaves.some(M=>M.strategy==="solid-triangle")&&!bt(r),i=new Map,s=typeof r.defaultView?.URL?.createObjectURL=="function"?r.defaultView.URL:globalThis.URL,d=r.defaultView?.Blob??globalThis.Blob,l=()=>{for(let M of i.values())s.revokeObjectURL(M);i.clear()},c=(M,R)=>{let z=i.get(M);if(z)return z;let q=t.resources?.get(M);(!q||q.descriptor.path!==M||q.descriptor.role!=="image")&&U("missing-resource",R,"image-backed leaves require their verified package resource"),(typeof s?.createObjectURL!="function"||typeof s?.revokeObjectURL!="function"||typeof d!="function")&&U("missing-object-url",R,"this browser cannot mount verified image bytes");let ee=q.bytes.slice(),de=s.createObjectURL(new d([ee.buffer],{type:q.descriptor.mediaType}));return i.set(M,de),de};try{for(let M of n.render.leaves)M.atlas&&c(M.atlas.resourcePath,M.id),a&&M.strategy==="solid-triangle"&&(M.fallback||U("missing-solid-triangle-fallback",`${M.id}.fallback`,"this browser requires a prepared per-polygon atlas slice"),c(M.fallback.atlas.resourcePath,M.id))}catch(M){throw l(),M}Pt(r);let p=r.defaultView?.getComputedStyle(o),y=o.style.position,b=!1;(!p||p.position==="static"||p.position==="")&&(o.style.position="relative",b=!0);let m=t.camera??gt({zoom:1}),u=r.createElement("div");u.className="polycss-camera polycss-morph-camera";let x=ko(m);u.style.perspective=x.appliedPerspectiveStyle,u.dataset.polycssCameraProjection=x.projection,o.appendChild(u);let g=r.createElement("div");g.className="polycss-scene polycss-morph-scene",g.setAttribute("aria-hidden","true");let v=wo(m.state);g.style.transform=v,u.appendChild(g);let I=r.createElement("div");I.className="polycss-mesh polycss-morph-model",I.dataset.polyMorphModel=n.identity.id;let E=fe(n.render.modelMatrix);I.style.transform=E,g.appendChild(I);let $=new Map,w=new Map;for(let M of n.render.shapes){let R=r.createElement("div");R.className="polycss-mesh polycss-morph-shape",R.dataset.polyMorphShape=M.id;let z=fe(M.matrix);R.style.transform=z,I.appendChild(R),$.set(M.id,R),w.set(M.id,z)}let W=new Map(n.materials.map(M=>[M.id,M])),V=new Map,B=new Map;for(let M of n.render.leaves){let R=$.get(M.shapeId),z=W.get(M.materialId);(!R||!z)&&U("mount-coverage",M.id,"leaf references are incomplete");let q=jt(r,M,z.color,c,a&&M.strategy==="solid-triangle");R.appendChild(q),V.set(M.id,{id:M.id,plan:M,element:q}),B.set(M.id,{transform:fe(Ye(M,M.matrix,a&&M.strategy==="solid-triangle")),visible:!0,opacity:1,atlasRow:0})}let te=[...$.entries()],T=[...V.entries()],L=!1,D=v,_={applyCount:0,totalTransformWrites:0,totalVisibilityWrites:0,totalOpacityWrites:0,totalAtlasRowWrites:0},P=()=>{L&&U("destroyed","$","mounted model is destroyed")},C=()=>{P(),($.size!==te.length||V.size!==T.length)&&U("identity-drift","$","retained handle maps changed");for(let[M,R]of te)($.get(M)!==R||R.parentElement!==I)&&U("identity-drift",M,"shape element identity changed");for(let[M,R]of T){let z=$.get(R.plan.shapeId);(V.get(M)!==R||R.element.parentElement!==z)&&U("identity-drift",M,"leaf element identity changed")}},S={model:n,camera:m,cameraElement:u,sceneElement:g,modelElement:I,shapeElements:$,leafHandles:V,get stats(){return{mountCount:1,shapeRoots:$.size,leafCount:V.size,topologyConstructions:1,atlasConstructions:0,schedulerCount:0,..._}},get destroyed(){return L},apply:M=>{P();let R=It(M),z=(R.shapes??[]).map(j=>{let Q=$.get(j.shapeId);return Q||U("unknown-shape",j.shapeId,"no retained shape handle"),{shape:j,element:Q}}),q=(R.leaves??[]).map(j=>{let Q=V.get(j.leafId),Y=B.get(j.leafId);(!Q||!Y)&&U("unknown-leaf",j.leafId,"no retained leaf handle");let Te;if(j.atlasRow!==void 0){let oe=Q.plan.atlas;oe||U("invalid-atlas-row",j.leafId,"leaf has no image rows");let so=oe.y+j.atlasRow*oe.height;so+oe.height>oe.pageHeight&&U("invalid-atlas-row",j.leafId,"row exceeds the image page"),Te=`${-oe.x}px ${-so}px`}return{leaf:j,handle:Q,state:Y,atlasPosition:Te}});C();let ee=0,de=0,he=0,ge=0,ce=0,$e=0;if(R.modelMatrix){let j=fe(R.modelMatrix);E!==j&&(E=j,I.style.transform=j,ee+=1)}for(let{shape:j,element:Q}of z){let Y=fe(j.matrix);w.get(j.shapeId)!==Y&&(w.set(j.shapeId,Y),Q.style.transform=Y,de+=1)}for(let{leaf:j,handle:Q,state:Y,atlasPosition:Te}of q){if(j.matrix){let oe=fe(Ye(Q.plan,j.matrix,a&&Q.plan.strategy==="solid-triangle"));Y.transform!==oe&&(Y.transform=oe,Q.element.style.transform=oe,he+=1)}if(j.visible!==void 0){let oe=j.visible?"visible":"hidden";Y.visible!==j.visible&&(Y.visible=j.visible,Q.element.style.visibility=oe,ge+=1)}if(j.opacity!==void 0){let oe=String(j.opacity);Y.opacity!==j.opacity&&(Y.opacity=j.opacity,Q.element.style.opacity=oe,ce+=1)}j.atlasRow!==void 0&&Y.atlasRow!==j.atlasRow&&(Y.atlasRow=j.atlasRow,Q.element.style.backgroundPosition=Te,$e+=1)}return C(),_.applyCount+=1,_.totalTransformWrites+=ee+de+he,_.totalVisibilityWrites+=ge,_.totalOpacityWrites+=ce,_.totalAtlasRowWrites+=$e,{modelTransformWrites:ee,shapeTransformWrites:de,leafTransformWrites:he,visibilityWrites:ge,opacityWrites:ce,atlasRowWrites:$e,dirtyLeavesVisited:R.leaves?.length??0,domCreations:0,domRemovals:0,topologyConstructions:0,atlasRedraws:0,schedulerCallbacks:0}},updateCamera(){P();let M=wo(m.state);if(D===M)return!1;D=M,g.style.transform=M;let R=ko(m);return u.style.perspective=R.appliedPerspectiveStyle,u.dataset.polycssCameraProjection=R.projection,!0},assertStableDomIdentity:C,destroy(){L||(L=!0,u.remove(),$.clear(),V.clear(),B.clear(),w.clear(),l(),b&&o.style.position==="relative"&&(o.style.position=y))}};return S.assertStableDomIdentity(),S}function re(o,e,t){throw new me(o,e,t)}function Ke(o,e){let t=o;return(!t||typeof t!="object"||!t.ownerDocument||typeof t.style?.setProperty!="function")&&re("invalid-target",e,"expected an HTMLElement"),t}function So(o,e){return typeof o!="string"&&re("invalid-transform",e,"expected a CSS transform string"),o}function Ro(o,e,t){let n,r,a,i;return Object.freeze({element:o,writeTransform(s){t();let d=So(s,`${e}.transform`);return n===d?!1:(o.style.transform=d,n=d,!0)},writeVisibility(s){return t(),typeof s!="boolean"&&re("invalid-visibility",`${e}.visible`,"expected a boolean"),r===s?!1:(o.style.visibility=s?"visible":"hidden",r=s,!0)},writeOpacity(s){return t(),(!Number.isFinite(s)||s<0||s>1)&&re("invalid-opacity",`${e}.opacity`,"expected a value in [0, 1]"),a===s?!1:(o.style.opacity=String(s),a=s,!0)},writeImagePositionY(s){return t(),(typeof s!="string"||s.length===0)&&re("invalid-image-position",`${e}.imagePositionY`,"expected a CSS position"),i===s?!1:(o.style.backgroundPositionY=s,i=s,!0)}})}function Tt(o){(!o||typeof o!="object"||Array.isArray(o))&&re("invalid-target","$","expected a prepared DOM target");let e=Ke(o.model?.element,"$.model.element");typeof o.model?.writeTransform!="function"&&re("invalid-target","$.model.writeTransform","expected a transform writer"),(!Array.isArray(o.shapes)||!Array.isArray(o.leaves))&&re("invalid-target","$","expected shape and leaf target arrays");let t=o.shapes.map((m,u)=>Ke(m?.element,`$.shapes[${u}].element`)),n=o.leaves.map((m,u)=>Ke(m?.element,`$.leaves[${u}].element`)),r=e.parentNode,a=t.map(m=>m.parentNode),i=n.map(m=>m.parentNode),s=!1,d=()=>{s&&re("target-destroyed","$","prepared DOM target is destroyed")},l=Object.freeze(t.map((m,u)=>Ro(m,`$.shapes[${u}]`,d))),c=Object.freeze(n.map((m,u)=>Ro(m,`$.leaves[${u}]`,d))),p,y=Object.freeze({element:e,writeTransform(m){d();let u=So(m,"$.model.transform");if(p===u)return!1;let x=o.model.writeTransform(u);return typeof x!="boolean"&&re("invalid-writer-result","$.model.writeTransform","expected a boolean"),p=u,x}});return Object.freeze({model:y,shapes:l,leaves:c,get destroyed(){return s},assertStableDomIdentity:()=>{d(),(e.parentNode!==r||l.some((u,x)=>u.element.parentNode!==a[x])||c.some((u,x)=>u.element.parentNode!==i[x]))&&re("identity-drift","$","retained DOM identity changed after adoption")},destroy(){s=!0}})}var X=class extends Error{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphRuntimeError",this.code=e,this.path=t}};function jo(o,e,t){throw new X(o,e,t)}function ze(o){return Object.freeze([...o])}function Ot(o,e){let{timesMs:t,values:n}=o;if(e<=t[0])return ze(n[0]);for(let r=1;r<t.length;r+=1){let a=t[r];if(e>a)continue;let i=t[r-1],s=n[r-1],d=n[r];if(e===a)return ze(d);if(o.interpolation==="step")return ze(s);let l=(e-i)/(a-i);if(o.target==="joint-rotation"){let p=s.reduce((m,u,x)=>m+u*d[x],0)<0?-1:1,y=s.map((m,u)=>m+(d[u]*p-m)*l),b=Math.hypot(...y);return Object.freeze(y.map(m=>m/b))}return Object.freeze(s.map((c,p)=>c+(d[p]-c)*l))}return ze(n[n.length-1])}function At(o,e){if(o.loop){let t=e%o.durationMs;return Object.is(t,-0)?0:t}return Math.min(e,o.durationMs)}function Xe(o){let e=F(o),t=new Map(e.animations.map(n=>[n.id,n]));return Object.freeze({model:e,clipIds:Object.freeze([...t.keys()]),sample(n,r){let a=t.get(n);a||jo("unknown-clip","$.clipId",n),(!Number.isFinite(r)||r<0)&&jo("invalid-time","$.timeMs","expected a finite non-negative time");let i=At(a,r),s={},d={},l=new Map,c=new Map;for(let p of a.channels){let y=Ot(p,i);if(p.target==="morph-weight"&&(s[p.targetId]=y[0]),p.target==="control-value"&&(d[p.targetId]=y[0]),p.target==="shape-matrix"&&c.set(p.targetId,y),p.target.startsWith("joint-")){let b=l.get(p.targetId)??{};p.target==="joint-translation"?b.translation=y:p.target==="joint-rotation"?b.rotation=y:b.scale=y,l.set(p.targetId,b)}}return{clipId:n,requestedTimeMs:r,sampledTimeMs:i,morphWeights:Object.freeze(s),controlValues:Object.freeze(d),jointTransforms:l,shapeMatrices:c}}})}function Ze(o,e,t){throw new X(o,e,t)}function Co(o){return o===null?null:((!Array.isArray(o)||o.length!==3||o.some(e=>typeof e!="number"||!Number.isFinite(e)))&&Ze("invalid-point","$.point","expected three finite components or null"),[o[0],o[1],o[2]])}function Lt(o){let e=Math.hypot(...o.axis);return[o.axis[0]/e,o.axis[1]/e,o.axis[2]/e]}function zt(o){let e=F(o);return Object.freeze({model:e,controlIds:Object.freeze(e.controls.map(t=>t.id)),controls:new Map(e.controls.map(t=>[t.id,t]))})}function Vt(o){return Object.freeze({tick:-1,active:!1,heldControlId:null,holdStartPoint:null,holdStartValue:0,values:Object.freeze(Object.fromEntries(o.controlIds.map(e=>[e,o.controls.get(e).initial]))),frozenControlIds:Object.freeze([])})}function To(o,e){let t=Co(e),n=null;for(let r of o.controlIds){let a=o.controls.get(r),i=Math.hypot(t[0]-a.anchor[0],t[1]-a.anchor[1],t[2]-a.anchor[2]);i<=a.radius&&(!n||i<n.distance)&&(n={id:r,distance:i})}return n?.id??null}function Et(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&Ze("invalid-state","$.state","control state is invalid"),typeof t?.active!="boolean"&&Ze("invalid-input","$.active","expected a boolean");let n=Co(t.point),r=e.heldControlId,a=e.holdStartPoint,i=e.holdStartValue,s=null,d=null,l={...e.values},c=new Set(e.frozenControlIds),p=t.active&&!e.active,y=!t.active&&e.active;if(p&&n&&(r=To(o,n),r&&(s=r,a=n,i=l[r]??o.controls.get(r).initial,c.delete(r))),t.active&&r&&n&&a){let m=o.controls.get(r),u=Lt(m),x=(n[0]-a[0])*u[0]+(n[1]-a[1])*u[1]+(n[2]-a[2])*u[2];l[r]=Math.max(m.minimum,Math.min(m.maximum,i+x))}y&&(d=r,r&&(t.freezeOnRelease===!0?c.add(r):c.delete(r)),r=null,a=null,i=0);let b=Object.freeze({tick:e.tick+1,active:t.active,heldControlId:r,holdStartPoint:a,holdStartValue:i,values:Object.freeze(l),frozenControlIds:Object.freeze([...c].sort())});return Object.freeze({state:b,pickedControlId:s,releasedControlId:d,heldTarget:t.active&&r?Object.freeze({controlId:r,value:l[r]}):null})}import{computeSolidTrianglePlanFromCssPoints as Lo,SOLID_TRIANGLE_CANONICAL_SIZE as Oo}from"@layoutit/polycss";function ne(o,e,t){throw new X(o,e,t)}function Ut(o,e){return(typeof o!="number"||!Number.isFinite(o))&&ne("invalid-number",e,"expected a finite number"),Object.is(o,-0)?0:o}function zo(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function Ve(o){return o.map(e=>[e[0],e[1],e[2]])}function Ee(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function Bt(o,e){let[t,n,r]=o.vertexIndices,a=e[t],i=e[n],s=e[r],d=Lo(o.polygon,0,{seamBleed:0},{basis:o.basis??void 0,includeColor:!1,primitive:"corner-bevel"},a[0],a[1],a[2],i[0],i[1],i[2],s[0],s[1],s[2]);if(!d)return{matrix:null,visible:!1};let l=/^matrix3d\(([^)]+)\)$/u.exec(d.transformText);l||ne("invalid-transform",o.leaf.id,"PolyCSS returned no matrix3d");let c=l[1].split(",").map(Number);(c.length!==16||c.some(b=>!Number.isFinite(b)))&&ne("invalid-transform",o.leaf.id,"PolyCSS returned an invalid matrix3d");let p=Oo/o.leaf.width,y=Oo/o.leaf.height;for(let b of[0,1,2])c[b]*=p;for(let b of[4,5,6])c[b]*=y;return{matrix:c,visible:!0}}function Dt(o,e){let[t,n,r,a]=o.vertexIndices,i=e[t],s=e[n],d=e[r],l=e[a],c=[s[0]+l[0]-i[0],s[1]+l[1]-i[1],s[2]+l[2]-i[2]];Math.hypot(c[0]-d[0],c[1]-d[1],c[2]-d[2])>1e-6&&ne("non-affine-polygon",o.leaf.id,"deformed quad is not a parallelogram");let p=[(s[0]-i[0])/o.leaf.width,(s[1]-i[1])/o.leaf.width,(s[2]-i[2])/o.leaf.width],y=[(l[0]-i[0])/o.leaf.height,(l[1]-i[1])/o.leaf.height,(l[2]-i[2])/o.leaf.height],b=[p[1]*y[2]-p[2]*y[1],p[2]*y[0]-p[0]*y[2],p[0]*y[1]-p[1]*y[0]],m=zo(b);return Math.hypot(...m)<=1e-12&&ne("degenerate-polygon",o.leaf.id,"deformed quad has no area"),{matrix:[p[0],p[1],p[2],0,y[0],y[1],y[2],0,m[0],m[1],m[2],0,i[0],i[1],i[2],1],visible:!0}}function eo(o,e){if(o.vertexIndices.length===3)return Bt(o,e);if(o.vertexIndices.length===4)return Dt(o,e);ne("unsupported-deformation",o.leaf.id,"caller-driven deformation supports prepared triangles and affine quads")}function oo(o,e){let t=o.topology.polygons.find(i=>i.id===e.polygonId);t||ne("unknown-polygon",e.id,e.polygonId);let n=t.vertexIndices.map(i=>[...o.topology.vertices[i]]),r={vertices:n},a=null;if(n.length===3){let[i,s,d]=n,l=Lo(r,0,{seamBleed:0},{includeColor:!1,primitive:"corner-bevel"},i[0],i[1],i[2],s[0],s[1],s[2],d[0],d[1],d[2]);l||ne("degenerate-polygon",e.id,"base triangle has no area"),a=l.basis}return{leaf:e,vertexIndices:t.vertexIndices,polygon:r,basis:a}}function Ao(o,e,t,n){let r=o??{};(!r||typeof r!="object"||Array.isArray(r))&&ne("invalid-input",t,"expected an object");let a=new Set(e),i=Object.keys(r).find(s=>!a.has(s));return i&&ne("unknown-id",t,i),Object.fromEntries(e.map(s=>{let[d,l]=n.get(s)??[0,1],c=Ut(r[s]??0,`${t}.${s}`);return(c<d||c>l)&&ne("out-of-range",`${t}.${s}`,`expected ${d} <= value <= ${l}`),[s,c]}))}function Nt(o){return new Map(o.deformation.kind==="morph-regions"?o.deformation.targets.map(e=>[e.id,e]):[])}function _t(o){let e=F(o);e.deformation.kind==="joint-skin"&&ne("profile-not-executable","$.profile","joint skin requires the skinning runtime");let t=Nt(e),n=[...t.keys()],r=e.controls.map(g=>g.id),a=new Map(n.map(g=>[g,[0,1]])),i=new Map(e.controls.map(g=>[g.id,[g.minimum,g.maximum]])),s=new Map(e.render.leaves.map(g=>[g.polygonId,g])),d=new Map;for(let g of e.topology.polygons)for(let v of g.vertexIndices){let I=d.get(v)??[];I.push(g.id),d.set(v,I)}let l=new Map;for(let g of t.values()){let v=new Set;for(let I of g.deltas)for(let E of d.get(I.vertexIndex)??[]){let $=s.get(E);$&&v.add($.id)}l.set(g.id,v)}let c=new Map(e.render.leaves.map(g=>[g.id,oo(e,g)])),p=Ee(Ve(e.topology.vertices)),y=Ee(Ve(e.topology.normals)),b=Object.fromEntries(n.map(g=>[g,0])),m=p,u=y,x=g=>{(!g||!Number.isSafeInteger(g.tick)||g.tick<0)&&ne("invalid-tick","$.tick","expected a non-negative safe integer");let v=Ao(g.morphWeights,n,"$.morphWeights",a),I=Ao(g.controlValues,r,"$.controlValues",i),E={...v};for(let T of e.controls){let L=I[T.id];for(let D of T.targets)E[D.targetId]=Math.max(0,Math.min(1,(E[D.targetId]??0)+L*D.scale))}let $=n.filter(T=>E[T]!==b[T]),w=m,W=u;if($.length>0){let T=Ve(p),L=Ve(y);for(let D of n){let _=E[D];if(_!==0)for(let P of t.get(D).deltas){let C=T[P.vertexIndex];P.position&&(C[0]+=P.position[0]*_,C[1]+=P.position[1]*_,C[2]+=P.position[2]*_);let f=L[P.vertexIndex];P.normal&&(f[0]+=P.normal[0]*_,f[1]+=P.normal[1]*_,f[2]+=P.normal[2]*_)}}L=L.map(zo),w=Ee(T),W=Ee(L)}let V=new Set;for(let T of $)for(let L of l.get(T)??[])V.add(L);let B=e.render.leaves.map(T=>T.id).filter(T=>V.has(T)),te=B.map(T=>{let L=eo(c.get(T),w);return{leafId:T,visible:L.visible,...L.matrix?{matrix:L.matrix}:{}}});return m=w,u=W,b={...E},{tick:g.tick,positions:w,normals:W,morphWeights:Object.freeze({...E}),controlValues:Object.freeze({...I}),dirtyLeafIds:Object.freeze(B),leafUpdates:Object.freeze(te),runtimePolygonConstructions:0,runtimeTopologyConstructions:0,atlasRedraws:0}};return Object.freeze({model:e,targetIds:Object.freeze(n),controlIds:Object.freeze(r),basePositions:Object.freeze(p),baseNormals:Object.freeze(y),sample:x,reset(){b=Object.fromEntries(n.map(g=>[g,0])),m=p,u=y}})}function je(o,e,t){throw new X(o,e,t)}function be(o){return Object.freeze([...o])}function to(o,e){return o.every((t,n)=>t===e[n])}function no(o){let e=F(o);return Object.freeze({modelMatrix:be(e.render.modelMatrix),shapes:Object.freeze(e.render.shapes.map(t=>Object.freeze({shapeId:t.id,matrix:be(t.matrix)}))),leaves:Object.freeze(e.render.leaves.map(t=>Object.freeze({leafId:t.id,matrix:be(t.matrix),visible:!0,opacity:1,atlasRow:0})))})}function ro(o,e){let t=new Map(e.shapes.map(r=>[r.shapeId,r])),n=new Map(e.leaves.map(r=>[r.leafId,r]));for(let r of t.keys())o.shapes.some(a=>a.shapeId===r)||je("unknown-shape","$.frame.shapes",r);for(let r of n.keys())o.leaves.some(a=>a.leafId===r)||je("unknown-leaf","$.frame.leaves",r);return Object.freeze({modelMatrix:e.modelMatrix===null?o.modelMatrix:be(e.modelMatrix),shapes:Object.freeze(o.shapes.map(r=>{let a=t.get(r.shapeId);return a?Object.freeze({shapeId:r.shapeId,matrix:be(a.matrix)}):r})),leaves:Object.freeze(o.leaves.map(r=>{let a=n.get(r.leafId);return a?Object.freeze({leafId:r.leafId,matrix:a.matrix===null?r.matrix:be(a.matrix),visible:a.visible??r.visible,opacity:a.opacity??r.opacity,atlasRow:a.atlasRow??r.atlasRow}):r}))})}function ao(o,e){(o.shapes.length!==e.shapes.length||o.leaves.length!==e.leaves.length)&&je("state-mismatch","$","prepared state topology differs");let t=!to(o.modelMatrix,e.modelMatrix),n=[];for(let a=0;a<e.shapes.length;a+=1){let i=o.shapes[a],s=e.shapes[a];i.shapeId!==s.shapeId&&je("state-mismatch","$.shapes","source order differs"),to(i.matrix,s.matrix)||n.push({shapeId:s.shapeId,matrix:s.matrix})}let r=[];for(let a=0;a<e.leaves.length;a+=1){let i=o.leaves[a],s=e.leaves[a];i.leafId!==s.leafId&&je("state-mismatch","$.leaves","source order differs");let d={leafId:s.leafId};to(i.matrix,s.matrix)||(d.matrix=s.matrix),i.visible!==s.visible&&(d.visible=s.visible),i.opacity!==s.opacity&&(d.opacity=s.opacity),i.atlasRow!==s.atlasRow&&(d.atlasRow=s.atlasRow),Object.keys(d).length>1&&r.push(d)}return Object.freeze({update:Object.freeze({...t?{modelMatrix:e.modelMatrix}:{},...n.length>0?{shapes:Object.freeze(n)}:{},...r.length>0?{leaves:Object.freeze(r)}:{}}),modelChanged:t,dirtyShapeIds:Object.freeze(n.map(a=>a.shapeId)),dirtyLeafIds:Object.freeze(r.map(a=>a.leafId))})}function Ce(o,e,t){throw new X(o,e,t)}function Ht(o,e,t){if(e){let n=t%o;return Object.is(n,-0)?0:n}return Math.min(t,o)}function Ft(o,e){let t=0,n=o.length-1;for(;t<=n;){let r=Math.floor((t+n)/2);o[r]<=e?t=r+1:n=r-1}return Math.max(0,n)}function qt(o){let e=F(o);(e.profile!=="prepared-playback"||!e.playback)&&Ce("profile-mismatch","$.profile","playback requires the prepared-playback profile");let t=e.playback,n=no(e),r=[],a=n,i=new Map(e.render.leaves.map(p=>[p.id,p]));for(let[p,y]of t.frames.entries()){for(let b of y.leaves){if(b.atlasRow===null)continue;let m=i.get(b.leafId);m.atlas||Ce("invalid-atlas-row",`$.playback.frames[${p}]`,`${m.id} has no image rows`),m.atlas.y+b.atlasRow*m.atlas.height+m.atlas.height>m.atlas.pageHeight&&Ce("invalid-atlas-row",`$.playback.frames[${p}]`,`${m.id} row exceeds its page`)}a=ro(a,y),r.push(a)}let s=t.frames.map(p=>p.timeMs),d=n,l=null,c=p=>{(!Number.isFinite(p)||p<0)&&Ce("invalid-time","$.timeMs","expected a finite non-negative time");let y=Ht(t.durationMs,t.loop,p),b=Ft(s,y),m=r[b],u=ao(d,m),x=Object.freeze({requestedTimeMs:p,sampledTimeMs:y,frameIndex:b,state:m,update:u.update,modelChanged:u.modelChanged,dirtyShapeIds:u.dirtyShapeIds,dirtyLeafIds:u.dirtyLeafIds,domCreations:0,domRemovals:0,topologyConstructions:0,atlasConstructions:0,atlasRedraws:0,schedulerCallbacks:0});return l=x,x};return Object.freeze({model:e,durationMs:t.durationMs,loop:t.loop,frameCount:t.frames.length,sample:c,commit(p){p!==l&&Ce("invalid-sample","$.sample","commit requires the latest unapplied playback sample"),d=p.state,l=null},reset(){d=n,l=null}})}var Jt=Object.freeze(["joint-skin","morph-regions","prepared-playback","static-prepared"]);function ae(o,e,t){throw new X(o,e,t)}function Wt(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function io(o,e){let t=new Array(16).fill(0);for(let n=0;n<4;n+=1)for(let r=0;r<4;r+=1){let a=0;for(let i=0;i<4;i+=1)a+=o[i*4+r]*e[n*4+i];t[n*4+r]=Object.is(a,-0)?0:a}return Object.freeze(t)}function Yt(o,e){if(o===void 0)return[0,0,0,1];(!Array.isArray(o)||o.length!==4||o.some(n=>typeof n!="number"||!Number.isFinite(n)))&&ae("invalid-quaternion",e,"expected four finite components");let t=Math.hypot(...o);return t<=1e-12&&ae("invalid-quaternion",e,"quaternion must be non-zero"),[o[0]/t,o[1]/t,o[2]/t,o[3]/t]}function Vo(o,e,t,n=!1){return o===void 0?e:((!Array.isArray(o)||o.length!==3||o.some(r=>typeof r!="number"||!Number.isFinite(r)))&&ae("invalid-vector",t,"expected three finite components"),n&&o.some(r=>r<=0)&&ae("invalid-scale",t,"scale components must be positive"),[o[0],o[1],o[2]])}function Bo(o,e){if(o===void 0)return Wt();(!o||typeof o!="object"||Array.isArray(o))&&ae("invalid-joint-transform",e,"expected an object"),Object.keys(o).some(v=>v!=="translation"&&v!=="rotation"&&v!=="scale")&&ae("invalid-joint-transform",e,"unknown transform field");let n=Vo(o.translation,[0,0,0],`${e}.translation`),r=Vo(o.scale,[1,1,1],`${e}.scale`,!0),[a,i,s,d]=Yt(o.rotation,`${e}.rotation`),l=a*a,c=i*i,p=s*s,y=a*i,b=a*s,m=i*s,u=d*a,x=d*i,g=d*s;return[(1-2*(c+p))*r[0],2*(y+g)*r[0],2*(b-x)*r[0],0,2*(y-g)*r[1],(1-2*(l+p))*r[1],2*(m+u)*r[1],0,2*(b+x)*r[2],2*(m-u)*r[2],(1-2*(l+c))*r[2],0,n[0],n[1],n[2],1]}function Gt(o,e){return[o[0]*e[0]+o[4]*e[1]+o[8]*e[2]+o[12],o[1]*e[0]+o[5]*e[1]+o[9]*e[2]+o[13],o[2]*e[0]+o[6]*e[1]+o[10]*e[2]+o[14]]}function Qt(o,e,t){let[n,r,a]=o,i=o[4],s=o[5],d=o[6],l=o[8],c=o[9],p=o[10],y=n*(s*p-c*d)-i*(r*p-c*a)+l*(r*d-s*a);return Math.abs(y)<=1e-12&&ae("invalid-normal-transform",t,"joint skin matrix is singular"),[((s*p-c*d)*e[0]+(c*a-r*p)*e[1]+(r*d-s*a)*e[2])/y,((l*d-i*p)*e[0]+(n*p-l*a)*e[1]+(i*a-n*d)*e[2])/y,((i*c-l*s)*e[0]+(l*r-n*c)*e[1]+(n*s-i*r)*e[2])/y]}function Kt(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function xe(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function Xt(o,e){return o.every((t,n)=>Math.abs(t-e[n])<=1e-12)}function Eo(o,e){let t=new Map(o.map(a=>[a.id,a])),n=new Map,r=a=>{let i=n.get(a.id);if(i)return i;let s=io(a.restMatrix,Bo(e.get(a.id),`$.jointTransforms.${a.id}`)),d=a.parentId===null?s:io(r(t.get(a.parentId)),s);return n.set(a.id,d),d};for(let a of o)r(a);return n}function Uo(o,e){return new Map(o.map(t=>[t.id,io(e.get(t.id),t.inverseBindMatrix)]))}function Zt(o,e){let t=o??new Map;(!t||typeof t.entries!="function")&&ae("invalid-joint-transform","$.jointTransforms","expected a map");for(let[n,r]of t)e.has(n)||ae("unknown-joint","$.jointTransforms",n),Bo(r,`$.jointTransforms.${n}`);return t}function en(o){let e=F(o);e.deformation.kind!=="joint-skin"&&ae("profile-mismatch","$.profile","skinning requires the joint-skin profile");let t=e.deformation,n=t.joints.map(w=>w.id),r=new Set(n),a=Eo(t.joints,new Map),i=Uo(t.joints,a),s=xe(e.topology.vertices.map(w=>[...w])),d=xe(e.topology.normals.map(w=>[...w])),l=new Map(e.render.leaves.map(w=>[w.id,oo(e,w)])),c=new Map;for(let w of e.topology.polygons)for(let W of w.vertexIndices){let V=c.get(W)??[];V.push(w.id),c.set(W,V)}let p=new Map(e.render.leaves.map(w=>[w.polygonId,w.id])),y=new Map(t.vertices.map(w=>[w.vertexIndex,w])),b=w=>{let W=[],V=[];for(let B=0;B<s.length;B+=1){let te=y.get(B),T=[0,0,0],L=[0,0,0];for(let D of te.influences){let _=w.get(D.jointId),P=Gt(_,s[B]),C=Qt(_,d[B],`$.skinMatrices.${D.jointId}`);T[0]+=P[0]*D.weight,T[1]+=P[1]*D.weight,T[2]+=P[2]*D.weight,L[0]+=C[0]*D.weight,L[1]+=C[1]*D.weight,L[2]+=C[2]*D.weight}W.push(T),V.push(Kt(L))}return{positions:W,normals:V}},m=b(i),u=xe(m.positions),x=xe(m.normals),g=new Map(i),v=u,I=x,E=Xe(e),$=w=>{(!w||!Number.isSafeInteger(w.tick)||w.tick<0)&&ae("invalid-tick","$.tick","expected a non-negative safe integer");let W=Zt(w.jointTransforms,r),V=Eo(t.joints,W),B=Uo(t.joints,V),te=new Set(n.filter(f=>!Xt(B.get(f),g.get(f)))),T=v,L=I;if(te.size>0){let f=b(B);T=xe(f.positions),L=xe(f.normals)}let D=new Set;if(te.size>0)for(let f of t.vertices)f.influences.some(S=>te.has(S.jointId))&&D.add(f.vertexIndex);let _=new Set;for(let f of D)for(let S of c.get(f)??[]){let M=p.get(S);M&&_.add(M)}let P=e.render.leaves.map(f=>f.id).filter(f=>_.has(f)),C=P.map(f=>{let S=eo(l.get(f),T);return{leafId:f,visible:S.visible,...S.matrix?{matrix:S.matrix}:{}}});return v=T,I=L,g=new Map(B),{tick:w.tick,positions:T,normals:L,globalJointMatrices:V,skinMatrices:B,dirtyLeafIds:Object.freeze(P),leafUpdates:Object.freeze(C),runtimePolygonConstructions:0,runtimeTopologyConstructions:0,atlasRedraws:0}};return Object.freeze({model:e,jointIds:Object.freeze(n),basePositions:Object.freeze(s),baseNormals:Object.freeze(d),sample:$,sampleClip(w,W,V){let B=E.sample(w,W);return $({tick:V,jointTransforms:B.jointTransforms})},reset(){g=new Map(i),v=u,I=x}})}function ue(o,e,t){throw new X(o,e,t)}function on(o,e,t,n,r){let a=n*n-4*t,i=1e-9*Math.max(1,n*n,t);if(Math.abs(a)<=i){let m=n/2,u=e+m*o,x=Math.exp(-m*r);return[x*(o+u*r),x*(e-m*u*r)]}if(a<0){let m=n/2,u=Math.sqrt(t-m*m),x=u*r,g=Math.cos(x),v=Math.sin(x),I=Math.exp(-m*r);return[I*(o*g+(e+m*o)/u*v),I*(e*g-(m*e+t*o)/u*v)]}let s=Math.sqrt(a),d=(-n+s)/2,l=(-n-s)/2,c=(e-l*o)/(d-l),p=o-c,y=c*Math.exp(d*r),b=p*Math.exp(l*r);return[y+b,d*y+l*b]}function tn(o){let e=F(o),t=new Map;for(let n of e.springs)t.set(n.controlId,n);return Object.freeze({model:e,controlIds:Object.freeze(e.controls.map(n=>n.id)),controls:new Map(e.controls.map(n=>[n.id,n])),springs:t})}function nn(o,e){let t=Object.keys(e??{}).find(r=>!o.controls.has(r));t&&ue("unknown-id","$.values",t);let n=Object.fromEntries(o.controlIds.map(r=>{let a=o.controls.get(r),i=e?.[r]??a.initial;return(!Number.isFinite(i)||i<a.minimum||i>a.maximum)&&ue("out-of-range",`$.values.${r}`,"value is outside control bounds"),[r,i]}));return Object.freeze({tick:-1,values:Object.freeze(n),velocities:Object.freeze(Object.fromEntries(o.controlIds.map(r=>[r,0]))),atRest:o.controlIds.every(r=>n[r]===o.controls.get(r).initial)})}function rn(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&ue("invalid-state","$.state","spring state is invalid"),(!Number.isFinite(t?.deltaMs)||t.deltaMs<=0||t.deltaMs>1e3)&&ue("invalid-time","$.deltaMs","expected 0 < deltaMs <= 1000");let n=t.heldTarget??null;if(n){let l=o.controls.get(n.controlId);l||ue("unknown-id","$.heldTarget.controlId",n.controlId),(!Number.isFinite(n.value)||n.value<l.minimum||n.value>l.maximum)&&ue("out-of-range","$.heldTarget.value","value is outside control bounds")}let r=new Set(t.frozenControlIds??[]);for(let l of r)o.controls.has(l)||ue("unknown-id","$.frozenControlIds",l);let a=t.deltaMs/1e3,i={},s={},d=!0;for(let l of o.controlIds){let c=o.controls.get(l),p=e.values[l]??c.initial,y=e.velocities[l]??0;if(n?.controlId===l)i[l]=n.value,s[l]=0;else if(r.has(l)||!o.springs.has(l))i[l]=p,s[l]=0;else{let b=o.springs.get(l),m=p-c.initial,[u,x]=on(m,y,b.stiffness,b.damping,a),g=x,v=c.initial+u,I=Math.max(c.minimum,Math.min(c.maximum,v));I!==v&&(g=0),v=I,Math.abs(v-c.initial)<1e-6&&Math.abs(g)<1e-6&&(v=c.initial,g=0),i[l]=Object.is(v,-0)?0:v,s[l]=Object.is(g,-0)?0:g}(i[l]!==c.initial||s[l]!==0)&&(d=!1)}return Object.freeze({tick:e.tick+1,values:Object.freeze(i),velocities:Object.freeze(s),atRest:d})}export{pe as POLY_MORPH_CATALOG_SCHEMA,Jt as POLY_MORPH_EXECUTABLE_PROFILES,ve as POLY_MORPH_MODEL_SCHEMA,ye as POLY_MORPH_PACKAGE_SCHEMA,Oe as PolyMorphContractError,k as PolyMorphPackageError,me as PolyMorphRenderError,X as PolyMorphRuntimeError,ro as applyPolyMorphPlaybackFrame,Je as assertPolyMorphPackageModelBinding,pt as buildPolyMorphCatalog,ct as buildPolyMorphPackage,Xe as createPolyMorphAnimationRuntime,zt as createPolyMorphControlRuntime,Vt as createPolyMorphControlState,_t as createPolyMorphDeformationRuntime,qt as createPolyMorphPlaybackRuntime,Tt as createPolyMorphPreparedDomTarget,no as createPolyMorphPreparedState,en as createPolyMorphSkinningRuntime,tn as createPolyMorphSpringRuntime,nn as createPolyMorphSpringState,ke as decodePolyMorphJson,ao as diffPolyMorphPreparedStates,we as encodePolyMorphCanonicalJson,se as hashPolyMorphBytes,Be as isPolyMorphId,De as isPolyMorphResourcePath,vo as loadPolyMorphCatalog,ht as loadPolyMorphPackage,Ct as mountPolyMorphModel,To as pickPolyMorphControl,Et as stepPolyMorphControls,rn as stepPolyMorphSprings,mo as stringifyPolyMorphCanonicalJson,Se as validatePolyMorphCatalog,F as validatePolyMorphModel,Re as validatePolyMorphPackageManifest};
1
+ var Re="polycss-morph.model@1",fe="polycss-morph.catalog@1",he="polycss-morph.package@1";var uo=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ho=/^[a-z0-9][a-z0-9._-]*$/,mo=/^\d+\.\d+\.\d+$/,Jo=/^[a-f0-9]{64}$/,Wo=new Set(["joint-skin","morph-regions","prepared-playback","static-prepared"]),Yo=new Set(["animation","joint-skinning","morph-targets","prepared-playback","retained-render","semantic-controls","sparse-updates","springs"]),Go=new Set(["atlas-slice","direct-image","solid-quad","solid-triangle"]),Qo=new Set(["control-value","joint-rotation","joint-scale","joint-translation","morph-weight","shape-matrix"]),ze=class extends TypeError{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphContractError",this.code=e,this.path=t}};function g(o,e,t){throw new ze(o,e,t)}function A(o,e,t){(!o||typeof o!="object"||Array.isArray(o))&&g("invalid-type",e,"expected an object");let n=Object.keys(o).sort(),r=[...t].sort();return(n.length!==r.length||n.some((a,i)=>a!==r[i]))&&g("invalid-keys",e,`expected exactly ${r.join(", ")}`),o}function z(o,e){return Array.isArray(o)||g("invalid-type",e,"expected an array"),o}function te(o,e){return(typeof o!="string"||o.length===0)&&g("invalid-string",e,"expected a non-empty string"),o}function G(o,e){return(typeof o!="number"||!Number.isFinite(o))&&g("invalid-number",e,"expected a finite number"),o}function X(o,e,t=0){let n=G(o,e);return(!Number.isSafeInteger(n)||n<t)&&g("invalid-integer",e,`expected an integer >= ${t}`),n}function Fe(o,e){return typeof o!="boolean"&&g("invalid-boolean",e,"expected a boolean"),o}function W(o,e){let t=te(o,e);return uo.test(t)||g("invalid-id",e,"expected a normalized kebab-case id"),t}function Q(o,e){let t=new Set;for(let n of o)t.has(n)&&g("duplicate-id",e,`duplicate id ${n}`),t.add(n)}function be(o,e){let t=z(o,e);return t.length!==3&&g("invalid-vector",e,"expected three components"),t.map((n,r)=>G(n,`${e}[${r}]`))}function de(o,e){let t=z(o,e);return t.length!==16&&g("invalid-matrix",e,"expected sixteen components"),t.map((n,r)=>G(n,`${e}[${r}]`))}function fo(o,e){let t=te(o,e);return t.split("/").some(n=>!Ho.test(n))&&g("invalid-path",e,"expected lowercase URL-safe package path segments"),t}function Ve(o,e,t){let n=X(o,e);return n>=t&&g("out-of-range",e,`expected an index below ${t}`),n}function Xo(o,e){let t=A(o,e,["normals","polygons","vertices"]),n=z(t.vertices,`${e}.vertices`).map((i,s)=>be(i,`${e}.vertices[${s}]`)),r=z(t.normals,`${e}.normals`).map((i,s)=>be(i,`${e}.normals[${s}]`));n.length===0&&g("missing-topology",`${e}.vertices`,"expected at least one vertex"),r.length===0&&g("missing-topology",`${e}.normals`,"expected at least one normal");let a=z(t.polygons,`${e}.polygons`).map((i,s)=>{let d=`${e}.polygons[${s}]`,l=A(i,d,["id","normalIndices","vertexIndices"]),c=z(l.vertexIndices,`${d}.vertexIndices`).map((y,P)=>Ve(y,`${d}.vertexIndices[${P}]`,n.length)),p=z(l.normalIndices,`${d}.normalIndices`).map((y,P)=>Ve(y,`${d}.normalIndices[${P}]`,r.length));return c.length<3&&g("invalid-polygon",d,"expected at least three vertices"),p.length!==c.length&&g("invalid-polygon",d,"normal and vertex index counts must match"),new Set(c).size!==c.length&&g("invalid-polygon",d,"vertex indices must be unique"),{id:W(l.id,`${d}.id`),vertexIndices:c,normalIndices:p}});return a.length===0&&g("missing-topology",`${e}.polygons`,"expected at least one polygon"),Q(a.map(i=>i.id),`${e}.polygons`),{vertices:n,normals:r,polygons:a}}function Ko(o,e,t){let n=A(o,e,["atlas","fallback","height","id","materialId","matrix","polygonId","shapeId","strategy","width"]),r=te(n.strategy,`${e}.strategy`);Go.has(r)||g("invalid-strategy",`${e}.strategy`,"unknown render strategy");let a=W(n.polygonId,`${e}.polygonId`),i=W(n.shapeId,`${e}.shapeId`),s=W(n.materialId,`${e}.materialId`);t.polygonIds.has(a)||g("unknown-reference",`${e}.polygonId`,a),t.shapeIds.has(i)||g("unknown-reference",`${e}.shapeId`,i),t.materialIds.has(s)||g("unknown-reference",`${e}.materialId`,s);let d=G(n.width,`${e}.width`),l=G(n.height,`${e}.height`);(d<=0||l<=0)&&g("invalid-size",e,"leaf dimensions must be positive");let c=r==="atlas-slice"||r==="direct-image",p=n.atlas===null?null:ho(n.atlas,`${e}.atlas`);c!==(p!==null)&&g("invalid-strategy",`${e}.atlas`,c?"image strategies require an atlas/source slice":"solid strategies cannot declare an atlas/source slice");let y=n.fallback===null?null:Zo(n.fallback,`${e}.fallback`);return y!==null&&r!=="solid-triangle"&&g("invalid-strategy",`${e}.fallback`,"only solid-triangle leaves may declare a prepared fallback"),{id:W(n.id,`${e}.id`),polygonId:a,shapeId:i,materialId:s,strategy:r,width:d,height:l,matrix:de(n.matrix,`${e}.matrix`),atlas:p,fallback:y}}function Zo(o,e){let t=A(o,e,["atlas","height","matrixFromLeaf","width"]),n=X(t.width,`${e}.width`,1),r=X(t.height,`${e}.height`,1),a=ho(t.atlas,`${e}.atlas`);return(a.width!==n||a.height!==r)&&g("invalid-size",e,"fallback dimensions must match its per-polygon atlas slice"),{width:n,height:r,matrixFromLeaf:de(t.matrixFromLeaf,`${e}.matrixFromLeaf`),atlas:a}}function ho(o,e){let t=A(o,e,["height","pageHeight","pageWidth","resourcePath","width","x","y"]),n={resourcePath:fo(t.resourcePath,`${e}.resourcePath`),x:X(t.x,`${e}.x`),y:X(t.y,`${e}.y`),width:X(t.width,`${e}.width`,1),height:X(t.height,`${e}.height`,1),pageWidth:X(t.pageWidth,`${e}.pageWidth`,1),pageHeight:X(t.pageHeight,`${e}.pageHeight`,1)};return(n.x+n.width>n.pageWidth||n.y+n.height>n.pageHeight)&&g("out-of-range",e,"slice must fit inside its page"),n}function et(o,e,t){(!o||typeof o!="object"||Array.isArray(o))&&g("invalid-type",e,"expected a deformation object");let n=te(o.kind,`${e}.kind`);if(n==="none")return A(o,e,["kind"]),{kind:n};if(n==="morph-regions"){let r=A(o,e,["kind","targets"]),a=z(r.targets,`${e}.targets`).map((i,s)=>{let d=`${e}.targets[${s}]`,l=A(i,d,["deltas","id"]),c=z(l.deltas,`${d}.deltas`).map((y,P)=>{let m=`${d}.deltas[${P}]`,f=A(y,m,["normal","position","vertexIndex"]),b=f.position===null?null:be(f.position,`${m}.position`),h=f.normal===null?null:be(f.normal,`${m}.normal`);return b===null&&h===null&&g("empty-delta",m,"expected a position or normal delta"),{vertexIndex:Ve(f.vertexIndex,`${m}.vertexIndex`,t.vertices.length),position:b,normal:h}});c.length===0&&g("missing-deltas",`${d}.deltas`,"expected at least one delta");let p=c.map(y=>String(y.vertexIndex));return Q(p,`${d}.deltas`),{id:W(l.id,`${d}.id`),deltas:c}});return a.length===0&&g("missing-targets",`${e}.targets`,"expected at least one target"),Q(a.map(i=>i.id),`${e}.targets`),{kind:n,targets:a}}if(n==="joint-skin"){let r=A(o,e,["joints","kind","vertices"]),a=z(r.joints,`${e}.joints`).map((l,c)=>{let p=`${e}.joints[${c}]`,y=A(l,p,["id","inverseBindMatrix","parentId","restMatrix"]);return{id:W(y.id,`${p}.id`),parentId:y.parentId===null?null:W(y.parentId,`${p}.parentId`),restMatrix:de(y.restMatrix,`${p}.restMatrix`),inverseBindMatrix:de(y.inverseBindMatrix,`${p}.inverseBindMatrix`)}});a.length===0&&g("missing-joints",`${e}.joints`,"expected at least one joint"),Q(a.map(l=>l.id),`${e}.joints`),ot(a,`${e}.joints`);let i=new Set(a.map(l=>l.id)),s=z(r.vertices,`${e}.vertices`).map((l,c)=>{let p=`${e}.vertices[${c}]`,y=A(l,p,["influences","vertexIndex"]),P=Ve(y.vertexIndex,`${p}.vertexIndex`,t.vertices.length),m=z(y.influences,`${p}.influences`).map((b,h)=>{let $=`${p}.influences[${h}]`,k=A(b,$,["jointId","weight"]),F=W(k.jointId,`${$}.jointId`);i.has(F)||g("unknown-reference",`${$}.jointId`,F);let v=G(k.weight,`${$}.weight`);return(v<=0||v>1)&&g("invalid-weight",`${$}.weight`,"expected 0 < weight <= 1"),{jointId:F,weight:v}});m.length===0&&g("missing-influences",`${p}.influences`,"expected at least one influence"),Q(m.map(b=>b.jointId),`${p}.influences`);let f=m.reduce((b,h)=>b+h.weight,0);return Math.abs(f-1)>1e-6&&g("invalid-weight",`${p}.influences`,"weights must sum to 1"),{vertexIndex:P,influences:m}});s.length!==t.vertices.length&&g("missing-skin-vertex",`${e}.vertices`,"every topology vertex must have one skin record");let d=s.map(l=>String(l.vertexIndex));return Q(d,`${e}.vertices`),{kind:n,joints:a,vertices:s}}g("invalid-deformation",`${e}.kind`,`unknown deformation kind ${n}`)}function ot(o,e){let t=new Map(o.map(r=>[r.id,r]));o.filter(r=>r.parentId===null).length!==1&&g("invalid-hierarchy",e,"expected exactly one root joint");for(let r of o){r.parentId!==null&&!t.has(r.parentId)&&g("unknown-reference",e,`joint ${r.id} references ${r.parentId}`);let a=new Set,i=r;for(;i;)a.has(i.id)&&g("invalid-hierarchy",e,`cycle at joint ${i.id}`),a.add(i.id),i=i.parentId===null?void 0:t.get(i.parentId)}}function tt(o){return o==="control-value"||o==="morph-weight"?1:o==="joint-rotation"?4:o==="shape-matrix"?16:3}function nt(o,e,t,n){let r=A(o,e,["interpolation","target","targetId","timesMs","values"]),a=te(r.target,`${e}.target`);Qo.has(a)||g("invalid-animation-target",`${e}.target`,a);let i=W(r.targetId,`${e}.targetId`);(a==="control-value"?t.controlIds:a==="morph-weight"?t.targetIds:a==="shape-matrix"?t.shapeIds:t.jointIds).has(i)||g("unknown-reference",`${e}.targetId`,i);let d=te(r.interpolation,`${e}.interpolation`);d!=="linear"&&d!=="step"&&g("invalid-interpolation",`${e}.interpolation`,d),a==="shape-matrix"&&d!=="step"&&g("invalid-interpolation",`${e}.interpolation`,"shape matrices require step interpolation");let l=z(r.timesMs,`${e}.timesMs`).map((p,y)=>G(p,`${e}.timesMs[${y}]`)),c=z(r.values,`${e}.values`).map((p,y)=>{let P=z(p,`${e}.values[${y}]`),m=tt(a);P.length!==m&&g("invalid-animation-value",`${e}.values[${y}]`,`expected ${m} components`);let f=P.map((b,h)=>G(b,`${e}.values[${y}][${h}]`));return a==="joint-rotation"&&Math.hypot(...f)<=1e-12&&g("invalid-animation-value",`${e}.values[${y}]`,"quaternion must be non-zero"),f});return(l.length===0||l.length!==c.length)&&g("invalid-animation-samples",e,"times and values must have the same non-zero length"),(l[0]!==0||l.some((p,y)=>p<0||p>n||y>0&&p<=l[y-1]))&&g("invalid-animation-time",`${e}.timesMs`,"times must start at zero and increase within the clip"),{target:a,targetId:i,interpolation:d,timesMs:l,values:c}}function rt(o,e,t,n){let r=A(o,e,["durationMs","frames","loop"]),a=G(r.durationMs,`${e}.durationMs`);a<=0&&g("invalid-duration",`${e}.durationMs`,"expected a positive duration");let i=z(r.frames,`${e}.frames`).map((s,d)=>{let l=`${e}.frames[${d}]`,c=A(s,l,["leaves","modelMatrix","shapes","timeMs"]),p=G(c.timeMs,`${l}.timeMs`),y=z(c.shapes,`${l}.shapes`).map((m,f)=>{let b=`${l}.shapes[${f}]`,h=A(m,b,["matrix","shapeId"]),$=W(h.shapeId,`${b}.shapeId`);return n.has($)||g("unknown-reference",`${b}.shapeId`,$),{shapeId:$,matrix:de(h.matrix,`${b}.matrix`)}});Q(y.map(m=>m.shapeId),`${l}.shapes`);let P=z(c.leaves,`${l}.leaves`).map((m,f)=>{let b=`${l}.leaves[${f}]`,h=A(m,b,["atlasRow","leafId","matrix","opacity","visible"]),$=W(h.leafId,`${b}.leafId`);t.has($)||g("unknown-reference",`${b}.leafId`,$);let k=h.opacity===null?null:G(h.opacity,`${b}.opacity`);return k!==null&&(k<0||k>1)&&g("out-of-range",`${b}.opacity`,"expected 0 <= opacity <= 1"),{leafId:$,matrix:h.matrix===null?null:de(h.matrix,`${b}.matrix`),visible:h.visible===null?null:Fe(h.visible,`${b}.visible`),opacity:k,atlasRow:h.atlasRow===null?null:X(h.atlasRow,`${b}.atlasRow`)}});return Q(P.map(m=>m.leafId),`${l}.leaves`),{timeMs:p,modelMatrix:c.modelMatrix===null?null:de(c.modelMatrix,`${l}.modelMatrix`),shapes:y,leaves:P}});return i.length===0&&g("missing-frames",`${e}.frames`,"expected at least one frame"),(i[0].timeMs!==0||i.some((s,d)=>s.timeMs<0||s.timeMs>a||d>0&&s.timeMs<=i[d-1].timeMs))&&g("invalid-frame-time",`${e}.frames`,"frames must start at zero and increase within the timeline"),{durationMs:a,loop:Fe(r.loop,`${e}.loop`),frames:i}}function at(o,e){let t=["retained-render"];return o==="morph-regions"&&t.push("morph-targets","sparse-updates"),o==="joint-skin"&&t.push("joint-skinning","sparse-updates"),o==="prepared-playback"&&t.push("prepared-playback","sparse-updates"),e.controls.length>0&&t.push("semantic-controls"),e.springs.length>0&&t.push("springs"),e.animations.length>0&&t.push("animation"),t}function Y(o){let t=A(o,"$",["animations","budgets","capabilities","controls","deformation","identity","materials","playback","profile","provenance","render","schema","springs","topology"]);t.schema!==Re&&g("invalid-schema","$.schema",`expected ${Re}`);let n=A(t.identity,"$.identity",["id","name","revision"]),r={id:W(n.id,"$.identity.id"),name:te(n.name,"$.identity.name"),revision:te(n.revision,"$.identity.revision")};mo.test(r.revision)||g("invalid-revision","$.identity.revision","expected x.y.z");let a=te(t.profile,"$.profile");Wo.has(a)||g("invalid-profile","$.profile",a);let i=z(t.capabilities,"$.capabilities").map((M,S)=>{let u=te(M,`$.capabilities[${S}]`);return Yo.has(u)||g("invalid-capability",`$.capabilities[${S}]`,u),u});Q(i,"$.capabilities"),i.some((M,S)=>S>0&&M<=i[S-1])&&g("non-canonical-order","$.capabilities","capabilities must be sorted");let s=A(t.budgets,"$.budgets",["maxBytes","maxFrames","maxJoints","maxLeaves","maxPolygons","maxResources","maxVertices"]),d={maxVertices:X(s.maxVertices,"$.budgets.maxVertices"),maxPolygons:X(s.maxPolygons,"$.budgets.maxPolygons"),maxLeaves:X(s.maxLeaves,"$.budgets.maxLeaves"),maxFrames:X(s.maxFrames,"$.budgets.maxFrames"),maxJoints:X(s.maxJoints,"$.budgets.maxJoints"),maxResources:X(s.maxResources,"$.budgets.maxResources"),maxBytes:X(s.maxBytes,"$.budgets.maxBytes")},l=Xo(t.topology,"$.topology"),c=z(t.materials,"$.materials").map((M,S)=>{let u=`$.materials[${S}]`,R=A(M,u,["color","id"]),j=z(R.color,`${u}.color`);j.length!==4&&g("invalid-color",`${u}.color`,"expected four components");let D=j.map((x,C)=>{let H=G(x,`${u}.color[${C}]`);return(H<0||H>1)&&g("out-of-range",`${u}.color[${C}]`,"expected 0 <= component <= 1"),H});return{id:W(R.id,`${u}.id`),color:D}});c.length===0&&g("missing-materials","$.materials","expected at least one material"),Q(c.map(M=>M.id),"$.materials");let p=A(t.render,"$.render",["leaves","modelMatrix","shapes"]),y=z(p.shapes,"$.render.shapes").map((M,S)=>{let u=`$.render.shapes[${S}]`,R=A(M,u,["id","matrix"]);return{id:W(R.id,`${u}.id`),matrix:de(R.matrix,`${u}.matrix`)}});y.length===0&&g("missing-shapes","$.render.shapes","expected at least one shape"),Q(y.map(M=>M.id),"$.render.shapes");let P=z(p.leaves,"$.render.leaves").map((M,S)=>Ko(M,`$.render.leaves[${S}]`,{polygonIds:new Set(l.polygons.map(u=>u.id)),shapeIds:new Set(y.map(u=>u.id)),materialIds:new Set(c.map(u=>u.id))}));Q(P.map(M=>M.id),"$.render.leaves"),Q(P.map(M=>M.polygonId),"$.render.leaves[*].polygonId"),P.length!==l.polygons.length&&g("unstable-topology","$.render.leaves","every polygon must bind exactly one retained leaf");let m={modelMatrix:de(p.modelMatrix,"$.render.modelMatrix"),shapes:y,leaves:P},f=et(t.deformation,"$.deformation",l);(a==="static-prepared"||a==="prepared-playback"?f.kind!=="none":f.kind!==a)&&g("profile-mismatch","$.deformation.kind",`does not match profile ${a}`);let b=new Set(f.kind==="morph-regions"?f.targets.map(M=>M.id):[]),h=new Set(f.kind==="joint-skin"?f.joints.map(M=>M.id):[]),$=z(t.controls,"$.controls").map((M,S)=>{let u=`$.controls[${S}]`,R=A(M,u,["anchor","axis","id","initial","maximum","minimum","radius","targets"]),j=G(R.minimum,`${u}.minimum`),D=G(R.maximum,`${u}.maximum`),x=G(R.initial,`${u}.initial`);(j>D||x<j||x>D)&&g("invalid-control-bounds",u,"expected minimum <= initial <= maximum");let C=be(R.anchor,`${u}.anchor`),H=be(R.axis,`${u}.axis`);Math.hypot(...H)<1e-9&&g("invalid-control-axis",`${u}.axis`,"axis must be non-zero");let ye=G(R.radius,`${u}.radius`);ye<=0&&g("invalid-control-radius",`${u}.radius`,"radius must be positive");let le=z(R.targets,`${u}.targets`).map((ue,ke)=>{let me=`${u}.targets[${ke}]`,Pe=A(ue,me,["scale","targetId"]),T=W(Pe.targetId,`${me}.targetId`);return b.has(T)||g("unknown-reference",`${me}.targetId`,T),{targetId:T,scale:G(Pe.scale,`${me}.scale`)}});return Q(le.map(ue=>ue.targetId),`${u}.targets`),{id:W(R.id,`${u}.id`),anchor:C,axis:H,radius:ye,minimum:j,maximum:D,initial:x,targets:le}});Q($.map(M=>M.id),"$.controls");let k=new Set($.map(M=>M.id)),F=z(t.springs,"$.springs").map((M,S)=>{let u=`$.springs[${S}]`,R=A(M,u,["controlId","damping","id","stiffness"]),j=W(R.controlId,`${u}.controlId`);k.has(j)||g("unknown-reference",`${u}.controlId`,j);let D=G(R.stiffness,`${u}.stiffness`),x=G(R.damping,`${u}.damping`);return(D<=0||x<0)&&g("invalid-spring",u,"expected stiffness > 0 and damping >= 0"),{id:W(R.id,`${u}.id`),controlId:j,stiffness:D,damping:x}});Q(F.map(M=>M.id),"$.springs");let v=new Set(y.map(M=>M.id)),w=z(t.animations,"$.animations").map((M,S)=>{let u=`$.animations[${S}]`,R=A(M,u,["channels","durationMs","id","loop"]),j=G(R.durationMs,`${u}.durationMs`);j<=0&&g("invalid-duration",`${u}.durationMs`,"expected a positive duration");let D=z(R.channels,`${u}.channels`).map((C,H)=>nt(C,`${u}.channels[${H}]`,{controlIds:k,jointIds:h,shapeIds:v,targetIds:b},j));D.length===0&&g("missing-channels",`${u}.channels`,"expected at least one channel");let x=D.map(C=>`${C.target}:${C.targetId}`);return Q(x,`${u}.channels`),{id:W(R.id,`${u}.id`),durationMs:j,loop:Fe(R.loop,`${u}.loop`),channels:D}});Q(w.map(M=>M.id),"$.animations");let L=t.playback===null?null:rt(t.playback,"$.playback",new Set(P.map(M=>M.id)),v);a==="prepared-playback"!=(L!==null)&&g("profile-mismatch","$.playback","playback is required only by the prepared-playback profile");let E=A(t.provenance,"$.provenance",["generator","generatorVersion","sources"]),B=z(E.sources,"$.provenance.sources").map((M,S)=>{let u=`$.provenance.sources[${S}]`,R=A(M,u,["id","kind","license","sha256","uri"]),j=te(R.kind,`${u}.kind`);j!=="authored"&&j!=="generated"&&j!=="open-data"&&g("invalid-source-kind",`${u}.kind`,j);let D=te(R.uri,`${u}.uri`);(D.startsWith("/")||D.startsWith("file:")||D.includes("\\"))&&g("invalid-source-uri",`${u}.uri`,"local filesystem paths are forbidden");let x=R.sha256===null?null:te(R.sha256,`${u}.sha256`);return x!==null&&!Jo.test(x)&&g("invalid-hash",`${u}.sha256`,"expected lowercase SHA-256"),{id:W(R.id,`${u}.id`),kind:j,uri:D,sha256:x,license:te(R.license,`${u}.license`)}});B.length===0&&g("missing-provenance","$.provenance.sources","expected at least one source"),Q(B.map(M=>M.id),"$.provenance.sources");let q={generator:W(E.generator,"$.provenance.generator"),generatorVersion:te(E.generatorVersion,"$.provenance.generatorVersion"),sources:B};mo.test(q.generatorVersion)||g("invalid-revision","$.provenance.generatorVersion","expected x.y.z");let O=at(a,{controls:$,springs:F,animations:w});for(let M of O)i.includes(M)||g("missing-capability","$.capabilities",`profile requires ${M}`);let V=f.kind==="joint-skin"?f.joints.length:0,N=L?.frames.length??0,_=[["maxVertices",l.vertices.length,d.maxVertices],["maxPolygons",l.polygons.length,d.maxPolygons],["maxLeaves",P.length,d.maxLeaves],["maxFrames",N,d.maxFrames],["maxJoints",V,d.maxJoints]];for(let[M,S,u]of _)S>u&&g("budget-exceeded",`$.budgets.${M}`,`${S} exceeds ${u}`);return{schema:Re,identity:r,profile:a,capabilities:i,budgets:d,topology:l,materials:c,render:m,deformation:f,controls:$,springs:F,animations:w,playback:L,provenance:q}}function _e(o){return uo.test(o)}function qe(o){try{return fo(o,"$"),!0}catch{return!1}}var I=class extends Error{constructor(e,t,n,r={}){super(`${t}: ${n}`),this.name="PolyMorphPackageError",this.code=e,this.path=t,"cause"in r&&(this.cause=r.cause)}};function He(o,e,t){if(o===null)return"null";if(typeof o=="string"||typeof o=="boolean")return JSON.stringify(o);if(typeof o=="number"){if(!Number.isFinite(o))throw new I("invalid-json",e,"numbers must be finite");return JSON.stringify(Object.is(o,-0)?0:o)}if(Array.isArray(o)){if(t.has(o))throw new I("invalid-json",e,"cycles are forbidden");t.add(o);let n=`[${o.map((r,a)=>He(r,`${e}[${a}]`,t)).join(",")}]`;return t.delete(o),n}if(typeof o=="object"&&o){if(t.has(o))throw new I("invalid-json",e,"cycles are forbidden");let n=Object.getPrototypeOf(o);if(n!==Object.prototype&&n!==null)throw new I("invalid-json",e,"expected a plain object");t.add(o);let r=o,a=`{${Object.keys(r).sort().map(i=>{let s=r[i];if(s===void 0||typeof s=="function"||typeof s=="symbol")throw new I("invalid-json",`${e}.${i}`,"value is not JSON");return`${JSON.stringify(i)}:${He(s,`${e}.${i}`,t)}`}).join(",")}}`;return t.delete(o),a}throw new I("invalid-json",e,"value is not JSON")}function go(o){return He(o,"$",new WeakSet)}function Se(o){return new TextEncoder().encode(go(o))}function je(o,e="$"){let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new I("invalid-utf8",e,"expected UTF-8 bytes")}try{return JSON.parse(t)}catch{throw new I("invalid-json",e,"expected valid JSON")}}async function ce(o){if(!globalThis.crypto?.subtle)throw new I("missing-crypto","$","Web Crypto is required");let e=Uint8Array.from(o),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var it=/^[a-f0-9]{64}$/,st=/^\d+\.\d+\.\d+$/,lt=/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/,dt=new Set(["joint-skin","morph-regions","prepared-playback","static-prepared"]),ct=new Set(["data","image","model"]);function J(o,e,t){throw new I(o,e,t)}function Ce(o,e,t){(!o||typeof o!="object"||Array.isArray(o))&&J("invalid-type",e,"expected an object");let n=Object.keys(o).sort(),r=[...t].sort();return(n.length!==r.length||n.some((a,i)=>a!==r[i]))&&J("invalid-keys",e,`expected exactly ${r.join(", ")}`),o}function Mo(o,e){return Array.isArray(o)||J("invalid-type",e,"expected an array"),o}function pe(o,e){return(typeof o!="string"||o.length===0)&&J("invalid-string",e,"expected a non-empty string"),o}function We(o,e){let t=pe(o,e);return _e(t)||J("invalid-id",e,"expected a normalized kebab-case id"),t}function Ye(o,e){let t=pe(o,e);return qe(t)||J("invalid-path",e,"expected a normalized package-relative path"),t}function Po(o,e){let t=pe(o,e);return st.test(t)||J("invalid-revision",e,"expected x.y.z"),t}function bo(o,e){let t=pe(o,e);return dt.has(t)||J("invalid-profile",e,t),t}function xo(o,e){let t=pe(o,e);return it.test(t)||J("invalid-hash",e,"expected lowercase SHA-256"),t}function pt(o,e){return(typeof o!="number"||!Number.isSafeInteger(o)||o<0)&&J("invalid-bytes",e,"expected a non-negative safe integer"),o}function yt(o,e){let t=Ce(o,e,["bytes","mediaType","path","role","sha256"]),n=pe(t.role,`${e}.role`);ct.has(n)||J("invalid-role",`${e}.role`,n);let r=pe(t.mediaType,`${e}.mediaType`).toLowerCase();return(!lt.test(r)||r!==t.mediaType)&&J("invalid-media-type",`${e}.mediaType`,"expected a normalized type/subtype"),n==="image"&&!r.startsWith("image/")&&J("invalid-media-type",`${e}.mediaType`,"image resources require an image media type"),{path:Ye(t.path,`${e}.path`),role:n,mediaType:r,bytes:pt(t.bytes,`${e}.bytes`),sha256:xo(t.sha256,`${e}.sha256`)}}function Je(o,e){let t=new Set;for(let n of o)t.has(n)&&J("duplicate",e,n),t.add(n)}function $o(o,e){o.some((t,n)=>n>0&&t<=o[n-1])&&J("non-canonical-order",e,"entries must be unique and sorted")}function Te(o){let e=Ce(o,"$",["identity","modelPath","profile","resources","schema"]);e.schema!==he&&J("invalid-schema","$.schema",`expected ${he}`);let t=Ce(e.identity,"$.identity",["id","name","revision"]),n={id:We(t.id,"$.identity.id"),name:pe(t.name,"$.identity.name"),revision:Po(t.revision,"$.identity.revision")},r=Mo(e.resources,"$.resources").map((d,l)=>yt(d,`$.resources[${l}]`));r.length===0&&J("missing-resource","$.resources","expected at least the model resource");let a=r.map(d=>d.path);Je(a,"$.resources"),$o(a,"$.resources");let i=Ye(e.modelPath,"$.modelPath"),s=r.filter(d=>d.role==="model");return(s.length!==1||s[0].path!==i)&&J("invalid-model-resource","$.resources","expected exactly one model resource matching modelPath"),s[0].mediaType!=="application/json"&&J("invalid-model-resource","$.resources","model resource must be application/json"),{schema:he,identity:n,profile:bo(e.profile,"$.profile"),modelPath:i,resources:r}}function mt(o,e){let t=Ce(o,e,["id","manifestPath","manifestSha256","name","profile","revision"]),n=Ye(t.manifestPath,`${e}.manifestPath`);return n.endsWith("/manifest.json")||J("invalid-manifest-path",`${e}.manifestPath`,"expected a package manifest.json path"),{id:We(t.id,`${e}.id`),name:pe(t.name,`${e}.name`),revision:Po(t.revision,`${e}.revision`),profile:bo(t.profile,`${e}.profile`),manifestPath:n,manifestSha256:xo(t.manifestSha256,`${e}.manifestSha256`)}}function Oe(o){let e=Ce(o,"$",["defaultId","packages","schema"]);e.schema!==fe&&J("invalid-schema","$.schema",`expected ${fe}`);let t=Mo(e.packages,"$.packages").map((a,i)=>mt(a,`$.packages[${i}]`));t.length===0&&J("missing-package","$.packages","expected at least one package");let n=t.map(a=>a.id);Je(n,"$.packages"),$o(n,"$.packages"),Je(t.map(a=>a.manifestPath),"$.packages[*].manifestPath");let r=We(e.defaultId,"$.defaultId");return n.includes(r)||J("unknown-default","$.defaultId",r),{schema:fe,defaultId:r,packages:t}}var Ge="model.json";function ut(o){return[...new Set(o.render.leaves.flatMap(e=>[...e.atlas?[e.atlas.resourcePath]:[],...e.fallback?[e.fallback.atlas.resourcePath]:[]]))].sort()}async function ft(o,e=[]){let t=Y(o),n=Se(t),r=new Map([[Ge,n]]),a=[{path:Ge,role:"model",mediaType:"application/json",bytes:n.byteLength,sha256:await ce(n)}];for(let l of e){if(r.has(l.path))throw new I("duplicate",l.path,"resource path is already present");let c=Uint8Array.from(l.bytes);r.set(l.path,c),a.push({path:l.path,role:l.role,mediaType:l.mediaType,bytes:c.byteLength,sha256:await ce(c)})}for(let l of ut(t)){let c=a.find(p=>p.path===l);if(!c)throw new I("missing-resource",l,"model image is not included in the package");if(c.role!=="image")throw new I("invalid-role",l,"model image resource must use the image role")}a.sort((l,c)=>l.path<c.path?-1:l.path>c.path?1:0);let i=Te({schema:he,identity:t.identity,profile:t.profile,modelPath:Ge,resources:a}),s=a.reduce((l,c)=>l+c.bytes,0);if(a.length>t.budgets.maxResources)throw new I("budget-exceeded","$.budgets.maxResources",`${a.length} resources exceed ${t.budgets.maxResources}`);if(s>t.budgets.maxBytes)throw new I("budget-exceeded","$.budgets.maxBytes",`${s} bytes exceed ${t.budgets.maxBytes}`);let d=Se(i);return{manifest:i,manifestBytes:d,manifestSha256:await ce(d),files:r}}async function ht(o,e){let t=e.map(a=>({id:a.manifest.identity.id,name:a.manifest.identity.name,revision:a.manifest.identity.revision,profile:a.manifest.profile,manifestPath:a.manifestPath,manifestSha256:a.manifestSha256}));t.sort((a,i)=>a.id<i.id?-1:a.id>i.id?1:0);let n=Oe({schema:fe,defaultId:o,packages:t}),r=Se(n);return{catalog:n,bytes:r,sha256:await ce(r)}}function Qe(o,e){if(e.identity.id!==o.identity.id||e.identity.name!==o.identity.name||e.identity.revision!==o.identity.revision||e.profile!==o.profile)throw new I("profile-mismatch","$.model","model identity or profile does not match its manifest")}var wo=64*1024*1024,gt=1024,Mt=128*1024*1024,ko=3e4;function xe(o,e,t){let n=o??e;if(!Number.isSafeInteger(n)||n<=0)throw new I("invalid-limit",t,"expected a positive safe integer");return n}function Io(o){if(typeof o!="string"||o.length===0||o.includes("\\")||o.includes("#")||o.includes("?"))throw new I("invalid-base-url","$.baseUrl","expected a clean HTTP(S) base URL");let e;try{e=new URL(o,globalThis.location?.href??"https://polycss.invalid/")}catch{throw new I("invalid-base-url","$.baseUrl","expected a valid URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new I("invalid-base-url","$.baseUrl","expected HTTP or HTTPS");return e.pathname.endsWith("/")||(e.pathname+="/"),e}async function Pt(o,e,t){let n=o.headers.get("content-length");if(n!==null){let a=Number(n);if(!Number.isSafeInteger(a)||a<0||a>t)throw new I("resource-too-large",e,`declared bytes exceed ${t}`)}if(o.body?.getReader){let a=o.body.getReader(),i=[],s=0;for(;;){let c=await a.read();if(c.done)break;if(s+=c.value.byteLength,s>t)throw await a.cancel(),new I("resource-too-large",e,`bytes exceed ${t}`);i.push(c.value)}let d=new Uint8Array(s),l=0;for(let c of i)d.set(c,l),l+=c.byteLength;return d}if(n===null)throw new I("resource-too-large",e,"content-length is required without a readable body");let r=new Uint8Array(await o.arrayBuffer());if(r.byteLength>t)throw new I("resource-too-large",e,`bytes exceed ${t}`);return r}async function Xe(o,e,t,n,r){let a=n??AbortSignal.timeout(r),i;try{i=await o(e,{cache:"no-store",signal:a})}catch(s){throw a.aborted?s:new I("request-failed",e.pathname,"request failed",{cause:s})}if(!i.ok)throw new I("request-failed",e.pathname,`HTTP ${i.status}`);return Pt(i,e.pathname,t)}async function vo(o,e,t){let n=await ce(o);if(n!==e)throw new I("stale-hash",t,`expected ${e}, received ${n}`)}function bt(o,e){let t=e.lastIndexOf("/");return Ee(o,e.slice(0,t+1))}function Ee(o,e){let t=new URL(e,o);if(t.origin!==o.origin||!t.href.startsWith(o.href))throw new I("invalid-path",e,"package path escapes its base URL");return t}async function Ro(o,e={}){let t=Io(o),n=xe(e.maxResourceBytes,wo,"$.maxResourceBytes"),r=e.fetchImpl??globalThis.fetch;if(typeof r!="function")throw new I("missing-fetch","$.fetchImpl","a fetch implementation is required");let a=xe(e.requestTimeoutMs,ko,"$.requestTimeoutMs"),i=await Xe(r,Ee(t,"catalog.json"),n,e.signal,a);return{catalog:Oe(je(i,"$.catalog")),bytes:i,sha256:await ce(i)}}async function xt(o,e={}){let t=Io(o),n=xe(e.maxResourceBytes,wo,"$.maxResourceBytes"),r=xe(e.maxResources,gt,"$.maxResources"),a=xe(e.maxTotalBytes,Mt,"$.maxTotalBytes"),i=xe(e.requestTimeoutMs,ko,"$.requestTimeoutMs"),s=e.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new I("missing-fetch","$.fetchImpl","a fetch implementation is required");let d=await Ro(t.href,{fetchImpl:s,maxResourceBytes:n,requestTimeoutMs:i,signal:e.signal}),l=e.modelId??d.catalog.defaultId,c=d.catalog.packages.find(v=>v.id===l);if(!c)throw new I("unknown-package","$.modelId",l);let p=await Xe(s,Ee(t,c.manifestPath),n,e.signal,i);await vo(p,c.manifestSha256,c.manifestPath);let y=Te(je(p,"$.manifest"));if(y.identity.id!==c.id||y.identity.name!==c.name||y.identity.revision!==c.revision||y.profile!==c.profile)throw new I("profile-mismatch","$.manifest","catalog row does not match its manifest");let P=bt(t,c.manifestPath);if(y.resources.length>r)throw new I("package-too-large","$.manifest.resources",`${y.resources.length} resources exceed ${r}`);let m=0;for(let v of y.resources){if(v.bytes>n)throw new I("resource-too-large",v.path,`declared bytes exceed ${n}`);if(m+=v.bytes,m>a)throw new I("package-too-large",v.path,`declared package bytes exceed ${a}`)}let f=new Map,b=async v=>{let w=await Xe(s,Ee(P,v.path),Math.min(n,v.bytes),e.signal,i);if(w.byteLength!==v.bytes)throw new I("stale-size",v.path,`expected ${v.bytes}, received ${w.byteLength}`);return await vo(w,v.sha256,v.path),{descriptor:v,bytes:w}},h=y.resources.find(v=>v.path===y.modelPath),$=await b(h);f.set(h.path,$);let k=Y(je($.bytes,"$.model"));if(Qe(y,k),y.resources.length>k.budgets.maxResources)throw new I("budget-exceeded","$.budgets.maxResources",`${y.resources.length} resources exceed ${k.budgets.maxResources}`);if(m>k.budgets.maxBytes)throw new I("budget-exceeded","$.budgets.maxBytes",`${m} bytes exceed ${k.budgets.maxBytes}`);for(let v of y.resources)v!==h&&f.set(v.path,await b(v));let F=new Set(k.render.leaves.flatMap(v=>[...v.atlas?[v.atlas.resourcePath]:[],...v.fallback?[v.fallback.atlas.resourcePath]:[]]));for(let v of F){let w=f.get(v);if(!w)throw new I("missing-resource",v,"model image is not declared by the package");if(w.descriptor.role!=="image")throw new I("invalid-role",v,"model image resource must use the image role")}return{catalog:d.catalog,catalogSha256:d.sha256,catalogRow:c,manifest:y,manifestSha256:c.manifestSha256,model:k,resources:f}}import{buildPolyCameraSceneTransform as So,capturePolyCameraSnapshot as jo,createPolyCamera as $t,formatMatrix3dValues as vt,injectPolyBaseStyles as wt,isSolidTriangleSupported as kt,safariCssProjectiveUnsupported as It}from"@layoutit/polycss";var ge=class extends Error{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphRenderError",this.code=e,this.path=t}};var Rt={"atlas-slice":"s","direct-image":"s","solid-quad":"b","solid-triangle":"u"},Co=1e-12;function U(o,e,t){throw new ge(o,e,t)}function Ze(o,e){return(!Array.isArray(o)||o.length!==16||o.some(t=>typeof t!="number"||!Number.isFinite(t)))&&U("invalid-matrix",e,"expected sixteen finite components"),o}function St(o){return o.map(e=>String(Object.is(e,-0)?0:e)).join(",")}function $e(o,e=!1){return`matrix3d(${e?St(o):vt(o)})`}function jt(o,e){return e&&o.fallback?[o.fallback.width,o.fallback.height]:[o.width,o.height]}function Ct(o,e,t){let[n,r]=jt(e,t);return Math.abs(o[3]*n)>Co||Math.abs(o[7]*r)>Co}function Tt(o,e){let t=new Array(16).fill(0);for(let n=0;n<4;n+=1)for(let r=0;r<4;r+=1){let a=0;for(let i=0;i<4;i+=1)a+=o[i*4+r]*e[n*4+i];t[n*4+r]=Object.is(a,-0)?0:a}return t}function Ot(o,e,t){return t&&o.fallback?Tt(e,o.fallback.matrixFromLeaf):e}function Ke(o,e,t){let n=Ot(o,e,t);return n.some(r=>!Number.isFinite(r))&&U("invalid-matrix",`${o.id}.matrix`,"resolved leaf matrix must remain finite"),{matrix:n,projective:Ct(n,o,t)}}function Oo(o,e,t){let n=Ke(o,e,t);return $e(n.matrix,n.projective)}function Lt(o){let[e,t,n,r]=o;return`rgba(${Math.round(e*255)}, ${Math.round(t*255)}, ${Math.round(n*255)}, ${r})`}function eo(o,e,t,n=[]){(!o||typeof o!="object"||Array.isArray(o))&&U("invalid-update",e,"expected an object");let r=new Set([...t,...n]),a=Object.keys(o);return(t.some(i=>!a.includes(i))||a.some(i=>!r.has(i)))&&U("invalid-update",e,`allowed keys are ${[...r].sort().join(", ")}`),o}function To(o,e){let t=new Set;for(let n of o)t.has(n)&&U("duplicate-update",e,n),t.add(n)}function At(o,e){let t=eo(o,e,["matrix","shapeId"]);return typeof t.shapeId!="string"&&U("invalid-update",`${e}.shapeId`,"expected a string"),{shapeId:t.shapeId,matrix:Ze(t.matrix,`${e}.matrix`)}}function zt(o,e){let t=eo(o,e,["leafId"],["atlasRow","matrix","opacity","visible"]);typeof t.leafId!="string"&&U("invalid-update",`${e}.leafId`,"expected a string");let n={leafId:t.leafId};return t.matrix!==void 0&&(n.matrix=Ze(t.matrix,`${e}.matrix`)),t.visible!==void 0&&(typeof t.visible!="boolean"&&U("invalid-update",`${e}.visible`,"expected a boolean"),n.visible=t.visible),t.opacity!==void 0&&((typeof t.opacity!="number"||!Number.isFinite(t.opacity)||t.opacity<0||t.opacity>1)&&U("invalid-update",`${e}.opacity`,"expected 0 <= opacity <= 1"),n.opacity=t.opacity),t.atlasRow!==void 0&&((!Number.isSafeInteger(t.atlasRow)||t.atlasRow<0)&&U("invalid-update",`${e}.atlasRow`,"expected a non-negative integer"),n.atlasRow=t.atlasRow),n}function Vt(o){let e=eo(o,"$",[],["leaves","modelMatrix","shapes"]),t=e.shapes===void 0?void 0:(()=>{Array.isArray(e.shapes)||U("invalid-update","$.shapes","expected an array");let r=e.shapes.map((a,i)=>At(a,`$.shapes[${i}]`));return To(r.map(a=>a.shapeId),"$.shapes"),r})(),n=e.leaves===void 0?void 0:(()=>{Array.isArray(e.leaves)||U("invalid-update","$.leaves","expected an array");let r=e.leaves.map((a,i)=>zt(a,`$.leaves[${i}]`));return To(r.map(a=>a.leafId),"$.leaves"),r})();return{...e.modelMatrix===void 0?{}:{modelMatrix:Ze(e.modelMatrix,"$.modelMatrix")},...t===void 0?{}:{shapes:t},...n===void 0?{}:{leaves:n}}}function Et(o,e,t,n){o.style.setProperty("--polycss-atlas-width",`${e.width}px`),o.style.setProperty("--polycss-atlas-height",`${e.height}px`),o.style.backgroundImage=`url("${n.replace(/"/gu,"%22")}")`,o.style.backgroundPosition=`${-t.x}px ${-t.y}px`,o.style.backgroundSize=`${t.pageWidth}px ${t.pageHeight}px`}function Ut(o,e,t,n,r){let a=`url("${r.replace(/"/gu,"%22")}")`,i=`${-e.x}px ${-e.y}px`,s=`${e.pageWidth}px ${e.pageHeight}px`;o.style.width=`${t}px`,o.style.height=`${n}px`,o.style.backgroundColor="currentColor",o.style.setProperty("mask-image",a),o.style.setProperty("mask-mode","alpha"),o.style.setProperty("mask-position",i),o.style.setProperty("mask-repeat","no-repeat"),o.style.setProperty("mask-size",s),o.style.setProperty("-webkit-mask-image",a),o.style.setProperty("-webkit-mask-position",i),o.style.setProperty("-webkit-mask-repeat","no-repeat"),o.style.setProperty("-webkit-mask-size",s)}function Bt(o,e,t,n,r){let a=r?e.fallback:null,i=o.createElement(a?"s":Rt[e.strategy]);return i.className="polycss-morph-leaf",i.dataset.polyMorphLeaf=e.id,i.dataset.polyMorphStrategy=e.strategy,i.dataset.polyMorphResolvedStrategy=a?"atlas-slice":e.strategy,i.style.transform=Oo(e,e.matrix,a!==null),i.style.color=Lt(t),i.style.backfaceVisibility="visible",i.style.backgroundRepeat="no-repeat",i.style.opacity="1",i.style.transformOrigin="0 0",i.style.visibility="visible",e.atlas?(i.style.width=`${e.width}px`,i.style.height=`${e.height}px`,Et(i,e,e.atlas,n(e.atlas.resourcePath,e.id))):a?Ut(i,a.atlas,a.width,a.height,n(a.atlas.resourcePath,e.id)):e.strategy==="solid-quad"&&(i.style.width=`${e.width}px`,i.style.height=`${e.height}px`),i}function Nt(o,e,t={}){(!o||typeof o.appendChild!="function"||!o.ownerDocument)&&U("invalid-host","$.host","expected an HTMLElement");let n=Y(e),r=o.ownerDocument,a=r.defaultView?.navigator?.userAgent??"",i=!It(a),s=n.render.leaves.some(x=>x.strategy==="solid-triangle")&&!kt(r),d=new Map,l=typeof r.defaultView?.URL?.createObjectURL=="function"?r.defaultView.URL:globalThis.URL,c=r.defaultView?.Blob??globalThis.Blob,p=()=>{for(let x of d.values())l.revokeObjectURL(x);d.clear()},y=(x,C)=>{let H=d.get(x);if(H)return H;let ne=t.resources?.get(x);(!ne||ne.descriptor.path!==x||ne.descriptor.role!=="image")&&U("missing-resource",C,"image-backed leaves require their verified package resource"),(typeof l?.createObjectURL!="function"||typeof l?.revokeObjectURL!="function"||typeof c!="function")&&U("missing-object-url",C,"this browser cannot mount verified image bytes");let ye=ne.bytes.slice(),le=l.createObjectURL(new c([ye.buffer],{type:ne.descriptor.mediaType}));return d.set(x,le),le};try{for(let x of n.render.leaves){let C=s&&x.strategy==="solid-triangle",H=Ke(x,x.matrix,C);!i&&H.projective&&U("unsupported-projective-quad",`${x.id}.matrix`,"this browser does not support projective leaf matrices"),x.atlas&&y(x.atlas.resourcePath,x.id),s&&x.strategy==="solid-triangle"&&(x.fallback||U("missing-solid-triangle-fallback",`${x.id}.fallback`,"this browser requires a prepared per-polygon atlas slice"),y(x.fallback.atlas.resourcePath,x.id))}}catch(x){throw p(),x}wt(r);let P=r.defaultView?.getComputedStyle(o),m=o.style.position,f=!1;(!P||P.position==="static"||P.position==="")&&(o.style.position="relative",f=!0);let b=t.camera??$t({zoom:1}),h=r.createElement("div");h.className="polycss-camera polycss-morph-camera";let $=jo(b);h.style.perspective=$.appliedPerspectiveStyle,h.dataset.polycssCameraProjection=$.projection,o.appendChild(h);let k=r.createElement("div");k.className="polycss-scene polycss-morph-scene",k.setAttribute("aria-hidden","true");let F=So(b.state);k.style.transform=F,h.appendChild(k);let v=r.createElement("div");v.className="polycss-mesh polycss-morph-model",v.dataset.polyMorphModel=n.identity.id;let w=$e(n.render.modelMatrix);v.style.transform=w,k.appendChild(v);let L=new Map,E=new Map;for(let x of n.render.shapes){let C=r.createElement("div");C.className="polycss-mesh polycss-morph-shape",C.dataset.polyMorphShape=x.id;let H=$e(x.matrix);C.style.transform=H,v.appendChild(C),L.set(x.id,C),E.set(x.id,H)}let B=new Map(n.materials.map(x=>[x.id,x])),q=new Map,O=new Map;for(let x of n.render.leaves){let C=L.get(x.shapeId),H=B.get(x.materialId);(!C||!H)&&U("mount-coverage",x.id,"leaf references are incomplete");let ne=Bt(r,x,H.color,y,s&&x.strategy==="solid-triangle");C.appendChild(ne),q.set(x.id,{id:x.id,plan:x,element:ne}),O.set(x.id,{transform:Oo(x,x.matrix,s&&x.strategy==="solid-triangle"),visible:!0,opacity:1,atlasRow:0})}let V=[...L.entries()],N=[...q.entries()],_=!1,M=F,S={applyCount:0,totalTransformWrites:0,totalVisibilityWrites:0,totalOpacityWrites:0,totalAtlasRowWrites:0},u=()=>{_&&U("destroyed","$","mounted model is destroyed")},R=()=>{u(),(L.size!==V.length||q.size!==N.length)&&U("identity-drift","$","retained handle maps changed");for(let[x,C]of V)(L.get(x)!==C||C.parentElement!==v)&&U("identity-drift",x,"shape element identity changed");for(let[x,C]of N){let H=L.get(C.plan.shapeId);(q.get(x)!==C||C.element.parentElement!==H)&&U("identity-drift",x,"leaf element identity changed")}},D={model:n,camera:b,cameraElement:h,sceneElement:k,modelElement:v,shapeElements:L,leafHandles:q,get stats(){return{mountCount:1,shapeRoots:L.size,leafCount:q.size,topologyConstructions:1,atlasConstructions:0,schedulerCount:0,...S}},get destroyed(){return _},apply:x=>{u();let C=Vt(x),H=(C.shapes??[]).map(T=>{let ee=L.get(T.shapeId);return ee||U("unknown-shape",T.shapeId,"no retained shape handle"),{shape:T,element:ee}}),ne=(C.leaves??[]).map(T=>{let ee=q.get(T.leafId),oe=O.get(T.leafId);(!ee||!oe)&&U("unknown-leaf",T.leafId,"no retained leaf handle");let De=s&&ee.plan.strategy==="solid-triangle",Ie;if(T.matrix){let se=Ke(ee.plan,T.matrix,De);!i&&se.projective&&U("unsupported-projective-quad",`${T.leafId}.matrix`,"this browser does not support projective leaf matrices"),Ie=$e(se.matrix,se.projective)}let ie;if(T.atlasRow!==void 0){let se=ee.plan.atlas;se||U("invalid-atlas-row",T.leafId,"leaf has no image rows");let yo=se.y+T.atlasRow*se.height;yo+se.height>se.pageHeight&&U("invalid-atlas-row",T.leafId,"row exceeds the image page"),ie=`${-se.x}px ${-yo}px`}return{leaf:T,handle:ee,state:oe,atlasPosition:ie,transform:Ie}});R();let ye=0,le=0,ue=0,ke=0,me=0,Pe=0;if(C.modelMatrix){let T=$e(C.modelMatrix);w!==T&&(w=T,v.style.transform=T,ye+=1)}for(let{shape:T,element:ee}of H){let oe=$e(T.matrix);E.get(T.shapeId)!==oe&&(E.set(T.shapeId,oe),ee.style.transform=oe,le+=1)}for(let{leaf:T,handle:ee,state:oe,atlasPosition:De,transform:Ie}of ne){if(Ie){let ie=Ie;oe.transform!==ie&&(oe.transform=ie,ee.element.style.transform=ie,ue+=1)}if(T.visible!==void 0){let ie=T.visible?"visible":"hidden";oe.visible!==T.visible&&(oe.visible=T.visible,ee.element.style.visibility=ie,ke+=1)}if(T.opacity!==void 0){let ie=String(T.opacity);oe.opacity!==T.opacity&&(oe.opacity=T.opacity,ee.element.style.opacity=ie,me+=1)}T.atlasRow!==void 0&&oe.atlasRow!==T.atlasRow&&(oe.atlasRow=T.atlasRow,ee.element.style.backgroundPosition=De,Pe+=1)}return R(),S.applyCount+=1,S.totalTransformWrites+=ye+le+ue,S.totalVisibilityWrites+=ke,S.totalOpacityWrites+=me,S.totalAtlasRowWrites+=Pe,{modelTransformWrites:ye,shapeTransformWrites:le,leafTransformWrites:ue,visibilityWrites:ke,opacityWrites:me,atlasRowWrites:Pe,dirtyLeavesVisited:C.leaves?.length??0,domCreations:0,domRemovals:0,topologyConstructions:0,atlasRedraws:0,schedulerCallbacks:0}},updateCamera(){u();let x=So(b.state);if(M===x)return!1;M=x,k.style.transform=x;let C=jo(b);return h.style.perspective=C.appliedPerspectiveStyle,h.dataset.polycssCameraProjection=C.projection,!0},assertStableDomIdentity:R,destroy(){_||(_=!0,h.remove(),L.clear(),q.clear(),O.clear(),E.clear(),p(),f&&o.style.position==="relative"&&(o.style.position=m))}};return D.assertStableDomIdentity(),D}function re(o,e,t){throw new ge(o,e,t)}function oo(o,e){let t=o;return(!t||typeof t!="object"||!t.ownerDocument||typeof t.style?.setProperty!="function")&&re("invalid-target",e,"expected an HTMLElement"),t}function Ao(o,e){return typeof o!="string"&&re("invalid-transform",e,"expected a CSS transform string"),o}function Lo(o,e,t){let n,r,a,i;return Object.freeze({element:o,writeTransform(s){t();let d=Ao(s,`${e}.transform`);return n===d?!1:(o.style.transform=d,n=d,!0)},writeVisibility(s){return t(),typeof s!="boolean"&&re("invalid-visibility",`${e}.visible`,"expected a boolean"),r===s?!1:(o.style.visibility=s?"visible":"hidden",r=s,!0)},writeOpacity(s){return t(),(!Number.isFinite(s)||s<0||s>1)&&re("invalid-opacity",`${e}.opacity`,"expected a value in [0, 1]"),a===s?!1:(o.style.opacity=String(s),a=s,!0)},writeImagePositionY(s){return t(),(typeof s!="string"||s.length===0)&&re("invalid-image-position",`${e}.imagePositionY`,"expected a CSS position"),i===s?!1:(o.style.backgroundPositionY=s,i=s,!0)}})}function Dt(o){(!o||typeof o!="object"||Array.isArray(o))&&re("invalid-target","$","expected a prepared DOM target");let e=oo(o.model?.element,"$.model.element");typeof o.model?.writeTransform!="function"&&re("invalid-target","$.model.writeTransform","expected a transform writer"),(!Array.isArray(o.shapes)||!Array.isArray(o.leaves))&&re("invalid-target","$","expected shape and leaf target arrays");let t=o.shapes.map((m,f)=>oo(m?.element,`$.shapes[${f}].element`)),n=o.leaves.map((m,f)=>oo(m?.element,`$.leaves[${f}].element`)),r=e.parentNode,a=t.map(m=>m.parentNode),i=n.map(m=>m.parentNode),s=!1,d=()=>{s&&re("target-destroyed","$","prepared DOM target is destroyed")},l=Object.freeze(t.map((m,f)=>Lo(m,`$.shapes[${f}]`,d))),c=Object.freeze(n.map((m,f)=>Lo(m,`$.leaves[${f}]`,d))),p,y=Object.freeze({element:e,writeTransform(m){d();let f=Ao(m,"$.model.transform");if(p===f)return!1;let b=o.model.writeTransform(f);return typeof b!="boolean"&&re("invalid-writer-result","$.model.writeTransform","expected a boolean"),p=f,b}});return Object.freeze({model:y,shapes:l,leaves:c,get destroyed(){return s},assertStableDomIdentity:()=>{d(),(e.parentNode!==r||l.some((f,b)=>f.element.parentNode!==a[b])||c.some((f,b)=>f.element.parentNode!==i[b]))&&re("identity-drift","$","retained DOM identity changed after adoption")},destroy(){s=!0}})}var K=class extends Error{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphRuntimeError",this.code=e,this.path=t}};function zo(o,e,t){throw new K(o,e,t)}function Ue(o){return Object.freeze([...o])}function Ft(o,e){let{timesMs:t,values:n}=o;if(e<=t[0])return Ue(n[0]);for(let r=1;r<t.length;r+=1){let a=t[r];if(e>a)continue;let i=t[r-1],s=n[r-1],d=n[r];if(e===a)return Ue(d);if(o.interpolation==="step")return Ue(s);let l=(e-i)/(a-i);if(o.target==="joint-rotation"){let p=s.reduce((m,f,b)=>m+f*d[b],0)<0?-1:1,y=s.map((m,f)=>m+(d[f]*p-m)*l),P=Math.hypot(...y);return Object.freeze(y.map(m=>m/P))}return Object.freeze(s.map((c,p)=>c+(d[p]-c)*l))}return Ue(n[n.length-1])}function _t(o,e){if(o.loop){let t=e%o.durationMs;return Object.is(t,-0)?0:t}return Math.min(e,o.durationMs)}function to(o){let e=Y(o),t=new Map(e.animations.map(n=>[n.id,n]));return Object.freeze({model:e,clipIds:Object.freeze([...t.keys()]),sample(n,r){let a=t.get(n);a||zo("unknown-clip","$.clipId",n),(!Number.isFinite(r)||r<0)&&zo("invalid-time","$.timeMs","expected a finite non-negative time");let i=_t(a,r),s={},d={},l=new Map,c=new Map;for(let p of a.channels){let y=Ft(p,i);if(p.target==="morph-weight"&&(s[p.targetId]=y[0]),p.target==="control-value"&&(d[p.targetId]=y[0]),p.target==="shape-matrix"&&c.set(p.targetId,y),p.target.startsWith("joint-")){let P=l.get(p.targetId)??{};p.target==="joint-translation"?P.translation=y:p.target==="joint-rotation"?P.rotation=y:P.scale=y,l.set(p.targetId,P)}}return{clipId:n,requestedTimeMs:r,sampledTimeMs:i,morphWeights:Object.freeze(s),controlValues:Object.freeze(d),jointTransforms:l,shapeMatrices:c}}})}function no(o,e,t){throw new K(o,e,t)}function Vo(o){return o===null?null:((!Array.isArray(o)||o.length!==3||o.some(e=>typeof e!="number"||!Number.isFinite(e)))&&no("invalid-point","$.point","expected three finite components or null"),[o[0],o[1],o[2]])}function qt(o){let e=Math.hypot(...o.axis);return[o.axis[0]/e,o.axis[1]/e,o.axis[2]/e]}function Ht(o){let e=Y(o);return Object.freeze({model:e,controlIds:Object.freeze(e.controls.map(t=>t.id)),controls:new Map(e.controls.map(t=>[t.id,t]))})}function Jt(o){return Object.freeze({tick:-1,active:!1,heldControlId:null,holdStartPoint:null,holdStartValue:0,values:Object.freeze(Object.fromEntries(o.controlIds.map(e=>[e,o.controls.get(e).initial]))),frozenControlIds:Object.freeze([])})}function Eo(o,e){let t=Vo(e),n=null;for(let r of o.controlIds){let a=o.controls.get(r),i=Math.hypot(t[0]-a.anchor[0],t[1]-a.anchor[1],t[2]-a.anchor[2]);i<=a.radius&&(!n||i<n.distance)&&(n={id:r,distance:i})}return n?.id??null}function Wt(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&no("invalid-state","$.state","control state is invalid"),typeof t?.active!="boolean"&&no("invalid-input","$.active","expected a boolean");let n=Vo(t.point),r=e.heldControlId,a=e.holdStartPoint,i=e.holdStartValue,s=null,d=null,l={...e.values},c=new Set(e.frozenControlIds),p=t.active&&!e.active,y=!t.active&&e.active;if(p&&n&&(r=Eo(o,n),r&&(s=r,a=n,i=l[r]??o.controls.get(r).initial,c.delete(r))),t.active&&r&&n&&a){let m=o.controls.get(r),f=qt(m),b=(n[0]-a[0])*f[0]+(n[1]-a[1])*f[1]+(n[2]-a[2])*f[2];l[r]=Math.max(m.minimum,Math.min(m.maximum,i+b))}y&&(d=r,r&&(t.freezeOnRelease===!0?c.add(r):c.delete(r)),r=null,a=null,i=0);let P=Object.freeze({tick:e.tick+1,active:t.active,heldControlId:r,holdStartPoint:a,holdStartValue:i,values:Object.freeze(l),frozenControlIds:Object.freeze([...c].sort())});return Object.freeze({state:P,pickedControlId:s,releasedControlId:d,heldTarget:t.active&&r?Object.freeze({controlId:r,value:l[r]}):null})}import{computeProjectiveQuadCoefficients as Yt,computeSolidTrianglePlanFromCssPoints as No,resolveProjectiveQuadGuards as Gt,SOLID_TRIANGLE_CANONICAL_SIZE as Uo}from"@layoutit/polycss";var Qt=Gt(void 0);function Z(o,e,t){throw new K(o,e,t)}function Xt(o,e){return(typeof o!="number"||!Number.isFinite(o))&&Z("invalid-number",e,"expected a finite number"),Object.is(o,-0)?0:o}function Kt(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function Be(o){return o.map(e=>[e[0],e[1],e[2]])}function Ne(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function Zt(o,e){let[t,n,r]=o.vertexIndices,a=e[t],i=e[n],s=e[r],d=No(o.polygon,0,{seamBleed:0},{basis:o.basis??void 0,includeColor:!1,primitive:"corner-bevel"},a[0],a[1],a[2],i[0],i[1],i[2],s[0],s[1],s[2]);if(!d)return{matrix:null,visible:!1};let l=/^matrix3d\(([^)]+)\)$/u.exec(d.transformText);l||Z("invalid-transform",o.leaf.id,"PolyCSS returned no matrix3d");let c=l[1].split(",").map(Number);(c.length!==16||c.some(P=>!Number.isFinite(P)))&&Z("invalid-transform",o.leaf.id,"PolyCSS returned an invalid matrix3d");let p=Uo/o.leaf.width,y=Uo/o.leaf.height;for(let P of[0,1,2])c[P]*=p;for(let P of[4,5,6])c[P]*=y;return{matrix:c,visible:!0}}function en(o,e){let[t,n,r,a]=o.vertexIndices,i=e[t],s=e[n],d=e[r],l=e[a],c=[s[0]-i[0],s[1]-i[1],s[2]-i[2]],p=[l[0]-i[0],l[1]-i[1],l[2]-i[2]],y=Math.hypot(...c),P=Math.hypot(...p);(!Number.isFinite(y)||!Number.isFinite(P)||y===0||P===0)&&Z("degenerate-polygon",o.leaf.id,"deformed quad has no area");let m=[c[0]/y,c[1]/y,c[2]/y],f=[p[0]/P,p[1]/P,p[2]/P],b=[m[1]*f[2]-m[2]*f[1],m[2]*f[0]-m[0]*f[2],m[0]*f[1]-m[1]*f[0]],h=Math.hypot(...b);(!Number.isFinite(h)||h<=1e-12)&&Z("degenerate-polygon",o.leaf.id,"deformed quad has no area");let $=[b[0]/h,b[1]/h,b[2]/h],k=[d[0]-i[0],d[1]-i[1],d[2]-i[2]],F=Math.hypot(...k),v=Math.abs($[0]*k[0]+$[1]*k[1]+$[2]*k[2]),w=Math.max(y,P,F);(!Number.isFinite(v)||!Number.isFinite(w)||v/w>1e-6)&&Z("non-planar-polygon",o.leaf.id,"deformed quad is not coplanar");let L=[[0,1],[0,2],[1,2]].map(([j,D])=>({first:j,second:D,determinant:m[j]*f[D]-m[D]*f[j]})).sort((j,D)=>Math.abs(D.determinant)-Math.abs(j.determinant))[0],E=[i,s,d,l].map(j=>[j[L.first],j[L.second]]),[B]=E,q=Math.max(...E.map(j=>Math.abs(j[0]-B[0]))),O=Math.max(...E.map(j=>Math.abs(j[1]-B[1])));(!Number.isFinite(q)||!Number.isFinite(O)||q===0||O===0)&&Z("degenerate-polygon",o.leaf.id,"deformed quad has no area");let V=E.map(j=>[(j[0]-B[0])/q,(j[1]-B[1])/O]),N=Yt(V,Qt);N||Z("degenerate-polygon",o.leaf.id,"deformed quad has no stable convex projective transform");let{g:_,h:M}=N,S=[((1+_)*s[0]-i[0])/o.leaf.width,((1+_)*s[1]-i[1])/o.leaf.width,((1+_)*s[2]-i[2])/o.leaf.width],u=[((1+M)*l[0]-i[0])/o.leaf.height,((1+M)*l[1]-i[1])/o.leaf.height,((1+M)*l[2]-i[2])/o.leaf.height],R=[S[0],S[1],S[2],_/o.leaf.width,u[0],u[1],u[2],M/o.leaf.height,$[0],$[1],$[2],0,i[0],i[1],i[2],1];return R.some(j=>!Number.isFinite(j))&&Z("invalid-transform",o.leaf.id,"deformed quad produced a non-finite matrix"),{matrix:R,visible:!0}}function ro(o,e){if(o.vertexIndices.length===3)return Zt(o,e);if(o.vertexIndices.length===4)return en(o,e);Z("unsupported-deformation",o.leaf.id,"caller-driven deformation supports prepared triangles and planar quads")}function ao(o,e){let t=o.topology.polygons.find(i=>i.id===e.polygonId);t||Z("unknown-polygon",e.id,e.polygonId);let n=t.vertexIndices.map(i=>[...o.topology.vertices[i]]),r={vertices:n},a=null;if(n.length===3){let[i,s,d]=n,l=No(r,0,{seamBleed:0},{includeColor:!1,primitive:"corner-bevel"},i[0],i[1],i[2],s[0],s[1],s[2],d[0],d[1],d[2]);l||Z("degenerate-polygon",e.id,"base triangle has no area"),a=l.basis}return{leaf:e,vertexIndices:t.vertexIndices,polygon:r,basis:a}}function Bo(o,e,t,n){let r=o??{};(!r||typeof r!="object"||Array.isArray(r))&&Z("invalid-input",t,"expected an object");let a=new Set(e),i=Object.keys(r).find(s=>!a.has(s));return i&&Z("unknown-id",t,i),Object.fromEntries(e.map(s=>{let[d,l]=n.get(s)??[0,1],c=Xt(r[s]??0,`${t}.${s}`);return(c<d||c>l)&&Z("out-of-range",`${t}.${s}`,`expected ${d} <= value <= ${l}`),[s,c]}))}function on(o){return new Map(o.deformation.kind==="morph-regions"?o.deformation.targets.map(e=>[e.id,e]):[])}function tn(o){let e=Y(o);e.deformation.kind==="joint-skin"&&Z("profile-not-executable","$.profile","joint skin requires the skinning runtime");let t=on(e),n=[...t.keys()],r=e.controls.map(h=>h.id),a=new Map(n.map(h=>[h,[0,1]])),i=new Map(e.controls.map(h=>[h.id,[h.minimum,h.maximum]])),s=new Map(e.render.leaves.map(h=>[h.polygonId,h])),d=new Map;for(let h of e.topology.polygons)for(let $ of h.vertexIndices){let k=d.get($)??[];k.push(h.id),d.set($,k)}let l=new Map;for(let h of t.values()){let $=new Set;for(let k of h.deltas)for(let F of d.get(k.vertexIndex)??[]){let v=s.get(F);v&&$.add(v.id)}l.set(h.id,$)}let c=new Map(e.render.leaves.map(h=>[h.id,ao(e,h)])),p=Ne(Be(e.topology.vertices)),y=Ne(Be(e.topology.normals)),P=Object.fromEntries(n.map(h=>[h,0])),m=p,f=y,b=h=>{(!h||!Number.isSafeInteger(h.tick)||h.tick<0)&&Z("invalid-tick","$.tick","expected a non-negative safe integer");let $=Bo(h.morphWeights,n,"$.morphWeights",a),k=Bo(h.controlValues,r,"$.controlValues",i),F={...$};for(let O of e.controls){let V=k[O.id];for(let N of O.targets)F[N.targetId]=Math.max(0,Math.min(1,(F[N.targetId]??0)+V*N.scale))}let v=n.filter(O=>F[O]!==P[O]),w=m,L=f;if(v.length>0){let O=Be(p),V=Be(y);for(let N of n){let _=F[N];if(_!==0)for(let M of t.get(N).deltas){let S=O[M.vertexIndex];M.position&&(S[0]+=M.position[0]*_,S[1]+=M.position[1]*_,S[2]+=M.position[2]*_);let u=V[M.vertexIndex];M.normal&&(u[0]+=M.normal[0]*_,u[1]+=M.normal[1]*_,u[2]+=M.normal[2]*_)}}V=V.map(Kt),w=Ne(O),L=Ne(V)}let E=new Set;for(let O of v)for(let V of l.get(O)??[])E.add(V);let B=e.render.leaves.map(O=>O.id).filter(O=>E.has(O)),q=B.map(O=>{let V=ro(c.get(O),w);return{leafId:O,visible:V.visible,...V.matrix?{matrix:V.matrix}:{}}});return m=w,f=L,P={...F},{tick:h.tick,positions:w,normals:L,morphWeights:Object.freeze({...F}),controlValues:Object.freeze({...k}),dirtyLeafIds:Object.freeze(B),leafUpdates:Object.freeze(q),runtimePolygonConstructions:0,runtimeTopologyConstructions:0,atlasRedraws:0}};return Object.freeze({model:e,targetIds:Object.freeze(n),controlIds:Object.freeze(r),basePositions:Object.freeze(p),baseNormals:Object.freeze(y),sample:b,reset(){P=Object.fromEntries(n.map(h=>[h,0])),m=p,f=y}})}function Le(o,e,t){throw new K(o,e,t)}function ve(o){return Object.freeze([...o])}function io(o,e){return o.every((t,n)=>t===e[n])}function so(o){let e=Y(o);return Object.freeze({modelMatrix:ve(e.render.modelMatrix),shapes:Object.freeze(e.render.shapes.map(t=>Object.freeze({shapeId:t.id,matrix:ve(t.matrix)}))),leaves:Object.freeze(e.render.leaves.map(t=>Object.freeze({leafId:t.id,matrix:ve(t.matrix),visible:!0,opacity:1,atlasRow:0})))})}function lo(o,e){let t=new Map(e.shapes.map(r=>[r.shapeId,r])),n=new Map(e.leaves.map(r=>[r.leafId,r]));for(let r of t.keys())o.shapes.some(a=>a.shapeId===r)||Le("unknown-shape","$.frame.shapes",r);for(let r of n.keys())o.leaves.some(a=>a.leafId===r)||Le("unknown-leaf","$.frame.leaves",r);return Object.freeze({modelMatrix:e.modelMatrix===null?o.modelMatrix:ve(e.modelMatrix),shapes:Object.freeze(o.shapes.map(r=>{let a=t.get(r.shapeId);return a?Object.freeze({shapeId:r.shapeId,matrix:ve(a.matrix)}):r})),leaves:Object.freeze(o.leaves.map(r=>{let a=n.get(r.leafId);return a?Object.freeze({leafId:r.leafId,matrix:a.matrix===null?r.matrix:ve(a.matrix),visible:a.visible??r.visible,opacity:a.opacity??r.opacity,atlasRow:a.atlasRow??r.atlasRow}):r}))})}function co(o,e){(o.shapes.length!==e.shapes.length||o.leaves.length!==e.leaves.length)&&Le("state-mismatch","$","prepared state topology differs");let t=!io(o.modelMatrix,e.modelMatrix),n=[];for(let a=0;a<e.shapes.length;a+=1){let i=o.shapes[a],s=e.shapes[a];i.shapeId!==s.shapeId&&Le("state-mismatch","$.shapes","source order differs"),io(i.matrix,s.matrix)||n.push({shapeId:s.shapeId,matrix:s.matrix})}let r=[];for(let a=0;a<e.leaves.length;a+=1){let i=o.leaves[a],s=e.leaves[a];i.leafId!==s.leafId&&Le("state-mismatch","$.leaves","source order differs");let d={leafId:s.leafId};io(i.matrix,s.matrix)||(d.matrix=s.matrix),i.visible!==s.visible&&(d.visible=s.visible),i.opacity!==s.opacity&&(d.opacity=s.opacity),i.atlasRow!==s.atlasRow&&(d.atlasRow=s.atlasRow),Object.keys(d).length>1&&r.push(d)}return Object.freeze({update:Object.freeze({...t?{modelMatrix:e.modelMatrix}:{},...n.length>0?{shapes:Object.freeze(n)}:{},...r.length>0?{leaves:Object.freeze(r)}:{}}),modelChanged:t,dirtyShapeIds:Object.freeze(n.map(a=>a.shapeId)),dirtyLeafIds:Object.freeze(r.map(a=>a.leafId))})}function Ae(o,e,t){throw new K(o,e,t)}function nn(o,e,t){if(e){let n=t%o;return Object.is(n,-0)?0:n}return Math.min(t,o)}function rn(o,e){let t=0,n=o.length-1;for(;t<=n;){let r=Math.floor((t+n)/2);o[r]<=e?t=r+1:n=r-1}return Math.max(0,n)}function an(o){let e=Y(o);(e.profile!=="prepared-playback"||!e.playback)&&Ae("profile-mismatch","$.profile","playback requires the prepared-playback profile");let t=e.playback,n=so(e),r=[],a=n,i=new Map(e.render.leaves.map(p=>[p.id,p]));for(let[p,y]of t.frames.entries()){for(let P of y.leaves){if(P.atlasRow===null)continue;let m=i.get(P.leafId);m.atlas||Ae("invalid-atlas-row",`$.playback.frames[${p}]`,`${m.id} has no image rows`),m.atlas.y+P.atlasRow*m.atlas.height+m.atlas.height>m.atlas.pageHeight&&Ae("invalid-atlas-row",`$.playback.frames[${p}]`,`${m.id} row exceeds its page`)}a=lo(a,y),r.push(a)}let s=t.frames.map(p=>p.timeMs),d=n,l=null,c=p=>{(!Number.isFinite(p)||p<0)&&Ae("invalid-time","$.timeMs","expected a finite non-negative time");let y=nn(t.durationMs,t.loop,p),P=rn(s,y),m=r[P],f=co(d,m),b=Object.freeze({requestedTimeMs:p,sampledTimeMs:y,frameIndex:P,state:m,update:f.update,modelChanged:f.modelChanged,dirtyShapeIds:f.dirtyShapeIds,dirtyLeafIds:f.dirtyLeafIds,domCreations:0,domRemovals:0,topologyConstructions:0,atlasConstructions:0,atlasRedraws:0,schedulerCallbacks:0});return l=b,b};return Object.freeze({model:e,durationMs:t.durationMs,loop:t.loop,frameCount:t.frames.length,sample:c,commit(p){p!==l&&Ae("invalid-sample","$.sample","commit requires the latest unapplied playback sample"),d=p.state,l=null},reset(){d=n,l=null}})}var sn=Object.freeze(["joint-skin","morph-regions","prepared-playback","static-prepared"]);function ae(o,e,t){throw new K(o,e,t)}function ln(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function po(o,e){let t=new Array(16).fill(0);for(let n=0;n<4;n+=1)for(let r=0;r<4;r+=1){let a=0;for(let i=0;i<4;i+=1)a+=o[i*4+r]*e[n*4+i];t[n*4+r]=Object.is(a,-0)?0:a}return Object.freeze(t)}function dn(o,e){if(o===void 0)return[0,0,0,1];(!Array.isArray(o)||o.length!==4||o.some(n=>typeof n!="number"||!Number.isFinite(n)))&&ae("invalid-quaternion",e,"expected four finite components");let t=Math.hypot(...o);return t<=1e-12&&ae("invalid-quaternion",e,"quaternion must be non-zero"),[o[0]/t,o[1]/t,o[2]/t,o[3]/t]}function Do(o,e,t,n=!1){return o===void 0?e:((!Array.isArray(o)||o.length!==3||o.some(r=>typeof r!="number"||!Number.isFinite(r)))&&ae("invalid-vector",t,"expected three finite components"),n&&o.some(r=>r<=0)&&ae("invalid-scale",t,"scale components must be positive"),[o[0],o[1],o[2]])}function qo(o,e){if(o===void 0)return ln();(!o||typeof o!="object"||Array.isArray(o))&&ae("invalid-joint-transform",e,"expected an object"),Object.keys(o).some($=>$!=="translation"&&$!=="rotation"&&$!=="scale")&&ae("invalid-joint-transform",e,"unknown transform field");let n=Do(o.translation,[0,0,0],`${e}.translation`),r=Do(o.scale,[1,1,1],`${e}.scale`,!0),[a,i,s,d]=dn(o.rotation,`${e}.rotation`),l=a*a,c=i*i,p=s*s,y=a*i,P=a*s,m=i*s,f=d*a,b=d*i,h=d*s;return[(1-2*(c+p))*r[0],2*(y+h)*r[0],2*(P-b)*r[0],0,2*(y-h)*r[1],(1-2*(l+p))*r[1],2*(m+f)*r[1],0,2*(P+b)*r[2],2*(m-f)*r[2],(1-2*(l+c))*r[2],0,n[0],n[1],n[2],1]}function cn(o,e){return[o[0]*e[0]+o[4]*e[1]+o[8]*e[2]+o[12],o[1]*e[0]+o[5]*e[1]+o[9]*e[2]+o[13],o[2]*e[0]+o[6]*e[1]+o[10]*e[2]+o[14]]}function pn(o,e,t){let[n,r,a]=o,i=o[4],s=o[5],d=o[6],l=o[8],c=o[9],p=o[10],y=n*(s*p-c*d)-i*(r*p-c*a)+l*(r*d-s*a);return Math.abs(y)<=1e-12&&ae("invalid-normal-transform",t,"joint skin matrix is singular"),[((s*p-c*d)*e[0]+(c*a-r*p)*e[1]+(r*d-s*a)*e[2])/y,((l*d-i*p)*e[0]+(n*p-l*a)*e[1]+(i*a-n*d)*e[2])/y,((i*c-l*s)*e[0]+(l*r-n*c)*e[1]+(n*s-i*r)*e[2])/y]}function yn(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function we(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function mn(o,e){return o.every((t,n)=>Math.abs(t-e[n])<=1e-12)}function Fo(o,e){let t=new Map(o.map(a=>[a.id,a])),n=new Map,r=a=>{let i=n.get(a.id);if(i)return i;let s=po(a.restMatrix,qo(e.get(a.id),`$.jointTransforms.${a.id}`)),d=a.parentId===null?s:po(r(t.get(a.parentId)),s);return n.set(a.id,d),d};for(let a of o)r(a);return n}function _o(o,e){return new Map(o.map(t=>[t.id,po(e.get(t.id),t.inverseBindMatrix)]))}function un(o,e){let t=o??new Map;(!t||typeof t.entries!="function")&&ae("invalid-joint-transform","$.jointTransforms","expected a map");for(let[n,r]of t)e.has(n)||ae("unknown-joint","$.jointTransforms",n),qo(r,`$.jointTransforms.${n}`);return t}function fn(o){let e=Y(o);e.deformation.kind!=="joint-skin"&&ae("profile-mismatch","$.profile","skinning requires the joint-skin profile");let t=e.deformation,n=t.joints.map(w=>w.id),r=new Set(n),a=Fo(t.joints,new Map),i=_o(t.joints,a),s=we(e.topology.vertices.map(w=>[...w])),d=we(e.topology.normals.map(w=>[...w])),l=new Map(e.render.leaves.map(w=>[w.id,ao(e,w)])),c=new Map;for(let w of e.topology.polygons)for(let L of w.vertexIndices){let E=c.get(L)??[];E.push(w.id),c.set(L,E)}let p=new Map(e.render.leaves.map(w=>[w.polygonId,w.id])),y=new Map(t.vertices.map(w=>[w.vertexIndex,w])),P=w=>{let L=[],E=[];for(let B=0;B<s.length;B+=1){let q=y.get(B),O=[0,0,0],V=[0,0,0];for(let N of q.influences){let _=w.get(N.jointId),M=cn(_,s[B]),S=pn(_,d[B],`$.skinMatrices.${N.jointId}`);O[0]+=M[0]*N.weight,O[1]+=M[1]*N.weight,O[2]+=M[2]*N.weight,V[0]+=S[0]*N.weight,V[1]+=S[1]*N.weight,V[2]+=S[2]*N.weight}L.push(O),E.push(yn(V))}return{positions:L,normals:E}},m=P(i),f=we(m.positions),b=we(m.normals),h=new Map(i),$=f,k=b,F=to(e),v=w=>{(!w||!Number.isSafeInteger(w.tick)||w.tick<0)&&ae("invalid-tick","$.tick","expected a non-negative safe integer");let L=un(w.jointTransforms,r),E=Fo(t.joints,L),B=_o(t.joints,E),q=new Set(n.filter(u=>!mn(B.get(u),h.get(u)))),O=$,V=k;if(q.size>0){let u=P(B);O=we(u.positions),V=we(u.normals)}let N=new Set;if(q.size>0)for(let u of t.vertices)u.influences.some(R=>q.has(R.jointId))&&N.add(u.vertexIndex);let _=new Set;for(let u of N)for(let R of c.get(u)??[]){let j=p.get(R);j&&_.add(j)}let M=e.render.leaves.map(u=>u.id).filter(u=>_.has(u)),S=M.map(u=>{let R=ro(l.get(u),O);return{leafId:u,visible:R.visible,...R.matrix?{matrix:R.matrix}:{}}});return $=O,k=V,h=new Map(B),{tick:w.tick,positions:O,normals:V,globalJointMatrices:E,skinMatrices:B,dirtyLeafIds:Object.freeze(M),leafUpdates:Object.freeze(S),runtimePolygonConstructions:0,runtimeTopologyConstructions:0,atlasRedraws:0}};return Object.freeze({model:e,jointIds:Object.freeze(n),basePositions:Object.freeze(s),baseNormals:Object.freeze(d),sample:v,sampleClip(w,L,E){let B=F.sample(w,L);return v({tick:E,jointTransforms:B.jointTransforms})},reset(){h=new Map(i),$=f,k=b}})}function Me(o,e,t){throw new K(o,e,t)}function hn(o,e,t,n,r){let a=n*n-4*t,i=1e-9*Math.max(1,n*n,t);if(Math.abs(a)<=i){let m=n/2,f=e+m*o,b=Math.exp(-m*r);return[b*(o+f*r),b*(e-m*f*r)]}if(a<0){let m=n/2,f=Math.sqrt(t-m*m),b=f*r,h=Math.cos(b),$=Math.sin(b),k=Math.exp(-m*r);return[k*(o*h+(e+m*o)/f*$),k*(e*h-(m*e+t*o)/f*$)]}let s=Math.sqrt(a),d=(-n+s)/2,l=(-n-s)/2,c=(e-l*o)/(d-l),p=o-c,y=c*Math.exp(d*r),P=p*Math.exp(l*r);return[y+P,d*y+l*P]}function gn(o){let e=Y(o),t=new Map;for(let n of e.springs)t.set(n.controlId,n);return Object.freeze({model:e,controlIds:Object.freeze(e.controls.map(n=>n.id)),controls:new Map(e.controls.map(n=>[n.id,n])),springs:t})}function Mn(o,e){let t=Object.keys(e??{}).find(r=>!o.controls.has(r));t&&Me("unknown-id","$.values",t);let n=Object.fromEntries(o.controlIds.map(r=>{let a=o.controls.get(r),i=e?.[r]??a.initial;return(!Number.isFinite(i)||i<a.minimum||i>a.maximum)&&Me("out-of-range",`$.values.${r}`,"value is outside control bounds"),[r,i]}));return Object.freeze({tick:-1,values:Object.freeze(n),velocities:Object.freeze(Object.fromEntries(o.controlIds.map(r=>[r,0]))),atRest:o.controlIds.every(r=>n[r]===o.controls.get(r).initial)})}function Pn(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&Me("invalid-state","$.state","spring state is invalid"),(!Number.isFinite(t?.deltaMs)||t.deltaMs<=0||t.deltaMs>1e3)&&Me("invalid-time","$.deltaMs","expected 0 < deltaMs <= 1000");let n=t.heldTarget??null;if(n){let l=o.controls.get(n.controlId);l||Me("unknown-id","$.heldTarget.controlId",n.controlId),(!Number.isFinite(n.value)||n.value<l.minimum||n.value>l.maximum)&&Me("out-of-range","$.heldTarget.value","value is outside control bounds")}let r=new Set(t.frozenControlIds??[]);for(let l of r)o.controls.has(l)||Me("unknown-id","$.frozenControlIds",l);let a=t.deltaMs/1e3,i={},s={},d=!0;for(let l of o.controlIds){let c=o.controls.get(l),p=e.values[l]??c.initial,y=e.velocities[l]??0;if(n?.controlId===l)i[l]=n.value,s[l]=0;else if(r.has(l)||!o.springs.has(l))i[l]=p,s[l]=0;else{let P=o.springs.get(l),m=p-c.initial,[f,b]=hn(m,y,P.stiffness,P.damping,a),h=b,$=c.initial+f,k=Math.max(c.minimum,Math.min(c.maximum,$));k!==$&&(h=0),$=k,Math.abs($-c.initial)<1e-6&&Math.abs(h)<1e-6&&($=c.initial,h=0),i[l]=Object.is($,-0)?0:$,s[l]=Object.is(h,-0)?0:h}(i[l]!==c.initial||s[l]!==0)&&(d=!1)}return Object.freeze({tick:e.tick+1,values:Object.freeze(i),velocities:Object.freeze(s),atRest:d})}export{fe as POLY_MORPH_CATALOG_SCHEMA,sn as POLY_MORPH_EXECUTABLE_PROFILES,Re as POLY_MORPH_MODEL_SCHEMA,he as POLY_MORPH_PACKAGE_SCHEMA,ze as PolyMorphContractError,I as PolyMorphPackageError,ge as PolyMorphRenderError,K as PolyMorphRuntimeError,lo as applyPolyMorphPlaybackFrame,Qe as assertPolyMorphPackageModelBinding,ht as buildPolyMorphCatalog,ft as buildPolyMorphPackage,to as createPolyMorphAnimationRuntime,Ht as createPolyMorphControlRuntime,Jt as createPolyMorphControlState,tn as createPolyMorphDeformationRuntime,an as createPolyMorphPlaybackRuntime,Dt as createPolyMorphPreparedDomTarget,so as createPolyMorphPreparedState,fn as createPolyMorphSkinningRuntime,gn as createPolyMorphSpringRuntime,Mn as createPolyMorphSpringState,je as decodePolyMorphJson,co as diffPolyMorphPreparedStates,Se as encodePolyMorphCanonicalJson,ce as hashPolyMorphBytes,_e as isPolyMorphId,qe as isPolyMorphResourcePath,Ro as loadPolyMorphCatalog,xt as loadPolyMorphPackage,Nt as mountPolyMorphModel,Eo as pickPolyMorphControl,Wt as stepPolyMorphControls,Pn as stepPolyMorphSprings,go as stringifyPolyMorphCanonicalJson,Oe as validatePolyMorphCatalog,Y as validatePolyMorphModel,Te as validatePolyMorphPackageManifest};