@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/README.md +26 -18
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/prepare.cjs +1 -1
- package/dist/prepare.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
# @layoutit/polycss-morph
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Prepare, load, and animate retained DOM models with PolyCSS.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
```bash
|
|
6
|
+
npm install @layoutit/polycss-morph
|
|
7
|
+
```
|
|
7
8
|
|
|
8
|
-
##
|
|
9
|
+
## Package entries
|
|
9
10
|
|
|
10
11
|
Morph has two public entries:
|
|
11
12
|
|
|
@@ -18,9 +19,8 @@ Morph has two public entries:
|
|
|
18
19
|
packages, mounts one retained PolyCSS graph, and exposes imperative,
|
|
19
20
|
caller-driven runtimes.
|
|
20
21
|
|
|
21
|
-
The
|
|
22
|
-
|
|
23
|
-
profiles:
|
|
22
|
+
The Node preparer creates `static-prepared` and `morph-regions` models. The
|
|
23
|
+
browser runtime supports all four profiles:
|
|
24
24
|
|
|
25
25
|
| Profile | Runtime contract |
|
|
26
26
|
|---|---|
|
|
@@ -70,6 +70,9 @@ const frame = deformation.sample({
|
|
|
70
70
|
mounted.apply({ leaves: frame.leafUpdates });
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
+
See the [cube-to-sphere example](https://polycss.com/guides/morph/#example-cube-to-sphere)
|
|
74
|
+
for a complete rendered deformation example.
|
|
75
|
+
|
|
73
76
|
The browser API is intentionally imperative:
|
|
74
77
|
|
|
75
78
|
- load or validate a model;
|
|
@@ -91,16 +94,21 @@ mounted model keeps the same leaf elements for its lifetime. Runtime updates do
|
|
|
91
94
|
not rebuild topology, add or remove leaves, construct image resources, or
|
|
92
95
|
redraw prepared image resources.
|
|
93
96
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
97
|
+
Sparse deformation supports retained solid triangles and affine solid quads.
|
|
98
|
+
Planar projective solid quads are available where PolyCSS enables projective
|
|
99
|
+
quad compositing. Deformation rejects non-coplanar, non-convex, or
|
|
100
|
+
compositor-unstable geometry, and the retained mount rejects projective quad
|
|
101
|
+
matrices on unsupported Safari-family browsers before DOM writes.
|
|
102
|
+
|
|
103
|
+
Morph chooses the triangle paint path once when it mounts. It uses
|
|
104
|
+
`corner-shape` where available, a larger CSS border triangle in Firefox, and
|
|
105
|
+
each leaf's prepared polygon-sized atlas slice in WebKit/Safari. Mount creates
|
|
106
|
+
object URLs from the loader's already-verified image bytes and revokes them at
|
|
107
|
+
teardown; it does not refetch package resources. Atlas pages are generated with
|
|
108
|
+
Node built-ins, so Morph has no Sharp or other native image dependency.
|
|
101
109
|
|
|
102
|
-
##
|
|
110
|
+
## Application ownership
|
|
103
111
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
112
|
+
Morph owns the prepared model format and sparse DOM updates. Your application
|
|
113
|
+
owns input, timing, presentation, model-specific preparation, and product
|
|
114
|
+
behavior.
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var We=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var nt=(o,e)=>{for(var t in e)We(o,t,{get:e[t],enumerable:!0})},rt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ot(e))!tt.call(o,r)&&r!==t&&We(o,r,{get:()=>e[r],enumerable:!(n=et(e,r))||n.enumerable});return o};var at=o=>rt(We({},"__esModule",{value:!0}),o);var sn={};nt(sn,{POLY_MORPH_CATALOG_SCHEMA:()=>ce,POLY_MORPH_EXECUTABLE_PROFILES:()=>qo,POLY_MORPH_MODEL_SCHEMA:()=>Pe,POLY_MORPH_PACKAGE_SCHEMA:()=>pe,PolyMorphContractError:()=>Ce,PolyMorphPackageError:()=>k,PolyMorphRenderError:()=>ye,PolyMorphRuntimeError:()=>K,applyPolyMorphPlaybackFrame:()=>qe,assertPolyMorphPackageModelBinding:()=>Ue,buildPolyMorphCatalog:()=>ko,buildPolyMorphPackage:()=>wo,createPolyMorphAnimationRuntime:()=>Ne,createPolyMorphControlRuntime:()=>Uo,createPolyMorphControlState:()=>Bo,createPolyMorphDeformationRuntime:()=>Ho,createPolyMorphPlaybackRuntime:()=>Fo,createPolyMorphPreparedDomTarget:()=>zo,createPolyMorphPreparedState:()=>Fe,createPolyMorphSkinningRuntime:()=>Qo,createPolyMorphSpringRuntime:()=>Ko,createPolyMorphSpringState:()=>Xo,decodePolyMorphJson:()=>$e,diffPolyMorphPreparedStates:()=>Je,encodePolyMorphCanonicalJson:()=>xe,hashPolyMorphBytes:()=>se,isPolyMorphId:()=>Ve,isPolyMorphResourcePath:()=>Ee,loadPolyMorphCatalog:()=>to,loadPolyMorphPackage:()=>Co,mountPolyMorphModel:()=>Oo,pickPolyMorphControl:()=>lo,stepPolyMorphControls:()=>Do,stepPolyMorphSprings:()=>Zo,stringifyPolyMorphCanonicalJson:()=>Qe,validatePolyMorphCatalog:()=>we,validatePolyMorphModel:()=>F,validatePolyMorphPackageManifest:()=>ve});module.exports=at(sn);var Pe="polycss-morph.model@1",ce="polycss-morph.catalog@1",pe="polycss-morph.package@1";var ho=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,it=/^[a-z0-9][a-z0-9._-]*$/,uo=/^\d+\.\d+\.\d+$/,st=/^[a-f0-9]{64}$/,lt=new Set(["joint-skin","morph-regions","prepared-playback","static-prepared"]),dt=new Set(["animation","joint-skinning","morph-targets","prepared-playback","retained-render","semantic-controls","sparse-updates","springs"]),ct=new Set(["atlas-slice","direct-image","solid-quad","solid-triangle"]),pt=new Set(["control-value","joint-rotation","joint-scale","joint-translation","morph-weight","shape-matrix"]),Ce=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 Ce(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 X(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 Ye(o,e){return typeof o!="boolean"&&h("invalid-boolean",e,"expected a boolean"),o}function H(o,e){let t=Z(o,e);return ho.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 be(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 le(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 go(o,e){let t=Z(o,e);return t.split("/").some(n=>!it.test(n))&&h("invalid-path",e,"expected lowercase URL-safe package path segments"),t}function ze(o,e,t){let n=X(o,e);return n>=t&&h("out-of-range",e,`expected an index below ${t}`),n}function yt(o,e){let t=O(o,e,["normals","polygons","vertices"]),n=A(t.vertices,`${e}.vertices`).map((i,s)=>be(i,`${e}.vertices[${s}]`)),r=A(t.normals,`${e}.normals`).map((i,s)=>be(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)=>ze(y,`${d}.vertexIndices[${b}]`,n.length)),p=A(l.normalIndices,`${d}.normalIndices`).map((y,b)=>ze(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 mt(o,e,t){let n=O(o,e,["atlas","fallback","height","id","materialId","matrix","polygonId","shapeId","strategy","width"]),r=Z(n.strategy,`${e}.strategy`);ct.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:Mo(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:ft(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:le(n.matrix,`${e}.matrix`),atlas:p,fallback:y}}function ft(o,e){let t=O(o,e,["atlas","height","matrixFromLeaf","width"]),n=X(t.width,`${e}.width`,1),r=X(t.height,`${e}.height`,1),a=Mo(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:le(t.matrixFromLeaf,`${e}.matrixFromLeaf`),atlas:a}}function Mo(o,e){let t=O(o,e,["height","pageHeight","pageWidth","resourcePath","width","x","y"]),n={resourcePath:go(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)&&h("out-of-range",e,"slice must fit inside its page"),n}function ut(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:be(u.position,`${m}.position`),g=u.normal===null?null:be(u.normal,`${m}.normal`);return x===null&&g===null&&h("empty-delta",m,"expected a position or normal delta"),{vertexIndex:ze(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:le(y.restMatrix,`${p}.restMatrix`),inverseBindMatrix:le(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`),ht(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=ze(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 ht(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 gt(o){return o==="control-value"||o==="morph-weight"?1:o==="joint-rotation"?4:o==="shape-matrix"?16:3}function Mt(o,e,t,n){let r=O(o,e,["interpolation","target","targetId","timesMs","values"]),a=Z(r.target,`${e}.target`);pt.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=gt(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 Pt(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:le(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:le(g.matrix,`${x}.matrix`),visible:g.visible===null?null:Ye(g.visible,`${x}.visible`),opacity:I,atlasRow:g.atlasRow===null?null:X(g.atlasRow,`${x}.atlasRow`)}});return G(b.map(m=>m.leafId),`${l}.leaves`),{timeMs:p,modelMatrix:c.modelMatrix===null?null:le(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:Ye(r.loop,`${e}.loop`),frames:i}}function bt(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!==Pe&&h("invalid-schema","$.schema",`expected ${Pe}`);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")};uo.test(r.revision)||h("invalid-revision","$.identity.revision","expected x.y.z");let a=Z(t.profile,"$.profile");lt.has(a)||h("invalid-profile","$.profile",a);let i=A(t.capabilities,"$.capabilities").map((P,C)=>{let f=Z(P,`$.capabilities[${C}]`);return dt.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: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=yt(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:le(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)=>mt(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:le(p.modelMatrix,"$.render.modelMatrix"),shapes:y,leaves:b},u=ut(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=be(S.anchor,`${f}.anchor`),ee=be(S.axis,`${f}.axis`);Math.hypot(...ee)<1e-9&&h("invalid-control-axis",`${f}.axis`,"axis must be non-zero");let ge=J(S.radius,`${f}.radius`);ge<=0&&h("invalid-control-radius",`${f}.radius`,"radius must be positive");let Me=A(S.targets,`${f}.targets`).map((fe,je)=>{let j=`${f}.targets[${je}]`,Q=O(fe,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(Me.map(fe=>fe.targetId),`${f}.targets`),{id:H(S.id,`${f}.id`),anchor:q,axis:ee,radius:ge,minimum:M,maximum:R,initial:z,targets:Me}});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)=>Mt(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:Ye(S.loop,`${f}.loop`),channels:R}});G(w.map(P=>P.id),"$.animations");let W=t.playback===null?null:Pt(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&&!st.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 ne={generator:H(V.generator,"$.provenance.generator"),generatorVersion:Z(V.generatorVersion,"$.provenance.generatorVersion"),sources:B};uo.test(ne.generatorVersion)||h("invalid-revision","$.provenance.generatorVersion","expected x.y.z");let T=bt(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:Pe,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:ne}}function Ve(o){return ho.test(o)}function Ee(o){try{return go(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 Ge(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)=>Ge(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)}:${Ge(s,`${e}.${i}`,t)}`}).join(",")}}`;return t.delete(o),a}throw new k("invalid-json",e,"value is not JSON")}function Qe(o){return Ge(o,"$",new WeakSet)}function xe(o){return new TextEncoder().encode(Qe(o))}function $e(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 xt=/^[a-f0-9]{64}$/,$t=/^\d+\.\d+\.\d+$/,vt=/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/,wt=new Set(["joint-skin","morph-regions","prepared-playback","static-prepared"]),kt=new Set(["data","image","model"]);function N(o,e,t){throw new k(o,e,t)}function Te(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 Po(o,e){return Array.isArray(o)||N("invalid-type",e,"expected an array"),o}function de(o,e){return(typeof o!="string"||o.length===0)&&N("invalid-string",e,"expected a non-empty string"),o}function Xe(o,e){let t=de(o,e);return Ve(t)||N("invalid-id",e,"expected a normalized kebab-case id"),t}function Ze(o,e){let t=de(o,e);return Ee(t)||N("invalid-path",e,"expected a normalized package-relative path"),t}function bo(o,e){let t=de(o,e);return $t.test(t)||N("invalid-revision",e,"expected x.y.z"),t}function xo(o,e){let t=de(o,e);return wt.has(t)||N("invalid-profile",e,t),t}function $o(o,e){let t=de(o,e);return xt.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 Rt(o,e){let t=Te(o,e,["bytes","mediaType","path","role","sha256"]),n=de(t.role,`${e}.role`);kt.has(n)||N("invalid-role",`${e}.role`,n);let r=de(t.mediaType,`${e}.mediaType`).toLowerCase();return(!vt.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:Ze(t.path,`${e}.path`),role:n,mediaType:r,bytes:It(t.bytes,`${e}.bytes`),sha256:$o(t.sha256,`${e}.sha256`)}}function Ke(o,e){let t=new Set;for(let n of o)t.has(n)&&N("duplicate",e,n),t.add(n)}function vo(o,e){o.some((t,n)=>n>0&&t<=o[n-1])&&N("non-canonical-order",e,"entries must be unique and sorted")}function ve(o){let e=Te(o,"$",["identity","modelPath","profile","resources","schema"]);e.schema!==pe&&N("invalid-schema","$.schema",`expected ${pe}`);let t=Te(e.identity,"$.identity",["id","name","revision"]),n={id:Xe(t.id,"$.identity.id"),name:de(t.name,"$.identity.name"),revision:bo(t.revision,"$.identity.revision")},r=Po(e.resources,"$.resources").map((d,l)=>Rt(d,`$.resources[${l}]`));r.length===0&&N("missing-resource","$.resources","expected at least the model resource");let a=r.map(d=>d.path);Ke(a,"$.resources"),vo(a,"$.resources");let i=Ze(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:pe,identity:n,profile:xo(e.profile,"$.profile"),modelPath:i,resources:r}}function St(o,e){let t=Te(o,e,["id","manifestPath","manifestSha256","name","profile","revision"]),n=Ze(t.manifestPath,`${e}.manifestPath`);return n.endsWith("/manifest.json")||N("invalid-manifest-path",`${e}.manifestPath`,"expected a package manifest.json path"),{id:Xe(t.id,`${e}.id`),name:de(t.name,`${e}.name`),revision:bo(t.revision,`${e}.revision`),profile:xo(t.profile,`${e}.profile`),manifestPath:n,manifestSha256:$o(t.manifestSha256,`${e}.manifestSha256`)}}function we(o){let e=Te(o,"$",["defaultId","packages","schema"]);e.schema!==ce&&N("invalid-schema","$.schema",`expected ${ce}`);let t=Po(e.packages,"$.packages").map((a,i)=>St(a,`$.packages[${i}]`));t.length===0&&N("missing-package","$.packages","expected at least one package");let n=t.map(a=>a.id);Ke(n,"$.packages"),vo(n,"$.packages"),Ke(t.map(a=>a.manifestPath),"$.packages[*].manifestPath");let r=Xe(e.defaultId,"$.defaultId");return n.includes(r)||N("unknown-default","$.defaultId",r),{schema:ce,defaultId:r,packages:t}}var eo="model.json";function jt(o){return[...new Set(o.render.leaves.flatMap(e=>[...e.atlas?[e.atlas.resourcePath]:[],...e.fallback?[e.fallback.atlas.resourcePath]:[]]))].sort()}async function wo(o,e=[]){let t=F(o),n=xe(t),r=new Map([[eo,n]]),a=[{path:eo,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 jt(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=ve({schema:pe,identity:t.identity,profile:t.profile,modelPath:eo,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=xe(i);return{manifest:i,manifestBytes:d,manifestSha256:await se(d),files:r}}async function ko(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=we({schema:ce,defaultId:o,packages:t}),r=xe(n);return{catalog:n,bytes:r,sha256:await se(r)}}function Ue(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 Ro=64*1024*1024,Ct=1024,Tt=128*1024*1024,So=3e4;function ke(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 jo(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 Ot(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 oo(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 Ot(i,e.pathname,t)}async function Io(o,e,t){let n=await se(o);if(n!==e)throw new k("stale-hash",t,`expected ${e}, received ${n}`)}function At(o,e){let t=e.lastIndexOf("/");return Be(o,e.slice(0,t+1))}function Be(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 to(o,e={}){let t=jo(o),n=ke(e.maxResourceBytes,Ro,"$.maxResourceBytes"),r=e.fetchImpl??globalThis.fetch;if(typeof r!="function")throw new k("missing-fetch","$.fetchImpl","a fetch implementation is required");let a=ke(e.requestTimeoutMs,So,"$.requestTimeoutMs"),i=await oo(r,Be(t,"catalog.json"),n,e.signal,a);return{catalog:we($e(i,"$.catalog")),bytes:i,sha256:await se(i)}}async function Co(o,e={}){let t=jo(o),n=ke(e.maxResourceBytes,Ro,"$.maxResourceBytes"),r=ke(e.maxResources,Ct,"$.maxResources"),a=ke(e.maxTotalBytes,Tt,"$.maxTotalBytes"),i=ke(e.requestTimeoutMs,So,"$.requestTimeoutMs"),s=e.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new k("missing-fetch","$.fetchImpl","a fetch implementation is required");let d=await to(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 oo(s,Be(t,c.manifestPath),n,e.signal,i);await Io(p,c.manifestSha256,c.manifestPath);let y=ve($e(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=At(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 oo(s,Be(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 Io(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($e(v.bytes,"$.model"));if(Ue(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}}var te=require("@layoutit/polycss");var ye=class extends Error{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphRenderError",this.code=e,this.path=t}};var Lt={"atlas-slice":"s","direct-image":"s","solid-quad":"b","solid-triangle":"u"};function U(o,e,t){throw new ye(o,e,t)}function ro(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 ue(o){return`matrix3d(${(0,te.formatMatrix3dValues)(o)})`}function zt(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 no(o,e,t){return t&&o.fallback?zt(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 ao(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 Et(o,e){let t=ao(o,e,["matrix","shapeId"]);return typeof t.shapeId!="string"&&U("invalid-update",`${e}.shapeId`,"expected a string"),{shapeId:t.shapeId,matrix:ro(t.matrix,`${e}.matrix`)}}function Ut(o,e){let t=ao(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=ro(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 Bt(o){let e=ao(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)=>Et(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)=>Ut(a,`$.leaves[${i}]`));return To(r.map(a=>a.leafId),"$.leaves"),r})();return{...e.modelMatrix===void 0?{}:{modelMatrix:ro(e.modelMatrix,"$.modelMatrix")},...t===void 0?{}:{shapes:t},...n===void 0?{}:{leaves:n}}}function Dt(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 Nt(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 _t(o,e,t,n,r){let a=r?e.fallback:null,i=o.createElement(a?"s":Lt[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=ue(no(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`,Dt(i,e,e.atlas,n(e.atlas.resourcePath,e.id))):a?Nt(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 Oo(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")&&!(0,te.isSolidTriangleSupported)(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(),me=s.createObjectURL(new d([ee.buffer],{type:q.descriptor.mediaType}));return i.set(M,me),me};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}(0,te.injectPolyBaseStyles)(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??(0,te.createPolyCamera)({zoom:1}),u=r.createElement("div");u.className="polycss-camera polycss-morph-camera";let x=(0,te.capturePolyCameraSnapshot)(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=(0,te.buildPolyCameraSceneTransform)(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=ue(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=ue(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=_t(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:ue(no(M,M.matrix,a&&M.strategy==="solid-triangle")),visible:!0,opacity:1,atlasRow:0})}let ne=[...$.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!==ne.length||V.size!==T.length)&&U("identity-drift","$","retained handle maps changed");for(let[M,R]of ne)($.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=Bt(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 Le;if(j.atlasRow!==void 0){let oe=Q.plan.atlas;oe||U("invalid-atlas-row",j.leafId,"leaf has no image rows");let fo=oe.y+j.atlasRow*oe.height;fo+oe.height>oe.pageHeight&&U("invalid-atlas-row",j.leafId,"row exceeds the image page"),Le=`${-oe.x}px ${-fo}px`}return{leaf:j,handle:Q,state:Y,atlasPosition:Le}});C();let ee=0,me=0,ge=0,Me=0,fe=0,je=0;if(R.modelMatrix){let j=ue(R.modelMatrix);E!==j&&(E=j,I.style.transform=j,ee+=1)}for(let{shape:j,element:Q}of z){let Y=ue(j.matrix);w.get(j.shapeId)!==Y&&(w.set(j.shapeId,Y),Q.style.transform=Y,me+=1)}for(let{leaf:j,handle:Q,state:Y,atlasPosition:Le}of q){if(j.matrix){let oe=ue(no(Q.plan,j.matrix,a&&Q.plan.strategy==="solid-triangle"));Y.transform!==oe&&(Y.transform=oe,Q.element.style.transform=oe,ge+=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,Me+=1)}if(j.opacity!==void 0){let oe=String(j.opacity);Y.opacity!==j.opacity&&(Y.opacity=j.opacity,Q.element.style.opacity=oe,fe+=1)}j.atlasRow!==void 0&&Y.atlasRow!==j.atlasRow&&(Y.atlasRow=j.atlasRow,Q.element.style.backgroundPosition=Le,je+=1)}return C(),_.applyCount+=1,_.totalTransformWrites+=ee+me+ge,_.totalVisibilityWrites+=Me,_.totalOpacityWrites+=fe,_.totalAtlasRowWrites+=je,{modelTransformWrites:ee,shapeTransformWrites:me,leafTransformWrites:ge,visibilityWrites:Me,opacityWrites:fe,atlasRowWrites:je,dirtyLeavesVisited:R.leaves?.length??0,domCreations:0,domRemovals:0,topologyConstructions:0,atlasRedraws:0,schedulerCallbacks:0}},updateCamera(){P();let M=(0,te.buildPolyCameraSceneTransform)(m.state);if(D===M)return!1;D=M,g.style.transform=M;let R=(0,te.capturePolyCameraSnapshot)(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 ae(o,e,t){throw new ye(o,e,t)}function io(o,e){let t=o;return(!t||typeof t!="object"||!t.ownerDocument||typeof t.style?.setProperty!="function")&&ae("invalid-target",e,"expected an HTMLElement"),t}function Lo(o,e){return typeof o!="string"&&ae("invalid-transform",e,"expected a CSS transform string"),o}function Ao(o,e,t){let n,r,a,i;return Object.freeze({element:o,writeTransform(s){t();let d=Lo(s,`${e}.transform`);return n===d?!1:(o.style.transform=d,n=d,!0)},writeVisibility(s){return t(),typeof s!="boolean"&&ae("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)&&ae("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)&&ae("invalid-image-position",`${e}.imagePositionY`,"expected a CSS position"),i===s?!1:(o.style.backgroundPositionY=s,i=s,!0)}})}function zo(o){(!o||typeof o!="object"||Array.isArray(o))&&ae("invalid-target","$","expected a prepared DOM target");let e=io(o.model?.element,"$.model.element");typeof o.model?.writeTransform!="function"&&ae("invalid-target","$.model.writeTransform","expected a transform writer"),(!Array.isArray(o.shapes)||!Array.isArray(o.leaves))&&ae("invalid-target","$","expected shape and leaf target arrays");let t=o.shapes.map((m,u)=>io(m?.element,`$.shapes[${u}].element`)),n=o.leaves.map((m,u)=>io(m?.element,`$.leaves[${u}].element`)),r=e.parentNode,a=t.map(m=>m.parentNode),i=n.map(m=>m.parentNode),s=!1,d=()=>{s&&ae("target-destroyed","$","prepared DOM target is destroyed")},l=Object.freeze(t.map((m,u)=>Ao(m,`$.shapes[${u}]`,d))),c=Object.freeze(n.map((m,u)=>Ao(m,`$.leaves[${u}]`,d))),p,y=Object.freeze({element:e,writeTransform(m){d();let u=Lo(m,"$.model.transform");if(p===u)return!1;let x=o.model.writeTransform(u);return typeof x!="boolean"&&ae("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]))&&ae("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 Vo(o,e,t){throw new K(o,e,t)}function De(o){return Object.freeze([...o])}function Ht(o,e){let{timesMs:t,values:n}=o;if(e<=t[0])return De(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 De(d);if(o.interpolation==="step")return De(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 De(n[n.length-1])}function Ft(o,e){if(o.loop){let t=e%o.durationMs;return Object.is(t,-0)?0:t}return Math.min(e,o.durationMs)}function Ne(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||Vo("unknown-clip","$.clipId",n),(!Number.isFinite(r)||r<0)&&Vo("invalid-time","$.timeMs","expected a finite non-negative time");let i=Ft(a,r),s={},d={},l=new Map,c=new Map;for(let p of a.channels){let y=Ht(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 so(o,e,t){throw new K(o,e,t)}function Eo(o){return o===null?null:((!Array.isArray(o)||o.length!==3||o.some(e=>typeof e!="number"||!Number.isFinite(e)))&&so("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 Uo(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 Bo(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 lo(o,e){let t=Eo(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 Do(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&so("invalid-state","$.state","control state is invalid"),typeof t?.active!="boolean"&&so("invalid-input","$.active","expected a boolean");let n=Eo(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=lo(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=qt(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})}var Ie=require("@layoutit/polycss");function re(o,e,t){throw new K(o,e,t)}function Jt(o,e){return(typeof o!="number"||!Number.isFinite(o))&&re("invalid-number",e,"expected a finite number"),Object.is(o,-0)?0:o}function _o(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function _e(o){return o.map(e=>[e[0],e[1],e[2]])}function He(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function Wt(o,e){let[t,n,r]=o.vertexIndices,a=e[t],i=e[n],s=e[r],d=(0,Ie.computeSolidTrianglePlanFromCssPoints)(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||re("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)))&&re("invalid-transform",o.leaf.id,"PolyCSS returned an invalid matrix3d");let p=Ie.SOLID_TRIANGLE_CANONICAL_SIZE/o.leaf.width,y=Ie.SOLID_TRIANGLE_CANONICAL_SIZE/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 Yt(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&&re("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=_o(b);return Math.hypot(...m)<=1e-12&&re("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 co(o,e){if(o.vertexIndices.length===3)return Wt(o,e);if(o.vertexIndices.length===4)return Yt(o,e);re("unsupported-deformation",o.leaf.id,"caller-driven deformation supports prepared triangles and affine quads")}function po(o,e){let t=o.topology.polygons.find(i=>i.id===e.polygonId);t||re("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=(0,Ie.computeSolidTrianglePlanFromCssPoints)(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||re("degenerate-polygon",e.id,"base triangle has no area"),a=l.basis}return{leaf:e,vertexIndices:t.vertexIndices,polygon:r,basis:a}}function No(o,e,t,n){let r=o??{};(!r||typeof r!="object"||Array.isArray(r))&&re("invalid-input",t,"expected an object");let a=new Set(e),i=Object.keys(r).find(s=>!a.has(s));return i&&re("unknown-id",t,i),Object.fromEntries(e.map(s=>{let[d,l]=n.get(s)??[0,1],c=Jt(r[s]??0,`${t}.${s}`);return(c<d||c>l)&&re("out-of-range",`${t}.${s}`,`expected ${d} <= value <= ${l}`),[s,c]}))}function Gt(o){return new Map(o.deformation.kind==="morph-regions"?o.deformation.targets.map(e=>[e.id,e]):[])}function Ho(o){let e=F(o);e.deformation.kind==="joint-skin"&&re("profile-not-executable","$.profile","joint skin requires the skinning runtime");let t=Gt(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,po(e,g)])),p=He(_e(e.topology.vertices)),y=He(_e(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)&&re("invalid-tick","$.tick","expected a non-negative safe integer");let v=No(g.morphWeights,n,"$.morphWeights",a),I=No(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=_e(p),L=_e(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(_o),w=He(T),W=He(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)),ne=B.map(T=>{let L=co(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(ne),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 Oe(o,e,t){throw new K(o,e,t)}function Re(o){return Object.freeze([...o])}function yo(o,e){return o.every((t,n)=>t===e[n])}function Fe(o){let e=F(o);return Object.freeze({modelMatrix:Re(e.render.modelMatrix),shapes:Object.freeze(e.render.shapes.map(t=>Object.freeze({shapeId:t.id,matrix:Re(t.matrix)}))),leaves:Object.freeze(e.render.leaves.map(t=>Object.freeze({leafId:t.id,matrix:Re(t.matrix),visible:!0,opacity:1,atlasRow:0})))})}function qe(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)||Oe("unknown-shape","$.frame.shapes",r);for(let r of n.keys())o.leaves.some(a=>a.leafId===r)||Oe("unknown-leaf","$.frame.leaves",r);return Object.freeze({modelMatrix:e.modelMatrix===null?o.modelMatrix:Re(e.modelMatrix),shapes:Object.freeze(o.shapes.map(r=>{let a=t.get(r.shapeId);return a?Object.freeze({shapeId:r.shapeId,matrix:Re(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:Re(a.matrix),visible:a.visible??r.visible,opacity:a.opacity??r.opacity,atlasRow:a.atlasRow??r.atlasRow}):r}))})}function Je(o,e){(o.shapes.length!==e.shapes.length||o.leaves.length!==e.leaves.length)&&Oe("state-mismatch","$","prepared state topology differs");let t=!yo(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&&Oe("state-mismatch","$.shapes","source order differs"),yo(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&&Oe("state-mismatch","$.leaves","source order differs");let d={leafId:s.leafId};yo(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 Qt(o,e,t){if(e){let n=t%o;return Object.is(n,-0)?0:n}return Math.min(t,o)}function Kt(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 Fo(o){let e=F(o);(e.profile!=="prepared-playback"||!e.playback)&&Ae("profile-mismatch","$.profile","playback requires the prepared-playback profile");let t=e.playback,n=Fe(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||Ae("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&&Ae("invalid-atlas-row",`$.playback.frames[${p}]`,`${m.id} row exceeds its page`)}a=qe(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=Qt(t.durationMs,t.loop,p),b=Kt(s,y),m=r[b],u=Je(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&&Ae("invalid-sample","$.sample","commit requires the latest unapplied playback sample"),d=p.state,l=null},reset(){d=n,l=null}})}var qo=Object.freeze(["joint-skin","morph-regions","prepared-playback","static-prepared"]);function ie(o,e,t){throw new K(o,e,t)}function Xt(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function mo(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 Zt(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)))&&ie("invalid-quaternion",e,"expected four finite components");let t=Math.hypot(...o);return t<=1e-12&&ie("invalid-quaternion",e,"quaternion must be non-zero"),[o[0]/t,o[1]/t,o[2]/t,o[3]/t]}function Jo(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)))&&ie("invalid-vector",t,"expected three finite components"),n&&o.some(r=>r<=0)&&ie("invalid-scale",t,"scale components must be positive"),[o[0],o[1],o[2]])}function Go(o,e){if(o===void 0)return Xt();(!o||typeof o!="object"||Array.isArray(o))&&ie("invalid-joint-transform",e,"expected an object"),Object.keys(o).some(v=>v!=="translation"&&v!=="rotation"&&v!=="scale")&&ie("invalid-joint-transform",e,"unknown transform field");let n=Jo(o.translation,[0,0,0],`${e}.translation`),r=Jo(o.scale,[1,1,1],`${e}.scale`,!0),[a,i,s,d]=Zt(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 en(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 on(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&&ie("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 tn(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function Se(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function nn(o,e){return o.every((t,n)=>Math.abs(t-e[n])<=1e-12)}function Wo(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=mo(a.restMatrix,Go(e.get(a.id),`$.jointTransforms.${a.id}`)),d=a.parentId===null?s:mo(r(t.get(a.parentId)),s);return n.set(a.id,d),d};for(let a of o)r(a);return n}function Yo(o,e){return new Map(o.map(t=>[t.id,mo(e.get(t.id),t.inverseBindMatrix)]))}function rn(o,e){let t=o??new Map;(!t||typeof t.entries!="function")&&ie("invalid-joint-transform","$.jointTransforms","expected a map");for(let[n,r]of t)e.has(n)||ie("unknown-joint","$.jointTransforms",n),Go(r,`$.jointTransforms.${n}`);return t}function Qo(o){let e=F(o);e.deformation.kind!=="joint-skin"&&ie("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=Wo(t.joints,new Map),i=Yo(t.joints,a),s=Se(e.topology.vertices.map(w=>[...w])),d=Se(e.topology.normals.map(w=>[...w])),l=new Map(e.render.leaves.map(w=>[w.id,po(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 ne=y.get(B),T=[0,0,0],L=[0,0,0];for(let D of ne.influences){let _=w.get(D.jointId),P=en(_,s[B]),C=on(_,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(tn(L))}return{positions:W,normals:V}},m=b(i),u=Se(m.positions),x=Se(m.normals),g=new Map(i),v=u,I=x,E=Ne(e),$=w=>{(!w||!Number.isSafeInteger(w.tick)||w.tick<0)&&ie("invalid-tick","$.tick","expected a non-negative safe integer");let W=rn(w.jointTransforms,r),V=Wo(t.joints,W),B=Yo(t.joints,V),ne=new Set(n.filter(f=>!nn(B.get(f),g.get(f)))),T=v,L=I;if(ne.size>0){let f=b(B);T=Se(f.positions),L=Se(f.normals)}let D=new Set;if(ne.size>0)for(let f of t.vertices)f.influences.some(S=>ne.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=co(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 he(o,e,t){throw new K(o,e,t)}function an(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 Ko(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 Xo(o,e){let t=Object.keys(e??{}).find(r=>!o.controls.has(r));t&&he("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)&&he("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 Zo(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&he("invalid-state","$.state","spring state is invalid"),(!Number.isFinite(t?.deltaMs)||t.deltaMs<=0||t.deltaMs>1e3)&&he("invalid-time","$.deltaMs","expected 0 < deltaMs <= 1000");let n=t.heldTarget??null;if(n){let l=o.controls.get(n.controlId);l||he("unknown-id","$.heldTarget.controlId",n.controlId),(!Number.isFinite(n.value)||n.value<l.minimum||n.value>l.maximum)&&he("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)||he("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]=an(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})}0&&(module.exports={POLY_MORPH_CATALOG_SCHEMA,POLY_MORPH_EXECUTABLE_PROFILES,POLY_MORPH_MODEL_SCHEMA,POLY_MORPH_PACKAGE_SCHEMA,PolyMorphContractError,PolyMorphPackageError,PolyMorphRenderError,PolyMorphRuntimeError,applyPolyMorphPlaybackFrame,assertPolyMorphPackageModelBinding,buildPolyMorphCatalog,buildPolyMorphPackage,createPolyMorphAnimationRuntime,createPolyMorphControlRuntime,createPolyMorphControlState,createPolyMorphDeformationRuntime,createPolyMorphPlaybackRuntime,createPolyMorphPreparedDomTarget,createPolyMorphPreparedState,createPolyMorphSkinningRuntime,createPolyMorphSpringRuntime,createPolyMorphSpringState,decodePolyMorphJson,diffPolyMorphPreparedStates,encodePolyMorphCanonicalJson,hashPolyMorphBytes,isPolyMorphId,isPolyMorphResourcePath,loadPolyMorphCatalog,loadPolyMorphPackage,mountPolyMorphModel,pickPolyMorphControl,stepPolyMorphControls,stepPolyMorphSprings,stringifyPolyMorphCanonicalJson,validatePolyMorphCatalog,validatePolyMorphModel,validatePolyMorphPackageManifest});
|
|
1
|
+
"use strict";var Xe=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.prototype.hasOwnProperty;var lt=(o,e)=>{for(var t in e)Xe(o,t,{get:e[t],enumerable:!0})},dt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of it(e))!st.call(o,r)&&r!==t&&Xe(o,r,{get:()=>e[r],enumerable:!(n=at(e,r))||n.enumerable});return o};var ct=o=>dt(Xe({},"__esModule",{value:!0}),o);var Mn={};lt(Mn,{POLY_MORPH_CATALOG_SCHEMA:()=>he,POLY_MORPH_EXECUTABLE_PROFILES:()=>Qo,POLY_MORPH_MODEL_SCHEMA:()=>$e,POLY_MORPH_PACKAGE_SCHEMA:()=>ge,PolyMorphContractError:()=>Ae,PolyMorphPackageError:()=>I,PolyMorphRenderError:()=>Me,PolyMorphRuntimeError:()=>X,applyPolyMorphPlaybackFrame:()=>Ye,assertPolyMorphPackageModelBinding:()=>De,buildPolyMorphCatalog:()=>jo,buildPolyMorphPackage:()=>So,createPolyMorphAnimationRuntime:()=>qe,createPolyMorphControlRuntime:()=>qo,createPolyMorphControlState:()=>Ho,createPolyMorphDeformationRuntime:()=>Yo,createPolyMorphPlaybackRuntime:()=>Go,createPolyMorphPreparedDomTarget:()=>Do,createPolyMorphPreparedState:()=>We,createPolyMorphSkinningRuntime:()=>ot,createPolyMorphSpringRuntime:()=>tt,createPolyMorphSpringState:()=>nt,decodePolyMorphJson:()=>ke,diffPolyMorphPreparedStates:()=>Ge,encodePolyMorphCanonicalJson:()=>we,hashPolyMorphBytes:()=>de,isPolyMorphId:()=>Be,isPolyMorphResourcePath:()=>Ne,loadPolyMorphCatalog:()=>io,loadPolyMorphPackage:()=>Ao,mountPolyMorphModel:()=>Uo,pickPolyMorphControl:()=>mo,stepPolyMorphControls:()=>Jo,stepPolyMorphSprings:()=>rt,stringifyPolyMorphCanonicalJson:()=>eo,validatePolyMorphCatalog:()=>Re,validatePolyMorphModel:()=>Y,validatePolyMorphPackageManifest:()=>Ie});module.exports=ct(Mn);var $e="polycss-morph.model@1",he="polycss-morph.catalog@1",ge="polycss-morph.package@1";var bo=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,pt=/^[a-z0-9][a-z0-9._-]*$/,Po=/^\d+\.\d+\.\d+$/,yt=/^[a-f0-9]{64}$/,mt=new Set(["joint-skin","morph-regions","prepared-playback","static-prepared"]),ut=new Set(["animation","joint-skinning","morph-targets","prepared-playback","retained-render","semantic-controls","sparse-updates","springs"]),ft=new Set(["atlas-slice","direct-image","solid-quad","solid-triangle"]),ht=new Set(["control-value","joint-rotation","joint-scale","joint-translation","morph-weight","shape-matrix"]),Ae=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 Ae(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 ne(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 K(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 Ke(o,e){return typeof o!="boolean"&&g("invalid-boolean",e,"expected a boolean"),o}function W(o,e){let t=ne(o,e);return bo.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 ve(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 ye(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 xo(o,e){let t=ne(o,e);return t.split("/").some(n=>!pt.test(n))&&g("invalid-path",e,"expected lowercase URL-safe package path segments"),t}function Ue(o,e,t){let n=K(o,e);return n>=t&&g("out-of-range",e,`expected an index below ${t}`),n}function gt(o,e){let t=A(o,e,["normals","polygons","vertices"]),n=z(t.vertices,`${e}.vertices`).map((i,s)=>ve(i,`${e}.vertices[${s}]`)),r=z(t.normals,`${e}.normals`).map((i,s)=>ve(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)=>Ue(y,`${d}.vertexIndices[${P}]`,n.length)),p=z(l.normalIndices,`${d}.normalIndices`).map((y,P)=>Ue(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 Mt(o,e,t){let n=A(o,e,["atlas","fallback","height","id","materialId","matrix","polygonId","shapeId","strategy","width"]),r=ne(n.strategy,`${e}.strategy`);ft.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:$o(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:Pt(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:ye(n.matrix,`${e}.matrix`),atlas:p,fallback:y}}function Pt(o,e){let t=A(o,e,["atlas","height","matrixFromLeaf","width"]),n=K(t.width,`${e}.width`,1),r=K(t.height,`${e}.height`,1),a=$o(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:ye(t.matrixFromLeaf,`${e}.matrixFromLeaf`),atlas:a}}function $o(o,e){let t=A(o,e,["height","pageHeight","pageWidth","resourcePath","width","x","y"]),n={resourcePath:xo(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)&&g("out-of-range",e,"slice must fit inside its page"),n}function bt(o,e,t){(!o||typeof o!="object"||Array.isArray(o))&&g("invalid-type",e,"expected a deformation object");let n=ne(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:ve(f.position,`${m}.position`),h=f.normal===null?null:ve(f.normal,`${m}.normal`);return b===null&&h===null&&g("empty-delta",m,"expected a position or normal delta"),{vertexIndex:Ue(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:ye(y.restMatrix,`${p}.restMatrix`),inverseBindMatrix:ye(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`),xt(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=Ue(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 xt(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 $t(o){return o==="control-value"||o==="morph-weight"?1:o==="joint-rotation"?4:o==="shape-matrix"?16:3}function vt(o,e,t,n){let r=A(o,e,["interpolation","target","targetId","timesMs","values"]),a=ne(r.target,`${e}.target`);ht.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=ne(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=$t(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 wt(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:ye(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:ye(h.matrix,`${b}.matrix`),visible:h.visible===null?null:Ke(h.visible,`${b}.visible`),opacity:k,atlasRow:h.atlasRow===null?null:K(h.atlasRow,`${b}.atlasRow`)}});return Q(P.map(m=>m.leafId),`${l}.leaves`),{timeMs:p,modelMatrix:c.modelMatrix===null?null:ye(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:Ke(r.loop,`${e}.loop`),frames:i}}function kt(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!==$e&&g("invalid-schema","$.schema",`expected ${$e}`);let n=A(t.identity,"$.identity",["id","name","revision"]),r={id:W(n.id,"$.identity.id"),name:ne(n.name,"$.identity.name"),revision:ne(n.revision,"$.identity.revision")};Po.test(r.revision)||g("invalid-revision","$.identity.revision","expected x.y.z");let a=ne(t.profile,"$.profile");mt.has(a)||g("invalid-profile","$.profile",a);let i=z(t.capabilities,"$.capabilities").map((M,S)=>{let u=ne(M,`$.capabilities[${S}]`);return ut.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: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=gt(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:ye(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)=>Mt(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:ye(p.modelMatrix,"$.render.modelMatrix"),shapes:y,leaves:P},f=bt(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=ve(R.anchor,`${u}.anchor`),H=ve(R.axis,`${u}.axis`);Math.hypot(...H)<1e-9&&g("invalid-control-axis",`${u}.axis`,"axis must be non-zero");let ue=G(R.radius,`${u}.radius`);ue<=0&&g("invalid-control-radius",`${u}.radius`,"radius must be positive");let pe=z(R.targets,`${u}.targets`).map((Pe,Oe)=>{let fe=`${u}.targets[${Oe}]`,xe=A(Pe,fe,["scale","targetId"]),T=W(xe.targetId,`${fe}.targetId`);return b.has(T)||g("unknown-reference",`${fe}.targetId`,T),{targetId:T,scale:G(xe.scale,`${fe}.scale`)}});return Q(pe.map(Pe=>Pe.targetId),`${u}.targets`),{id:W(R.id,`${u}.id`),anchor:C,axis:H,radius:ue,minimum:j,maximum:D,initial:x,targets:pe}});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)=>vt(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:Ke(R.loop,`${u}.loop`),channels:D}});Q(w.map(M=>M.id),"$.animations");let L=t.playback===null?null:wt(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=ne(R.kind,`${u}.kind`);j!=="authored"&&j!=="generated"&&j!=="open-data"&&g("invalid-source-kind",`${u}.kind`,j);let D=ne(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:ne(R.sha256,`${u}.sha256`);return x!==null&&!yt.test(x)&&g("invalid-hash",`${u}.sha256`,"expected lowercase SHA-256"),{id:W(R.id,`${u}.id`),kind:j,uri:D,sha256:x,license:ne(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:ne(E.generatorVersion,"$.provenance.generatorVersion"),sources:B};Po.test(q.generatorVersion)||g("invalid-revision","$.provenance.generatorVersion","expected x.y.z");let O=kt(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:$e,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 Be(o){return bo.test(o)}function Ne(o){try{return xo(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 Ze(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)=>Ze(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)}:${Ze(s,`${e}.${i}`,t)}`}).join(",")}}`;return t.delete(o),a}throw new I("invalid-json",e,"value is not JSON")}function eo(o){return Ze(o,"$",new WeakSet)}function we(o){return new TextEncoder().encode(eo(o))}function ke(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 de(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}$/,Rt=/^\d+\.\d+\.\d+$/,St=/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/,jt=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 ze(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 vo(o,e){return Array.isArray(o)||J("invalid-type",e,"expected an array"),o}function me(o,e){return(typeof o!="string"||o.length===0)&&J("invalid-string",e,"expected a non-empty string"),o}function to(o,e){let t=me(o,e);return Be(t)||J("invalid-id",e,"expected a normalized kebab-case id"),t}function no(o,e){let t=me(o,e);return Ne(t)||J("invalid-path",e,"expected a normalized package-relative path"),t}function wo(o,e){let t=me(o,e);return Rt.test(t)||J("invalid-revision",e,"expected x.y.z"),t}function ko(o,e){let t=me(o,e);return jt.has(t)||J("invalid-profile",e,t),t}function Io(o,e){let t=me(o,e);return It.test(t)||J("invalid-hash",e,"expected lowercase SHA-256"),t}function Tt(o,e){return(typeof o!="number"||!Number.isSafeInteger(o)||o<0)&&J("invalid-bytes",e,"expected a non-negative safe integer"),o}function Ot(o,e){let t=ze(o,e,["bytes","mediaType","path","role","sha256"]),n=me(t.role,`${e}.role`);Ct.has(n)||J("invalid-role",`${e}.role`,n);let r=me(t.mediaType,`${e}.mediaType`).toLowerCase();return(!St.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:no(t.path,`${e}.path`),role:n,mediaType:r,bytes:Tt(t.bytes,`${e}.bytes`),sha256:Io(t.sha256,`${e}.sha256`)}}function oo(o,e){let t=new Set;for(let n of o)t.has(n)&&J("duplicate",e,n),t.add(n)}function Ro(o,e){o.some((t,n)=>n>0&&t<=o[n-1])&&J("non-canonical-order",e,"entries must be unique and sorted")}function Ie(o){let e=ze(o,"$",["identity","modelPath","profile","resources","schema"]);e.schema!==ge&&J("invalid-schema","$.schema",`expected ${ge}`);let t=ze(e.identity,"$.identity",["id","name","revision"]),n={id:to(t.id,"$.identity.id"),name:me(t.name,"$.identity.name"),revision:wo(t.revision,"$.identity.revision")},r=vo(e.resources,"$.resources").map((d,l)=>Ot(d,`$.resources[${l}]`));r.length===0&&J("missing-resource","$.resources","expected at least the model resource");let a=r.map(d=>d.path);oo(a,"$.resources"),Ro(a,"$.resources");let i=no(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:ge,identity:n,profile:ko(e.profile,"$.profile"),modelPath:i,resources:r}}function Lt(o,e){let t=ze(o,e,["id","manifestPath","manifestSha256","name","profile","revision"]),n=no(t.manifestPath,`${e}.manifestPath`);return n.endsWith("/manifest.json")||J("invalid-manifest-path",`${e}.manifestPath`,"expected a package manifest.json path"),{id:to(t.id,`${e}.id`),name:me(t.name,`${e}.name`),revision:wo(t.revision,`${e}.revision`),profile:ko(t.profile,`${e}.profile`),manifestPath:n,manifestSha256:Io(t.manifestSha256,`${e}.manifestSha256`)}}function Re(o){let e=ze(o,"$",["defaultId","packages","schema"]);e.schema!==he&&J("invalid-schema","$.schema",`expected ${he}`);let t=vo(e.packages,"$.packages").map((a,i)=>Lt(a,`$.packages[${i}]`));t.length===0&&J("missing-package","$.packages","expected at least one package");let n=t.map(a=>a.id);oo(n,"$.packages"),Ro(n,"$.packages"),oo(t.map(a=>a.manifestPath),"$.packages[*].manifestPath");let r=to(e.defaultId,"$.defaultId");return n.includes(r)||J("unknown-default","$.defaultId",r),{schema:he,defaultId:r,packages:t}}var ro="model.json";function At(o){return[...new Set(o.render.leaves.flatMap(e=>[...e.atlas?[e.atlas.resourcePath]:[],...e.fallback?[e.fallback.atlas.resourcePath]:[]]))].sort()}async function So(o,e=[]){let t=Y(o),n=we(t),r=new Map([[ro,n]]),a=[{path:ro,role:"model",mediaType:"application/json",bytes:n.byteLength,sha256:await de(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 de(c)})}for(let l of At(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=Ie({schema:ge,identity:t.identity,profile:t.profile,modelPath:ro,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=we(i);return{manifest:i,manifestBytes:d,manifestSha256:await de(d),files:r}}async function jo(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=Re({schema:he,defaultId:o,packages:t}),r=we(n);return{catalog:n,bytes:r,sha256:await de(r)}}function De(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 To=64*1024*1024,zt=1024,Vt=128*1024*1024,Oo=3e4;function Se(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 Lo(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 Et(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 ao(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 Et(i,e.pathname,t)}async function Co(o,e,t){let n=await de(o);if(n!==e)throw new I("stale-hash",t,`expected ${e}, received ${n}`)}function Ut(o,e){let t=e.lastIndexOf("/");return Fe(o,e.slice(0,t+1))}function Fe(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 io(o,e={}){let t=Lo(o),n=Se(e.maxResourceBytes,To,"$.maxResourceBytes"),r=e.fetchImpl??globalThis.fetch;if(typeof r!="function")throw new I("missing-fetch","$.fetchImpl","a fetch implementation is required");let a=Se(e.requestTimeoutMs,Oo,"$.requestTimeoutMs"),i=await ao(r,Fe(t,"catalog.json"),n,e.signal,a);return{catalog:Re(ke(i,"$.catalog")),bytes:i,sha256:await de(i)}}async function Ao(o,e={}){let t=Lo(o),n=Se(e.maxResourceBytes,To,"$.maxResourceBytes"),r=Se(e.maxResources,zt,"$.maxResources"),a=Se(e.maxTotalBytes,Vt,"$.maxTotalBytes"),i=Se(e.requestTimeoutMs,Oo,"$.requestTimeoutMs"),s=e.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new I("missing-fetch","$.fetchImpl","a fetch implementation is required");let d=await io(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 ao(s,Fe(t,c.manifestPath),n,e.signal,i);await Co(p,c.manifestSha256,c.manifestPath);let y=Ie(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 I("profile-mismatch","$.manifest","catalog row does not match its manifest");let P=Ut(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 ao(s,Fe(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 Co(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(ke($.bytes,"$.model"));if(De(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}}var ee=require("@layoutit/polycss");var Me=class extends Error{constructor(e,t,n){super(`${t}: ${n}`),this.name="PolyMorphRenderError",this.code=e,this.path=t}};var Bt={"atlas-slice":"s","direct-image":"s","solid-quad":"b","solid-triangle":"u"},zo=1e-12;function U(o,e,t){throw new Me(o,e,t)}function lo(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 Nt(o){return o.map(e=>String(Object.is(e,-0)?0:e)).join(",")}function je(o,e=!1){return`matrix3d(${e?Nt(o):(0,ee.formatMatrix3dValues)(o)})`}function Dt(o,e){return e&&o.fallback?[o.fallback.width,o.fallback.height]:[o.width,o.height]}function Ft(o,e,t){let[n,r]=Dt(e,t);return Math.abs(o[3]*n)>zo||Math.abs(o[7]*r)>zo}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 qt(o,e,t){return t&&o.fallback?_t(e,o.fallback.matrixFromLeaf):e}function so(o,e,t){let n=qt(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:Ft(n,o,t)}}function Eo(o,e,t){let n=so(o,e,t);return je(n.matrix,n.projective)}function Ht(o){let[e,t,n,r]=o;return`rgba(${Math.round(e*255)}, ${Math.round(t*255)}, ${Math.round(n*255)}, ${r})`}function co(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 Vo(o,e){let t=new Set;for(let n of o)t.has(n)&&U("duplicate-update",e,n),t.add(n)}function Jt(o,e){let t=co(o,e,["matrix","shapeId"]);return typeof t.shapeId!="string"&&U("invalid-update",`${e}.shapeId`,"expected a string"),{shapeId:t.shapeId,matrix:lo(t.matrix,`${e}.matrix`)}}function Wt(o,e){let t=co(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=lo(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 Yt(o){let e=co(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)=>Jt(a,`$.shapes[${i}]`));return Vo(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)=>Wt(a,`$.leaves[${i}]`));return Vo(r.map(a=>a.leafId),"$.leaves"),r})();return{...e.modelMatrix===void 0?{}:{modelMatrix:lo(e.modelMatrix,"$.modelMatrix")},...t===void 0?{}:{shapes:t},...n===void 0?{}:{leaves:n}}}function Gt(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 Qt(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 Xt(o,e,t,n,r){let a=r?e.fallback:null,i=o.createElement(a?"s":Bt[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=Eo(e,e.matrix,a!==null),i.style.color=Ht(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`,Gt(i,e,e.atlas,n(e.atlas.resourcePath,e.id))):a?Qt(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 Uo(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=!(0,ee.safariCssProjectiveUnsupported)(a),s=n.render.leaves.some(x=>x.strategy==="solid-triangle")&&!(0,ee.isSolidTriangleSupported)(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 re=t.resources?.get(x);(!re||re.descriptor.path!==x||re.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 ue=re.bytes.slice(),pe=l.createObjectURL(new c([ue.buffer],{type:re.descriptor.mediaType}));return d.set(x,pe),pe};try{for(let x of n.render.leaves){let C=s&&x.strategy==="solid-triangle",H=so(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}(0,ee.injectPolyBaseStyles)(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??(0,ee.createPolyCamera)({zoom:1}),h=r.createElement("div");h.className="polycss-camera polycss-morph-camera";let $=(0,ee.capturePolyCameraSnapshot)(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=(0,ee.buildPolyCameraSceneTransform)(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=je(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=je(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 re=Xt(r,x,H.color,y,s&&x.strategy==="solid-triangle");C.appendChild(re),q.set(x.id,{id:x.id,plan:x,element:re}),O.set(x.id,{transform:Eo(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=Yt(x),H=(C.shapes??[]).map(T=>{let oe=L.get(T.shapeId);return oe||U("unknown-shape",T.shapeId,"no retained shape handle"),{shape:T,element:oe}}),re=(C.leaves??[]).map(T=>{let oe=q.get(T.leafId),te=O.get(T.leafId);(!oe||!te)&&U("unknown-leaf",T.leafId,"no retained leaf handle");let Qe=s&&oe.plan.strategy==="solid-triangle",Le;if(T.matrix){let le=so(oe.plan,T.matrix,Qe);!i&&le.projective&&U("unsupported-projective-quad",`${T.leafId}.matrix`,"this browser does not support projective leaf matrices"),Le=je(le.matrix,le.projective)}let se;if(T.atlasRow!==void 0){let le=oe.plan.atlas;le||U("invalid-atlas-row",T.leafId,"leaf has no image rows");let Mo=le.y+T.atlasRow*le.height;Mo+le.height>le.pageHeight&&U("invalid-atlas-row",T.leafId,"row exceeds the image page"),se=`${-le.x}px ${-Mo}px`}return{leaf:T,handle:oe,state:te,atlasPosition:se,transform:Le}});R();let ue=0,pe=0,Pe=0,Oe=0,fe=0,xe=0;if(C.modelMatrix){let T=je(C.modelMatrix);w!==T&&(w=T,v.style.transform=T,ue+=1)}for(let{shape:T,element:oe}of H){let te=je(T.matrix);E.get(T.shapeId)!==te&&(E.set(T.shapeId,te),oe.style.transform=te,pe+=1)}for(let{leaf:T,handle:oe,state:te,atlasPosition:Qe,transform:Le}of re){if(Le){let se=Le;te.transform!==se&&(te.transform=se,oe.element.style.transform=se,Pe+=1)}if(T.visible!==void 0){let se=T.visible?"visible":"hidden";te.visible!==T.visible&&(te.visible=T.visible,oe.element.style.visibility=se,Oe+=1)}if(T.opacity!==void 0){let se=String(T.opacity);te.opacity!==T.opacity&&(te.opacity=T.opacity,oe.element.style.opacity=se,fe+=1)}T.atlasRow!==void 0&&te.atlasRow!==T.atlasRow&&(te.atlasRow=T.atlasRow,oe.element.style.backgroundPosition=Qe,xe+=1)}return R(),S.applyCount+=1,S.totalTransformWrites+=ue+pe+Pe,S.totalVisibilityWrites+=Oe,S.totalOpacityWrites+=fe,S.totalAtlasRowWrites+=xe,{modelTransformWrites:ue,shapeTransformWrites:pe,leafTransformWrites:Pe,visibilityWrites:Oe,opacityWrites:fe,atlasRowWrites:xe,dirtyLeavesVisited:C.leaves?.length??0,domCreations:0,domRemovals:0,topologyConstructions:0,atlasRedraws:0,schedulerCallbacks:0}},updateCamera(){u();let x=(0,ee.buildPolyCameraSceneTransform)(b.state);if(M===x)return!1;M=x,k.style.transform=x;let C=(0,ee.capturePolyCameraSnapshot)(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 ae(o,e,t){throw new Me(o,e,t)}function po(o,e){let t=o;return(!t||typeof t!="object"||!t.ownerDocument||typeof t.style?.setProperty!="function")&&ae("invalid-target",e,"expected an HTMLElement"),t}function No(o,e){return typeof o!="string"&&ae("invalid-transform",e,"expected a CSS transform string"),o}function Bo(o,e,t){let n,r,a,i;return Object.freeze({element:o,writeTransform(s){t();let d=No(s,`${e}.transform`);return n===d?!1:(o.style.transform=d,n=d,!0)},writeVisibility(s){return t(),typeof s!="boolean"&&ae("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)&&ae("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)&&ae("invalid-image-position",`${e}.imagePositionY`,"expected a CSS position"),i===s?!1:(o.style.backgroundPositionY=s,i=s,!0)}})}function Do(o){(!o||typeof o!="object"||Array.isArray(o))&&ae("invalid-target","$","expected a prepared DOM target");let e=po(o.model?.element,"$.model.element");typeof o.model?.writeTransform!="function"&&ae("invalid-target","$.model.writeTransform","expected a transform writer"),(!Array.isArray(o.shapes)||!Array.isArray(o.leaves))&&ae("invalid-target","$","expected shape and leaf target arrays");let t=o.shapes.map((m,f)=>po(m?.element,`$.shapes[${f}].element`)),n=o.leaves.map((m,f)=>po(m?.element,`$.leaves[${f}].element`)),r=e.parentNode,a=t.map(m=>m.parentNode),i=n.map(m=>m.parentNode),s=!1,d=()=>{s&&ae("target-destroyed","$","prepared DOM target is destroyed")},l=Object.freeze(t.map((m,f)=>Bo(m,`$.shapes[${f}]`,d))),c=Object.freeze(n.map((m,f)=>Bo(m,`$.leaves[${f}]`,d))),p,y=Object.freeze({element:e,writeTransform(m){d();let f=No(m,"$.model.transform");if(p===f)return!1;let b=o.model.writeTransform(f);return typeof b!="boolean"&&ae("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]))&&ae("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 Fo(o,e,t){throw new X(o,e,t)}function _e(o){return Object.freeze([...o])}function Kt(o,e){let{timesMs:t,values:n}=o;if(e<=t[0])return _e(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 _e(d);if(o.interpolation==="step")return _e(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 _e(n[n.length-1])}function Zt(o,e){if(o.loop){let t=e%o.durationMs;return Object.is(t,-0)?0:t}return Math.min(e,o.durationMs)}function qe(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||Fo("unknown-clip","$.clipId",n),(!Number.isFinite(r)||r<0)&&Fo("invalid-time","$.timeMs","expected a finite non-negative time");let i=Zt(a,r),s={},d={},l=new Map,c=new Map;for(let p of a.channels){let y=Kt(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 yo(o,e,t){throw new X(o,e,t)}function _o(o){return o===null?null:((!Array.isArray(o)||o.length!==3||o.some(e=>typeof e!="number"||!Number.isFinite(e)))&&yo("invalid-point","$.point","expected three finite components or null"),[o[0],o[1],o[2]])}function en(o){let e=Math.hypot(...o.axis);return[o.axis[0]/e,o.axis[1]/e,o.axis[2]/e]}function qo(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 Ho(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 mo(o,e){let t=_o(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 Jo(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&yo("invalid-state","$.state","control state is invalid"),typeof t?.active!="boolean"&&yo("invalid-input","$.active","expected a boolean");let n=_o(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=mo(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=en(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})}var ce=require("@layoutit/polycss");var on=(0,ce.resolveProjectiveQuadGuards)(void 0);function Z(o,e,t){throw new X(o,e,t)}function tn(o,e){return(typeof o!="number"||!Number.isFinite(o))&&Z("invalid-number",e,"expected a finite number"),Object.is(o,-0)?0:o}function nn(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function He(o){return o.map(e=>[e[0],e[1],e[2]])}function Je(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function rn(o,e){let[t,n,r]=o.vertexIndices,a=e[t],i=e[n],s=e[r],d=(0,ce.computeSolidTrianglePlanFromCssPoints)(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=ce.SOLID_TRIANGLE_CANONICAL_SIZE/o.leaf.width,y=ce.SOLID_TRIANGLE_CANONICAL_SIZE/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 an(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=(0,ce.computeProjectiveQuadCoefficients)(V,on);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 uo(o,e){if(o.vertexIndices.length===3)return rn(o,e);if(o.vertexIndices.length===4)return an(o,e);Z("unsupported-deformation",o.leaf.id,"caller-driven deformation supports prepared triangles and planar quads")}function fo(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=(0,ce.computeSolidTrianglePlanFromCssPoints)(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 Wo(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=tn(r[s]??0,`${t}.${s}`);return(c<d||c>l)&&Z("out-of-range",`${t}.${s}`,`expected ${d} <= value <= ${l}`),[s,c]}))}function sn(o){return new Map(o.deformation.kind==="morph-regions"?o.deformation.targets.map(e=>[e.id,e]):[])}function Yo(o){let e=Y(o);e.deformation.kind==="joint-skin"&&Z("profile-not-executable","$.profile","joint skin requires the skinning runtime");let t=sn(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,fo(e,h)])),p=Je(He(e.topology.vertices)),y=Je(He(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 $=Wo(h.morphWeights,n,"$.morphWeights",a),k=Wo(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=He(p),V=He(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(nn),w=Je(O),L=Je(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=uo(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 Ve(o,e,t){throw new X(o,e,t)}function Ce(o){return Object.freeze([...o])}function ho(o,e){return o.every((t,n)=>t===e[n])}function We(o){let e=Y(o);return Object.freeze({modelMatrix:Ce(e.render.modelMatrix),shapes:Object.freeze(e.render.shapes.map(t=>Object.freeze({shapeId:t.id,matrix:Ce(t.matrix)}))),leaves:Object.freeze(e.render.leaves.map(t=>Object.freeze({leafId:t.id,matrix:Ce(t.matrix),visible:!0,opacity:1,atlasRow:0})))})}function Ye(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)||Ve("unknown-shape","$.frame.shapes",r);for(let r of n.keys())o.leaves.some(a=>a.leafId===r)||Ve("unknown-leaf","$.frame.leaves",r);return Object.freeze({modelMatrix:e.modelMatrix===null?o.modelMatrix:Ce(e.modelMatrix),shapes:Object.freeze(o.shapes.map(r=>{let a=t.get(r.shapeId);return a?Object.freeze({shapeId:r.shapeId,matrix:Ce(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:Ce(a.matrix),visible:a.visible??r.visible,opacity:a.opacity??r.opacity,atlasRow:a.atlasRow??r.atlasRow}):r}))})}function Ge(o,e){(o.shapes.length!==e.shapes.length||o.leaves.length!==e.leaves.length)&&Ve("state-mismatch","$","prepared state topology differs");let t=!ho(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&&Ve("state-mismatch","$.shapes","source order differs"),ho(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&&Ve("state-mismatch","$.leaves","source order differs");let d={leafId:s.leafId};ho(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 Ee(o,e,t){throw new X(o,e,t)}function ln(o,e,t){if(e){let n=t%o;return Object.is(n,-0)?0:n}return Math.min(t,o)}function dn(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 Go(o){let e=Y(o);(e.profile!=="prepared-playback"||!e.playback)&&Ee("profile-mismatch","$.profile","playback requires the prepared-playback profile");let t=e.playback,n=We(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||Ee("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&&Ee("invalid-atlas-row",`$.playback.frames[${p}]`,`${m.id} row exceeds its page`)}a=Ye(a,y),r.push(a)}let s=t.frames.map(p=>p.timeMs),d=n,l=null,c=p=>{(!Number.isFinite(p)||p<0)&&Ee("invalid-time","$.timeMs","expected a finite non-negative time");let y=ln(t.durationMs,t.loop,p),P=dn(s,y),m=r[P],f=Ge(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&&Ee("invalid-sample","$.sample","commit requires the latest unapplied playback sample"),d=p.state,l=null},reset(){d=n,l=null}})}var Qo=Object.freeze(["joint-skin","morph-regions","prepared-playback","static-prepared"]);function ie(o,e,t){throw new X(o,e,t)}function cn(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function go(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 pn(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)))&&ie("invalid-quaternion",e,"expected four finite components");let t=Math.hypot(...o);return t<=1e-12&&ie("invalid-quaternion",e,"quaternion must be non-zero"),[o[0]/t,o[1]/t,o[2]/t,o[3]/t]}function Xo(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)))&&ie("invalid-vector",t,"expected three finite components"),n&&o.some(r=>r<=0)&&ie("invalid-scale",t,"scale components must be positive"),[o[0],o[1],o[2]])}function et(o,e){if(o===void 0)return cn();(!o||typeof o!="object"||Array.isArray(o))&&ie("invalid-joint-transform",e,"expected an object"),Object.keys(o).some($=>$!=="translation"&&$!=="rotation"&&$!=="scale")&&ie("invalid-joint-transform",e,"unknown transform field");let n=Xo(o.translation,[0,0,0],`${e}.translation`),r=Xo(o.scale,[1,1,1],`${e}.scale`,!0),[a,i,s,d]=pn(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 yn(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 mn(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&&ie("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 un(o){let e=Math.hypot(...o);return e<=1e-12?[0,0,0]:[o[0]/e,o[1]/e,o[2]/e]}function Te(o){for(let e of o)Object.freeze(e);return Object.freeze(o)}function fn(o,e){return o.every((t,n)=>Math.abs(t-e[n])<=1e-12)}function Ko(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=go(a.restMatrix,et(e.get(a.id),`$.jointTransforms.${a.id}`)),d=a.parentId===null?s:go(r(t.get(a.parentId)),s);return n.set(a.id,d),d};for(let a of o)r(a);return n}function Zo(o,e){return new Map(o.map(t=>[t.id,go(e.get(t.id),t.inverseBindMatrix)]))}function hn(o,e){let t=o??new Map;(!t||typeof t.entries!="function")&&ie("invalid-joint-transform","$.jointTransforms","expected a map");for(let[n,r]of t)e.has(n)||ie("unknown-joint","$.jointTransforms",n),et(r,`$.jointTransforms.${n}`);return t}function ot(o){let e=Y(o);e.deformation.kind!=="joint-skin"&&ie("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=Ko(t.joints,new Map),i=Zo(t.joints,a),s=Te(e.topology.vertices.map(w=>[...w])),d=Te(e.topology.normals.map(w=>[...w])),l=new Map(e.render.leaves.map(w=>[w.id,fo(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=yn(_,s[B]),S=mn(_,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(un(V))}return{positions:L,normals:E}},m=P(i),f=Te(m.positions),b=Te(m.normals),h=new Map(i),$=f,k=b,F=qe(e),v=w=>{(!w||!Number.isSafeInteger(w.tick)||w.tick<0)&&ie("invalid-tick","$.tick","expected a non-negative safe integer");let L=hn(w.jointTransforms,r),E=Ko(t.joints,L),B=Zo(t.joints,E),q=new Set(n.filter(u=>!fn(B.get(u),h.get(u)))),O=$,V=k;if(q.size>0){let u=P(B);O=Te(u.positions),V=Te(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=uo(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 be(o,e,t){throw new X(o,e,t)}function gn(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 tt(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 nt(o,e){let t=Object.keys(e??{}).find(r=>!o.controls.has(r));t&&be("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)&&be("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 rt(o,e,t){(!e||!Number.isSafeInteger(e.tick)||e.tick<-1)&&be("invalid-state","$.state","spring state is invalid"),(!Number.isFinite(t?.deltaMs)||t.deltaMs<=0||t.deltaMs>1e3)&&be("invalid-time","$.deltaMs","expected 0 < deltaMs <= 1000");let n=t.heldTarget??null;if(n){let l=o.controls.get(n.controlId);l||be("unknown-id","$.heldTarget.controlId",n.controlId),(!Number.isFinite(n.value)||n.value<l.minimum||n.value>l.maximum)&&be("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)||be("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]=gn(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})}0&&(module.exports={POLY_MORPH_CATALOG_SCHEMA,POLY_MORPH_EXECUTABLE_PROFILES,POLY_MORPH_MODEL_SCHEMA,POLY_MORPH_PACKAGE_SCHEMA,PolyMorphContractError,PolyMorphPackageError,PolyMorphRenderError,PolyMorphRuntimeError,applyPolyMorphPlaybackFrame,assertPolyMorphPackageModelBinding,buildPolyMorphCatalog,buildPolyMorphPackage,createPolyMorphAnimationRuntime,createPolyMorphControlRuntime,createPolyMorphControlState,createPolyMorphDeformationRuntime,createPolyMorphPlaybackRuntime,createPolyMorphPreparedDomTarget,createPolyMorphPreparedState,createPolyMorphSkinningRuntime,createPolyMorphSpringRuntime,createPolyMorphSpringState,decodePolyMorphJson,diffPolyMorphPreparedStates,encodePolyMorphCanonicalJson,hashPolyMorphBytes,isPolyMorphId,isPolyMorphResourcePath,loadPolyMorphCatalog,loadPolyMorphPackage,mountPolyMorphModel,pickPolyMorphControl,stepPolyMorphControls,stepPolyMorphSprings,stringifyPolyMorphCanonicalJson,validatePolyMorphCatalog,validatePolyMorphModel,validatePolyMorphPackageManifest});
|