@kvmet/beefwife 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ /*! Beefwife v0.1.0. Generated from beefwife/src; do not edit.
2
+ (c) Kristen Metcalfe, MPL-2.0. */
3
+ var Beefwife=(function(e){var t=Object.create,n=Object.defineProperty,__name=(e,t)=>n(e,`name`,{value:t,configurable:!0}),r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,__exportAll=(e,t)=>{let r=Object.setPrototypeOf({},null);for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t&1||n(r,Symbol.toStringTag,{value:`Module`}),t&2?r:Object.preventExtensions(r)},__copyProps=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},__toESM=(e,r,i)=>(i=e==null?{}:t(a(e)),__copyProps(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e));e=__toESM(e,1);var s=e,c=typeof s?.Container==`function`,l=1e9,u=1e-6,d=1e6,f=1e6,p=1/60,m=[`head`,`trunk`,`tail`],h=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,g=/^[a-z0-9][a-z0-9-]{0,63}$/,_=Object.freeze({name:64,definitions:256,chunks:256,placements:512,instances:512,path:65536,pathTotal:1048576}),number=(e,t,n=!1)=>({kind:`number`,min:e,max:t,integer:n}),px=(e,t)=>({...number(e,t),length:1}),perPx=(e,t)=>({...number(e,t),length:-1}),string=(e,t,n=null)=>({kind:`string`,minLength:e,maxLength:t,pattern:n}),choice=(...e)=>({kind:`choice`,values:e}),literal=e=>({kind:`literal`,value:e}),nullable=e=>({kind:`nullable`,item:e}),object=e=>({kind:`object`,fields:e}),array=(e,t)=>({kind:`array`,item:e,maxLength:t}),record=(e,t=0)=>({kind:`record`,item:e,minLength:t,maxLength:_.definitions}),v=string(1,64,h),y=number(0,1),b=px(.001,1e3),x=number(.001,100),S=px(1e-6,1e4),C=px(-1e4,1e4),nonBlank=e=>({...e,blank:!1}),w=nullable(nonBlank(string(1,256))),T=object({velocityRetention:y,jointCorrection:y,linkCorrection:number(.001,1),grip:object({forward:y,backward:y,lateral:y})}),E=object({path:nonBlank(string(1,_.path))}),D=object({fill:w,stroke:nullable(object({colour:nonBlank(string(1,256)),width:px(0,1e3)}))}),O=object({start:px(0,1e3),end:px(0,1e3)}),sectionOf=e=>object({chunks:number(e,_.chunks,!0),spacing:px(1e-6,1e3),material:v,motionScale:object({bend:number(0,4),thrust:number(0,4),gather:number(0,4),contact:number(0,4)}),profile:object({ribbonWidth:O,plateScale:object({start:number(0,100),end:number(0,100)})})}),k=object({section:nullable(choice(...m)),from:choice(`head`,`tail`),offset:number(0,_.chunks-1,!0)}),A=object({count:nullable(number(1,_.chunks,!0)),step:number(1,_.chunks,!0)}),j=object({id:v,shape:v,paint:v,at:k,repeat:A,scale:b}),M=object({id:v,shape:v,paint:v,at:k,repeat:A,side:choice(`left`,`right`,`both`),layer:choice(`under`,`over`),offset:object({forward:C,outward:C}),angleDegrees:number(-180,180),scale:b,source:y,react:number(-4,4),recover:number(0,1e3),wobble:y}),N=object({schemaVersion:literal(1),name:string(1,_.name,g),definitions:object({materials:record(T,1),shapes:record(E,1),paints:record(D,1)}),gait:object({cyclesPerSecond:number(0,15),phaseLagRadiansPerPixel:perPx(-1e3,1e3),bend:object({amplitude:number(0,10),harmonic:number(1,8,!0)}),thrust:object({acceleration:px(0,1e6),harmonic:number(1,8,!0),phaseOffset:number(-Math.PI,Math.PI),dutyCycle:number(.01,1)}),gather:object({amplitude:number(0,.95),harmonic:number(1,8,!0),phaseOffset:number(-Math.PI,Math.PI)}),contact:object({amplitude:y,harmonic:number(1,8,!0),phaseOffset:number(-Math.PI,Math.PI),dutyCycle:number(.01,1)})}),chain:object({physics:object({autoLift:object({amount:y,share:y,rate:number(0,1e3)}),steering:object({gain:number(0,100),limit:number(0,Math.PI),rate:number(0,1e3)})}),breathing:y,sections:object({head:sectionOf(1),trunk:sectionOf(1),tail:sectionOf(0)}),skin:object({loadScale:number(-1,10),ribbon:object({paint:v}),plates:array(j,_.chunks),ornaments:array(M,_.placements)})}),legs:object({section:choice(...m),pairs:number(0,128,!0),reach:S,spread:number(0,4),lead:y,fold:y,jointBend:number(-1,1),jointLean:number(-1,1),jointLeanCenter:number(-1,1),sidePhase:y,liftThreshold:y,swingCycles:number(.001,60),swingArc:number(0,4),jitter:y,skin:object({limbPaint:v,limbWidth:px(0,1e3),foot:object({shape:v,paint:v,scale:b,plantedScale:x})})})}),ee=/* @__PURE__ */ __exportAll({ID_PATTERN:()=>h,LIMITS:()=>_,NAME_PATTERN:()=>g,VERSION:()=>1,bounds:()=>bounds,parse:()=>parse,read:()=>read,scale:()=>scale,stringify:()=>stringify}),fail=(e,t)=>{throw Error(`${e}: ${t}`)},te=/* @__PURE__ */ __name((e,t)=>{(!e||typeof e!=`object`||Array.isArray(e))&&fail(t,`must be an object`);let n=Object.getPrototypeOf(e);n!==Object.prototype&&n!==null&&fail(t,`must be a plain JSON object`)},`plainObject`),ownKeys=(e,t)=>{let n=Reflect.ownKeys(e);return n.some(e=>typeof e!=`string`)&&fail(t,`must not contain symbol keys`),n.forEach(n=>{let r=Object.getOwnPropertyDescriptor(e,n);r.enumerable&&`value`in r||fail(`${t}.${n}`,`must be an enumerable data property`)}),n},readNode=(e,t,n,r)=>{if(e.kind===`nullable`)return t===null?null:readNode(e.item,t,n,r);if(e.kind===`literal`)return t!==e.value&&fail(n,`must equal ${e.value}`),t;if(e.kind===`choice`)return e.values.includes(t)||fail(n,`must be one of ${e.values.join(`, `)}`),t;if(e.kind===`number`)return typeof t==`number`&&Number.isFinite(t)||fail(n,`must be a finite number`),e.integer&&!Number.isInteger(t)&&fail(n,`must be an integer`),(t<e.min||t>e.max)&&fail(n,`must be between ${e.min} and ${e.max}`),Object.is(t,-0)?0:t;if(e.kind===`string`)return typeof t!=`string`&&fail(n,`must be a string`),(t.length<e.minLength||t.length>e.maxLength)&&fail(n,`must contain ${e.minLength} to ${e.maxLength} characters`),e.pattern&&!e.pattern.test(t)&&fail(n,`contains characters that are not allowed`),t;e.kind===`array`?Array.isArray(t)||fail(n,`must be an array`):te(t,n),r.has(t)&&fail(n,`must not contain a cycle`),r.add(t);try{if(e.kind===`array`){t.length>e.maxLength&&fail(n,`must contain at most ${e.maxLength} entries`);let i=Reflect.ownKeys(t).filter(e=>e!==`length`);i.some(e=>typeof e!=`string`)&&fail(n,`must not contain symbol keys`),i.forEach(e=>{let r=Object.getOwnPropertyDescriptor(t,e);r.enumerable&&`value`in r||fail(`${n}.${String(e)}`,`must be an enumerable data property`)});for(let e=0;e<t.length;e++)Object.hasOwn(t,e)||fail(`${n}[${e}]`,`is missing`);return i.some(e=>!/^(0|[1-9][0-9]*)$/.test(e))&&fail(n,`must not contain named properties`),t.map((t,i)=>readNode(e.item,t,`${n}[${i}]`,r))}let i=ownKeys(t,n);if(e.kind===`record`){(i.length<e.minLength||i.length>e.maxLength)&&fail(n,`must contain ${e.minLength} to ${e.maxLength} definitions`);let a={};return i.sort().forEach(i=>{h.test(i)||fail(`${n}.${i}`,`has an invalid id`),a[i]=readNode(e.item,t[i],`${n}.${i}`,r)}),a}let a=Object.keys(e.fields);i.forEach(t=>{Object.hasOwn(e.fields,t)||fail(`${n}.${t}`,`is unknown`)});let o={};return a.forEach(i=>{Object.hasOwn(t,i)||fail(`${n}.${i}`,`is required`),o[i]=readNode(e.fields[i],t[i],`${n}.${i}`,r)}),o}finally{r.delete(t)}},reference=(e,t,n)=>{Object.hasOwn(e,t)||fail(n,`references missing "${t}"`)},resolvedChunks=(e,t,n)=>{let r=e.chain.sections,i={head:0,trunk:r.head.chunks,tail:r.head.chunks+r.trunk.chunks},a=t.at.section,o=a?r[a].chunks:m.reduce((e,t)=>e+r[t].chunks,0);o||fail(`${n}.at`,`cannot address an empty scope`);let s=t.at.offset;s>=o&&fail(`${n}.at.offset`,`falls outside its scope`);let c=t.at.from===`head`?1:-1,l=c>0?s:o-1-s,u=Math.floor((o-1-s)/t.repeat.step)+1,d=t.repeat.count??u;d>u&&fail(`${n}.repeat.count`,`runs outside its scope`);let f=a?i[a]:0;return Array.from({length:d},(e,n)=>f+l+c*n*t.repeat.step)},validate=e=>{let{definitions:t,chain:n,gait:r,legs:i}=e,a=n.sections,o=m.reduce((e,t)=>e+a[t].chunks,0);(o<2||o>_.chunks)&&fail(`$.chain.sections`,`must contain 2 to ${_.chunks} chunks`),m.forEach(e=>reference(t.materials,a[e].material,`$.chain.sections.${e}.material`)),m.forEach(t=>{let n=a[t].motionScale;e.gait.gather.amplitude*n.gather>=1&&fail(`$.chain.sections.${t}.motionScale.gather`,`makes the gathered link length zero or negative`),e.gait.contact.amplitude*n.contact>1&&fail(`$.chain.sections.${t}.motionScale.contact`,`makes ground contact negative`)}),[[t.paints,n.skin.ribbon.paint,`$.chain.skin.ribbon.paint`],[t.paints,i.skin.limbPaint,`$.legs.skin.limbPaint`],[t.shapes,i.skin.foot.shape,`$.legs.skin.foot.shape`],[t.paints,i.skin.foot.paint,`$.legs.skin.foot.paint`]].forEach(e=>reference(...e));let s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Map;n.skin.plates.forEach((n,r)=>{let i=`$.chain.skin.plates[${r}]`;s.has(n.id)&&fail(`${i}.id`,`must be unique`),s.add(n.id),reference(t.shapes,n.shape,`${i}.shape`),reference(t.paints,n.paint,`${i}.paint`),resolvedChunks(e,n,i).forEach(e=>{c.has(e)&&fail(`${i}.at`,`overlaps plate "${c.get(e)}" at chunk ${e}`),c.set(e,n.id)})});let l=0;n.skin.ornaments.forEach((n,r)=>{let i=`$.chain.skin.ornaments[${r}]`;s.has(n.id)&&fail(`${i}.id`,`must be unique`),s.add(n.id),reference(t.shapes,n.shape,`${i}.shape`),reference(t.paints,n.paint,`${i}.paint`),l+=resolvedChunks(e,n,i).length*(n.side===`both`?2:1),l>_.instances&&fail(`$.chain.skin.ornaments`,`must expand to at most ${_.instances} instances`)}),[`bend`,`thrust`,`gather`,`contact`].forEach(e=>{r.cyclesPerSecond*r[e].harmonic>15&&fail(`$.gait.${e}.harmonic`,`times cyclesPerSecond must be at most 15`)}),i.pairs&&!a[i.section].chunks&&fail(`$.legs.section`,`cannot attach legs to an empty section`),Object.entries(t.paints).forEach(([e,t])=>{t.fill!==null&&!t.fill.trim()&&fail(`$.definitions.paints.${e}.fill`,`must not be blank`),t.stroke!==null&&!t.stroke.colour.trim()&&fail(`$.definitions.paints.${e}.stroke.colour`,`must not be blank`),t.fill!==null||t.stroke!==null&&t.stroke.width||fail(`$.definitions.paints.${e}`,`must draw a fill or visible stroke`)});let u=0;return Object.entries(t.shapes).forEach(([e,t])=>{t.path.trim()||fail(`$.definitions.shapes.${e}.path`,`must not be blank`),u+=t.path.length}),u>_.pathTotal&&fail(`$.definitions.shapes`,`paths must total at most ${_.pathTotal} characters`),e},read=e=>validate(readNode(N,e,`$`,/* @__PURE__ */ new WeakSet)),resolve=e=>{let t=N;for(let n of e){for(;t.kind===`nullable`;)t=t.item;if(t.kind===`object`&&Object.hasOwn(t.fields,n))t=t.fields[n];else if(t.kind===`record`&&n===`*`)t=t.item;else if(t.kind===`array`&&n===`[]`)t=t.item;else return null}let n=t.kind===`nullable`;return{node:n?t.item:t,nullable:n}},shapeOf=e=>e.kind===`number`?{kind:`number`,min:e.min,max:e.max,integer:e.integer}:e.kind===`string`?{kind:`string`,minLength:e.minLength,maxLength:e.maxLength,pattern:e.pattern&&new RegExp(e.pattern.source,e.pattern.flags),blankAllowed:e.blank!==!1}:e.kind===`choice`?{kind:`choice`,values:Object.freeze([...e.values])}:e.kind===`literal`?{kind:`literal`,value:e.value}:e.kind===`object`?{kind:`object`,fields:Object.freeze(Object.keys(e.fields))}:e.kind===`record`?{kind:`record`,minEntries:e.minLength,maxEntries:e.maxLength,keyPattern:new RegExp(h.source,h.flags)}:{kind:`array`,maxLength:e.maxLength},bounds=e=>{typeof e==`string`&&e||fail(`$`,`bounds path must be a non-empty string`);let t=resolve(e.replace(/\[\]/g,`.[]`).split(`.`));return t||fail(`$.${e}`,`is not a field in this schema`),Object.freeze({...shapeOf(t.node),nullable:t.nullable})},scaleNode=(e,t,n)=>{if(e.kind===`nullable`)return t===null?null:scaleNode(e.item,t,n);if(e.kind===`number`)return e.length?t*n**e.length:t;if(e.kind===`object`){let r={};return Object.keys(e.fields).forEach(i=>{r[i]=scaleNode(e.fields[i],t[i],n)}),r}if(e.kind===`record`){let r={};return Object.keys(t).forEach(i=>{r[i]=scaleNode(e.item,t[i],n)}),r}return e.kind===`array`?t.map(t=>scaleNode(e.item,t,n)):t},scale=(e,t)=>{(typeof t!=`number`||!Number.isFinite(t)||t<=0)&&fail(`$`,`scale factor must be a finite number greater than 0`);let n=read(e),r=scaleNode(N,n,t),i=/* @__PURE__ */ new Set([n.chain.skin.ribbon.paint,n.legs.skin.limbPaint]),a=[r.legs.skin.foot,...r.chain.skin.plates,...r.chain.skin.ornaments],o=new Set(a.map(({paint:e})=>e));for(let e of o){let o=n.definitions.paints[e];if(!o.stroke||o.stroke.width===0||t===1)continue;let s=e;if(i.has(e)){let t=1;do s=`shape-paint-${t++}`;while(Object.hasOwn(r.definitions.paints,s));for(let t of a)t.paint===e&&(t.paint=s)}r.definitions.paints[s]=o}return read(r)},parse=e=>{typeof e!=`string`&&fail(`$`,`JSON input must be a string`);let t;try{t=JSON.parse(e)}catch(e){fail(`$`,`invalid JSON: ${e.message}`)}return read(t)},stringify=(e,t=2)=>((!Number.isInteger(t)||t<0||t>10)&&fail(`$`,`indentation must be an integer from 0 to 10`),JSON.stringify(read(e),null,t)),ne=[`head`,`trunk`,`tail`],P=.1,re=.15,F=.4,I=2*P*2*Math.PI*F,L=14,ie=.01,freeze=e=>!e||typeof e!=`object`||Object.isFrozen(e)?e:(Object.values(e).forEach(freeze),Object.freeze(e)),R=/* @__PURE__ */ __name((e,t,n)=>e+(t-e)*n,`lerp`),z=/* @__PURE__ */ __name((e,t,n)=>Math.max(t,Math.min(n,e)),`clamp`),profileAt=(e,t,n)=>n===1?(e.start+e.end)/2:R(e.start,e.end,t/(n-1)),spatialAngle=(e,t,n)=>t.phaseOffset-t.harmonic*n*e.phaseLagRadiansPerPixel,breathingRateFor=e=>z(re*Math.sqrt(16/e),.1,F),placementChunks=(e,t,n)=>{let r=e.at.section,i=r?t[r]:{start:0,count:n},a=e.at.from===`head`?1:-1,o=a>0?e.at.offset:i.count-1-e.at.offset,s=Math.floor((i.count-1-e.at.offset)/e.repeat.step)+1,c=e.repeat.count??s;return Array.from({length:c},(t,n)=>i.start+o+a*n*e.repeat.step)},normalizePaints=e=>{let t={};return Object.entries(e).forEach(([e,n])=>{t[e]={fill:n.fill,stroke:n.stroke?n.stroke.colour:null,strokeWidth:n.stroke?n.stroke.width:0}}),t},compile=e=>{let t=read(e),n={...t.gait,bend:{...t.gait.bend,phaseOffset:0}},r=t.chain.sections,i={},a=[];ne.forEach(e=>{let n=r[e],o=a.length,s=t.definitions.materials[n.material];for(let t=0;t<n.chunks;t++)a.push({index:a.length,section:e,localIndex:t,restDistance:0,materialId:n.material,material:s,motionScale:n.motionScale,bendScale:0,ribbonWidth:profileAt(n.profile.ribbonWidth,t,n.chunks),plateScale:profileAt(n.profile.plateScale,t,n.chunks)});i[e]={name:e,start:o,end:a.length,count:n.chunks,spacing:n.spacing,materialId:n.material,material:s,motionScale:n.motionScale,profile:n.profile}});let o={strain:t.chain.breathing*P,cyclesPerSecond:breathingRateFor(i.trunk.count)},s=[],c=0;for(let e=0;e<a.length-1;e++){let t=a[e],n=a[e+1],r=i[t.section],l=i[n.section],u=t.section===n.section?r.spacing:(r.spacing+l.spacing)/2,d=(t.material.linkCorrection+n.material.linkCorrection)/2;c+=u,n.restDistance=c,s.push({index:e,from:e,to:e+1,restLength:u,phaseDistance:(t.restDistance+n.restDistance)/2,linkCorrection:d,gatherScale:(t.motionScale.gather+n.motionScale.gather)/2,breathingScale:t.section===`trunk`&&n.section===`trunk`?o.strain:0})}for(let e=1;e<a.length-1;e++)a[e].bendScale=(s[e-1].restLength+s[e].restLength)/2/i.trunk.spacing;a.forEach(e=>{let t=spatialAngle(n,n.bend,e.restDistance);e.bendPhaseSine=Math.sin(t),e.bendPhaseCosine=Math.cos(t)}),s.forEach(e=>{let t=spatialAngle(n,n.gather,e.phaseDistance);e.gatherPhaseSine=Math.sin(t),e.gatherPhaseCosine=Math.cos(t)});let l=t.definitions.shapes,u=normalizePaints(t.definitions.paints),d=t.chain.skin.plates.flatMap(e=>placementChunks(e,i,a.length).map(t=>({id:e.id,chunk:t,shape:l[e.shape],paint:u[e.paint],scale:e.scale}))),f=t.chain.skin.ornaments.flatMap(e=>{let t=e.side===`both`?[`left`,`right`]:[e.side];return placementChunks(e,i,a.length).flatMap(n=>t.map(t=>{let r=t===`left`?-1:1,i=e.angleDegrees*Math.PI*r/180;return{id:e.id,chunk:n,side:t,sideSign:r,layer:e.layer,shape:l[e.shape],paint:u[e.paint],offset:e.offset,angleDegrees:e.angleDegrees,angleCosine:Math.cos(i),angleSine:Math.sin(i),scale:e.scale,waveGain:e.react*(1-e.source),physGain:e.react*e.source,recover:e.recover,wobble:e.wobble}}))});return freeze({descriptor:t,sections:i,chunks:a,links:s,restLength:c,gait:n,paints:u,physics:t.chain.physics,breathing:o,skin:{lateralRate:L*i.trunk.spacing,loadScale:t.chain.skin.loadScale,hasRibbon:a.some(e=>e.ribbonWidth>0),ribbonPaintId:t.chain.skin.ribbon.paint,ribbonPaint:u[t.chain.skin.ribbon.paint],plates:d,platesTailFirst:[...d].sort((e,t)=>t.chunk-e.chunk),ornaments:f},legs:{...t.legs,spread:t.legs.spread*t.legs.reach,swingArc:t.legs.swingArc*t.legs.reach,swingSeconds:t.legs.swingCycles/Math.max(t.gait.cyclesPerSecond,ie),start:i[t.legs.section].start,end:i[t.legs.section].end,skin:{limbPaint:u[t.legs.skin.limbPaint],limbWidth:t.legs.skin.limbWidth,foot:{shape:l[t.legs.skin.foot.shape],paint:u[t.legs.skin.foot.paint],scale:t.legs.skin.foot.scale,plantedScale:t.legs.skin.foot.plantedScale}}}})},B=Math.PI*2,positiveModulo=(e,t)=>(e%t+t)%t,Gait=class{constructor(e,t=0){this.gait=e,this.phase=positiveModulo(t,B)}advance(e,t){this.phase=positiveModulo(this.phase+B*this.gait.cyclesPerSecond*t*e,B)}_phaseAt(e,t,n=0){return t.harmonic*(this.phase-e*this.gait.phaseLagRadiansPerPixel)+t.phaseOffset+n}_pulseAt(e,t,n=0){let r=positiveModulo(this._phaseAt(e,t,n),B)/B;return r>=t.dutyCycle?0:Math.sin(Math.PI*r/t.dutyCycle)}bendAt(e,t,n){let r=this.gait.bend;return r.amplitude*n*t*Math.sin(this._phaseAt(e,r))}thrustAt(e,t,n){let r=this.gait.thrust;return r.acceleration*n*t*this._pulseAt(e,r)}restAt(e,t,n){let r=this.gait.gather;return 1+r.amplitude*n*t*Math.cos(this._phaseAt(e,r))}contactAt(e,t,n,r=0){let i=this.gait.contact;return 1-i.amplitude*n*t*this._pulseAt(e,i,r)}},V=60,H=480,shareAtRate=(e,t,n)=>t===n?e:e>0?e>=1?1:1-(1-e)**(n/t):0,ChainTables=class{constructor(e,t,n,r){let i=e.chunks.length,a=e.links.length;this.retention=new Float64Array(i),this.gripForward=new Float64Array(i),this.gripBackward=new Float64Array(i),this.gripLateral=new Float64Array(i),this.motionThrust=new Float64Array(i),this.motionContact=new Float64Array(i),this.motionBend=new Float64Array(i),this.bendScale=new Float64Array(i),this.bendPhaseSine=new Float64Array(i),this.bendPhaseCosine=new Float64Array(i),this.jointCorrectionHalf=new Float64Array(i),this.phaseLag=new Float64Array(i),this.linkRestLength=new Float64Array(a),this.linkCorrectionHalf=new Float64Array(a),this.gatherScale=new Float64Array(a),this.gatherPhaseSine=new Float64Array(a),this.gatherPhaseCosine=new Float64Array(a),this.linkBreathes=new Uint8Array(a),this.refresh(e,t,n,r)}refresh(e,t,n,r){let i=t.phaseLagRadiansPerPixel,a=1/n,o=r/n,perSubstep=e=>shareAtRate(e,a,V);for(let t=0;t<e.chunks.length;t++){let r=e.chunks[t],a=r.material.grip;this.retention[t]=r.material.velocityRetention**+n,this.gripForward[t]=perSubstep(a.forward),this.gripBackward[t]=perSubstep(a.backward),this.gripLateral[t]=perSubstep(a.lateral),this.motionThrust[t]=r.motionScale.thrust,this.motionContact[t]=r.motionScale.contact,this.motionBend[t]=r.motionScale.bend,this.bendScale[t]=r.bendScale,this.bendPhaseSine[t]=r.bendPhaseSine,this.bendPhaseCosine[t]=r.bendPhaseCosine,this.jointCorrectionHalf[t]=perSubstep(r.material.jointCorrection)*.5,this.phaseLag[t]=r.restDistance*i}for(let t=0;t<e.links.length;t++){let n=e.links[t];this.linkRestLength[t]=n.restLength,this.linkCorrectionHalf[t]=shareAtRate(n.linkCorrection,o,H)*.5,this.gatherScale[t]=n.gatherScale,this.gatherPhaseSine[t]=n.gatherPhaseSine,this.gatherPhaseCosine[t]=n.gatherPhaseCosine,this.linkBreathes[t]=+!!n.breathingScale}}},ChainState=class{constructor(e){this.count=e,this.x=new Float64Array(e),this.y=new Float64Array(e),this.px=new Float64Array(e),this.py=new Float64Array(e),this.dx=new Float64Array(e),this.dy=new Float64Array(e),this.idle=new Float64Array(e),this.gain=new Float64Array(e),this.gaitContact=new Float64Array(e),this.contact=new Float64Array(e),this.correction={x:0,y:0},this.dx.fill(1),this.gaitContact.fill(1),this.contact.fill(1)}translate(e){let{x:t,y:n,px:r,py:i,count:a}=this;for(let o=0;o<a;o++)t[o]+=e.x,n[o]+=e.y,r[o]+=e.x,i[o]+=e.y}fitsTranslation(e,t){let{x:n,y:r,px:i,py:a,count:o}=this,within=(e,n)=>{let r=e+n;return Number.isFinite(r)&&Math.abs(r)<=t};for(let t=0;t<o;t++)if(!within(n[t],e.x)||!within(r[t],e.y)||!within(i[t],e.x)||!within(a[t],e.y))return!1;return!0}worldCorrection(e){let{x:t,y:n,px:r,py:i,count:a}=this,o=1/0,s=-1/0,c=1/0,l=-1/0;for(let e=0;e<a;e++)o=Math.min(o,t[e],r[e]),s=Math.max(s,t[e],r[e]),c=Math.min(c,n[e],i[e]),l=Math.max(l,n[e],i[e]);let correction=(t,n)=>n>e?e-n:t<-e?-e-t:0;return this.correction.x=correction(o,s),this.correction.y=correction(c,l),this.correction}},nameOf=e=>`${e.section}:${e.localIndex}`,U=[`x`,`y`,`px`,`py`,`dx`,`dy`,`idle`,`gain`],carryChunks=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;r.chunks.forEach((e,t)=>i.set(nameOf(e),t));let a=t.chunks.map((t,r)=>{let a=i.get(nameOf(t));if(a===void 0)return!1;for(let t of U)e[t][r]=n[t][a];return!0}),{x:o,y:s,px:c,py:l,dx:u,dy:d,idle:f,gain:p,count:m}=e;for(let e=0;e<m;e++){if(a[e])continue;let n=e-1;for(;n>=0&&!a[n];)n--;let r=e+1;for(;r<m&&!a[r];)r++;if(n>=0&&r<m){let t=(e-n)/(r-n);o[e]=o[n]+(o[r]-o[n])*t,s[e]=s[n]+(s[r]-s[n])*t,c[e]=c[n]+(c[r]-c[n])*t,l[e]=l[n]+(l[r]-l[n])*t,u[e]=u[n],d[e]=d[n]}else{let i=n>=0?n:r,a=n>=0?-1:1,f=t.links[n>=0?e-1:e],p=(f?f.restLength:0)*Math.abs(e-i);o[e]=o[i]+u[i]*a*p,s[e]=s[i]+d[i]*a*p,c[e]=o[e],l[e]=s[e],u[e]=u[i],d[e]=d[i]}f[e]=0,p[e]=0}},Bend=class{constructor(e){this.targets=new Float64Array(e),this.wantedX=new Float64Array(e),this.wantedY=new Float64Array(e),this.spanX=new Float64Array(e),this.spanY=new Float64Array(e)}update(e,t,n,r,i,a){let o=e.gait.bend,s=o.harmonic*t.phase,c=Math.sin(s),l=Math.cos(s),u=o.amplitude,d=a*i,{motionBend:f,bendPhaseSine:p,bendPhaseCosine:m,bendScale:h}=n,g=this.targets,_=this.wantedX,v=this.wantedY,y=g.length-1,b=0;_[0]=0,v[0]=0;for(let e=0;e<y;e++){if(e>0){let t=u*f[e]*i*(c*m[e]+l*p[e]);g[e]=(t+d)*h[e],b+=g[e]}_[e+1]=_[e]+Math.cos(b)*r[e],v[e+1]=v[e]+Math.sin(b)*r[e]}}relax(e,t){for(let n=Math.max(1,Math.min(2,e.count>>2));n>=1;n>>=1)this.relaxSpan(e,t,n)}relaxSpan(e,t,n){let r=e.count,i=e.x,a=e.y,o=this.wantedX,s=this.wantedY,c=this.spanX,l=this.spanY;for(let e=n;e+n<r;e+=n){let r=e-n,u=e+n,d=i[e],f=a[e],p=d-i[r],m=f-a[r],h=i[u]-d,g=a[u]-f,_=Math.atan2(p*g-m*h,p*h+m*g),v=o[e]-o[r],y=s[e]-s[r],b=o[u]-o[e],x=s[u]-s[e],S=(Math.atan2(v*x-y*b,v*b+y*x)-_)*t[e],C=Math.cos(S),w=Math.sin(S);for(let t=r;t<=u;t++){let n=i[t]-d,r=a[t]-f,o=t<e?-w:w;c[t]=d+n*C-r*o,l[t]=f+n*o+r*C}let T=u-r+1,E=0,D=0,O=0,k=0;for(let e=r;e<=u;e++)E+=c[e]-i[e],D+=l[e]-a[e],O+=i[e],k+=a[e];E/=T,D/=T,O/=T,k/=T;let A=0,j=0;for(let e=r;e<=u;e++){let t=i[e]-O,n=a[e]-k;A+=t*(l[e]-a[e]-D)-n*(c[e]-i[e]-E),j+=t*t+n*n}let M=j>1e-12?A/j:0;for(let e=r;e<=u;e++){let t=i[e]-O,n=a[e]-k;i[e]=c[e]-E+M*n,a[e]=l[e]-D-M*t}}}response(e,t=[]){let n=this.targets,{x:r,y:i,count:a}=e;t.length=0;for(let e=1;e<a-1;e++){let a=r[e]-r[e-1],o=i[e]-i[e-1],s=r[e+1]-r[e],c=i[e+1]-i[e];t.push({joint:e,commanded:n[e],delivered:Math.atan2(a*c-o*s,a*s+o*c)})}return t}},W=Math.PI*2,G=8,K=1.5,q=/* @__PURE__ */ __name((e,t)=>Math.sqrt(e*e+t*t),`magnitude`),compareGain=(e,t,n)=>e[t]-e[n]||t-n,selectLowest=(e,t,n)=>{if(n<=0||n>=e.length)return;let r=n-1,i=0,a=e.length-1;for(;i<a;){let n=e[i+a>>1],o=i,s=a;for(;o<=s;){for(;o<=a&&compareGain(t,e[o],n)<0;)o++;for(;s>=i&&compareGain(t,n,e[s])<0;)s--;if(o<=s){let t=e[o];e[o++]=e[s],e[s--]=t}}if(r<=s)a=s;else if(r>=o)i=o;else return}},Body=class{constructor(e,t,n=t.phase){this.model=e,this.gait=t,this.breathingPhase=n,this.breathingScale=0,this.accumulator=0,this.axis={x:1,y:0},this.steeringBias=0,this.chain=new ChainState(e.chunks.length),this.linkTargets=new Float64Array(e.links.length),this.bend=new Bend(e.chunks.length),this.breathingShiftX=new Float64Array(e.chunks.length),this.breathingShiftY=new Float64Array(e.chunks.length),this.liftOrder=e.chunks.map((e,t)=>t),this.liftTargets=new Float64Array(e.chunks.length),this.tables=new ChainTables(e,e.gait,p,G)}reconfigure(e,t,n=1,r=this.breathingPhase){if(e.chunks.length!==this.chain.count)throw Error(`cannot reconfigure a different chunk count`);this.model=e,this.gait=t,this.breathingPhase=r,this.tables.refresh(e,e.gait,p,G),this.refreshContacts(n)}place(e,t){let{x:n,y:r,px:i,py:a,dx:o,dy:s,idle:c,gain:l,count:u}=this.chain;for(let d=0;d<u;d++){let u=this.model.chunks[d].restDistance;n[d]=e.x-t.x*u,r[d]=e.y-t.y*u,i[d]=n[d],a[d]=r[d],o[d]=t.x,s[d]=t.y,c[d]=0,l[d]=0}this.axis={...t},this.steeringBias=0,this.accumulator=0,this.breathingScale=0,this._breathe(this._breathingTarget());let d=e.x-n[0],f=e.y-r[0];for(let e=0;e<u;e++)n[e]+=d,r[e]+=f,i[e]+=d,a[e]+=f;this.refreshContacts(1)}adopt(e){carryChunks(this.chain,this.model,e.chain,e.model),this.axis={...e.axis},this.steeringBias=e.steeringBias,this.accumulator=e.accumulator,this.breathingScale=e.breathingScale}refreshContacts(e){let t=this.model.physics.autoLift,{idle:n,gaitContact:r,contact:i,count:a}=this.chain;for(let o=0;o<a;o++){let a=this.model.chunks[o];r[o]=this.gait.contactAt(a.restDistance,e,a.motionScale.contact),i[o]=Math.max(0,Math.min(1,r[o]*(1-t.amount*n[o]*e)))}}step(e,t,n,r){let i=this.accumulator+e,a=2**-52*Math.max(1,i),o=Math.floor((i+a)/p);this.accumulator=i;for(let e=1;e<=o;e++)this.accumulator=Math.max(0,i-e*p),this._substep(p,t,n),r&&r(p);return o>0}_substep(e,t,n){this.gait.advance(e,t),this.breathingPhase=(this.breathingPhase+W*this.model.breathing.cyclesPerSecond*e)%W,this._updateTangentsAndAxis(e);let r=I*e,i=this._breathingTarget()-this.breathingScale;this._breathe(this.breathingScale+Math.max(-r,Math.min(r,i))),this._integrate(e,t),this._updateLinkTargets(t),this.bend.update(this.model,this.gait,this.tables,this.linkTargets,t,this._steer(n,e)),this.bend.relax(this.chain,this.tables.jointCorrectionHalf);for(let e=0;e<G;e++)this._relaxLinks();this._clampLinks(),this._applyAutoLift(e,t)}_breathingTarget(){return this.model.breathing.strain*Math.sin(this.breathingPhase)}_breathe(e){let t=e-this.breathingScale;if(this.breathingScale=e,Math.abs(t)<1e-15)return;let{start:n,end:r,count:i,spacing:a}=this.model.sections.trunk,o=(i-1)/2,{x:s,y:c,px:l,py:u,dx:d,dy:f,count:p}=this.chain,m=0,h=0;for(let e=0;e<p;e++){let i=e<n?o:e>=r?-o:o-(e-n),s=e<n?n:e>=r?r-1:e,c=i*a*t,l=d[s]*c,u=f[s]*c;this.breathingShiftX[e]=l,this.breathingShiftY[e]=u,m+=l/p,h+=u/p}for(let e=0;e<p;e++){let t=this.breathingShiftX[e]-m,n=this.breathingShiftY[e]-h;s[e]+=t,c[e]+=n,l[e]+=t,u[e]+=n}}_updateTangentsAndAxis(e){let{x:t,y:n,px:r,py:i,dx:a,dy:o,count:s}=this.chain,c=s-1,l=0,u=0;for(let e=0;e<s;e++){let s=e===0?0:e-1,d=e===c?c:e+1,f=t[s]-t[d],p=n[s]-n[d],m=Math.sqrt(f*f+p*p);m>=1e-9&&(a[e]=f/m,o[e]=p/m),l+=t[e]-r[e],u+=n[e]-i[e]}let d=Math.sqrt(l*l+u*u);if(d<1e-9)return;let f=Math.min(1,e*K);this.axis.x+=(l/d-this.axis.x)*f,this.axis.y+=(u/d-this.axis.y)*f;let p=q(this.axis.x,this.axis.y)||1;this.axis.x/=p,this.axis.y/=p}_integrate(e,t){let n=e*e,r=this.gait.gait,i=this.gait.phase,a=r.contact,o=r.thrust,s=a.harmonic,c=o.harmonic,l=a.phaseOffset,u=o.phaseOffset,d=a.dutyCycle,f=o.dutyCycle,p=a.amplitude,m=o.acceleration,h=this.model.physics.autoLift.amount,g=this.axis.x,_=this.axis.y,{retention:v,gripForward:y,gripBackward:b,gripLateral:x,motionContact:S,motionThrust:C,phaseLag:w}=this.tables,{x:T,y:E,px:D,py:O,dx:k,dy:A,idle:j,gain:M,gaitContact:N,contact:ee,count:te}=this.chain;for(let e=0;e<te;e++){let r=v[e],a=T[e],o=E[e],te=(a-D[e])*r,ne=(o-O[e])*r;D[e]=a,O[e]=o;let P=a+te,re=o+ne,F=k[e],I=A[e],L=P-a,ie=re-o,R=L*F+ie*I,z=L*-I+ie*F,B=i-w[e],V=positiveModulo(s*B+l,W)/W,H=V>=d?1:1-p*S[e]*t*Math.sin(Math.PI*V/d);N[e]=H;let U=Math.max(0,Math.min(1,H*(1-h*j[e]*t)));ee[e]=U;let G=R*(1-U*(R<0?b[e]:y[e])),K=z*(1-U*x[e]),q=a+F*G-I*K,J=o+I*G+F*K;M[e]=-((R-G)*(F*g+I*_)+(z-K)*(-I*g+F*_));let Y=positiveModulo(c*B+u,W)/W,X=Y>=f?0:m*C[e]*t*Math.sin(Math.PI*Y/f);T[e]=q+F*X*n,E[e]=J+I*X*n}}_steer(e,t){let n=this.model.physics.steering,{dx:r,dy:i}=this.chain,a=Math.atan2(r[0]*e.y-i[0]*e.x,r[0]*e.x+i[0]*e.y),o=-Math.max(-n.limit,Math.min(n.limit,a*n.gain));return this.steeringBias+=(o-this.steeringBias)*Math.min(1,t*n.rate),this.steeringBias}_updateLinkTargets(e){let t=this.model.gait.gather,n=t.harmonic*this.gait.phase,r=Math.sin(n),i=Math.cos(n),a=t.amplitude,o=this.breathingScale,s=this.linkTargets,{linkRestLength:c,gatherScale:l,gatherPhaseSine:u,gatherPhaseCosine:d,linkBreathes:f}=this.tables;for(let t=0;t<s.length;t++){let n=i*d[t]-r*u[t],p=1+a*l[t]*e*n;s[t]=c[t]*p*(f[t]?1+o:1)}}_relaxLinks(){let{x:e,y:t}=this.chain,n=this.linkTargets,r=this.tables.linkCorrectionHalf,i=n.length,a=e[0],o=t[0];for(let s=0;s<i;s++){let i=e[s+1],c=t[s+1],l=i-a,u=c-o,d=Math.sqrt(l*l+u*u)||.001,f=(d-n[s])/d*r[s];e[s]=a+l*f,t[s]=o+u*f,a=i-l*f,o=c-u*f}e[i]=a,t[i]=o}_clampLinks(){let{x:e,y:t}=this.chain,n=this.linkTargets,r=n.length,i=e[0],a=t[0];for(let o=0;o<r;o++){let r=n[o]*3,s=e[o+1]-i,c=t[o+1]-a,l=Math.sqrt(s*s+c*c);if(l>r){let n=r/l;i+=s*n,a+=c*n,e[o+1]=i,t[o+1]=a}else i=e[o+1],a=t[o+1]}}_applyAutoLift(e,t){let n=this.model.physics.autoLift;if(!n.amount)return;let{idle:r,gain:i,gaitContact:a,contact:o,count:s}=this.chain,c=Math.round(n.share*s);selectLowest(this.liftOrder,i,c),this.liftTargets.fill(0);for(let e=0;e<c;e++)this.liftTargets[this.liftOrder[e]]=t;let l=Math.min(1,e*n.rate);for(let e=0;e<s;e++)r[e]+=(this.liftTargets[e]-r[e])*l,o[e]=Math.max(0,Math.min(1,a[e]*(1-n.amount*r[e]*t)))}getPose(e){let{x:t,y:n,dx:r,dy:i,count:a}=this.chain,o=t[0]-t[1],s=n[0]-n[1],c=q(o,s);c<1e-9?(e.direction.x=r[0],e.direction.y=i[0]):(e.direction.x=o/c,e.direction.y=s/c);let l=0,u=0;for(let e=0;e<a;e++)l+=t[e]/a,u+=n[e]/a;return e.head.x=t[0],e.head.y=n[0],e.center.x=l,e.center.y=u,e}},lerp=(e,t,n)=>e+(t-e)*n,clamp=(e,t,n)=>Math.max(t,Math.min(n,e)),J=/* @__PURE__ */ __name((e,t)=>Math.sqrt(e*e+t*t),`magnitude`),limbLength=(e,t,n)=>{let r=n<=.5?lerp(.9,1.35,n*2):lerp(1.35,1.72,(n-.5)*2);return e*t*r},Legs=class{constructor(e,t,n,r){this.model=e,this.body=t,this.gait=n,this.random=r,this.legs=[],this._build()}reconfigure(e,t,n){this.model=e,this.body=t,this.gait=n;let r=this._anchors();this.legs.forEach(e=>e.anchor=r[e.pair])}_signedRandom(){return this.random()*2-1}_vary(e){return 1+e*this._signedRandom()}_anchors(){let{pairs:e,start:t,end:n}=this.model.legs;if(!e)return[];let r=this.model.chunks[t].restDistance,i=this.model.chunks[n-1].restDistance;return Array.from({length:e},(a,o)=>{let s=e===1?.5:o/(e-1),c=lerp(r,i,s),l=t;for(let e=t+1;e<n;e++)Math.abs(this.model.chunks[e].restDistance-c)<Math.abs(this.model.chunks[l].restDistance-c)&&(l=e);return l})}_build(){let e=this.model.legs;this._anchors().forEach((t,n)=>{[[`left`,-1],[`right`,1]].forEach(([r,i])=>{let a={pair:n,anchor:t,side:r,sideSign:i,character:this._signedRandom(),reachScale:this._vary(e.jitter*.28),spreadScale:this._vary(e.jitter*.3),leadScale:this._vary(e.jitter*.45),dragScale:1,swingScale:1,liftAt:e.liftThreshold,scatter:{x:0,y:0},plantSpan:0,progress:1,contactLow:!1,foot:{x:0,y:0},hold:{x:0,y:0},from:{x:0,y:0}};this._rollStep(a);let o=this._plantAt(a);Object.assign(a.foot,o),Object.assign(a.hold,o),Object.assign(a.from,o),a.plantSpan=J(o.x-this.body.chain.x[t],o.y-this.body.chain.y[t]),this.legs.push(a)})})}_rollStep(e){let t=this.model.legs.jitter;e.dragScale=this._vary(t*.4)*(1+t*.35*e.character),e.swingScale=this._vary(t*.3),e.liftAt=clamp(this.model.legs.liftThreshold+t*.2*e.character,0,1);let n=Math.max(this.model.legs.reach,this.model.legs.spread)*t*.1;e.scatter={x:n*this._signedRandom(),y:n*this._signedRandom()}}_plantAt(e){let t=this.model.legs,{x:n,y:r,dx:i,dy:a}=this.body.chain,o=e.anchor,s=t.reach*e.reachScale*(.5+t.lead*.5)*e.leadScale,c=t.spread*e.spreadScale*e.sideSign;return{x:n[o]+i[o]*s-a[o]*c,y:r[o]+a[o]*s+i[o]*c}}contactFor(e,t){let n=this.model.chunks[e.anchor],r=e.side===`right`?Math.PI*this.model.legs.sidePhase:0;return clamp(this.gait.contactAt(n.restDistance,t,n.motionScale.contact,r)*(1-this.model.physics.autoLift.amount*this.body.chain.idle[e.anchor]*t),0,1)}update(e,t){let n=this.model.legs,r=this.body.chain;for(let i=0;i<this.legs.length;i++){let a=this.legs[i],o=r.x[a.anchor],s=r.y[a.anchor],c=r.dx[a.anchor],l=r.dy[a.anchor],u=this.contactFor(a,t)<a.liftAt,d=u&&!a.contactLow;if(a.contactLow=u,a.progress<1){let t=n.swingSeconds*a.swingScale;a.progress=Math.min(1,a.progress+e/t);let r=Math.sin(Math.PI*a.progress)*n.swingArc;a.foot.x=lerp(a.from.x,a.hold.x,a.progress)-l*r*a.sideSign,a.foot.y=lerp(a.from.y,a.hold.y,a.progress)+c*r*a.sideSign;continue}Object.assign(a.foot,a.hold);let f=a.foot.x-o,p=a.foot.y-s,m=f*c+p*l,h=n.reach*a.reachScale,g=m<-(h*(.5-n.lead*.5))*a.dragScale,_=J(h,n.spread*a.spreadScale),v=J(f,p)>Math.max(_,a.plantSpan)*1.55;if(d||g||v){Object.assign(a.from,a.foot);let e=this._plantAt(a);a.hold.x=e.x+a.scatter.x,a.hold.y=e.y+a.scatter.y,a.plantSpan=J(a.hold.x-o,a.hold.y-s),a.progress=0,this._rollStep(a),a.contactLow=this.contactFor(a,t)<a.liftAt}}}translate(e){this.legs.forEach(t=>{[t.foot,t.hold,t.from].forEach(t=>{t.x+=e.x,t.y+=e.y})})}armLength(e){return limbLength(this.model.legs.reach,e.reachScale,this.model.legs.fold)}},Y=Object.freeze({chunkStride:4,legStride:11,ornamentStride:6,plateStride:5}),X=13,Z=Math.PI/2,magnitude=(e,t)=>Math.sqrt(e*e+t*t),springCoefficients=(e,t,n,r)=>{let i=t*r;if(i<1e-9){e.positionPosition=1,e.positionVelocity=r,e.velocityPosition=0,e.velocityVelocity=1;return}let a=Math.exp(-n*i);if(n>=1-1e-8){e.positionPosition=a*(1+i),e.positionVelocity=a*r,e.velocityPosition=-a*t*i,e.velocityVelocity=a*(1-i);return}let o=t*Math.sqrt(1-n*n),s=Math.cos(o*r),c=Math.sin(o*r),l=n*t/o;e.positionPosition=a*(s+l*c),e.positionVelocity=a*c/o,e.velocityPosition=-a*t*t*c/o,e.velocityVelocity=a*(s-l*c)},rootFor=(e,t,n)=>{let r=e.chunk,i=t.dx[r],a=t.dy[r];return n.x=t.x[r]+i*e.offset.forward-a*e.offset.outward*e.sideSign,n.y=t.y[r]+a*e.offset.forward+i*e.offset.outward*e.sideSign,n.dx=i*e.angleCosine-a*e.angleSine,n.dy=a*e.angleCosine+i*e.angleSine,n},jointFor=(e,t,n,r,i)=>{let a=t.x-e.x,o=t.y-e.y,s=magnitude(a,o),c=s>.001?-o/s:-e.dy,l=s>.001?a/s:e.dx,u=n/2,d=Math.min(s,n)/2,f=Math.sqrt(Math.max(0,u**2-d**2));return i.x=e.x+a/2+c*f*r,i.y=e.y+o/2+l*f*r,i},Skin=class{constructor(e,t,n){this.model=e,this.body=t,this.legs=n,this.joint={x:0,y:0},this.hip={x:0,y:0,dx:0,dy:0},this.ornaments=[],this._buildOrnaments()}reconfigure(e,t,n){this.model=e,this.body=t,this.legs=n,this.ornaments.forEach((n,r)=>{n.spec=e.skin.ornaments[r],n.coefficientDt=null;let i=rootFor(n.spec,t.chain,n.root),a=Math.cos(n.angle),o=Math.sin(n.angle);n.directionX=i.dx*a-i.dy*o,n.directionY=i.dy*a+i.dx*o})}_buildOrnaments(){this.ornaments=this.model.skin.ornaments.map(e=>{let t=rootFor(e,this.body.chain,{});return{spec:e,root:t,nextRoot:{...t},angle:0,velocity:0,directionX:t.dx,directionY:t.dy,coefficientDt:null,positionPosition:1,positionVelocity:0,velocityPosition:0,velocityVelocity:1}})}_fitRenderState(e){e||={layout:Y},e.model=this.model;let t={chunks:this.body.chain.count*Y.chunkStride,legs:this.legs.legs.length*Y.legStride,ornaments:this.ornaments.length*Y.ornamentStride,plates:this.model.skin.platesTailFirst.length*Y.plateStride};for(let[n,r]of Object.entries(t))e[n]&&e[n].length===r||(e[n]=new Float64Array(r));return e}writeRenderState(e){e=this._fitRenderState(e);let t=this.body.chain,n=Y.chunkStride;for(let r=0;r<t.count;r++){let i=r*n;e.chunks[i]=t.x[r],e.chunks[i+1]=t.y[r],e.chunks[i+2]=t.dx[r],e.chunks[i+3]=t.dy[r]}let r=this.model.legs.skin.foot,i=Y.legStride,a=this.legs.legs.length?this.model.chunks[this.model.legs.start].restDistance:0,o=this.legs.legs.length?this.model.chunks[this.model.legs.end-1].restDistance-a:0,{jointBend:s,jointLeanCenter:c}=this.model.legs;for(let n=0;n<this.legs.legs.length;n++){let l=this.legs.legs[n],u=this.hip;u.x=t.x[l.anchor],u.y=t.y[l.anchor],u.dx=t.dx[l.anchor],u.dy=t.dy[l.anchor];let d=this.legs.armLength(l),f=jointFor(u,l.foot,d,l.sideSign*s,this.joint),p=o?2*(this.model.chunks[l.anchor].restDistance-a)/o-1:0,m=n*i;e.legs[m]=u.x,e.legs[m+1]=u.y,e.legs[m+2]=f.x,e.legs[m+3]=f.y,e.legs[m+4]=l.foot.x,e.legs[m+5]=l.foot.y,e.legs[m+6]=u.dx,e.legs[m+7]=u.dy,e.legs[m+8]=r.scale*(l.progress<1?1:r.plantedScale),e.legs[m+9]=l.sideSign,e.legs[m+10]=(p-c)*d}let l=Y.ornamentStride;for(let t=0;t<this.ornaments.length;t++){let n=this.ornaments[t],r=t*l;e.ornaments[r]=n.root.x,e.ornaments[r+1]=n.root.y,e.ornaments[r+2]=n.directionX,e.ornaments[r+3]=n.directionY,e.ornaments[r+4]=n.spec.scale,e.ornaments[r+5]=n.spec.sideSign}let u=this.model.skin.platesTailFirst,d=Y.plateStride;for(let n=0;n<u.length;n++){let r=u[n],i=r.chunk,a=n*d;e.plates[a]=t.x[i],e.plates[a+1]=t.y[i],e.plates[a+2]=t.dx[i],e.plates[a+3]=t.dy[i],e.plates[a+4]=r.scale*this.model.chunks[i].plateScale*(1+this.model.skin.loadScale*t.contact[i])}return e}update(e){for(let t=0;t<this.ornaments.length;t++){let n=this.ornaments[t],{spec:r}=n,i=n.root,a=rootFor(r,this.body.chain,n.nextRoot);n.coefficientDt!==e&&(n.coefficientDt=e,springCoefficients(n,r.recover,1-r.wobble*.98,e));let o=Math.atan2(i.dx*a.dy-i.dy*a.dx,i.dx*a.dx+i.dy*a.dy)/e,s=((a.x-i.x)*-a.dy+(a.y-i.y)*a.dx)/e,c=Math.min(Z,Math.max(-Z,r.waveGain*-o/X+r.physGain*-s/this.model.skin.lateralRate)),l=n.angle-c,u=c+l*n.positionPosition+n.velocity*n.positionVelocity,d=l*n.velocityPosition+n.velocity*n.velocityVelocity;u>Z?(u=Z,d=0):u<-Z&&(u=-Z,d=0),n.angle=u,n.velocity=d;let f=Math.cos(u),p=Math.sin(u);n.directionX=a.dx*f-a.dy*p,n.directionY=a.dy*f+a.dx*p,n.root=a,n.nextRoot=i}}translate(e){this.ornaments.forEach(t=>{t.root.x+=e.x,t.root.y+=e.y})}},ae=4,oe=14,limbIndicesFor=e=>{let t=new Uint32Array(e*6*6),n=0;for(let r=0;r<e;r++){let e=r*oe,i=e+oe-1;for(let r=0;r<6;r++){let a=e+r,o=i-r;t.set([a,o,a+1,a+1,o,o-1],n),n+=6}}return t},se=/* @__PURE__ */ new Float64Array(13),ce=/* @__PURE__ */ new Float64Array(13);for(let e=0;e<=12;e++){let t=Math.PI*e/12;se[e]=Math.cos(t),ce[e]=Math.sin(t)}var ribbonPositionsFor=e=>new Float32Array((e*2+28)*2),ribbonIndicesFor=e=>{let t=Math.max(0,e-1),n=new Uint32Array(t*6+72),r=0;for(let e=0;e<t;e++){let t=e*2;n.set([t,t+1,t+2,t+2,t+1,t+3],r),r+=6}for(let t of[e*2,e*2+14])for(let e=0;e<12;e++)n.set([t,t+1+e,t+2+e],r),r+=3;return n},snapCoordinate=(e,t,n)=>t===1?Math.round(e):t>0?Math.round(e*t)*n:e,snapPositions=(e,t,n,r,i)=>{if(r===1)for(let r=t;r<n;r++)e[r]=Math.round(e[r]);else if(r>0)for(let a=t;a<n;a++)e[a]=Math.round(e[a]*r)*i},writeCap=(e,t,n,r,i,a,o,s,c,l,u)=>{e[t]=n,e[t+1]=r;for(let l=0;l<=12;l++){let u=t+2+l*2,d=se[l],f=ce[l];e[u]=n+i*(d*a+f*s),e[u+1]=r+i*(d*o+f*c)}snapPositions(e,t,t+28,l,u)},writeLimb=(e,t,n,r,i,a,o,s,c,l=0,u=0)=>{let d=c*.5,f=i-n,p=a-r,m=Math.hypot(f,p)||1,h=o-i,g=s-a,_=Math.hypot(h,g)||1,v=-p/m,y=f/m,b=-g/_,x=h/_,S=1+v*b+y*x,C=v,w=y;if(S>1e-6){C=(v+b)/S,w=(y+x)/S;let e=Math.abs((C*f+w*p)/m*d),t=Math.min(m,_);e>t&&(C=C*t/e,w=w*t/e)}let T=Math.atan2(v*x-y*b,v*b+y*x),E=Math.cos(T/ae),D=Math.sin(T/ae),O=T<=0,k=v,A=y,j=t+12,M=t+28-2;e[t]=n+v*d,e[t+1]=r+y*d,e[j]=o+b*d,e[j+1]=s+x*d,e[j+2]=o-b*d,e[j+3]=s-x*d,e[M]=n-v*d,e[M+1]=r-y*d;for(let n=0;n<5;n++){let r=O?k:C,o=O?A:w,s=O?C:k,c=O?w:A,l=t+(1+n)*2,u=t+(12-n)*2;e[l]=i+r*d,e[l+1]=a+o*d,e[u]=i-s*d,e[u+1]=a-c*d;let f=k*E-A*D;A=k*D+A*E,k=f}snapPositions(e,t,t+28,l,u)},discard=(e,t)=>{t.parent===e&&e.removeChild(t);let n=t.geometry??null;t.destroy(),n&&n.destroy(!0)},contextFor=(e,t,n)=>{let r=new s.GraphicsPath(e.path).transform(new s.Matrix(n,0,0,n,0,0)),i=new s.GraphicsContext().path(r);return t.fill!==null&&i.fill(t.fill),t.stroke!==null&&t.strokeWidth>0&&i.stroke({color:t.stroke,width:t.strokeWidth*n,cap:`butt`,join:`miter`}),i},paintMesh=(e,t)=>{let n=new s.Color(t);e.tint=n.toNumber(),e.alpha=n.alpha},meshFor=(e,t,n)=>{let r=new s.MeshGeometry({positions:e,uvs:new Float32Array(e.length),indices:t,shrinkBuffersToFit:!1}),i=new s.Mesh({geometry:r,texture:s.Texture.WHITE,roundPixels:!1});return paintMesh(i,n),i.dynamicPositions=e,i.positionBuffer=r.getBuffer(`aPosition`),i},le=1,ue=1,de=1024,frameKeyFor=(e,t)=>`${e.path}|${t.fill}|${t.stroke}|${t.strokeWidth}`,Q=/* @__PURE__ */ new WeakMap,fe=/* @__PURE__ */ new WeakMap,planAtlas=(e,t)=>{let n=t*4,r=/* @__PURE__ */ new Map,claim=(e,t,n)=>{if(!(n>0))return null;let i=frameKeyFor(e,t),a=r.get(i);return a?a.scale=Math.max(a.scale,n):r.set(i,{key:i,shape:e,paint:t,scale:n}),i},i=e.legs.skin.foot,a=e.legs.pairs?claim(i.shape,i.paint,i.scale*Math.max(1,i.plantedScale)):null,o=1+Math.max(0,e.skin.loadScale),s=e.skin.platesTailFirst.map(t=>claim(t.shape,t.paint,t.scale*e.chunks[t.chunk].plateScale*o)),c=e.skin.ornaments.map(e=>claim(e.shape,e.paint,e.scale));return{key:`${n}\n${[...r.values()].map(({key:e,scale:t})=>`${e}|${t}`).sort().join(`
4
+ `)}`,resolution:n,frames:[...r.values()],feet:a,plates:s,ornaments:c}},arrangeEntries=e=>{e.sort((e,t)=>t.height-e.height||e.key.localeCompare(t.key));let t=0,n=0,r=0,i=0;for(let a of e)t>0&&t+a.width>2048&&(t=0,n+=r,r=0),a.x=t,a.y=n,t+=a.width,r=Math.max(r,a.height),i=Math.max(i,t);return{width:i,height:n+r}},packAtlas=e=>{let t=e.resolution,n=[];try{for(let t of e.frames){let e=contextFor(t.shape,t.paint,t.scale),r={...t,context:e,requestedScale:t.scale};n.push(r);let i=e.bounds;if(r.bounds={minX:i.minX,minY:i.minY,width:i.width,height:i.height},!Object.values(r.bounds).every(Number.isFinite))throw RangeError(`atlas shape bounds must be finite`)}let r=de,i;for(;;){for(let e of n){let{bounds:n,paint:i,requestedScale:a}=e,o=i.strokeWidth*a*le*t,s=Math.max(n.width,n.height)*t,c=Math.ceil(s)+2*Math.max(ue,Math.ceil(o))<=r?1:(r-3)/(s+2*o);e.scale=a*c,e.pad=Math.max(ue,Math.ceil(o*c)),e.originX=e.pad+Math.ceil(-n.minX*c*t),e.originY=e.pad+Math.ceil(-n.minY*c*t),e.width=Math.ceil(n.width*c*t)+e.pad*2,e.height=Math.ceil(n.height*c*t)+e.pad*2}if(i=arrangeEntries(n),i.width<=2048&&i.height<=2048)break;if(r===4)throw RangeError(`too many atlas frames for the texture budget`);r=Math.max(4,Math.floor(r*.75))}for(let e of n)e.scale!==e.requestedScale&&(e.context.destroy(),e.context=null,e.context=contextFor(e.shape,e.paint,e.scale));return{resolution:t,...i,entries:n}}catch(e){for(let e of n)e.context?.destroy();throw e}},prepareAtlas=(e,t)=>{let n=fe.get(e);if(n?.renderResolution===t)return n.plan;if(!Number.isFinite(t)||t<=0)throw RangeError(`pixelResolution must be finite and positive`);let r=planAtlas(e,t),i=packAtlas(r);for(let e of i.entries)e.context.destroy();return fe.set(e,{renderResolution:t,plan:r}),r},bakeAtlas=(e,t)=>{let n=packAtlas(e),r=1/n.resolution,i=s.RenderTexture.create({width:n.width*r,height:n.height*r,resolution:n.resolution,antialias:!1,scaleMode:`nearest`}),a=/* @__PURE__ */ new Map,o=!1;try{let e=!0;for(let o of n.entries){let n=new s.Graphics(o.context);try{t.render({container:n,target:i,clear:e,transform:new s.Matrix(1,0,0,1,(o.x+o.originX)*r,(o.y+o.originY)*r)})}finally{n.destroy()}e=!1,a.set(o.key,{texture:new s.Texture({source:i.source,frame:new s.Rectangle(o.x*r,o.y*r,o.width*r,o.height*r)}),scale:o.scale,anchorX:o.originX/o.width,anchorY:o.originY/o.height})}o=!0}finally{for(let e of n.entries)e.context.destroy();if(!o){for(let e of a.values())e.texture.destroy();i.destroy(!0)}}return{key:e.key,renderer:t,target:i,frames:a}},acquireAtlas=(e,t)=>{if(!e.frames.length)return null;let n=Q.get(t);n||Q.set(t,n=/* @__PURE__ */ new Map);let r=n.get(e.key);return r||(r={atlas:bakeAtlas(e,t),uses:0},n.set(e.key,r)),r.uses++,r.atlas},releaseAtlas=e=>{let t=e&&Q.get(e.renderer),n=t&&t.get(e.key);if(!(!n||--n.uses>0)){t.delete(e.key);for(let t of e.frames.values())t.texture.destroy();e.target.source.removeAllListeners(`change`),e.target.destroy(!0)}},pe=[`feet`,`ornaments-under`,`plates`,`ornaments-over`],me={position:!0,vertex:!0,rotation:!0,uvs:!1,color:!1},HeadlessGraphics=class{static available=!1;static prepare(){}static prepareAtlas(){}},he=l*2,pixelResolutionOf=e=>{let t=e?.pixelResolution;if(t===void 0)return 1;if(!Number.isFinite(t))throw RangeError(`pixelResolution must be finite and positive`);return Math.max(u,Math.min(d,t))},afterPass=e=>queueMicrotask(e),Graphics=class{static available=!0;static prepare(e){for(let[t,n]of Object.entries(e.descriptor.definitions.shapes))try{new s.GraphicsPath(n.path)}catch(e){throw Error(`$.definitions.shapes.${t}.path: ${e.message}`)}for(let[t,n]of Object.entries(e.paints))for(let e of[`fill`,`stroke`])if(n[e]!==null)try{new s.Color(n[e])}catch(n){throw Error(`$.definitions.paints.${t}.${e===`stroke`?`stroke.colour`:e}: ${n.message}`)}}static prepareAtlas(e,t){return prepareAtlas(e,pixelResolutionOf(t))}constructor(e,t,n=null){this.host=e,this.failedBake=null,this.parent=e.addChild(new s.Container),this.model=t.model,this.options=n||{},this.footParticles=[],this.ornamentParticles=[],this.plateParticles=[],this.shapeContainers=[],this.atlas=null,this.atlasRenderer=null,this.bakeRenderer=null,this.plan=null,this.legCount=0,this.limbPositions=null,this.limbFill=null,this.limbStroke=null,this.limbCount=-1,this.ribbonPositions=null,this.ribbonFill=null,this.ribbonStroke=null,this.ribbonCount=-1,this.reportedResolution=null,this.baking=!1,this.state=null,this.adopt(t)}adopt(e){let t=pixelResolutionOf(this.options),n=prepareAtlas(e.model,t),r=e.legs.length/e.layout.legStride;this._samePlacements(n,e.model,r)?this._sameFrames(n)&&(this.plan=n):(this.plan=null,this.footParticles=[],this.ornamentParticles=[],this.plateParticles=[]),this.nextPlan=n,this.nextResolution=t,this.failedBake=null,this.model=e.model,this.legCount=r;let i=this._syncLimbParts(this.legCount);i=this._syncRibbonParts()||i,i&&this._arrange(),this.sync(e)}_samePlacements(e,t,n){let r=this.plan;if(!r||n!==this.legCount)return!1;let drawn=(e,t)=>e===null==(t===null);return drawn(r.feet,e.feet)&&r.plates.length===e.plates.length&&r.plates.every((t,n)=>drawn(t,e.plates[n]))&&r.ornaments.length===e.ornaments.length&&r.ornaments.every((n,r)=>drawn(n,e.ornaments[r])&&this.model.skin.ornaments[r].layer===t.skin.ornaments[r].layer)}_sameFrames(e){let t=this.plan;return t.key===e.key&&t.feet===e.feet&&t.plates.every((t,n)=>t===e.plates[n])&&t.ornaments.every((t,n)=>t===e.ornaments[n])}_drop(e){discard(this.parent,e)}_syncLimbParts(e){let t=this.model.legs.skin.limbPaint,n=e>0&&t.fill!==null,r=e>0&&t.stroke!==null&&t.strokeWidth>0,i=e!==this.limbCount,a=!1;return i&&(this.limbCount=e,this.limbPositions=new Float32Array(e*28)),this.limbFill&&(i||!n)&&(this._drop(this.limbFill),this.limbFill=null,a=!0),n&&!this.limbFill?(this.limbFill=meshFor(this.limbPositions,limbIndicesFor(e),t.fill),a=!0):this.limbFill&&paintMesh(this.limbFill,t.fill),this.limbStroke&&!r?(this._drop(this.limbStroke),this.limbStroke=null,a=!0):r&&!this.limbStroke&&(this.limbStroke=new s.Graphics,a=!0),a}_syncRibbonParts(){let e=this.model.skin.ribbonPaint,t=this.model.chunks.length,n=e.fill!==null,r=e.stroke!==null&&e.strokeWidth>0,i=t!==this.ribbonCount,a=!1;return i&&(this.ribbonCount=t,this.ribbonPositions=ribbonPositionsFor(t)),this.ribbonFill&&(i||!n)&&(this._drop(this.ribbonFill),this.ribbonFill=null,a=!0),n&&!this.ribbonFill?(this.ribbonFill=meshFor(this.ribbonPositions,ribbonIndicesFor(t),e.fill),a=!0):this.ribbonFill&&paintMesh(this.ribbonFill,e.fill),this.ribbonStroke&&!r?(this._drop(this.ribbonStroke),this.ribbonStroke=null,a=!0):r&&!this.ribbonStroke&&(this.ribbonStroke=new s.Graphics,a=!0),a}_arrange(){let[e,t,n,r]=this.shapeContainers;for(let i of[e,this.limbFill,this.limbStroke,t,this.ribbonFill,this.ribbonStroke,n,r])i&&this.parent.addChild(i)}_buildParticles(e){let t=[null,null,null,null],bandFor=e=>(t[e]||(t[e]=new s.ParticleContainer({label:pe[e],dynamicProperties:me})),t[e]),place=(e,t)=>{let n=t===null?null:this.atlas.frames.get(t);if(!n)return null;let r=new s.Particle({texture:n.texture,anchorX:n.anchorX,anchorY:n.anchorY});return r.bakeScale=n.scale,bandFor(e).addParticle(r),r};this.footParticles=Array.from({length:this.legCount},()=>place(0,e.feet)),this.ornamentParticles=e.ornaments.map((e,t)=>place(this.model.skin.ornaments[t].layer===`under`?1:3,e)),this.plateParticles=e.plates.map(e=>place(2,e)),this.shapeContainers=t,this._arrange()}_syncAtlas(e){let t=this._liveResolution();if(t!==this.nextResolution&&(this.nextPlan=prepareAtlas(this.model,t),this.nextResolution=t),e&&(this.plan!==this.nextPlan||this.atlasRenderer!==e)&&(this.failedBake?.plan!==this.nextPlan||this.failedBake.renderer!==e)){if(this.atlasRenderer&&this.atlasRenderer!==e)for(let e of this.shapeContainers)e&&(e.visible=!1);this.bakeRenderer=e,this.baking||(this.baking=!0,afterPass(()=>{if(this.baking=!1,!this.parent.destroyed)try{this._bake(this.bakeRenderer)}catch(e){if(this.failedBake={plan:this.nextPlan,renderer:this.bakeRenderer},!this.host.emit(`error`,e))throw e}}))}}_liveResolution(){let e=this.options.pixelResolution;try{let e=pixelResolutionOf(this.options);return this.reportedResolution=null,e}catch(t){if(!(t instanceof RangeError))throw t;let n=this.reportedResolution;return n&&Object.is(n.value,e)||(this.reportedResolution={value:e},afterPass(()=>{if(!this.parent.destroyed&&!this.host.emit(`error`,t))throw t})),this.nextResolution}}_bake(e){let t=this.nextPlan,n=acquireAtlas(t,e),r=this.atlas,i=this.shapeContainers;this.atlas=n,this.atlasRenderer=e,this.plan=t,this._buildParticles(t);let a=this._snapResolution();this._placeParticles(this.state,a,a>0?1/a:0);for(let e of i)e&&e.destroy();releaseAtlas(r)}_place(e,t,n,r,i,a,o,s,c){if(!e)return;e.x=snapCoordinate(t,s,c),e.y=snapCoordinate(n,s,c),e.rotation=Math.atan2(i,r);let l=a/e.bakeScale;e.scaleX=l,e.scaleY=l*o}_syncLimbs(e,t,n){let r=e.legs,i=this.model.legs.skin.limbWidth,a=this.limbPositions;if(this.limbStroke&&this.limbStroke.clear(),i<=0){a.fill(0),this.limbFill&&this.limbFill.positionBuffer.update();return}let o=e.layout.legStride,s=this.options.kneeProjection??null,c=s?.centerX,u=s?.centerY,d=s?.perspective;Number.isFinite(c)&&Number.isFinite(u)&&Number.isFinite(d)?(c=Math.max(-l,Math.min(l,c)),u=Math.max(-l,Math.min(l,u)),d=Math.max(0,Math.min(f,d))):d=0;let p=s?.maxOffset,m=Number.isFinite(p)?Math.max(0,Math.min(l,p)):he,h=this.model.legs.jointLean;for(let e=0;e<r.length;e+=o){let s=e/o*28,l=r[e+2],f=r[e+3];if(d>0){let t=Math.hypot(l-c,f-u);if(t>0){let n=Math.hypot(l-(r[e]+r[e+4])/2,f-(r[e+1]+r[e+5])/2),i=Math.min(m,t*n*d);l+=(l-c)/t*i,f+=(f-u)/t*i}}if(h!==0){let t=r[e+10]*h;l+=r[e+6]*t,f+=r[e+7]*t}writeLimb(a,s,r[e],r[e+1],l,f,r[e+4],r[e+5],i,t,n)}if(this.limbFill&&this.limbFill.positionBuffer.update(),!this.limbStroke)return;for(let e=0;e<a.length;e+=28){let t=a[e],n=a[e+1];this.limbStroke.moveTo(t,n);for(let r=2;r<28;r+=2){let i=a[e+r],o=a[e+r+1];(i!==t||o!==n)&&(this.limbStroke.lineTo(i,o),t=i,n=o)}this.limbStroke.closePath()}let g=this.model.legs.skin.limbPaint;this.limbStroke.stroke({color:g.stroke,width:g.strokeWidth,cap:`butt`,join:`bevel`})}_syncRibbon(e,t,n){let r=e.chunks,i=e.layout.chunkStride,a=this.model.chunks.length,o=a-1,s=this.ribbonPositions;for(let e=0;e<a;e++){let a=e*i,o=e*4,c=this.model.chunks[e].ribbonWidth;s[o]=r[a]-r[a+3]*c,s[o+1]=r[a+1]+r[a+2]*c,s[o+2]=r[a]+r[a+3]*c,s[o+3]=r[a+1]-r[a+2]*c,snapPositions(s,o,o+4,t,n)}let c=o*i,l=r[c+2],u=r[c+3];writeCap(s,a*4,r[c],r[c+1],this.model.chunks[o].ribbonWidth,-u,l,-l,-u,t,n);let d=r[2],f=r[3];if(writeCap(s,a*4+28,r[0],r[1],this.model.chunks[0].ribbonWidth,f,-d,d,f,t,n),this.ribbonFill&&this.ribbonFill.positionBuffer.update(),!this.ribbonStroke||(this.ribbonStroke.clear(),!this.model.skin.hasRibbon))return;let p=a*4+2,m=a*4+28+2;this.ribbonStroke.moveTo(s[0],s[1]);for(let e=1;e<a;e++)this.ribbonStroke.lineTo(s[e*4],s[e*4+1]);for(let e=1;e<12;e++)this.ribbonStroke.lineTo(s[p+e*2],s[p+e*2+1]);for(let e=o;e>=0;e--)this.ribbonStroke.lineTo(s[e*4+2],s[e*4+3]);for(let e=1;e<12;e++)this.ribbonStroke.lineTo(s[m+e*2],s[m+e*2+1]);this.ribbonStroke.closePath();let h=this.model.skin.ribbonPaint;this.ribbonStroke.stroke({color:h.stroke,width:h.strokeWidth})}sync(e,t=null,n=!0){if(e.model!==this.model)throw Error(`render state model does not match Beefwife graphics`);if(this.state=e,this._syncAtlas(t),!n)return;let r=this._snapResolution(),i=r>0?1/r:0;this._syncLimbs(e,r,i),this._syncRibbon(e,r,i),this._placeParticles(e,r,i)}_snapResolution(){return this.options.roundVertices===!0?this.nextResolution:0}_placeParticles(e,t,n){let r=e.legs;for(let i=0;i<this.footParticles.length;i++){let a=i*e.layout.legStride;this._place(this.footParticles[i],r[a+4],r[a+5],r[a+6],r[a+7],r[a+8],r[a+9],t,n)}let i=e.ornaments;for(let r=0;r<this.ornamentParticles.length;r++){let a=r*e.layout.ornamentStride;this._place(this.ornamentParticles[r],i[a],i[a+1],i[a+2],i[a+3],i[a+4],i[a+5],t,n)}let a=e.plates;for(let r=0;r<this.plateParticles.length;r++){let i=r*e.layout.plateStride;this._place(this.plateParticles[r],a[i],a[i+1],a[i+2],a[i+3],a[i+4],1,t,n)}}destroy(){let e=[...this.shapeContainers,this.limbFill,this.limbStroke,this.ribbonFill,this.ribbonStroke];for(let t of e)t&&discard(this.parent,t);releaseAtlas(this.atlas),this.atlas=null,this.parent.destroy()}},$=c?Graphics:HeadlessGraphics,HeadlessContainer=class{destroy(){this.destroyed=!0}},ge=c?s.Container:HeadlessContainer,_e=/* @__PURE__ */ new WeakMap,freezeDeep=e=>!e||typeof e!=`object`?e:(Object.values(e).forEach(freezeDeep),Object.freeze(e)),modelFor=e=>{let t=_e.get(e);if(t)return t;let n=compile(e);return $.prepare(n),_e.set(e,n),freezeDeep(e),n},ve=Math.PI*2,ye=/* @__PURE__ */ new Set([`position`,`direction`,`phase`,`random`,`render`]),be=/* @__PURE__ */ new Set([`roundVertices`,`pixelResolution`,`kneeProjection`]),xe=/* @__PURE__ */ new Set([`centerX`,`centerY`,`perspective`,`maxOffset`]),Se=/* @__PURE__ */ new Set([`position`,`direction`,`phase`]),Ce=/* @__PURE__ */ new Set([`throttle`,`direction`]),plainObject=(e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`${t} must be an object`);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`${t} must be a plain object`);return e},optionsOf=(e,t,n)=>{if(e===void 0)return{};let r=plainObject(e,n);for(let e in r)if(!t.has(e))throw TypeError(`${n}.${e} is unknown`);return r},defaulted=(e,t)=>e===void 0?t:e,finite=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`${t} must be a finite number`);return e},renderOptionsOf=e=>{if(e===void 0)return null;let t=optionsOf(e,be,`options.render`);if(t.roundVertices!==void 0&&typeof t.roundVertices!=`boolean`)throw TypeError(`options.render.roundVertices must be a boolean`);if(t.pixelResolution!==void 0){let e=finite(t.pixelResolution,`options.render.pixelResolution`);if(e<=0)throw RangeError(`options.render.pixelResolution must be positive`);if(e<1e-6||e>1e6)throw RangeError(`options.render.pixelResolution must be from ${u} to ${d}`)}let n=t.kneeProjection;if(n!=null){optionsOf(n,xe,`options.render.kneeProjection`),worldPoint({x:n.centerX,y:n.centerY},null,`options.render.kneeProjection.center`);let e=finite(n.perspective,`options.render.kneeProjection.perspective`);if(e<0)throw RangeError(`options.render.kneeProjection.perspective must be nonnegative`);if(e>1e6)throw RangeError(`options.render.kneeProjection.perspective must be at most ${f}`);if(n.maxOffset!==void 0){let e=finite(n.maxOffset,`options.render.kneeProjection.maxOffset`);if(e<0)throw RangeError(`options.render.kneeProjection.maxOffset must be nonnegative`);if(e>1e9)throw RangeError(`options.render.kneeProjection.maxOffset must be at most ${l}`)}}return t},point=(e,t,n)=>{if(e===void 0){if(t===null)throw TypeError(`${n} is required`);return{...t}}let r=plainObject(e,n);for(let e in r)if(e!==`x`&&e!==`y`)throw TypeError(`${n}.${e} is unknown`);return{x:finite(r.x,`${n}.x`),y:finite(r.y,`${n}.y`)}},worldPoint=(e,t,n)=>{let r=point(e,t,n);if(Math.abs(r.x)>1e9||Math.abs(r.y)>1e9)throw RangeError(`${n} coordinates must be from ${-l} to ${l}`);return r},directionInto=(e,t,n,r)=>{let i=e===void 0?t:plainObject(e,n);if(e!==void 0){for(let e in i)if(e!==`x`&&e!==`y`)throw TypeError(`${n}.${e} is unknown`)}let a=finite(i.x,`${n}.x`),o=finite(i.y,`${n}.y`),s=Math.max(Math.abs(a),Math.abs(o));if(!s)throw RangeError(`${n} must be nonzero`);let c=a/s,l=o/s,u=Math.hypot(c,l);return r.x=c/u,r.y=l/u,r},direction=(e,t,n)=>directionInto(e,t,n,{}),newPose=()=>({head:{x:0,y:0},center:{x:0,y:0},direction:{x:0,y:0}}),bodyFitsWorld=e=>e.chain.fitsTranslation({x:0,y:0},l),sameTopology=(e,t)=>[`head`,`trunk`,`tail`].every(n=>e.sections[n].count===t.sections[n].count),legCountKey=e=>e.descriptor.legs.pairs,ornamentKey=e=>e.skin.ornaments.map(e=>`${e.id}:${e.side}`).join(`|`),Beefwife=class extends ge{#e;#t;#n;#r;#i;#a;#o;#s=null;#c=!1;#l=null;#u=null;#d=newPose();#f;#p;#m=e=>{this.#f=this.#p,this.#a.update(e,this.#p),this.#o.update(e)};constructor(e,t){super();let n=optionsOf(t,ye,`options`),r=worldPoint(n.position,{x:0,y:0},`options.position`),i=direction(n.direction,{x:1,y:0},`options.direction`),a=finite(defaulted(n.phase,0),`options.phase`);if(n.random!==void 0&&typeof n.random!=`function`)throw TypeError(`options.random must be a function`);this.#e=n.random??Math.random,this.#l=renderOptionsOf(n.render),this.#t={...i},this.#n=modelFor(e),$.prepareAtlas(this.#n,this.#l),this.#r=new Gait(this.#n.gait,a);let o=this.#n.breathing.strain?ve*this.#g():this.#r.phase;if(this.#i=new Body(this.#n,this.#r,o),this.#i.place(r,i),!bodyFitsWorld(this.#i))throw RangeError(`options.position places the body outside the world`);this.#a=new Legs(this.#n,this.#i,this.#r,()=>this.#g()),this.#f=1,this.#p=1,this.#o=new Skin(this.#n,this.#i,this.#a),this.#_(),this.label=this.#n.descriptor.name,this.onRender=$.available?e=>this.#y(e):null,this.#v()}get descriptor(){return this.#n.descriptor}get restLength(){return this.#n.restLength}step(e,t){this.#h(`step`);let n=finite(e,`dt`);if(n<0)throw RangeError(`dt must be nonnegative`);let r=optionsOf(t,Ce,`controls`),i=finite(defaulted(r.throttle,1),`controls.throttle`);if(i<0||i>1)throw RangeError(`controls.throttle must be from 0 to 1`);let a=directionInto(r.direction,this.#t,`controls.direction`,this.#t);if(this.#p=i,this.#i.step(n,i,a,this.#m)){let e=this.#i.chain.worldCorrection(l);(e.x||e.y)&&(this.#i.chain.translate(e),this.#a.translate(e),this.#o.translate(e)),this.#_()}}setDescriptor(e){this.#h(`setDescriptor`);let t=modelFor(e);$.prepareAtlas(t,this.#l);let n=new Gait(t.gait,this.#r.phase),r=!this.#n.breathing.strain&&t.breathing.strain?ve*this.#g():this.#i.breathingPhase,i=sameTopology(this.#n,t),a=this.#i;if(!i&&(a=new Body(t,n,r),a.adopt(this.#i),a.refreshContacts(this.#f),!bodyFitsWorld(a)))throw RangeError(`descriptor places the body outside the world`);let o=legCountKey(this.#n)===legCountKey(t)?null:new Legs(t,a,n,()=>this.#g()),s=ornamentKey(this.#n)===ornamentKey(t)?null:new Skin(t,a,o||this.#a);i?this.#i.reconfigure(t,n,this.#f,r):this.#i=a,o?this.#a=o:this.#a.reconfigure(t,this.#i,n),s?this.#o=s:this.#o.reconfigure(t,this.#i,this.#a),this.#n=t,this.#r=n,this.#_(),this.label=t.descriptor.name,this.#v()}reset(e){this.#h(`reset`);let t=optionsOf(e,Se,`options`),n=this.#i.getPose(this.#d),r=worldPoint(t.position,n.head,`options.position`),i=direction(t.direction,n.direction,`options.direction`),a=finite(defaulted(t.phase,this.#r.phase),`options.phase`),o=new Gait(this.#n.gait,a),s=this.#n.breathing.strain?ve*this.#g():o.phase,c=new Body(this.#n,o,s);if(c.place(r,i),!bodyFitsWorld(c))throw RangeError(`options.position places the body outside the world`);let l=new Legs(this.#n,c,o,()=>this.#g()),u=new Skin(this.#n,c,l);t.direction!==void 0&&(this.#t={...i}),this.#r=o,this.#i=c,this.#a=l,this.#o=u,this.#f=1,this.#_(),this.#s&&this.#y()}translate(e){this.#h(`translate`);let t=worldPoint(e,null,`offset`);if(!this.#i.chain.fitsTranslation(t,1e9))throw RangeError(`offset places the body outside the world`);this.#i.chain.translate(t),this.#a.translate(t),this.#o.translate(t),this.#_()}getPose(){return this.#d}getBendResponse(e){return this.#h(`getBendResponse`),this.#i.bend.response(this.#i.chain,e)}destroy(e){this.onRender=null,this.#s&&=(this.#s.destroy(),null),this.#c=!0,super.destroy(e)}#h(e){if(this.#c)throw Error(`${e} was called on a destroyed beefwife`)}#g(){let e=this.#e();if(typeof e!=`number`||!Number.isFinite(e))throw TypeError(`random() must return a finite number`);if(e<0||e>=1)throw RangeError(`random() must return a number from 0 to 1`);return e}#_(){this.#i.getPose(this.#d)}#v(){this.#u=this.#o.writeRenderState(this.#u),this.#s?this.#s.adopt(this.#u):$.available&&(this.#s=new $(this,this.#u,this.#l))}#y(e=null){let t=this.visible&&this.renderable;t&&(this.#u=this.#o.writeRenderState(this.#u)),this.#s.sync(this.#u,e,t)}};return Object.defineProperty(Beefwife,"MAX_WORLD_COORDINATE",{value:l,enumerable:!0}),Object.defineProperty(Beefwife,"Descriptor",{value:ee,enumerable:!0}),Beefwife})(globalThis.PIXI);typeof module<`u`&&module.exports&&(module.exports=Beefwife);
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@kvmet/beefwife",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Procedurally animated chain-body creatures for the web.",
5
+ "license": "MPL-2.0",
6
+ "author": "Kristen Metcalfe",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/kvmet/beefwife.git",
10
+ "directory": "beefwife"
11
+ },
12
+ "homepage": "https://github.com/kvmet/beefwife/tree/main/beefwife#readme",
13
+ "bugs": "https://github.com/kvmet/beefwife/issues",
14
+ "keywords": [
15
+ "animation",
16
+ "browser",
17
+ "creature",
18
+ "physics",
19
+ "pixi",
20
+ "procedural",
21
+ "verlet"
22
+ ],
23
+ "main": "./beefwife.js",
24
+ "module": "./src/beefwife.mjs",
25
+ "browser": "./beefwife.js",
26
+ "unpkg": "./beefwife.min.js",
27
+ "jsdelivr": "./beefwife.min.js",
28
+ "exports": {
29
+ ".": {
30
+ "import": "./src/beefwife.mjs",
31
+ "require": "./beefwife.js",
32
+ "default": "./beefwife.js"
33
+ },
34
+ "./beefwife.js": "./beefwife.js",
35
+ "./beefwife.min.js": "./beefwife.min.js",
36
+ "./beefwife.example.json": "./beefwife.example.json",
37
+ "./samples/*": "./samples/*",
38
+ "./package.json": "./package.json"
39
+ },
40
+ "files": [
41
+ "CHANGELOG.md",
42
+ "LICENSE",
43
+ "README.md",
44
+ "beefwife.example.json",
45
+ "beefwife.js",
46
+ "beefwife.min.js",
47
+ "samples",
48
+ "src"
49
+ ],
50
+ "sideEffects": false,
51
+ "engines": {
52
+ "node": ">=20.0.0"
53
+ },
54
+ "peerDependencies": {
55
+ "pixi.js": "^8.21.0"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "pixi.js": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "scripts": {
63
+ "build": "rolldown -c rolldown.config.mjs",
64
+ "prepack": "npm run build && npm test",
65
+ "test": "node ../test/beefwife/run.js"
66
+ },
67
+ "publishConfig": {
68
+ "access": "public"
69
+ },
70
+ "devDependencies": {
71
+ "pixi.js": "^8.23.0",
72
+ "rolldown": "1.3.2"
73
+ }
74
+ }
@@ -0,0 +1,260 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "bounding",
4
+ "definitions": {
5
+ "materials": {
6
+ "body": {
7
+ "velocityRetention": 0.2079975983298351,
8
+ "jointCorrection": 0.62,
9
+ "linkCorrection": 0.6,
10
+ "grip": {
11
+ "forward": 0.036,
12
+ "backward": 0.834,
13
+ "lateral": 0.74
14
+ }
15
+ }
16
+ },
17
+ "shapes": {
18
+ "foot": {
19
+ "path": "M -1.2 -0.65 L 0.65 -0.9 L 1.2 -0.35 L 1.2 0.35 L 0.65 0.9 L -1.2 0.65 Z"
20
+ },
21
+ "ornament-1": {
22
+ "path": "M -2 -2 L 0 -3 L 2.5 -2 L 2.5 0.5 L 0 1.5 L -2.5 0 Z"
23
+ },
24
+ "plate-1": {
25
+ "path": "M -5.5 -2 L 2 -2 L 3.5 -1 L 3.5 1 L 2 2 L -5.5 2 Z"
26
+ },
27
+ "plate-2": {
28
+ "path": "M -4 -4 L 0 -5.5 L 4.5 -4 L 6 0 L 4.5 4 L 0 5 L -4 3.5 L -5.5 0 Z"
29
+ }
30
+ },
31
+ "paints": {
32
+ "foot": {
33
+ "fill": "#39424e",
34
+ "stroke": {
35
+ "colour": "#ff0000",
36
+ "width": 3.1
37
+ }
38
+ },
39
+ "leg": {
40
+ "fill": "#39424e",
41
+ "stroke": null
42
+ },
43
+ "ornament-1": {
44
+ "fill": "#050505",
45
+ "stroke": {
46
+ "colour": "#ffffff",
47
+ "width": 3.1
48
+ }
49
+ },
50
+ "ribbon": {
51
+ "fill": "#7a1414",
52
+ "stroke": null
53
+ },
54
+ "shell": {
55
+ "fill": "#ff0000",
56
+ "stroke": {
57
+ "colour": "#ff0000",
58
+ "width": 3.1
59
+ }
60
+ }
61
+ }
62
+ },
63
+ "gait": {
64
+ "cyclesPerSecond": 1.07,
65
+ "phaseLagRadiansPerPixel": 0.12833333333333333,
66
+ "bend": {
67
+ "amplitude": 0.89,
68
+ "harmonic": 1
69
+ },
70
+ "thrust": {
71
+ "acceleration": 1043,
72
+ "harmonic": 1,
73
+ "phaseOffset": 0.81,
74
+ "dutyCycle": 0.5
75
+ },
76
+ "gather": {
77
+ "amplitude": 0.14,
78
+ "harmonic": 2,
79
+ "phaseOffset": 0
80
+ },
81
+ "contact": {
82
+ "amplitude": 0.9,
83
+ "harmonic": 1,
84
+ "phaseOffset": 0.81,
85
+ "dutyCycle": 0.5
86
+ }
87
+ },
88
+ "chain": {
89
+ "physics": {
90
+ "autoLift": {
91
+ "amount": 0.559,
92
+ "share": 0.329,
93
+ "rate": 40
94
+ },
95
+ "steering": {
96
+ "gain": 0.6,
97
+ "limit": 0.5,
98
+ "rate": 6
99
+ }
100
+ },
101
+ "breathing": 0,
102
+ "sections": {
103
+ "head": {
104
+ "chunks": 1,
105
+ "spacing": 12,
106
+ "material": "body",
107
+ "motionScale": {
108
+ "bend": 0,
109
+ "thrust": 1,
110
+ "gather": 1,
111
+ "contact": 1
112
+ },
113
+ "profile": {
114
+ "ribbonWidth": {
115
+ "start": 2.5,
116
+ "end": 4.5
117
+ },
118
+ "plateScale": {
119
+ "start": 1,
120
+ "end": 1
121
+ }
122
+ }
123
+ },
124
+ "trunk": {
125
+ "chunks": 7,
126
+ "spacing": 12,
127
+ "material": "body",
128
+ "motionScale": {
129
+ "bend": 1,
130
+ "thrust": 1,
131
+ "gather": 1,
132
+ "contact": 1
133
+ },
134
+ "profile": {
135
+ "ribbonWidth": {
136
+ "start": 4.5,
137
+ "end": 4.5
138
+ },
139
+ "plateScale": {
140
+ "start": 1,
141
+ "end": 1
142
+ }
143
+ }
144
+ },
145
+ "tail": {
146
+ "chunks": 3,
147
+ "spacing": 12,
148
+ "material": "body",
149
+ "motionScale": {
150
+ "bend": 1,
151
+ "thrust": 1,
152
+ "gather": 1,
153
+ "contact": 1
154
+ },
155
+ "profile": {
156
+ "ribbonWidth": {
157
+ "start": 4.5,
158
+ "end": 0
159
+ },
160
+ "plateScale": {
161
+ "start": 1,
162
+ "end": 0.55
163
+ }
164
+ }
165
+ }
166
+ },
167
+ "skin": {
168
+ "loadScale": 0.35,
169
+ "ribbon": {
170
+ "paint": "ribbon"
171
+ },
172
+ "plates": [
173
+ {
174
+ "id": "plate-1-1",
175
+ "shape": "plate-1",
176
+ "paint": "shell",
177
+ "at": {
178
+ "section": null,
179
+ "from": "head",
180
+ "offset": 0
181
+ },
182
+ "repeat": {
183
+ "count": 1,
184
+ "step": 1
185
+ },
186
+ "scale": 1
187
+ },
188
+ {
189
+ "id": "plate-2-2",
190
+ "shape": "plate-2",
191
+ "paint": "shell",
192
+ "at": {
193
+ "section": null,
194
+ "from": "head",
195
+ "offset": 1
196
+ },
197
+ "repeat": {
198
+ "count": 10,
199
+ "step": 1
200
+ },
201
+ "scale": 1
202
+ }
203
+ ],
204
+ "ornaments": [
205
+ {
206
+ "id": "ornament-1",
207
+ "shape": "ornament-1",
208
+ "paint": "ornament-1",
209
+ "at": {
210
+ "section": null,
211
+ "from": "head",
212
+ "offset": 1
213
+ },
214
+ "repeat": {
215
+ "count": 1,
216
+ "step": 1
217
+ },
218
+ "side": "both",
219
+ "layer": "over",
220
+ "offset": {
221
+ "forward": 0,
222
+ "outward": 8
223
+ },
224
+ "angleDegrees": 52,
225
+ "scale": 1,
226
+ "source": 0.4,
227
+ "react": 1,
228
+ "recover": 30,
229
+ "wobble": 0.85
230
+ }
231
+ ]
232
+ }
233
+ },
234
+ "legs": {
235
+ "section": "trunk",
236
+ "pairs": 0,
237
+ "reach": 17,
238
+ "spread": 0.78,
239
+ "lead": 0.5,
240
+ "fold": 0.5,
241
+ "jointBend": 1,
242
+ "jointLean": 0,
243
+ "jointLeanCenter": 0,
244
+ "sidePhase": 1,
245
+ "liftThreshold": 0.45,
246
+ "swingCycles": 0.17120000000000002,
247
+ "swingArc": 0.3,
248
+ "jitter": 0.3,
249
+ "skin": {
250
+ "limbPaint": "leg",
251
+ "limbWidth": 2.4,
252
+ "foot": {
253
+ "shape": "foot",
254
+ "paint": "foot",
255
+ "scale": 3,
256
+ "plantedScale": 1.35
257
+ }
258
+ }
259
+ }
260
+ }